text stringlengths 37 1.41M |
|---|
# coding=utf-8
# TASKS:================================================================================================================
# Exploring Ensemble Methods
# In this homework we will explore the use of boosting. For this assignment, we will use the pre-implemented gradient
# boosted trees. You will:
# - Use Pandas to do some feature engineering.
# - Train a boosted ensemble of decision-trees (gradient boosted trees) on the lending club dataset.
# - Predict whether a loan will default along with prediction probabilities (on a validation set).
# - Evaluate the trained model and compare it with a baseline.
# - Find the most positive and negative loans using the learned model.
# - Explore how the number of trees influences classification performance.
# ======================================================================================================================
import pandas as pd
import numpy as np
import string
import math
from sklearn.ensemble import GradientBoostingClassifier
import time
start = time.time()
# ======================================================================================================================
# 1. load data
loans = pd.read_csv('./lending-club-data.csv')
# ======================================================================================================================
# 2. we re-assign the target to have +1 as a safe (good) loan, and -1 as a risky (bad) loan.
# Next, we select four categorical features:
# - grade of the loan
# - the length of the loan term
# - the home ownership status: own, mortgage, rent
# - number of years of employment.
features = ['grade', # grade of the loan (categorical)
'sub_grade_num', # sub-grade of the loan as a number from 0 to 1
'short_emp', # one year or less of employment
'emp_length_num', # number of years of employment
'home_ownership', # home_ownership status: own, mortgage or rent
'dti', # debt to income ratio
'purpose', # the purpose of the loan
'payment_inc_ratio', # ratio of the monthly payment to income
'delinq_2yrs', # number of delinquincies
'delinq_2yrs_zero', # no delinquincies in last 2 years
'inq_last_6mths', # number of creditor inquiries in last 6 months
'last_delinq_none', # has borrower had a delinquincy
'last_major_derog_none', # has borrower had 90 day or worse rating
'open_acc', # number of open credit accounts
'pub_rec', # number of derogatory public records
'pub_rec_zero', # no derogatory public records
'revol_util', # percent of available credit being used
'total_rec_late_fee', # total late fees received to day
'int_rate', # interest rate of the loan
'total_rec_int', # interest received to date
'annual_inc', # annual income of borrower
'funded_amnt', # amount committed to the loan
'funded_amnt_inv', # amount committed by investors for the loan
'installment', # monthly payment owed by the borrower
]
loans['safe_loans'] = loans['bad_loans'].apply(lambda x : +1 if x==0 else -1)
loans.drop('bad_loans', axis=1, inplace=True)
target = 'safe_loans'
loans = loans[features + [target]]
# ======================================================================================================================
# Skipping observations with missing values
# Recall that one common approach to coping with missing values is to skip observations that contain missing values.
print len(loans.index)
# loans.dropna(axis=0, how='any', inplace=True)
# loans.dropna(inplace=True)
# print len(loans.index)
# Then follow the following steps:
# - Apply one-hot encoding to loans.
# - Load the JSON files into the lists train_idx and test_idx.
# - Perform train/validation split using train_idx and test_idx.
loans_one_hot_coded = pd.get_dummies(loans)
features = list(loans_one_hot_coded)
features.remove('safe_loans')
train_idx = pd.read_json('./module-8-assignment-2-train-idx.json')
valid_idx = pd.read_json('./module-8-assignment-2-test-idx.json')
train_data = loans_one_hot_coded.iloc[train_idx[0]]
# train_data = loans.iloc[train_idx[0]]
train_data.dropna(axis=0, how='any', inplace=True)
validation_data = loans_one_hot_coded.iloc[valid_idx[0]]
# validation_data = loans.iloc[valid_idx[0]]
validation_data.dropna(axis=0, how='any', inplace=True)
# ======================================================================================================================
# Gradient boosted tree classifier
# Gradient boosted trees are a powerful variant of boosting methods; they have been used to win many Kaggle competitions
# , and have been widely used in industry. We will explore the predictive power of multiple decision trees as opposed to
# a single decision tree.
# We will now train models to predict safe_loans using the features above. In this section, we will experiment with
# training an ensemble of 5 trees.
# 9. Now, let's use the built-in scikit learn gradient boosting classifier (sklearn.ensemble.GradientBoostingClassifier)
# to create a gradient boosted classifier on raining data. You will need to import sklearn, sklearn.ensemble, and numpy.
# You will have to first convert dataFrame into a numpy data matrix. You will also have to extract the label column.
# Make sure to set max_depth=6 and n_estimators=5.
dt = GradientBoostingClassifier(n_estimators=5, max_depth=6)
train_matrix = train_data[features].values # np.asarray(train_data)
train_target = train_data[target].values
dt.fit(train_matrix, train_target)
# ======================================================================================================================
# Making predictions
# Just like we did in previous sections, let us consider a few positive and negative examples from the validation set.
# We will do the following:
# Predict whether or not a loan is likely to default.
# Predict the probability with which the loan is likely to default.
# 10. First, let's grab 2 positive examples and 2 negative examples.
validation_safe_loans = validation_data[validation_data[target] == 1]
validation_risky_loans = validation_data[validation_data[target] == -1]
sample_validation_data_risky = validation_risky_loans[0:2]
sample_validation_data_safe = validation_safe_loans[0:2]
sample_validation_data = sample_validation_data_safe.append(sample_validation_data_risky)
# ======================================================================================================================
# 11. For each row in the sample_validation_data, write code to make model_5 predict whether or not the loan is
# classified as a safe loan.
# Quiz question:
# What percentage of the predictions on sample_validation_data did model_5 get correct?
predictions = dt.predict(sample_validation_data[features].values)
print predictions
# [ 1 -1 -1 1]
print dt.score(validation_data[features].values, validation_data[target].values) # accuracy
# ======================================================================================================================
end = time.time()
print 'Time of Process was: ' + str(round((end - start), 2)) + '[sec]'
|
def plus_multiples_of_3_and_5(limit):
result = 0
i = 1
while i <= limit:
if (i % 3) or (i % 5):
result += i
i += 1
return result
print(plus_multiples_of_3_and_5(1000))
|
# while문의 기본 구조
# while <조건문>:
# <수행할 문장1>
# <수행할 문장2>
# ...
treeHit = 0
while treeHit < 10:
treeHit = treeHit + 1
print("나무를 %d번 찍었습니다." % treeHit)
if treeHit == 10:
print("나무 넘어갑니다.")
prompt = """
1. Add
2. Del
3. List
4. Quit
Enter number: """
number = 0
while True:
print(prompt)
number = int(input())
if number == 1:
print("Add")
elif number == 2:
print("Del")
elif number == 3:
print("List")
elif number == 4:
break
|
def oddeven(x,y):
if(y%2 == 0):
even.append(x[y])
else:
odd.append(x[y])
from tkinter import Tk,simpledialog,messagebox
root = Tk()
root.withdraw()
messagebox.showinfo('Information','this is an encrypter and decrypter software for me and my friends')
a=int(simpledialog.askstring('Q.','PRESS 1 TO ENCRYPT AND 2 TO DECRYPT AND ANY OTHER KEY TO EXIT.'))
x=0
z=0
e=0
p=''
if(a==1):
c=simpledialog.askstring('','type a word')
d=[]
d.extend(c)
even=[]
odd=[]
gurnoor=[]
for y in c:
oddeven(c,x)
x+=1
if len(odd)<len(even):
odd.append('$')
while z<len(odd):
gurnoor.append(odd[z])
gurnoor.append(even[z])
z+=1
while e<len(gurnoor):
p=p+gurnoor[e]
e+=1
messagebox.showinfo('encrypted message',p)
elif(a==2):
c=simpledialog.askstring('','type a word')
d=[]
d.extend(c)
even=[]
odd=[]
gurnoor=[]
for y in c:
oddeven(c,x)
x+=1
while z<len(odd):
gurnoor.append(odd[z])
gurnoor.append(even[z])
z+=1
if(len(gurnoor)%2!=0):
gurnoor.pop()
while e<len(gurnoor):
p=p+gurnoor[e]
e+=1
messagebox.showinfo('decrypted message',p)
else:
exit()
|
import random
from faker import Faker
fake = Faker()
def generate_fake_names(n):
names = set()
while len(names) != n:
name = fake.name().split(" ")[0].lower()
if "." not in name:
names.add(name)
return list(names)
def names_used(s):
ret = set()
for n1, n2 in s:
ret.add(n1)
ret.add(n2)
return list(ret)
def main():
n_friendships = random.randint(10, 1000)
n_queries = random.randint(10, 100)
names = generate_fake_names(n_friendships)
print n_friendships
friendships_used = set()
while len(friendships_used) != n_friendships:
n1, n2 = random.choice(names), random.choice(names)
if n1 != n2 and (n1, n2) not in friendships_used:
print n1 + " " + n2
friendships_used.add((n1, n2))
print n_queries
queries_used = set()
names = names_used(friendships_used)
while len(queries_used) != n_queries:
n1, n2 = random.choice(names), random.choice(names)
if n1 != n2 and (n1, n2) not in queries_used:
print n1 + " " + n2
queries_used.add((n1, n2))
main()
|
import random
NOT_CONNECTED = 0
def empty_dogenet(n):
return [[NOT_CONNECTED for i in range(n)] for j in range(n)]
def random_coordinate(n):
return random.randint(0, n-1), random.randint(0, n-1)
def can_reach_all(net, start_row):
seen = set()
def visit(row):
for doge, weight in enumerate(row):
if weight != NOT_CONNECTED and doge not in seen:
seen.add(doge)
visit(net[doge])
visit(net[start_row])
return len(seen) == len(net)
def is_connected(net):
return all(can_reach_all(net, row) for row in range(len(net)))
def randomly_connected_net(n):
net = empty_dogenet(n)
while not is_connected(net):
x, y = random_coordinate(n)
if x != y:
w = random.randint(1, 1000)
net[x][y] = w
net[y][x] = w
return net
def main():
net_size = random.randint(2, 100)
print net_size
net = randomly_connected_net(net_size)
for row in net:
print " ".join(map(str, row))
main()
|
class Graph:
def __init__(self):
self._g = {}
def connect(self, u, v):
if u not in self._g:
self._g[u] = set()
self._g[u].add(v)
def connect_bidirectional(self, u, v):
self.connect(u, v)
self.connect(v, u)
def __getitem__(self, u):
return self._g[u]
def rolls_with(g, u, v):
seen = set()
to_visit = [u]
while len(to_visit) != 0:
current = to_visit.pop()
if current == v:
return True
for friend in g[current]:
if friend not in seen:
seen.add(friend)
to_visit.append(friend)
return False
def main():
friend_graph = Graph()
n_friendships = int(raw_input())
for i in range(n_friendships):
n1, n2 = raw_input().split(" ")
friend_graph.connect_bidirectional(n1, n2)
n_queries = int(raw_input())
for i in range(n_queries):
u, v = raw_input().split(" ")
if rolls_with(friend_graph, u, v):
print "yes"
else:
print "no"
main()
|
import sys
from array import array
""" The purpose of this program is to ensure that everyone who registered has participated
Instructions: Simply write your name and then write your ID # """
names = []
numbers = []
names.append('Horatiu')
numbers.append(0)
num = "-1"
name = ""
#Clear the screen
def clear():
print "--------------------------------------------------------------"
#Get the input from the user. x means stop!
def getInput():
print "Please enter your name:",
name = str(raw_input())
if name != "x":
print "Please enter your unique registration number:",
try:
num = input()
except (RuntimeError, TypeError, NameError):
print "Error: Enter a valid number."
getInput()
return ""
print "Thank you,",
print name,
print "has successfully registered with #",
print num
names.append(name)
try:
numbers.append(num)
except (RuntimeError, TypeError, NameError):
print "Error: Enter a number."
getInput()
clear()
return ""
else:
return "x"
#Output the final array of numbers and words
def outputArr():
file = open("contest.txt", "w")
file.write("Math Contest Registration Confirmation System:\n")
for x in range (len(names)):
file.write(names[x])
file.write(" ")
file.write(str(numbers[x]))
file.write("\n")
file.close()
#This is the main program
while(True):
if (getInput() == "x"):
print "Done!"
outputArr()
sys.exit() |
from collections import deque
class Node:
def __init__(self, k):
self.key = k
self.left = None
self.right = None
def printLevelOrderLine(root):
if root == None:
return
q = deque()
q.append(root)
q.append(None)
while len(q) > 1:
curr = q.popleft()
if curr == None:
print('')
q.append(None)
continue
print(curr.key, end=' ')
if curr.left != None:
q.append(curr.left)
if curr.right != None:
q.append(curr.right)
root = Node(10)
root.left = Node(15)
root.right = Node(20)
root.left.left = Node(30)
root.right.left = Node(40)
root.right.right = Node(50)
root.right.left.left = Node(60)
root.right.left.right = Node(70)
printLevelOrderLine(root)
|
class minHeap:
def __init__(self, c):
self.arr = [None for _ in range(c)]
self.size = 0
self.capacity = c
def left(self, i):
return 2*i + 1
def right(self, i):
return 2*i + 2
def parent(self, i):
return int((i-1)/2)
def decreaseKey(i, x):
arr[i] = x
# if parent is bigger swap
while i != 0 and arr[parent(i)] > arr[i]:
swap(arr, i, parent(i))
i = parent(i) # update i
# decreaseKey(i, -INF)
# extract min
def deleteKey(i):
def buildHeap():
# do minHeapify from parent of last child to root
i = parent(size-1)
while i >= 0:
minHeapify(i)
i -= 1
|
class minHeap:
def __init__(self, c):
self.arr = [None for _ in range(c)]
self.size = 0
self.capacity = c
def left(self, i):
return 2*i + 1
def right(self, i):
return 2*i + 2
def parent(self, i):
return int((i-1)/2)
def insert(self, x):
if self.size == self.capacity: # full
return
self.size += 1
arr[size-1] = x
i = size-1
while i != 0 and arr[parent(i)] > arr[i]:
swap(arr, i, parent(i))
i = parent(i)
def swap(arr, i1, i2):
arr[i1], arr[i2] = arr[i2], arr[i1]
|
import queue
class Node:
def __init__(self, k):
self.key = k
self.left = None
self.right = None
def printLeft(root):
if root == None:
return
q = queue.Queue()
q.put(root)
while q.empty() == False:
count = q.qsize()
for i in range(count): # i: 0 ~ count-1
curr = q.get()
# print only first node in queue
if i == 0:
print(curr.key, end=' ')
if curr.left != None:
q.put(curr.left)
if curr.right != None:
q.put(curr.right)
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.right.left = Node(40)
root.right.right = Node(50)
printLeft(root) |
class Node:
def __init__(self, k):
self.key = k
self.left = None
self.right = None
# time: O(h)
# aux space: O(h)
def delNode(root, x):
if root == None:
return None
if root.key > x:
root.left = delNode(root.left, x)
else if root.key < x:
root.right = delNode(root.right, x)
else: # delete root
if root.left == None:
return root.right
else if root.right == None:
return root.left
else:
succ = getSucc(root)
root.key = succ.key # replace root with succ
root.right = delNode(root.right, succ.key)
return root
def getSucc(root):
curr = root.right
while curr != None and curr.left != None:
curr = curr.left
return curr
|
# -*- coding: utf-8 -*-
# Author: BellaWu
# Date: 2021/2/17 11:25
# File: zip_lambda_map.py
# IDE: PyCharm
# zip: 接受多个任意序列为参数,合并后返回一个tuple列表
a = [1,2,3]
b = [4,5,6]
ab = zip(a,b)
print(list(ab))
for i, j in zip(a,b):
print(i/2, j*2)
# lambda:简单的函数,实现简化代码的功能
func = lambda x, y: x+y
x = int(input('Please input a number x = '))
y = int(input('Please input another number y = '))
print(func(x,y))
# map:把函数和参数绑定在一起
print(list(map(func, [1,2], [3,4])))
|
# -*- coding: utf-8 -*-
# Author: bellawu
# Date: 2021/2/21 11:51
# File: multiprocessing_pool.py
# IDE: PyCharm
# pool用来完成多进程,将要运行的东西直接放入进程池中。
import multiprocessing
def job(x):
return x*x
def multi_process():
pool = multiprocessing.Pool(processes=3)
res = pool.map(job, range(10))
print(res)
# apply_async:只能传递一个值,它只会放入一个核进行运算,注意参数是可迭代的,要加','
res2 = pool.apply_async(job, (2,))
print(res2.get())
results = [pool.apply_async(job, (i,)) for i in range(10)]
print([result.get() for result in results])
if __name__ == '__main__':
multi_process()
|
# -*- coding: utf-8 -*-
x = 3
y = 2
z = 0
if x > y:
print("x is greater than y.")
else:
print("x is less than y.")
worked = False
# 通过行内表达式完成类似三目操作符
result = 'done' if worked else 'not yet'
print(result)
if x > 1:
print('x>1')
elif x < 1:
print('x<1')
else:
print('x=1')
|
def rotate(a, n, k):
i = 0
for item in range(len(a)):
if i < n:
print(a[(i+n-k)%n], end = " ")
else:
print(a[i], end = " ")
i += 1
#main function
s = str(input())
s = s.split(' ')
size = int(s[0])
i = 0
array = []
while i < size:
array.append(int(s[i+1]))
i += 1
n = int(s[i+1])
k = int(s[i+2])
rotate(array, n, k)
|
from screen import screen
#sub class of screen class
class myScreen(screen):
#constructor contains attributes (size of screen , type of screen and color of screen
def __init__(self,sizeScreen,typeScreen,colorScreen):
super(myScreen, self).__init__(sizeScreen,typeScreen,colorScreen)
#abstract method with implementation to declear type of system screen
def screenSystem(self):
return "Screen type System is %s" % self.screenType
#abstract method with implementation to declear type of system color screen
def screenColorSystem(self, type):
return "color system of screen is %s" %type |
from states import *
import time
from levels import *
def bfs(start):
#Performs a breadth first search from the start state to the goal
# Start Timer
startTime = time.time()
print("BFS start")
# Vector with boards already seen, so there is no cicles
seen = []
# Initial node
start_node = Node(start, None, None, 0, 0)
# A list (in form of a stack) for the nodes.
bfs_stack = []
bfs_stack.append(start_node)
# Current node
current = bfs_stack.pop(0)
# Final path to be returned
path = []
seen.append(current.state)
expanded_nodes = 0
while(objectiveTest(current.state) != True):
# Gets all the possible expandable nodes
temp = expand_node(current)
expanded_nodes += 1
for item in temp:
# Check for cicles and repeated states
if (item.state not in seen):
# Inserts node to seen list so it is not seen again
seen.append(item.state)
bfs_stack.append(item)
else:
continue
# Updates current node
if len(bfs_stack)!=0:
current = bfs_stack.pop(0)
else:
return "No Soluction"
# Records the path to be returned
while(current.parent != None):
path.insert(0,current.operator)
current = current.parent
# Calculates time of the function
endTime = time.time()
timeElapsed = endTime - startTime
# Prints time in a friendly way
if timeElapsed > 1:
print("Time: " + str(round(timeElapsed, 10)) + "s")
else:
print("Time: " + str(round(timeElapsed*1000, 3)) + "ms")
return path
|
def new_Password(oldPassword, newPassword):
return newPassword != oldPassword and len(newPassword) >= 6
oldPassword = input("Oude Password: ")
newPassword = input("Nieuwe Password: ")
x = new_Password(oldPassword, newPassword)
print(x)
|
def BMI(gewicht, lengte):
bmiWaarde = (gewicht * 703) / lengte**2
return bmiWaarde
gewicht = int(input("Hoeveel weeg je? (pounds) "))
lengte = int(input("Hoe lang ben je? (inches) "))
print(round(BMI(gewicht, lengte), 2))
if BMI(gewicht, lengte) < 18.5:
print('Underweight')
elif BMI(gewicht, lengte) < 25.0:
print('Normal Weight')
else:
print('Overweight') |
import pandas as pd
import numpy as np
from pandas import DataFrame, Series
def groupby1():
df = DataFrame({'key1':['a', 'a', 'b', 'b', 'a'],
'key2':['one', 'two', 'three', 'four', 'five'],
'data1': np.random.randn(5),
'data2': np.random.randn(5)})
print(df)
# 方法一
grouped = df['data1'].groupby([df['key1']])
print(grouped.mean())
# 多个分组键
means = df['data1'].groupby([df['key1'], df['key2']]).mean()
print('mean1:')
print(means)
print(means.unstack())
# 分组键为数组
states = np.array(['Ohio', 'Ohio', 'California', 'California', 'Ohio'])
years = np.array([2000, 2001, 2002, 2003, 2004])
means = df['data1'].groupby([states, years]).mean()
print('means2:')
print(means)
print(means.unstack())
# 列名作为
means = df.groupby(['key1','key2']).mean()
print(means)
print(means.unstack())
print(df.groupby(['key1', 'key2']).size())
#
# 对分组进行迭代
print('对分组进行迭代')
for name, group in df.groupby('key1'):
print('-----------')
print(name)
print('---')
print(group)
print('-----------')
for (key1,key2), group in df.groupby(['key1', 'key2']):
print('-----------')
print(key1, key2)
print('---')
print(group)
print('-----------')
# 自作成字典
pieces = dict(list(df.groupby('key1')))
print(pieces['b'])
# 根据列进行分组
print('根据列进行分组')
print(df.dtypes)
print(type(df.dtypes))
grouped = df.groupby(df.dtypes, axis=1)
print(dict(list(grouped)))
print(df.groupby('key1')['data1'])
print(df['data1'].groupby(df['key1']))
print(df.groupby('key1')['data2'])
print(df['data2'].groupby(df['key1']))
print(df.groupby('key1')['data2'].mean())
print(df['data2'].groupby(df['key1']).mean())
# 通过字典或series进行分组
def dict_series_groupby():
df = DataFrame(np.random.randn(5,5),
columns={'a', 'b', 'c', 'd', 'e'},
index={'jow', 'steve', 'wes', 'jim', 'travis'})
df.ix[2:3, ['b', 'c']] = np.nan
print(df)
mapping = {'a': 'red', 'b': 'red', 'c': 'blue', 'd': 'blue', 'e': 'red', 'f': 'orange'}
by_columns = df.groupby(mapping, axis=1)
print(by_columns.sum())
map_series = Series(mapping)
print(map_series)
by_columns = df.groupby(map_series, axis=1).count()
print(by_columns)
def fun_groupby():
df = DataFrame(np.random.randn(5, 5),
columns={'a', 'b', 'c', 'd', 'e'},
index={'jow', 'steve', 'wes', 'jim', 'travis'})
df.ix[2:3, ['b', 'c']] = np.nan
print(df)
print(df.groupby(len).sum()) # 根据index长度进行分类
# 同数组,列表,字典,series进行混用
key_list = ['one', 'one', 'one', 'two', 'two']
print(df.groupby([len, key_list]).min())
# 根据索引级别分组
def index_level_group():
columns = pd.MultiIndex.from_arrays([['US', 'US', 'US', 'JP', 'JP'],
[1, 3, 4, 1, 3]], names=['city', 'tenor'])
df = DataFrame(np.random.randn(4, 5), columns=columns)
print(df)
print(df.groupby(level='city', axis=1).count())
# 分位数
def quantile():
df = DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'],
'key2': ['one', 'two', 'three', 'four', 'five'],
'data1': np.random.randn(5),
'data2': np.random.randn(5)})
grouped = df.groupby('key1')
print(grouped['data1'].quantile(0.9))
# 使用自定义函数
print(grouped.agg(peak_to_peak))
def peak_to_peak(arr):
return arr.max() - arr.min()
if __name__ == '__main__':
# groupby1()
# dict_series_groupby()
# fun_groupby()
# index_level_group()
quantile()
|
'''
http://en.wikipedia.org/wiki/Hypotrochoid
'''
import numpy as np
import pylab as pl
def hypotorochoids(R=5, r=3, d=5):
t = np.linspace(-4*np.pi, 4*np.pi, 300)
x = (R-r) * np.cos(t) + d * np.cos((R-r)*t / r)
y = (R-r) * np.sin(t) - d * np.sin((R-r)*t / r)
return x, y
def draw():
x, y = hypotorochoids(R=5, r=3, d=5)
pl.plot(x, y, 'r')
pl.axis('equal')
pl.show()
if __name__ == '__main__':
draw()
|
def findprimes(b):
A=[]
for i in range(0,b+1):
A.append(i)
for j in range(2,(b//2)+1):
n=2
if A[j]==0:
pass
else:
while n <= b/j:
A[j*n]=0
n=n+1
k=0
L=len(A)
while k<L:
if A[k]==0:
del A[k]
L=len(A)
else:
k=k+1
return A[1:]
#10,001 st prime
def isprime(num):
if num <2:
return False
if num == 2:
return True
if num == 3:
return True
if num > 2:
for i in range(2,num//2+1):
if num%i == 0:
return False
return True
def nthprime(a):
count = 0
working = 2
while count < a:
if isprime(working):
count = count +1
prime = working
working = working + 1
else:
working = working + 1
return prime |
import pandas as pd
import json
def cleanList():
#Open file
f = open("city.list.json", encoding="utf8")
content = f.read()
f.close()
#Load to dataframe
df = pd.read_json(content)
#Set all city name (keys) to lower case
df["name"] = df["name"].str.lower()
df["c"] = df["country"].str.lower()
#Drop duplicates when name and country is same, keep first copy
df["name_country"] = df["name"] + "," +df["country"]
df.drop_duplicates(subset="name_country",keep="first", inplace=True)
#Mark and handle duplicated cities
df["d"] = df.duplicated(subset=["name"], keep=False)
#Get all duplicated city names, use for later
duplicated_cities = df[df.duplicated(subset=["name"], keep=False)]
#Handle duplicates here
df.drop(columns=["name_country", "coord", "country"], inplace=True)
#Set name as key, drop all rows that's duplicated.
df.drop_duplicates(subset="name", keep=False, inplace=True)
df.set_index("name", inplace=True)
#Convert back to JSON. JSON for all unique city names
df.to_json(r'modifiedCityList.json', orient="index")
handleDuplicates(duplicated_cities)
#Work with duplicated city names
def handleDuplicates(df):
# Dictionary, key = city
# Value = dictionary with key of country, value of cityid
cities = {}
for index, row in df.iterrows():
if row["name"] not in cities:
cities[row["name"]] = {}
cities[row["name"]][row["country"]] = row["id"]
f = open("duplicateCities.json", "w+")
output = json.dumps(cities, sort_keys=True)
f.write(output)
f.close()
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_rows', 500)
cleanList() |
def is_prime(_number):
for x in range(2, _number):
if _number % x == 0:
return False
return True
def next_prime(prime):
next = prime + 1
while not is_prime(next):
next += 1
return next
if __name__ == '__main__':
count = 1
prime_number = 1
while count < 10002:
count += 1
prime_number = next_prime(prime_number)
print("# %d: %d" % (count, prime_number))
print("Found prime: " + str(prime_number))
|
choose = input()
if choose == 'paper':
print("Sorry, but the computer chose scissors")
if choose == 'scissors':
print("Sorry, but the computer chose rock")
if choose == 'rock':
print("Sorry, but the computer chose paper")
|
#Funcion de potenciacion en python
def potenciacion(numero,expn):
if expn==0:
print 1
potencia=numero
for i in range(expn-1):
potencia=potencia*numero
print potencia
potenciacion(4.6,1.2)
def suma(self):
decimal.Decimal('0.1')+decimal.Decimal('0.2')
return suma('0.3')
def Division(numero):
return decimal.Decimal(numero)/decimal.Decimal(numero)
from decimal import Decimal
from fractions import Fraccion
Fraccion.from_float(0.1)
Fraccion(3602879701896397, 36028797018963968)
(0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)
Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
format(Decimal.from_float(0.1), '.17')
'0.10000000000000001'
##################
def suma(self):
decimal.Decimal('0.1')+decimal.Decimal('0.2')
return suma('0.3')
def Division(self):
decimal.Decimal('4')/decimal.Decimal('100')
return('0.04') |
from random import randint
number =randint(1,9)
if number %2==0:
raise NameError("%d is even "% number)
else:
raise NameError("%d is odd"%number)
|
sum = 0
for i in range(10):
sum += float(input("number " + str(i+1) + ": "))
print(sum/10)
|
# -- coding:utf-8 --
# filter是筛选器,参数有两个,第一个是函数,第二个是列表,作用是将列表中每个元素执行函数,根据返回值时True or False决定是否保留,删除返回true的值
# 本程序实现删除1-100中的素数
def is_su(m):
fin = False
if(m==1):
fin = True
else:
for i in range(2,m):
if(m%i==0):
fin = True
return fin
l = range(1,101)
print l
print filter(is_su, l)
|
# --coding:utf-8--
# --test git push--
i = 0
number = []
while i < 6:
print "At the top i is %d" % i
number.append(i)
i = i + 1
print "Number now: " , number
print "At the bottom i is %d" % i
print "The number:"
for num in number:
print num
|
def main(x):
for i in range(x):
print(fibonacciLoop(i))
def fibonacciLoop(number):
fib1,fib2,result = 1,1,1
if(number == 1 or number == 2):
return 1
for i in range(3, number, 1):
result = fib1 + fib2
fib1 = fib2
fib2 = result
return result
main(15)
|
# A palindrome is a series of characters that read the same forwards as backwards such as "hannah", "racecar" and "lol".
# For this Kata you need to write a function that takes a string of characters and returns the length,
# as an integer value, of longest alphanumeric palindrome that could be made by combining the characters in any order
# but using each character only once. The function should not be case sensitive.
# For example if passed "Hannah" it should return 6 and if passed "aabbccyYx" it should return 9 because
# one possible palindrome would be "abcyxycba".
# Test.describe("Basic Tests")
# Test.assert_equals(longest_palindrome("A"), 1)
# Test.assert_equals(longest_palindrome("Hannah"), 6)
# Test.assert_equals(longest_palindrome("xyz__a_/b0110//a_zyx"), 13)
# Test.assert_equals(longest_palindrome("$aaabbbccddd_!jJpqlQx_.///yYabababhii_"), 25)
# Test.assert_equals(longest_palindrome(""), 0)
# print("<COMPLETEDIN::>")
def longest_palindrome(s):
print(s)
if s.isalnum() and len(s) == 1:
return 1
elif s.isalnum() == False and len(s) < 1:
return 0
s = s.lower()
s2 = {}
total = 0
for l in s:
s2[l] = l
s2[l] = s.count(l)
for x in range(len(s2)):
if list(s2.keys())[x].isalnum():
if list(s2.values())[x] % 2 == 0:
total += list(s2.values())[x]
elif list(s2.values())[x] > 2 and list(s2.values())[x] != 0:
total += list(s2.values())[x] - 1
if total == 6:
return total
else:
return total + 1
|
# coding: utf-8
""" Project Euler problem #50. """
import itertools as it
def problem():
u""" Solve the problem.
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below
one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a
prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most
consecutive primes?
Answer: 997651
"""
limit = 10**6
primes = list(primes_xrange(limit))
sums = [0]
while sums[-1] < limit:
sums.append(sums[-1] + primes[len(sums) - 1])
return max(
set(a - b for b, a in it.combinations(sums[:-1], 2)) & set(primes))
def primes_xrange(a, b=0):
""" Get prime numbers below passed stop value. """
stop, start = (a, b) if not b else (b, a)
primes = [True] * stop
primes[0], primes[1] = [False, False]
for idx, value in enumerate(primes):
if value is True:
primes[idx*2::idx] = [False] * ((stop - 1)/idx - 1)
if idx >= start:
yield idx
if __name__ == '__main__':
print problem()
|
""" Project Euler problem #22. """
import os.path as op
def problem():
""" Solve the problem.
Using names.txt, a 46K text file containing over five-thousand first names,
begin by sorting it into alphabetical order. Then working out the
alphabetical value for each name, multiply this value by its alphabetical
position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which
is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So,
COLIN would obtain a score of 938 * 53 = 49714.
What is the total of all the name scores in the file?
Answer: 871198282
"""
path = op.join(op.dirname(__file__), 'names.txt')
with open(path, 'r') as ff:
names = [n.strip('"') for n in ff.read().split(',')]
names = sorted(names)
return sum(
sum((ord(c) - 64) for c in name) * pos
for pos, name in enumerate(names, 1))
if __name__ == '__main__':
print problem()
|
""" Project Euler problem #18. """
def problem():
""" Solve the problem.
Find the maximum total from top to bottom of the triangle below.
Answer: 1074
"""
triangle = """
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
"""
triangle = [
map(int, l.strip().split()) for l in triangle.split('\n') if l.strip()]
gen = iter(reversed(triangle))
sums = next(gen)
def grouper(nodes):
for n in range(len(nodes) - 1):
yield nodes[n], nodes[n+1]
for nodes in gen:
sums = [s + max(nn) for s, nn in zip(nodes, grouper(sums))]
return sums[0]
if __name__ == '__main__':
print problem()
|
""" Project Euler problem #17. """
def problem():
""" Solve the problem.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out
in words, how many letters would be used?.
Answer: 21124
"""
cnv = {
0: '',
1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six',
7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven',
12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen',
16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen',
20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty',
70: 'seventy', 80: 'eighty', 90: 'ninety'}
def num_to_words(num, space=' ', hypthen='-'):
if num == 1000:
return 'one' + space + 'thousand'
text = ''
hundreds, rest = divmod(num, 100)
if hundreds:
text = num_to_words(hundreds, space=space, hypthen=hypthen) \
+ space + 'hundred'
if not rest:
return text
text += space + 'and' + space
if cnv.get(rest):
return text + cnv[rest]
tens, rest = divmod(rest, 10)
text += cnv[tens * 10]
if rest:
text += hypthen + cnv[rest]
return text
return sum(
len(num_to_words(n, space='', hypthen=''))
for n in range(1, 1001))
if __name__ == '__main__':
print problem()
|
# coding: utf-8
""" Project Euler problem #X. """
import itertools as it
def problem():
u""" Solve the problem.
The number, 1406357289, is a 0 to 9 pandigital number because it is made up
of each of the digits 0 to 9 in some order, but it also has a rather
interesting sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way,
we note the following:
d2*d3*d4=406 is divisible by 2
d3*d4*d5=063 is divisible by 3
d4*d5*d6=635 is divisible by 5
d5*d6*d7=357 is divisible by 7
d6*d7*d8=572 is divisible by 11
d7*d8*d9=728 is divisible by 13
d8*d9*d10=289 is divisible by 17
Find the sum of all 0 to 9 pandigital numbers with this property.
Answer: 16695334890
"""
primes = list(enumerate((2, 3, 5, 7, 11, 13, 17), 1))
_sum = 0
for pandigital in it.permutations('0123456789'):
if any(int(''.join(pandigital[num:num + 3])) % prime
for num, prime in primes):
continue
_sum += int(''.join(pandigital))
return _sum
def is_pandigital(*args):
""" Check numbers is pandigital through 9. """
return '123456789'.startswith(
''.join(sorted(x for arg in args for x in str(arg))))
if __name__ == '__main__':
print problem()
|
""" Project Euler problem #10. """
import math as mt
def problem():
""" Solve the problem.
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
Answer: 142913828922
"""
return sum(prime_numbers(2000000))
def prime_numbers(_max):
""" Get prime numbers below passed max. """
a = [True] * _max
for n in range(2, int(mt.sqrt(_max)) + 1):
if not a[n]:
continue
for j in range(n ** 2, _max, n):
a[j] = False
return [n for n in range(2, _max) if a[n]]
if __name__ == '__main__':
print problem()
|
import unittest
from main import LinkedList, Solution
class SumTwoNumbersTestCase(unittest.TestCase):
@staticmethod
def setup_test_case_one():
list_one = LinkedList()
list_one.push(3)
list_one.push(4)
list_one.push(2)
list_two = LinkedList()
list_two.push(4)
list_two.push(6)
list_two.push(5)
solution = Solution()
result_list = (solution.add_two_numbers(list_one, list_two))
return result_list
def test_case_one_solution(self):
result_list = self.setup_test_case_one()
self.assertEqual(result_list.convert_to_number(), 708)
@staticmethod
def setup_test_case_two():
list_one = LinkedList()
list_one.push(0)
list_two = LinkedList()
list_two.push(0)
solution = Solution()
result_list = (solution.add_two_numbers(list_one, list_two))
return result_list
def test_case_two_solution(self):
result_list = self.setup_test_case_two()
self.assertEqual(result_list.convert_to_number(), 0)
@staticmethod
def setup_test_case_three():
list_one = LinkedList()
list_one.push(9)
list_one.push(9)
list_one.push(9)
list_one.push(9)
list_one.push(9)
list_one.push(9)
list_one.push(9)
list_two = LinkedList()
list_two.push(9)
list_two.push(9)
list_two.push(9)
list_two.push(9)
solution = Solution()
result_list = (solution.add_two_numbers(list_one, list_two))
return result_list
def test_case_three_solution(self):
result_list = self.setup_test_case_three()
self.assertEqual(result_list.convert_to_number(), 89990001)
if __name__ == '__main__':
unittest.main()
|
departure = ["Auckland", "Wellington", "Christchurch"]
destinations = ["Sydney", "Tonga", "Shanghai", "London"]
print ("welcome to my travel system")
print ("please enter your departure location")
print ("Auckland")
print ("Wellington")
print ("Christchurch")
departure_location=input ("")
if departure_location=="Auckland":
print (departure[0])
elif departure_location=="Wellington":
print (departure[1])
else:
print (departure[2])
|
#!/usr/bin/env python3
import sys #couldnt find a use case , too lazy to delete
#representation of a tic-tac-toe board
theboard={
'top-l':"",'top-mid':"",'top-r':"",
'mid-l':'','mid-mid':'','mid-r':'',
'dwn-l':'','dwn-mid':'','dwn-r':''
}
def printboard(board):
'''
function to print the state of the game after each play
'''
print(theboard['top-l']+"\t|"+theboard['top-mid']+"\t|"+theboard["top-r"])
print("-----------------------------")
print(theboard['mid-l']+"\t|"+theboard['mid-mid']+"\t|"+theboard['mid-r'])
print("-----------------------------")
print(theboard['dwn-l']+"\t|"+theboard['dwn-mid']+"\t|"+theboard['dwn-r'])
print("-----------------------------")
printboard(theboard)
def instruction():
print("\n < == >instructions< == >")
print("\"top-l\", \"top-mid\", \"top-r\" for top left, middle, or right "\
"position")
print("\"mid-l\", \"mid-mid\", \"mid-r\" to fill the middle "\
"positions respectively")
print("\"dwn-r\", \"ndwn-mid\", \"dwn-l\" to fill the bottomd "\
"boards" )
print("\n < == >tips< == >")
print("\"mid-l\" means the middle left board and \"dwn-l\" means the "\
"downmost-left board\n")
instruction()
printboard(theboard)
def check_win_x(theboard):
#this is a very terrible line of code , i know
if((theboard['top-l']=="x" and theboard['top-r']=='x' and theboard['top-mid']=='x') or \
(theboard['mid-l']=='x' and theboard['mid-mid']=='x' and theboard['mid-r']=='x') or \
(theboard['dwn-r']=='x' and theboard['dwn-l']=='x' and theboard['dwn-mid']=='x') or \
(theboard['top-l']=='x' and theboard['mid-l']=='x' and theboard['dwn-l']=='x') or \
(theboard['top-mid']=='x' and theboard['mid-mid']=='x' and theboard['dwn-mid']=='x') or \
(theboard['top-r']=='x' and theboard['mid-r']=='x' and theboard['dwn-r']=='x') or \
(theboard['top-r']=='x' and theboard['mid-mid']=='x' and theboard['dwn-l']=='x') or \
(theboard['top-l']=='x' and theboard['mid-mid']=='x' and theboard['dwn-r']=='x')):
print("playerX is the winner")
return True
def check_win_o(theboard):
#another of the terrible code above
if((theboard['top-l']=="o" and theboard['top-r']=='o' and theboard['top-mid']=='o') or \
(theboard['mid-l']=='o' and theboard['mid-mid']=='o' and theboard['mid-r']=='o') or \
(theboard['dwn-r']=='o' and theboard['dwn-l']=='o' and theboard['dwn-mid']=='o') or \
(theboard['top-l']=='o' and theboard['mid-l']=='o' and theboard['dwn-l']=='o') or \
(theboard['top-mid']=='o' and theboard['mid-mid']=='o' and theboard['dwn-mid']=='o') or \
(theboard['top-r']=='o' and theboard['mid-r']=='o' and theboard['dwn-r']=='o') or \
(theboard['top-r']=='o' and theboard['mid-mid']=='o' and theboard['dwn-l']=='o') or \
(theboard['top-l']=='o' and theboard['mid-mid']=='o' and theboard['dwn-r']=='o')):
print("playerO is the winner")
return True
print()
def no_more_moves(theboard):
if "" not in theboard.values():
return True
return False
while(True):
try:
#check if any move is till possible else end the game
if(no_more_moves(theboard)):
break
xturn= input("playerX enter your position : ")
if(theboard[xturn]!=''): #reject input if the location is not empy
print("**************************************\n")
print("you can overide an already played box")
print("****************")
printboard(theboard)
contin
theboard[xturn]="x" #set the location entered to X
printboard(theboard)
#check for possible moves , if none end the game
if(no_more_moves(theboard)):
print("\n!!no more move possible, game ended in a DRAW")
break
if(check_win_x(theboard)):
break
Oturn=input("playerO enter your position : ")
if(theboard[Oturn]!=''):
print("**************************************\n")
print("you can overide an already played box")
print("this will cause x to play ahead of you")
print("****************")
printboard(theboard)
theboard[Oturn]='o' #set the location to "o" as enterd by player0
printboard(theboard)
if(check_win_o(theboard)):
print("\n!!no more move possible, game ended in a DRAW")
break
#handle wrong location error
except KeyError:
print("wrong location")
print("read instruction\n")
instruction()
|
def fibonacci(n):
a = 0
b = 1
if n < 0:
print("Incorrect input")
elif n == 0:
return a
elif n == 1:
return b
else:
for i in range(2,n):
c = a + b
a = b
b = c
return b
def fizzbuzz():
for i in range(101):
if i % 15 == 0:
print("fizzbuzz")
i+=1
elif i % 3 ==0:
print("fizz")
i+=1
elif i % 5 == 0:
print("buzz")
i+=1
else:
print(i)
i+=1
def fib_printer(x, y):
fib_lst = []
for i in range(x, y+1):
fib_lst.append(fibonacci(i))
seq = str(fib_lst[0])
for num in range(1, len(fib_lst)):
seq = seq + ", " + str(fib_lst[num])
print(seq)
def thousand_fib_digits():
thousand_fib_lst = []
for i in range(10000):
thousand_fib_lst.append(fibonacci(i))
for x in range(len(thousand_fib_lst)):
print(len(str(thousand_fib_lst[x])))
# thousand_fib_digits()
# fib_printer(0, 8)
# fizzbuzz()
|
import sys
arg1 = sys.argv[1]
def myfunc(arg1):
"""return first char that is not repeated in the string
ignore case when counting but return original char.
if all repeating, return empty string.
"""
check = ""
for char in arg1:
if arg1.lower().count(char.lower()) == 1:
check = char
break
return check
print(myfunc(arg1)) |
import sys
class Sphere:
Pi = 3.14
def __init__(self, radius):
self.radius = radius
# self.PI = 3.14
def get_surface_area(self):
return 4*self.Pi*self.radius**2
def get_volume(self):
return 4/3*self.Pi*self.radius**3
def set_radius(self, x):
self.radius = x
n=Sphere(int(sys.argv[1]))
print(n.get_surface_area())
print(n.get_volume())
n.set_radius(int(sys.argv[1])*2)
print(n.get_surface_area())
print(n.get_volume()) |
# class TicTacToe():
""" This is the well-known game of Tic-Tac-Toe. Players X and Y
take turns choosing a square on the board until one player
scores three in a row. """
def gameBoard(currentlst):
# A new game will start with blank inputs. Every time a user input is added to currentlst, this function will be re-run to update and print the board.
row_label = [" ", " ", " ", "1", " ", "2", " ", "3"]
row_sepa = [" ", " ", " ", "_", "_", "_", "_", "_"]
row_sepb = [" ", " ", " ", " ", " ", " ", " ", " "]
rowa = ["1", "|", " ", " ", "|", " ", "|", " "]
rowlina = [" ", "|", " ", "-", "-", "-", "-", "-"]
rowb = ["2", "|", " ", " ", "|", " ", "|", " "]
rowlinb = [" ", "|", " ", "-", "-", "-", "-", "-"]
rowc = ["3", "|", " ", " ", "|", " ", "|", " "]
for i in range(0,3):
for j in range(0, 3):
if currentlst[i][j] != "":
if i == 0:
if j == 0:
rowa[j+3] = currentlst[i][j]
elif j == 1:
rowa[j+4] = currentlst[i][j]
elif j == 2:
rowa[j+5] = currentlst[i][j]
elif i == 1:
if j == 0:
rowb[j+3] = currentlst[i][j]
elif j == 1:
rowb[j+4] = currentlst[i][j]
elif j == 2:
rowb[j+5] = currentlst[i][j]
elif i == 2:
if j == 0:
rowc[j+3] = currentlst[i][j]
elif j == 1:
rowc[j+4] = currentlst[i][j]
elif j == 2:
rowc[j+5] = currentlst[i][j]
currentBoard = []
currentBoard.append(row_label)
currentBoard.append(row_sepa)
currentBoard.append(row_sepb)
currentBoard.append(rowa)
currentBoard.append(rowlina)
currentBoard.append(rowb)
currentBoard.append(rowlinb)
currentBoard.append(rowc)
return currentBoard
def isWin(currentlst):
#There are 8 WIN conditions. There are 3 rows, 3 columns, and 2 diagonals. Check each for 3 equal chars and return True if there is a match
victory = False
player = ""
if (currentlst[0][0] == currentlst[1][0] == currentlst[2][0]) and currentlst[0][0] != '': #First Column
victory = True
player += currentlst[0][0]
if (currentlst[0][1] == currentlst[1][1] == currentlst[2][1]) and currentlst[0][1] != '': #Second Column
victory = True
player += currentlst[0][1]
if (currentlst[0][2] == currentlst[1][2] == currentlst[2][2]) and currentlst[0][2] != '': #Third Column
victory = True
player += currentlst[0][2]
if (currentlst[0][0] == currentlst[0][1] == currentlst[0][2]) and currentlst[0][0] != '': #First Row
victory = True
player += currentlst[0][0]
if (currentlst[1][0] == currentlst[1][1] == currentlst[1][2]) and currentlst[1][0] != '': #Second Row
victory = True
player += currentlst[1][0]
if (currentlst[2][0] == currentlst[2][1] == currentlst[2][2]) and currentlst[2][0] != '': #Third Row
victory = True
player += currentlst[2][0]
if (currentlst[0][0] == currentlst[1][1] == currentlst[2][2]) and currentlst[0][0] != '': #Diagonal TL to BR
victory = True
player += currentlst[0][0]
if (currentlst[0][2] == currentlst[1][1] == currentlst[2][0]) and currentlst[0][2] != '': #Diagonal TR to BL
victory = True
player += currentlst[0][2]
if victory == True:
print("Congratulations! Player '%s' has won the game!!" %(player))
return victory
def main():
currentlst = [["","",""],["","",""],["","",""]]
victory = False
x_turn = 0 # counts number of turns to ensure players alternate
y_turn = 0
while not victory: #iterate until one player achieves the victory condition
if x_turn == 5:
currentBoard = gameBoard(currentlst) #print out current board
for s in currentBoard:
print(*s)
print("You have reached a draw! Thanks for playing.")
break
if x_turn == y_turn:
x_good = False
while not x_good:
try: #take players input, repeating if the player fails to input a valid selection
currentBoard = gameBoard(currentlst) #print out current board
for s in currentBoard:
print(*s)
x_row = int(input("Player X --> Choose a row: "))
x_col = int(input("Player X --> Choose a column: "))
if currentlst[x_row-1][x_col-1] == "": #checks that the square isn't already taken
currentlst[x_row-1][x_col-1] = "X"
x_good = True #mark that the turn is valid
victory = isWin(currentlst) #recheck the victory condition
x_turn +=1 #iterate player X's turn
else:
print()
print("That square is already taken. Try again.")
except ValueError:
print("You did not enter a positive integer between 1 and 3. Try again")
elif y_turn < x_turn:
y_good = False
while not y_good:
try:
currentBoard = gameBoard(currentlst)
for s in currentBoard:
print(*s)
y_row = int(input("Player Y --> Choose a row: "))
y_col = int(input("Player Y --> Choose a column: "))
if currentlst[y_row-1][y_col-1] == "":
currentlst[y_row-1][y_col-1] = "Y"
y_good = True
victory = isWin(currentlst)
y_turn +=1
else:
print()
print("That square is already taken. Try again.")
except ValueError:
print("You did not enter a positive integer between 1 and 3. Try again")
if __name__ == "__main__":
main() |
import copy
def compute(myinput):
i = 0
operation = myinput[i]
while i < len(myinput) and operation != 99:
val1, val2, pos = myinput[myinput[i+1]], myinput[myinput[i+2]], myinput[i+3]
if operation == 1:
myinput[pos] = val1 + val2
elif operation == 2:
myinput[pos] = val1*val2
i += 4
operation = myinput[i]
return myinput
with open('input', 'r') as f:
startinput = [int(i) for i in f.read().split(",")]
# startinput[1], startinput[2] = 12, 2 # part 1 overrides
# print(compute(myinput))
for noun in range(99):
for verb in range(99):
myinput = copy.deepcopy(startinput)
myinput[1], myinput[2] = noun, verb
candidate_result = compute(myinput)
if candidate_result[0] == 19690720:
print("noun:", noun)
print("verb:", verb)
print("Answer = 100 * noun + verb =", 100*noun+verb) |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 18:04:36 2017
@author: User
"""
class LinkedStack:
class Node:
def __init__(self):
self.item = None
self.next = None
def __init__(self):
self.first = None
def isEmpty(self):
return self.first == None
def push(self, item):
old_first = self.first
self.first = self.Node()
self.first.item = item
self.first.next = old_first
def pop(self):
item = self.first.item
self.first = self.first.next
return item
stack = LinkedStack()
stack.push('A')
stack.push('B')
print(stack.pop())
stack.push('C')
print(stack.pop())
print(stack.pop()) |
import sys
number = int(input("\nEnter the number of Primes to compute: "))
if number == 1:
print("The first prime is 2")
sys.exit(0)
m = 3
PrimeList = [2]
def isPrime(m, L):
for L in PrimeList:
if m < L**2:
PrimeList.append(m)
return m
if m%L == 0:
return m
isPrime(m, PrimeList)
while (len(PrimeList) != number):
m += 1
isPrime(m, PrimeList)
print("\nThe first "+str(number)+" primes are:")
for i in range(len(PrimeList)/10+1):
print " ".join(map(str,PrimeList[i*10:(i+1)*10]))
|
import calendar
print(calendar.weekheader(3))
print()
print(calendar.firstweekday())
print()
print(calendar.month(2021, 8))
print()
print(calendar.calendar(2021))
day_of_the_week_=calendar.weekday(2021, 9, 9)
print(day_of_the_week_)
is_leap=calendar.isleap(2021)
print(is_leap)
how_many_leap_days= calendar.leapdays(2000, 2021)
print(how_many_leap_days) |
from Deck import Deck
from Hand import Hand
import time
class Blackjack:
def __init__(self):
self.deck = Deck()
self.deck.shuffle()
self.balance = 0
self.start()
def start(self):
while True:
self.balance = input("How much would you like to deposit?: ")
try:
self.balance = int(self.balance)
break
except ValueError:
print('Invalid deposit, please enter a number')
continue
while True:
print(f'Balance: {self.balance}')
bet = input('Enter your bet amount to play again (N to quit): ')
if bet.upper() == 'N':
print(f'Exiting with ${self.balance}')
break
elif bet.isdigit():
bet = float(bet)
if bet > self.balance:
print('Insufficient funds, try again')
continue
else:
print(f'Betting ${bet}')
self.balance -= bet
self.balance += self.play_round(bet)
else:
print('Invalid bet, please enter a number')
continue
def display(self, p_hand, d_hand):
dealer_values = d_hand.hand_value()
player_values = p_hand.hand_value()
num_dealer_values = len(dealer_values)
num_player_values = len(player_values)
print(' ')
print(f'Balance: {self.balance}')
print('----------------------')
print(f'Dealer: {d_hand} (', end='')
for i, value in enumerate(dealer_values):
if num_dealer_values > i + 1:
print(f'{value} or ', end='')
else:
print(f'{value})')
print(f'Player: {p_hand} (', end='')
for i, value in enumerate(player_values):
if num_player_values > i + 1:
print(f'{value} or ', end='')
else:
print(f'{value})')
print('----------------------')
def play_round(self, bet):
p_hand = Hand(self.deck.deal_double())
d_hand = Hand(self.deck.deal_double(deal_type='dealer'))
p_final = 0
while True:
self.display(p_hand, d_hand)
if input('Hit or Stay? (H or S)').upper() == 'H':
p_hand.add_card(self.deck.deal())
status = p_hand.check_hand()
if status == 'bust':
p_final = 0
break
elif status == 'blackjack':
p_final = 21
break
else:
continue
else:
p_final = max(p_hand.hand_value())
break
time.sleep(3)
d_hand.cards[1].flip()
self.display(p_hand, d_hand)
print(f'Dealer flipped a {d_hand.cards[1]}')
while max(d_hand.hand_value()) < 17 and max(d_hand.hand_value()) < p_final:
time.sleep(3)
card = self.deck.deal()
d_hand.add_card(card)
self.display(p_hand, d_hand)
status = d_hand.check_hand()
print(f'Dealer flipped a {card}')
if status == 'bust':
d_final = 0
break
elif status == 'blackjack':
d_final = 21
break
else:
continue
else:
d_final = max(d_hand.hand_value())
self.display(p_hand, d_hand)
if p_final > d_final and p_hand.bust is False:
print('Game Over: Player wins')
self.return_hands(p_hand, d_hand)
if p_final == 21:
return bet * 2.5
else:
return bet * 2
elif d_final > p_final and d_hand.bust is False:
print('Game Over: Dealer wins')
self.return_hands(p_hand, d_hand)
return 0
else:
print('Game Over: Push')
self.return_hands(p_hand, d_hand)
return bet
def return_hands(self, p_hand, d_hand):
self.deck.to_reserve(p_hand.cards)
self.deck.to_reserve(d_hand.cards)
|
def main():
q=nr()
for i in range(0,q):
if q-i-1>0:
for j in range(0,q-i-1):
print(" ",end="")
j+=1
for j in range(j,q):
print("#",end="")
print()
else:
for j in range(q):
print('#',end='')
def nr():
while True:
a=int(input("please give a number from 1 to 8\n"))
if a>0 and a<9:
return a
main() |
import csv
import math
import numpy as np
import pandas as pd
with open('data.csv', newline = '') as f:
reader = csv.reader(f)
filedata = list(reader)
data = filedata[0]
def mean(data):
n = len(data)
total = 0
for x in data:
total += int(x)
mean = total / n
return mean
squared_list = []
for n in data:
a = int(n) - mean(data)
a = a**2
squared_list.append(a)
sum = 0
for i in squared_list:
sum += i
result = sum/(len(data)-1)
std = math.sqrt(result)
print(std) |
# Prakriti Kharel
import random
#final array that stores the mancala board with the correct values
#at the beginning, all the holes have rocks # of stones in them
rocks = 4
al = [0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks]
first = [0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks]
second = [0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks,0,rocks,rocks,rocks,rocks,rocks]
count = 0
c = 0
redMoves = [1, 2, 9, 10, 11, 13, 14, 21, 22, 23]
redMancala = [0, 12]
blueMoves = [3, 4, 5, 7, 8, 15, 16, 17, 19, 20]
blueMancala = [6, 18]
def reset(one,two):
for i in range(23):
two[i] = one[i]
def redCount():
count = 0
for i in range (10):
count+= al[redMoves[i]]
return count
def blueCount():
count = 0
for i in range (10):
count+= al[blueMoves[i]]
return count
#a function to decide who goes first
def flipaCoin():
global turn;
h1 = random.randint(0, 1)
if (h1 == 0):
print("Red Starts")
turn = 'R'
print("----------------------------------------------------------------------")
else:
print("Blue Starts")
turn = 'B'
print("----------------------------------------------------------------------")
def printfunc(final):
print (" ", "\033[96m {}\033[00m" .format(final[6]))
print(" ", "\033[96m {}\033[00m" .format(final[7]), " ", "\033[96m {}\033[00m" .format(final[5]))
print(" ", "\033[96m {}\033[00m" .format(final[8]), " ", "\033[96m {}\033[00m" .format(final[4]))
print(" ", "\033[91m {}\033[00m" .format(final[11]), " ", "\033[91m {}\033[00m" .format(final[10]), " ", "\033[91m {}\033[00m" .format(final[9]), " ", "\033[96m {}\033[00m" .format(final[3]), " ", "\033[91m {}\033[00m" .format(final[2]), " ", "\033[91m {}\033[00m" .format(final[1]), " ")
print("\033[91m {}\033" .format(final[12]), " ", "\033[91m {}\033[00m" .format(final[0]))
print(" ", "\033[91m {}\033[00m" .format(final[13]), " ", "\033[91m {}\033[00m" .format(final[14]), " ", "\033[96m {}\033[00m" .format(final[15]), " ", "\033[91m {}\033[00m" .format(final[21]), " ", "\033[91m {}\033[00m" .format(final[22]), " ", "\033[91m {}\033[00m" .format(final[23]), " ")
print(" ", "\033[96m {}\033[00m".format(final[16]), " ", "\033[96m {}\033[00m".format(final[20]))
print(" ", "\033[96m {}\033[00m".format(final[17]), " ", "\033[96m {}\033[00m".format(final[19]))
print (" ", "\033[96m {}\033[00m" .format(final[18]))
#without color
'''
print (" ", final[6])
print (" ", final[7]," ", final[5])
print (" ", final[8]," ", final[4])
print (" ", final[8]," ", final[4]," ", final[8]," ", final[8]," ",final[8]," ",final[8]," ")
print (" ",final[12]," ", final[0])
print (" ", final[13]," ", final[14]," ", final[15]," ", final[21]," ",final[22]," ",final[23]," ")
print (" ", final[16]," ", final[20])
print (" ", final[17]," ", final[19])
print (" ", final[18])
'''
#The red positions are 1 2 9 10 11 13 14 21 22 23
#given a particular index move the stones
#def blue moves
def moves(given, temp):
global turn;
#first check if its a blue moving or red moving
if given in blueMoves:
turn = 'B'
if given in redMoves:
turn = 'R'
#figuring out how many rocks are there at a given index
#decided on a clockwise direction
storing = temp[given]
temp[given] = 0
while storing != 0:
storing -= 1
#figuring out how to loop after 23, i want to go to 0
if (given == 23):
given = 0
else:
given += 1
#skip the other player's mancala
if (turn == 'B' and (given == 0 or given == 12)):
given += 1
if (temp == al):
print("skipping red's mancala")
elif (turn == 'R' and (given == 6 or given == 18)):
given += 1
if (temp == al):
print(" skipping blue's mancala")
temp[given] += 1
#need to figure out if it lands on empty on its side, which rocks to add to whose mancala
# + 6, - 6 works because then you are emptying two of opponents and adding it to your mancala
#the only problem is there are special cases: 23 + 6, 0 -6 # edge cases
if ((turn == 'R') and (given in redMoves) and (temp[given] == 1)):
if (temp == al):
print("adjacent stones added to red's mancala")
temp[0] += 1 #adding that particular one
temp[given] -= 0
#dealing with edge cases
if(given == 2):
temp[0] += temp[20]
temp[20] = 0
temp[0] += temp[given + 6]
temp[given + 6] = 0
elif (given == 1):
temp[0] += temp[19]
temp[19] = 0
temp[0] += temp[given + 6]
temp[given + 6] = 0
elif (given == 23):
temp[0] += temp[5]
temp[5] = 0
temp[0] += temp[given - 6]
temp[given - 6] = 0
elif (given == 22):
temp[0] += temp[4]
temp[4] = 0
temp[0] += temp[given - 6]
temp[given - 6] = 0
elif (given == 21):
temp[0] += temp[3]
temp[3] = 0
temp[0] += temp[given - 6]
temp[given - 6] = 0
else: #rest of the cases
temp[0] += temp[given+6]
temp[0] += temp[given-6]
temp[given - 6] = 0
temp[given + 6] = 0
#take all the stone from adjacent and add to blue's mancala
elif ((turn == 'B') and (given in blueMoves) and (temp[given] == 1)):
if (temp == al):
print("adjacent stones added to blue's mancala")
temp[6] += 1
temp[given] -= 0
#dealing with edge cases
if (given == 20):
temp[6] += temp[2]
temp[2] = 0
temp[6] += temp[given - 6]
temp[given - 6] = 0
elif (given == 19):
temp[6] += temp[1]
temp[1] = 0
temp[6] += temp[given - 6]
temp[given - 6] = 0
elif (given == 5):
temp[6] += temp[23]
temp[23] = 0
temp[6] += temp[given + 6]
temp[given + 6] = 0
elif (given == 4):
temp[6] += temp[22]
temp[22] = 0
temp[6] += temp[given + 6]
temp[given + 6] = 0
elif (given == 3):
temp[6] += temp[21]
temp[21] = 0
temp[6] += temp[given + 6]
temp[given + 6] = 0
else: #rest of the cases
temp[6] += temp[given + 6]
temp[6] += temp[given - 6]
temp[given - 6] = 0
temp[given + 6] = 0
#Notes:
def whoNext(given):
global turn
printfunc(al)
# ends in their own mancala
if (turn == 'R' and (given == 0 or given == 12)):
turn == 'R'
print("Next, its red's turn again")
elif (turn == 'B' and (given == 6 or given == 18)):
print("Next, its blue's turn again")
turn = 'B'
elif (turn == 'B'):
print("Next, it's reds turn")
turn = 'R'
else:
print("Next, it's blue's turn")
turn = 'B'
print("")
#if all of red moves is 0 or all of blue moves is 0, then the game has ended
def gameOver():
if (redCount() == 0 or blueCount() == 0):
return True
else:
return False
#should use h1 and h2
def computerVcomputer1():
flipaCoin()
temp = 0
while (not gameOver()):
temp += 1
if (turn == 'B'):
minMax1b()
else:
minMax2r()
print("the count for red is ", count)
print("the count for blue is ", c)
print("# of rounds ", temp)
mancalaCount(al)
def computerVcomputer2():
flipaCoin()
temp = 0
while (not gameOver()):
temp += 1
if (turn == 'B'):
minMax2b()
else:
minMax1r()
print("the count is ", count)
print("# of rounds ", temp)
mancalaCount(al)
#should use either h1 or h2 random
def computerVperson():
temp = 0
whoAmI= "red"
heuristic = "one"
h1 = random.randint(0, 1)
if (h1 == 0):
print("you are red")
else:
whoAmI= "blue"
print("you are blue")
h2 = random.randint(0, 1)
if (h2 == 0):
print("hint: the computer will use heuristic 1, this was decided using the rand.randint function")
heuristic = "zero"
else:
print("hint: the computer will use heuristic 2, this was decided using the rand.randint function")
heuristic = "one"
flipaCoin()
if (whoAmI == "red"):
while (not gameOver()):
# printfunc(al)
temp += 1
if (turn == 'B'):
if (heuristic == "one"):
minMax1b()
else:
minMax2b()
else:
print("What moves would you like to make, you are red, your options are the following positions: ", redMoves)
given = int(input())
moves(given, al)
whoNext(al)
else:
while (not gameOver()):
# printfunc(al)
temp +=1
if (turn == 'R'):
if (heuristic == "one"):
minMax1r()
else:
minMax2r()
else:
print("What moves would you like to make, you are blue, your options are the following positions: ", blueMoves)
given = int(input())
moves(given, al)
whoNext(al)
print("the count is ", count)
print("# of rounds ", temp)
mancalaCount(al)
#want minMax to make one move, #try to get most rocks in mancala
#right now assuming red moves first
def minMax1r():
# assume red is starting first
global count
reset(al, first)
reset(al, second)
# count = 0
redsmax = [] # array of blue's choices, red wants to pick the maximum one
bluesmax = []
redsmin = [] # mancala count for red player, when blue expands, blue is gonna choose the one where red mancala count is lowest
bluesmin = []
for i in range(10): # select the max
min = 0
count += 1
moves(redMoves[i], first)
moves(redMoves[i], second)
for i in range(10): # select the min #add if else for alpha-beta pruning
count += 1
# print("the count in the second loop is ", count)
moves(blueMoves[i], second)
# printfunc(second)
redsmin.append(redFinal(second))
#bluesmin.append(blueFinal(second))
reset(first, second)
if (redFinal(second) == 0):
break
# print("reds min is", redsmin)
# go through redsmin, and add the smallest one to redsmax
#alpha-beta pruning, its going to choose the minimum, if its 0, stop
#alpha > beta, you cut off
beta = 100
for i in range(len(redsmin)):
count+=1
if (redsmin[i] < beta):
beta = redsmin[i]
if (beta == 0):
break
redsmax.append(beta)
redsmin = []
bluesmin = []
reset(al, first)
# print("redsmax is ", redsmax)
alpha = 0
s = 0
for i in range(len(redsmax)):
if (redsmax[i] > alpha and al[redMoves[i]] != 0):
choice = redsmax[i]
s = i
print("R chose", redMoves[s], "which has", al[redMoves[s]], "stones")
moves(redMoves[s], al)
whoNext(redMoves[s])
def minMax1b():
global c
#assume red is starting first
reset(al, first)
reset(al, second)
redsmax= [] #array of blue's choices, red wants to pick the maximum one
bluesmax= []
redsmin = [] #mancala count for red player, when blue expands, blue is gonna choose the one where red mancala count is lowest
bluesmin = []
for i in range(10): #select the max
c+=1
moves(blueMoves[i], first)
moves(blueMoves[i], second)
for i in range(10): #select the min #add if else for alpha-beta pruning
c+=1
moves(redMoves[i], second)
# printfunc(second)
# redsmin.append(redFinal(second))
bluesmin.append(blueFinal(second))
reset(first, second)
if (blueFinal(second) == 0):
break
# print("reds min is ", redsmin)
# print("blues min is ", bluesmin)
#go through redsmin, and add the smallest one to redsmax
beta = 100
for i in range(len(bluesmin)):
c += 1
if (bluesmin[i] < beta):
beta= bluesmin[i]
if (beta == 0):
break
bluesmax.append(beta)
redsmin = []
bluesmin = []
reset(al, first)
alpha = 0
s = 0
for i in range (len(bluesmax)):
if (bluesmax[i] > alpha and al[blueMoves[i]] != 0 ):
alpha = bluesmax[i]
s = i
print("B chose", blueMoves[s], "which has", al[blueMoves[s]], "stones")
moves(blueMoves[s], al)
whoNext(blueMoves[s])
#make the move
#store bluecount, store red count
#reset
#get as many holes empty as possible
def minMax2r():
global count
# assume red is starting first
reset(al, first)
reset(al, second)
redsmax = [] # array of blue's choices, red wants to pick the maximum one
bluesmax = []
redsmin = [] # mancala count for red player, when blue expands, blue is gonna choose the one where red mancala count is lowest
bluesmin = []
for i in range(10): # select the max
count += 1
moves(redMoves[i], first)
moves(redMoves[i], second)
for i in range(10): # select the min #add if else for alpha-beta pruning
count += 1
moves(blueMoves[i], second)
# printfunc(second)
redsmin.append(emptyHoles(second))
reset(first, second)
# if (emptyHoles(second) == 1):
# break
# print("reds min is ", redsmin)
# go through redsmin, and add the smallest one to redsmax
#alpha-beta pruning, its going to choose the minimum, if its 0, stop
beta = 100
for i in range(len(redsmin)):
count+=1
if (redsmin[i] < beta):
beta = redsmin[i]
# if (beta == 1):
# break
redsmax.append(beta)
redsmin = []
bluesmin = []
reset(al, first)
# print("redsmax is ", redsmax)
alpha = 0
s = 0
for i in range(len(redsmax)):
if (redsmax[i] > alpha and al[redMoves[i]] != 0):
choice = redsmax[i]
s = i
print("R chose", redMoves[s], "which has", al[redMoves[s]], "stones")
moves(redMoves[s], al)
whoNext(redMoves[s])
def minMax2b():
global count
#assume red is starting first
reset(al, first)
reset(al, second)
redsmax= [] #array of blue's choices, red wants to pick the maximum one
bluesmax= []
redsmin = [] #mancala count for red player, when blue expands, blue is gonna choose the one where red mancala count is lowest
bluesmin = []
for i in range(10): #select the max
count+=1
#moves(blueMoves[i], first)
#moves(blueMoves[i], second)
for i in range(10): #select the min #add if else for alpha-beta pruning
count+=1
#moves(redMoves[i], second)
# printfunc(second)
bluesmin.append(emptyHoles(second))
reset(first, second)
if (emptyHoles(second) == 1):
break
# print("reds min is ", redsmin)
# print("blues min is ", bluesmin)
#go through redsmin, and add the smallest one to redsmax
beta = 100
for i in range(len(bluesmin)):
count+=1
if (bluesmin[i] < beta):
beta= bluesmin[i]
if (beta == 1):
break
bluesmax.append(beta)
redsmin = []
bluesmin = []
reset(al, first)
alpha = 0
s = 0
for i in range (len(bluesmax)):
if (bluesmax[i] > alpha and al[blueMoves[i]] != 0 ):
alpha = bluesmax[i]
s = i
print("B chose", blueMoves[s], "which has", al[blueMoves[s]], "stones")
moves(blueMoves[s], al)
whoNext(blueMoves[s])
def emptyHoles(final):
temp = 0
for i in range(10):
if (final[i] == 0):
temp += 1
return temp
def blueFinal(final):
temp = 0
temp +=final[6]
temp += final[18]
return temp
def redFinal(final):
temp = 0
temp += final[0]
temp += final[12]
return temp
#final count
def mancalaCount(final):
#combining 2 mancala
final[0] += final[12]
final[12] = 0
final[6] += final[18]
final[18] = 0
#if turn == b, all of blue's spots are empty, so red can add all the remaining to their mancala
if (turn == 'B'):
#go through the remining
for x in redMoves:
final[0] += final[x]
final[x] = 0
#if turn == r, then red's spots are empty, so blue can add all the reaminign thir mancala
else:
for x in blueMoves:
final[6] += final[x]
final[x] = 0
print("blues total count is", final[6], "red's total count is", final[0])
if (final[6] > final[0]):
print ("Blue won this round")
elif(final[0] > final[6]):
print("Red won this round")
else:
print("It was a tie")
#redundant for now but want to wrap it around main incase i want to add code later on
def main():
# computerVcomputer1()
#computerVcomputer2()
computerVperson()
main()
|
#########################################################
# Exercice 4 :
#Votre fenêtre graphique doit contenir un canevas de couleur de fond blanche et de taille 500x500 ainsi qu’un bouton avec le texte “Pause” placé en dessous du canevas.
#Afficher un carré rempli de rouge de côté 50 au milieu du canevas.
#Si l’utilisateur clique à l’intérieur du carré et que le côté du carré est au moins égale à 20, alors le côté du carré diminue de 10 (effacer et réafficher).
#Si l’utilisateur clique à l’extérieur du carré et que le côté du carré est au plus égal à 100, alors le côté du carré augmente de 10 (effacer et réafficher).
#Si l’utilisateur clique sur le bouton “Pause”, alors le programme est suspendu (c’est-à-dire que cliquer ne modifie plus le carré) et le nom du bouton devient “Restart”.
#Si l’utilisateur clique de nouveau sur le bouton “Restart” alors que le programme était suspendu, alors le programme reprend là où il en était, et le nom du bouton redevient “Pause”.
#########################################################
import tkinter as tk
cote = 50
pause = False
def bouton_pause():
global pause
if not pause:
bouton.config(text="Restart")
pause = True
else:
bouton.config(text="Pause")
pause = False
def est_dans_carre(x, y):
"""La fonction retourne True si le point de coordonnées (x,y) est dans le carré et False sinon"""
inf = 250-cote//2
sup = 250+cote//2
return inf <= x <= sup and inf <= y <= sup
def change_taille(event):
global cote
if not pause:
if est_dans_carre(event.x, event.y) and cote >= 20:
cote -= 10
canvas.coords(carre, 250-cote//2, 250-cote//2,250+cote//2, 250+cote//2)
elif not est_dans_carre(event.x, event.y) and cote <= 100:
cote += 10
canvas.coords(carre, 250-cote//2, 250-cote//2,250+cote//2, 250+cote//2)
racine = tk.Tk()
canvas = tk.Canvas(racine, bg="white", width=500, height=500)
canvas.grid(row=0, column=0)
bouton = tk.Button(racine, text="Pause", command=bouton_pause)
bouton.grid(row=1)
carre = canvas.create_rectangle((250-cote//2, 250-cote//2),(250+cote//2, 250+cote//2), fill="red", outline="red")
canvas.bind("<Button-1>", change_taille)
racine.mainloop() |
# Create a two integer variables a and b
a=3
b=4
# if a is greater than b print a-b else a+b
if a > b:
print (a-b)
else:
print (a+b)
# Create a list of squared numbers
squares_list = [0, 1, 4, 9, 16, 25]
# Store the length of squares_list in square_len
square_len = len(squares_list)
# if square_len is less than 5 then print "Less than 5" else "Greater than 5"
if square_len < 5:
print ("Less than 5")
else:
print ("Greater than 5")
|
price_of_trip = float(input())
puzzles = float(input())
talking_doll = float(input())
bears = float(input())
minions = float(input())
truck = float(input())
puzzle_price = 2.6
talking_doll_price = 3
bear_price = 4.1
minions_price = 8.2
truck_price = 2
first_price = puzzles*puzzle_price+talking_doll*talking_doll_price + \
bears*bear_price + minions*minions_price + truck*truck_price
count_toys = puzzles+talking_doll+bears+minions+truck
if count_toys>=50:
first_price = first_price*0.75
first_price = first_price*0.9
final_result = first_price - price_of_trip
if final_result>=0:
print('Yes! ' + str(format(final_result, '.2f')) + ' lv left.')
else: print('Not enough money! '+ str(format(final_result*-1,'.2f')) + ' lv needed.')
|
name = input()
count = 1
grade = 0.0
while count <= 12:
curr = float(input())
if curr >= 4:
grade = grade + curr
count += 1
average = grade / 12
if average >= 4:
print(f'{name} graduated. Average grade: {average:.2f}')
|
budget = float(input())
begin = budget
balloons_count = 0
ribbon_size = 0
flowers_count = 0
candles_count = 0
while True:
if budget<=0:
break
stock = input()
if stock == 'stop':
break
count_stock = float(input())
if stock == 'balloons':
balloons_count+=count_stock
budget-= count_stock*0.1
elif stock == 'flowers':
flowers_count+=count_stock
budget-= count_stock*1.5
elif stock == 'candles':
candles_count+=count_stock
budget-=count_stock*0.5
elif stock == 'ribbon':
ribbon_size+=count_stock
budget-= count_stock * 2
if budget>0:
print(f'Spend money: {begin-budget:.2f}')
print(f'Money left: {budget:.2f}')
else:
print('All money is spent!')
print(f'Purchased decoration is {balloons_count:.0f} balloons, {ribbon_size:.0f} m ribbon, {flowers_count:.0f} flowers and {candles_count:.0f} candles.') |
temperature = int(input())
time = input().lower()
if 10<=temperature<=18:
if time == "morning":
print(f'It\'s {temperature} degrees, get your Sweatshirt and Sneakers.')
elif time == 'afternoon':
print(f'It\'s {temperature} degrees, get your Shirt and Moccasins.')
elif time == 'evening':
print(f'It\'s {temperature} degrees, get your Shirt and Moccasins.')
elif 18<temperature<24:
if time == "morning":
print(f'It\'s {temperature} degrees, get your Shirt and Moccasins.')
elif time == 'afternoon':
print(f'It\'s {temperature} degrees, get your T-Shirt and Sandals.')
elif time == 'evening':
print(f'It\'s {temperature} degrees, get your Shirt and Moccasins.')
elif 25<=temperature:
if time == "morning":
print(f'It\'s {temperature} degrees, get your T-Shirt and Sandals.')
elif time == 'afternoon':
print(f'It\'s {temperature} degrees, get your Swim Suit and Barefoot.')
elif time == 'evening':
print(f'It\'s {temperature} degrees, get your Shirt and Moccasins.') |
l = float(input())
w = float(input())
h = float(input())
percent = float(input())/100
volume= l*w*h*0.001
volume = (volume-volume*percent)
print(f'{volume:.3f}')
|
num1 = float(input())
num2 = float(input())
num3 = float(input())
if num1==num2 and num2==num3:
print('yes')
else: print('no') |
value_type = input()
val1 = input()
val2 = input()
def compare_values(a, b):
if a > b:
printable(a)
else:
printable(b)
def printable(greater_value):
print(greater_value)
compare_values(val1, val2)
|
sentence, sub = input().lower(), input().lower()
occurrences = 0
index = 0
while index!=-1:
index = sentence.find(sub, index)
if index is not -1:
occurrences+=1
index+=1
print(occurrences)
|
money_for_vacation = float(input())
curr_money = float(input())
days = 0
all_days = 0
while True:
action = input()
transfer_money = float(input())
all_days += 1
if action == 'spend':
days += 1
if days == 5:
print(f'You can\'t save the money.')
print(days)
break
elif curr_money >= transfer_money:
curr_money -= transfer_money
elif curr_money < transfer_money:
curr_money = 0
elif action == 'save':
curr_money += transfer_money
if curr_money >= money_for_vacation:
print(f'You saved the money for {all_days} days.')
break
|
import math
hour_exam = int(input())
minute_exam = int(input())
hour_arrive = int(input())
minute_arrive = int(input())
all_minute_exam = hour_exam * 60 + minute_exam
all_minute_arrive = hour_arrive * 60 + minute_arrive
if all_minute_arrive <= all_minute_exam:
if all_minute_exam - all_minute_arrive <= 30:
diff = all_minute_exam - all_minute_arrive
print("On time")
if diff != 0:
print(f'{diff} minutes before the start')
else:
diff = all_minute_exam - all_minute_arrive
diff_hour = math.floor(diff / 60)
diff_min = math.floor(diff % 60)
if diff_hour == 0:
print("Early")
print(f'{diff} minutes before the start')
elif 0 <= diff_min < 10:
print("Early")
print(f'{diff_hour}:0{diff_min} hours before the start')
else:
print("Early")
print(f'{diff_hour}:{diff_min} hours before the start')
else:
diff = all_minute_arrive - all_minute_exam
diff_hour = math.floor(diff / 60)
diff_min = math.floor(diff % 60)
if diff_hour == 0:
print("Late")
print(f'{diff} minutes after the start')
else:
if 0<=diff_min<10:
print("Late")
print(f'{diff_hour}:0{diff_min} hours after the start')
else:
print("Late")
print(f'{diff_hour}:{diff_min} hours after the start')
|
name = input()
age = int(input())
town = input()
salary = float(input())
print(f'Name: {name}')
print(f'Age: {age}')
print(f'Town: {town}')
print(f'Salary: ${salary:.2f}')
if age<18:
print(f'Age range: teen')
elif age<70:
print(f'Age range: adult')
else:
print(f'Age range: elder')
if salary<500:
print(f'Salary range: low')
elif salary<2000:
print(f'Salary range: medium')
else:
print(f'Salary range: high')
|
import math
all_Steps = float(input())
dancers = float(input())
days_For_Learning = float(input())
steps_per_day = math.ceil(((all_Steps/days_For_Learning)/all_Steps)*100)
steps_per_dancer = steps_per_day/dancers
if steps_per_day<=13:
print(f'Yes, they will succeed in that goal! {steps_per_dancer:.2f}%.')
else:
print(f'No, They will not succeed in that goal! Required {steps_per_dancer:.2f}% steps to be learned per day.') |
number = int(input())
bonus = 0
if number<=100:
bonus = 5
elif number >100 and number<=1000:
bonus=number*0.2
else: bonus = number*0.1
if number%2 == 0:
bonus = bonus+1
elif number%10 == 5:
bonus=bonus+2
print(bonus)
print(number+bonus) |
town = input().lower()
sell_count = float(input())
if 0<=sell_count<=500:
if town == "sofia":
comission = sell_count*0.05
print(f'{comission:.2f}')
elif town=="varna":
comission = sell_count * 0.045
print(f'{comission:.2f}')
elif town == "plovdiv":
comission = sell_count * 0.055
print(f'{comission:.2f}')
else:
print('error')
elif 500<sell_count<=1000:
if town == "sofia":
comission = sell_count*0.07
print(f'{comission:.2f}')
elif town=="varna":
comission = sell_count * 0.075
print(f'{comission:.2f}')
elif town == "plovdiv":
comission = sell_count * 0.08
print(f'{comission:.2f}')
else:
print('error')
elif 1000<sell_count<=10000:
if town == "sofia":
comission = sell_count*0.08
print(f'{comission:.2f}')
elif town=="varna":
comission = sell_count * 0.10
print(f'{comission:.2f}')
elif town == "plovdiv":
comission = sell_count * 0.12
print(f'{comission:.2f}')
else:
print('error')
elif 10000 < sell_count:
if town == "sofia":
comission = sell_count*0.12
print(f'{comission:.2f}')
elif town=="varna":
comission = sell_count * 0.13
print(f'{comission:.2f}')
elif town == "plovdiv":
comission = sell_count * 0.145
print(f'{comission:.2f}')
else:
print('error')
else:
print('error') |
def is_inside(first_rectangle, second_rectangle):
if first_rectangle.top <= second_rectangle.top and first_rectangle.bottom >= second_rectangle.bottom and \
first_rectangle.left >= second_rectangle.left and \
first_rectangle.right <= second_rectangle.right:
print("Inside")
else:
print('Not inside')
class Rectangle:
def __init__(self, left, bottom, width, height):
self.left = left
self.bottom = bottom
self.width = width
self.height = height
self.right = left + width
self.top = bottom + height
rectengles_list = []
for i in range(0, 2):
read_input = list(map(int, input().split()))
rectengles_list.append(Rectangle(read_input[0], read_input[1], read_input[2], read_input[3]))
check_is_inside = is_inside(rectengles_list[0], rectengles_list[1])
|
passengers_start = int(input())
stops = int(input())
curr_stop = 0
while True:
if stops == curr_stop:
break
curr_stop += 1
passengers_off = int(input())
passengers_in = int(input())
if curr_stop % 2 != 0:
passengers_start = passengers_start - passengers_off + passengers_in + 2
else:
passengers_start = passengers_start - passengers_off + passengers_in - 2
print(f'The final number of passengers is : {passengers_start}')
|
from _ctypes import Array
num = float(input())
a = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
if num == 1:
print(a[int(num) - 1])
elif num == 2:
print(a[int(num) - 1])
elif num == 3:
print(a[int(num) - 1])
elif num == 4:
print(a[int(num) - 1])
elif num == 5:
print(a[int(num) - 1])
elif num == 6:
print(a[int(num) - 1])
elif num == 7:
print(a[int(num) - 1])
else:
print('Error')
|
num_list = list(map(float, input().split()))
dict = {}
for x in num_list:
if x in dict:
dict[x] += 1
else:
dict[x] = 1
# sorted(dict)
for key in sorted(dict):
print('%s -> %s times' % (key, dict[key]))
|
class Str_List_Converter:
def __init__(self):pass
def get_remove_list(self,remove_word,string):
words = string.split()
try:
words.remove(remove_word)
except ValueError as e:
print(e)
return words
def get_all_words_starting_from(self,starting_word,string):
words = string.split()
word_index =words.index(starting_word)
words = [word for index,word in enumerate(words) if index > word_index]
return words
def list_to_string(self,word_list,concate_with=' '):
string =' '.join([word + concate_with for word in word_list ])
return string.strip(concate_with)
if __name__ == "__main__":
converter = Str_List_Converter()
data=converter.get_remove_list("my","this is my name",)
print(data)
data=converter.get_all_words_starting_from("define","Would you please define Sky ?")
print(data)
print(converter.list_to_string(data))
|
def isPrime(n):
if n<=1:
return False
elif n ==2 :
return True
else:
for i in range(2,int(n**.5)+2):
if(n%i==0):
return False
return True
# print(isPrime(4))
for i in range(100):
print(str(i)+" -> "+str(isPrime(i)))
|
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution(object):
def levelOrder(self, root):
if not root: return []
import collections
queue = collections.deque()
res = []
queue.append(root)
while queue:
size = len(queue)
tmp = []
while size:
front = queue.popleft()
for c in front.children:
queue.append(c)
tmp.append(front.val)
size -= 1
res.append(tmp)
return res
def isSymmetric(self, root):
return self.helper(root, root)
def helper(self, r1, r2):
# the order of two condition below cannot be reversed
if not r1 and not r2: return True
if not r1 or not r2: return False
return r1.val == r2.val and self.helper(r1.right, r2.left) and self.helper(r1.left, r2.right)
def isSymmetric_iter(self, root):
import collections
# intuition: mirror of itself, we can actually compare two tree at the same time
queue = collections.deque([root, root])
while queue:
n1 = queue.popleft()
n2 = queue.popleft()
if not n1 and not n2: continue
if not n1 or not n2: return False
if n1.val != n2.val: return False
queue.append(n1.right)
queue.append(n2.left)
queue.append(n1.left)
queue.append(n2.right)
return True
# dfs
def maxDepth(self, root):
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
# find number of level will be the depth of the tree
def maxDepth_bfs(self, root):
if not root: return 0
import collections
queue = collections.deque()
queue.append(root)
level = 0
while queue:
size = len(queue)
while size:
front = queue.popleft()
if front.left:
queue.append(front.left)
if front.right:
queue.append(front.right)
size -= 1
level += 1
return level
# very slow coz repeatedly calculate the height of nodes from bottom up
def isBalanced(self, root):
if not root: return True
return self.isBalanced(root.left) and self.isBalanced(root.right) and abs(self.height(root.left) - self.height(root.right)) <= 1
def height(self, root):
if not root: return 0
return max(self.height(root.left), self.height(root.right)) + 1
# faster version: calculate the height and at the same time check if subtree is
# follow the balanced tree definition by using a signal -1 to indicate that.
def isBalanced(self, root):
def check(root):
if not root:
return 0
left = check(root.left)
right = check(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left, right) + 1
return check(root) != -1
def minDepth(self, root):
if not root:
return 0
left = self.minDepth(root.left)
right = self.minDepth(root.right)
if left == 0:
return right + 1
if right == 0:
return left + 1
return min(left, right) + 1
def deepestLeavesSum(self, root):
if not root: return 0
queue = collections.deque([root])
res = None
while queue:
size = len(queue)
res = 0
while size:
front = queue.popleft()
res += front.val
if front.left:
queue.append(front.left)
if front.right:
queue.append(front.right)
size -= 1
return res
# using set
def isUnivalTree(self, root):
def helper(root, path):
if not root: return
path.add(root.val)
helper(root.left, path)
helper(root.right, path)
path = set()
helper(root, path)
return len(path) == 1
# O(1) space
def isUnivalTree_(self, root):
if not root:
return True
if root.left:
if root.val != root.left.val:
return False
if root.right:
if root.val != root.right.val:
return False
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
|
# 301
# TLE
class Solution:
def removeInvalidParentheses(self, s):
if not s:
return ['']
l, r = self.invalid_count(s)
res = []
self.dfs(s, l, r, res)
return res
# """ smart way to count unbalanced open and closing paren """
def invalid_count(self, s):
l, r = 0, 0
for c in s:
l += (c == '(')
""" when opening paren is 0 and current paren is closing, then the unbalanced closing should increment by 1
if opening unbalanced paren is not 0, and current paren is closing paren, then meaning they are matched, so decrese openning
unbalanced paren count by 1
"""
if l == 0:
r += (c == ')')
else:
l -= (c == ')')
return [l, r]
""" simple way to check if paren are matched for not, we do not need to use stack to do it when there is only one type of paren """
def is_valid(self, s):
count = 0
for c in s:
if c == '(':
count += 1
elif c == ')':
count -= 1
# whenever count is less than 0 during the loop, meaning there is unbalanced closing paren
if count < 0:
return False
return count == 0
def dfs(self, s, l, r, res):
if l == 0 and r == 0:
if self.is_valid(s) and s not in res:
res.append(s)
return
for i in range(len(s)):
if i > 0 and s[i] == s[i-1]:
continue
if s[i] in '()':
if r > 0:
self.dfs(s[:i]+s[i+1:], l, r-1, res)
elif l > 0:
self.dfs(s[:i]+s[i+1:], l-1, r, res)
obj = Solution()
res = obj.removeInvalidParentheses(")()(e()))))))((((")
print(res)
""" AC dfs """
""" bfs solution """
# 212
# TLE
class Solution:
def findWords(self, board, words):
res = []
for w in words:
if self.exists(board, w):
res.append(w)
return res
def exists(self, b, w):
if not b:
return False
n, m = len(b), len(b[0])
for i in range(n):
for j in range(m):
if self.find_path(i, j, b, w, 0):
return True
return False
def find_path(self, i, j, b, w, k):
if i < 0 or i >= len(b) or j < 0 or j >= len(b[0]) or b[i][j] != w[k]:
return False
if k == (len(w)-1):
return True
tmp = b[i][j]
b[i][j] = '#'
found = (self.find_path(i+1, j, b, w, k+1) or
self.find_path(i-1, j, b, w, k + 1) or
self.find_path(i, j+1, b, w, k+1) or
self.find_path(i, j-1, b, w, k+1))
""" for this problem, we need to reuse the same board, so for the true case, we also need to recover the # back to original value """
b[i][j] = tmp
return found
""" implement trie solution """
# 37
class Solution:
def solveSudoku(self, board):
self.fill(board)
def fill(self, board):
for i in range(9):
for j in range(9):
if board[i][j] == '.':
for k in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
# if k is valid for current cell, then fill the rest, if it works return true else, put '.' back and try other digits
if self.is_valid(board, i, j, k):
board[i][j] = k
if self.fill(board):
return True
else:
board[i][j] = '.'
return False
return True
def is_valid(self, board, i, j, k):
for x in range(9):
""" there are some . in the cells also.
the condition not false including cur cell is . or cur cell not equal to k
so the opposite is board[i][x] != '.' and board[i][x] == k
"""
#check col
if board[i][x] != '.' and board[i][x] == k:
return False
#check row
if board[x][j] != '.' and board[x][j] == k:
return False
#check box
""" think about the subbox as flat-out array
3 * (i // 3) to get the starting row, 3 * (j // 3) to get starting colomn
x//3 to increment the row, when x <= 3 row will not increment,
x%3 to find the colmn
"""
if board[3 * (i // 3) + x // 3][3 * (j // 3) + x % 3] != '.' and board[3 * (i // 3) + x // 3][3 * (j // 3) + x % 3] == k:
return False
return True
# clean version
class Solution(object):
def solveSudoku(self, board):
self.fill(board)
def fill(self, board):
for i in range(9):
for j in range(9):
if board[i][j] == '.':
for d in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
if self.check(i, j, board, d):
board[i][j] = d
if self.fill(board):
return True
board[i][j] = '.'
return False
return True
def check(self, i, j, board, d):
for x in range(9):
if board[x][j] == d:
return False
if board[i][x] == d:
return False
if board[3 * (i // 3) + x // 3][3 * (j // 3) + x % 3] == d:
return False
return True
""" bitmask solution optimized """
# https: // leetcode.com/problems/sudoku-solver/discuss/15796/Singapore-prime-minister-Lee-Hsien-Loong's-Sudoku-Solver-code-runs-in-1ms
# 51
class Solution(object):
def solveNQueens(self, n):
res = []
queen_cols = [-1]*n # marks the col i-th queen is placed
self.dfs(n, 0, queen_cols, [], res)
return res
# idx means row and also means idx-th queen
# using call stack frames to represent rows
def dfs(self, n, idx, cols, path, res):
# goal is placing n queens in n x n board
if idx == n:
res.append(path)
return
# choices are n columns, each queen will take a column
for i in range(n):
# means put idx-th queen at column i
cols[idx] = i
if self.is_valid(cols, idx):
tmp = '.' * n
self.dfs(n, idx+1, cols, path + [tmp[:i] + 'Q' + tmp[i+1:]], res)
# check vertical and diagonal
def is_valid(self, cols, r):
for i in range(r):
'''
cols[i] == cols[r] means r-th queen col is the same as i-th queen col
abs(cols[i] - cols[r]) == r - i means r-th queen and i-th queen col and row distance are the same, thus they are on the same diagnals.
'''
if cols[i] == cols[r] or abs(cols[i] - cols[r]) == r - i:
return False
return True
|
# memo
def longest_increasing_subsequence(nums):
def dfs(nums, start, cur, dic):
if start == len(nums):
return 0
if nums[start] in dic and dic[nums[start]] > 0:
return dic[nums[start]]
mx = float('-inf')
for i in range(start, len(nums)):
if nums[i] > cur:
mx = max(mx, dfs(nums, i+1, nums[i], dic) + 1)
dic[start] = mx
return mx
return dfs(nums, 0, float('-inf'), {})
nums = [10,9,2,5,3,7,101,18]
# print(longest_increasing_subsequence(nums))
print('dp-----------')
# prefix i solution below, alternative solution is LIS ended with [i] not implemented here
def longest_increasing_subsequence_dp(nums):
dp = [1]*(len(nums)+1)
dp[0] = 0
for i in range(2, len(nums)+1):
tmp = 0
for k in range(1, i):
if nums[i-1] > nums[k-1]:
tmp = max(tmp, dp[k])
dp[i] = tmp + 1
return dp[-1]
print(longest_increasing_subsequence_dp(nums))
|
"""
three templates
"""
# 1
# [l, r]
def binary_search_i(nums, target):
if not nums: return -1
left, right = 0, len(nums)-1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# 2
# [l,r]
# ending condition left + 1 == right
# two elements left and we just need to check both of them.
def binary_search_iii(nums, target):
if not nums:
return -1
left, right = 0, len(nums)-1
while left + 1 < right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid
else:
right = mid
if nums[left] == target:
return left
if nums[right] == target:
return right
return -1
# 3
# [l, r)
def binary_search_ii(nums, target):
if not nums: return -1
left, right = 0, len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
else:
right = mid
if nums[left] == target: return left
return -1
"""
sorted array contains duplicates
1. find the first number that is >= target
2. find the first number that is > target
"""
# lower bound
def binary_search_lower_bound(nums, target):
if not nums: return -1
left, right = 0, len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
else:
right = mid
if nums[left] == target:
return left
return -1
# higher bound
def binary_search_higher_bound(nums, target):
if not nums: return -1
left, right = 0, len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] <= target:
left = mid + 1
else:
right = mid
if nums[left-1] == target:
return left-1
return -1
nums = [1, 2, 3, 3, 3, 4, 5, 6, 7]
target = 3
# print(binary_search_iii(nums, target)) # 5
print(binary_search_lower_bound(nums, target)) # 2
print(binary_search_higher_bound(nums, target)) # 4
|
#Exercise 2 - Part 3
#Tapio Koskinen
asking = True
while asking:
try:
number_of_exercises = int(input("How many exercises did you do: "))
break
except ValueError:
continue
grade_book = {9:1,10:2,11:3,12:4,13:5}
if number_of_exercises < 9:
print("You did not pass the course")
elif number_of_exercises > 13:
print("Your grade is 5")
else:
print("Your grade is:",grade_book[number_of_exercises])
|
RED = "\033[31m"
BLUE = "\033[34m"
DEFAULT = "\033[0m"
class Board:
def __init__(self,rows,cols):
self.col_num = cols
self.row_num = rows
self.board = [[0]*cols for row in range(rows)]
def __getitem__(self,A):
if isinstance(A,tuple):
return self.board[A[0]][A[1]]
else:
return self.board[A]
def __setitem__(self,A,c):
if isinstance(A,tuple):
self.board[A[0]][A[1]] = c
else:
self.board[A] = c
def __str__(self):
pieces = [".",RED+"o"+DEFAULT,BLUE+"x"+DEFAULT]
output = []
for r,row in enumerate(self.board):
line = ""
for piece in row:
line += pieces[piece]
if r==0: line += " Player 1 is "+pieces[1]+"."
if r==1: line += " Player 2 is "+pieces[2]+"."
output.append(line)
line = ""
for i in range(len(row)):
line += str(i)
output.append(line)
return "\n".join(output)
def rows(self):
return [[self.board[row][col] for col in range(self.col_num)] for row in range(self.row_num)]
def row(self,row_n):
return self.rows()[row_n]
def cols(self):
return [[self.board[row][col] for row in range(self.row_num)] for col in range(self.col_num)]
def col(self,col_n):
return self.cols()[col_n]
def forward_diags(self):
return (
[[self.board[i][col-i] for i in range(min(col+1,self.row_num))] for col in range(self.col_num)]
+ [[self.board[i][row-1-i] for i in range(row,self.row_num)] for row in range(1,self.row_num)]
)
def forward_diag(self,d_n):
return self.forward_diags()[d_n]
def backward_diags(self):
return (
[[self.board[row+i][i] for i in range(self.row_num-row)] for row in range(self.row_num-1,0,-1)]
+ [[self.board[i][col+i] for i in range(min(self.col_num-col,self.row_num))] for col in range(self.col_num)]
)
def backward_diag(self,d_n):
return self.backward_diags()[d_n]
def copy(self):
return_me = Board(self.row_num,self.col_num)
return_me.board = self.rows()
return return_me
|
#I have the numbers saved in a .txt file.
#I will read them in as strings, take the first 13 digits,
#turn those into ints, and sum them.
#Finally, I will read the first 10 digits of the result
#by turning to a string to shorten
nums = []
with open('p013_numbers.txt') as f:
for line in f:
nums.append([v for v in line.split()])
for i in range(len(nums)):
nums[i] = int(nums[i][0][:13])
print(int(str(sum(nums))[:10]))
|
import math
PropDivSum = 0
#This method compiles a list of proper divisors, sums them, then returns the sum
def PropDiv (n):
divisors = [1] #by starting with 1, the list doesn't add n to it
for i in range(2,math.floor(math.sqrt(n))+1): #check divison of numbers 2 thru sqrt(n)
if n%i == 0:
divisors.append(i)
if i != n/i:
divisors.append(n//i)
return sum(divisors) #using built in sum feature to add all values in list
#The main program calculates all the amicable numbers below 10,000.
#This doesn't count numbers that have divisors summing to themselves (ie. 28)
for j in range(1,10000):
holder=PropDiv(j)
if holder != 1: #no reason to check prime numbers
if (holder!=j) & (j == PropDiv(holder)):
PropDivSum += j
print(PropDivSum)
|
#I am going to build an array of increasing factorials
#Memoization is faster here than re-calculating each multiple up to 100
factorials = [1]
summation = 0
for i in range(2,100):
factorials.append(i*factorials[i-2])
for digits in str(factorials[len(factorials)-1]):
summation += int(digits)
print(summation)
|
import numpy as np
from numpy import random
import matplotlib.pyplot as plt
from math import sqrt
#####################################################
# 1. compute distance between every two cities
# random example
n = 20 # number of city
city = random.randint(0, 1000, (n, 2)) # x,y, random generate n cities
# trivial example
n = 9
city = np.array([
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[1, 0],
[1, 1],
[1, 2],
[1, 3],
[0.5, 0]
])
# example
n = 51
a = np.loadtxt('./eil51.txt')
city = a[:, 1:]
D = np.zeros((n, n))
def compute_dis():
for i in range(0, n):
for j in range(0, n):
if i != j:
temp = (city[i, :] - city[j, :])
D[i][j] = round(sqrt(np.square(temp).sum()))
else:
D[i][j] = 1e-4
compute_dis()
#####################################################
# 2. Initialize all parameters
m = 51 # number of ants
alpha = 1 # Pheromone importance factor
beta = 5 # Heuristic Function Importance Factor
vol = 0.2 # volatilization Factor
Q = 100 # Pheromone constant
Heu_F = 1/D # Heuristic function
Tau = np.ones((n, n))*0.01 # Pheromone matrix
# Path record every ants in one iteration
Table = np.zeros((m, n), dtype=np.int32) # path of all ants in one iteration
Length = np.zeros((m, 1))
iteration = 0
iter_max = 2500 # iter_max
# best route until this iteration
Route_best = np.zeros((iter_max, n), dtype=np.int32)
# length of best route until this iteration
Length_best = np.zeros((iter_max, 1))
Length_ave = np.zeros((iter_max, 1)) # average length of every iteration
Limit_iter = 0 # number of iteration when get the best solution
#####################################################
# 3. iter for best path until get to the iter_max
# 3.1 place ants randomly
# 3.2 For every ants, construct a path
# 3.3 compute the length of every path for every ant
# 3.4 get shortest path(length and path) until this iteration
# and average length of this interation
# 3.5 update pheromone
# iter for best path
while iteration < iter_max:
print('%f%% iteartion:%d Length_best:%f' % (iteration*100/iter_max, iteration, Length_best[iteration-1]))
start = random.randint(0, n, size=(m,))
Table[:, 0] = start
# for each ant
for i in range(0, m):
# for each city
for j in range(1, n):
# find the cities that never visited
visited_city = Table[i, 0:j]
all_city = np.arange(n, dtype=np.int32)
allow_city = np.array(
list(set(all_city).difference(set(visited_city))),
dtype=np.int32)
P = np.zeros(allow_city.shape)
# Computate transfer probability, and next city
for k in range(len(allow_city)):
P[k] = pow(Tau[visited_city[-1], allow_city[k]], alpha) * \
pow(Heu_F[visited_city[-1], allow_city[k]], beta)
P = np.array(P/sum(P))
for k in range(1, len(allow_city)):
P[k] += P[k - 1]
P[len(allow_city)-1] = 1.0
Pc = random.rand()
target_index = np.where(P > Pc)
target = allow_city[target_index[0][0]]
Table[i][j] = target
# compute path length of every ants
Length = np.zeros((m, 1))
for i in range(m):
Route = Table[i, :]
for j in range(n-1):
Length[i] = Length[i] + D[Route[j], Route[j + 1]]
Length[i] = Length[i] + D[Route[n-1], Route[0]]
# compute shortest path length until this iteration
# and average length of this iteration
if iteration == 0:
min_Length = np.min(Length)
min_index = np.where(Length == min_Length)
# from tuple to single value int
min_index = min_index[0][0]
Length_best[iteration] = min_Length
Length_ave[iteration] = np.mean(Length)
Route_best[iteration, :] = Table[min_index, :]
Limit_iter = 1
else:
min_Length = np.min(Length)
min_index = np.where(Length == min_Length)
# from tuple to single value int
min_index = min_index[0][0]
Length_best[iteration] = min(min_Length, Length_best[iteration-1])
Length_ave[iteration] = np.mean(Length)
if Length_best[iteration] == min_Length:
Route_best[iteration, :] = Table[min_index, :]
if Length_best[iteration] != Length_best[iteration-1]:
Limit_iter = iteration
else:
Route_best[iteration, :] = Route_best[iteration-1, :]
# update pheromone
Delta_Tau = np.zeros((n, n))
for i in range(m):
for j in range(n-1):
Delta_Tau[Table[i][j], Table[i][j+1]] += Q/Length[i]
Delta_Tau[Table[i][n-1], Table[i][0]] += Q/Length[i]
Tau = (1-vol)*Tau + Delta_Tau
# iteration + 1. clear Table
iteration += 1
Table = np.zeros((m, n), dtype=np.int32)
#####################################################
# 4. display the path
print('Route_best:',Route_best[iter_max-1])
print('ants number:%d iter_max:%d Limit_iter:%d best_length:%f \n' % (m, iter_max, Limit_iter, Length_best[iter_max - 1]))
x = []
y = []
for i in range(n):
x.append(city[Route_best[iter_max-1, i]][0])
y.append(city[Route_best[iter_max-1, i]][1])
x.append(city[Route_best[iter_max-1, 0]][0])
y.append(city[Route_best[iter_max-1, 0]][1])
plt.plot(x, y, color='b', linewidth=2, alpha=0.5)
plt.scatter(x, y, color='r', s=25)
plt.title('Route_Best')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.show()
|
# Import modules for creating file paths across operating systems and reading CSV files
import os
import csv
# Map the path where the input csv file is located
csvpath = os.path.join("Resources","budget_data.csv");
# Open the csv file
with open(csvpath) as csvfile:
# Specify the delimiter for the budget_data.csv file
csvreader = csv.reader(csvfile, delimiter = ',')
# Read the header of the budget_data.csv file
csv_header = next(csvreader)
# Define the variables needed for the Financial Analysis summary and set them all as zero so we add to them as the loop parses through the budget_data.csv file
total_months = 0
current_revenue = 0
prior_revenue = 0
total_revenue = 0
change_in_revenue = 0
total_change_in_revenue = 0
highest_change_in_revenue = 0
lowest_change_in_revenue = 0
# Initiate the loop to analyse each record contained in the budget_data.csv file
for data in csvreader:
# As the loop goes through the current revenues and add each occurence to the total revenue
current_revenue = int(data[1])
total_revenue = total_revenue + current_revenue
change_in_revenue = current_revenue - prior_revenue
# Calculate the change in revenue from the second month onwards by setting the below condition
if total_months != 0:
total_change_in_revenue = total_change_in_revenue + change_in_revenue
# Calculate if the change in revenue in a particular row is greater than the value recorded against this variable so far
if highest_change_in_revenue < change_in_revenue:
# If the latest change in revenue is greater than the value recorded against this variable so far, record this value as the newest highest change in revenue
highest_change_in_revenue = change_in_revenue
# Look for the corresponding month and year with the highest revenue
highest_change_in_revenue_month_and_year = data[0]
# If the latest change in revenue is lesser than the value recorded against this variable so far, record this value as the newest lowest change in revenue
if lowest_change_in_revenue > change_in_revenue:
# Calculate if the change in revenue in a particular row is lesser than the value recorded against this variable so far
lowest_change_in_revenue = change_in_revenue
# Look for the corresponding month and year with the lowest revenue
lowest_change_in_revenue_month_and_year = data[0]
# Capture the current month's revenue as the previous month's revenue for future loop iterations
prior_revenue = current_revenue
# Count each row of revenue data towards total months
total_months +=1
# Divide the overall change in revenue by the total months
# To arrive at the average for the net count of months that have recorded a change in revenue, I have deducted 1 on account of the first month
average_change = str(round(total_change_in_revenue/(total_months-1),2))
# Publish the Financial Analysis summary to the terminal as requested
print (f"----------------------------------------------------")
print (f"Financial Analysis")
print (f"----------------------------------------------------")
print (f"Total Months:", total_months)
print (f"Total: $", total_revenue)
print (f"Average Change: $", average_change)
print (f"Greatest Increase in Profits:",highest_change_in_revenue_month_and_year,"($",highest_change_in_revenue,")")
print (f"Greatest Decrease in Profits:",lowest_change_in_revenue_month_and_year,"($",lowest_change_in_revenue,")")
print (f"----------------------------------------------------")
# Create a text file to publish the Financial Analysis summary as requested
output = "Financial_Analysis.txt"
# Open the text file using "write" mode to publish the Financial Analysis summary results as requested
with open(output, 'w') as textfile:
textfile.write (f"----------------------------------------------------")
textfile.write (f"\nFinancial Analysis")
textfile.write (f"\n----------------------------------------------------")
textfile.write (f"\nTotal Months: " + str(total_months))
textfile.write (f"\nTotal: ${total_revenue}")
textfile.write (f"\nAverage Change:${average_change}")
textfile.write (f"\nGreatest Increase in Profits: {highest_change_in_revenue_month_and_year} (${highest_change_in_revenue})")
textfile.write (f"\nGreatest Decrease in Profits: {lowest_change_in_revenue_month_and_year} (${lowest_change_in_revenue})")
textfile.write (f"\n----------------------------------------------------") |
from collections import Counter
import csv
import datetime
months = {
"January": 1,
"February": 2,
"March": 3,
"April": 4,
"May": 5,
"June": 6,
"July": 7,
"August": 8,
"September": 9,
"October": 10,
"November": 11,
"December": 12
}
tau = 30
fileName = 'H2'
booking_tuples = []
with open('./CSV/' + fileName + '.csv') as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
first_line = True
for row in csv_reader:
if first_line:
first_line = False
else:
daysPastInt = int(row['LeadTime'])
if(daysPastInt < tau):
daysPast = datetime.timedelta(daysPastInt)
bookingDate = datetime.date(int(row['ArrivalDateYear']), int(months[row['ArrivalDateMonth']]), int(row['ArrivalDateDayOfMonth']))
bookDate = bookingDate - daysPast
booking_tuples.append((bookDate, daysPastInt))
booking_tuples = sorted(booking_tuples)
booking_counted = Counter(booking_tuples)
booking_by_day_raw = {}
for key in booking_counted.keys():
if key[0] not in booking_by_day_raw:
booking_by_day_raw[key[0]] = [0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0] #tau days of 0s
booking_by_day_raw[key[0]][key[1]] = booking_counted[key]
oneDay = datetime.timedelta(1)
firstDate = True
currentDate = None
booking_by_day = {}
for key in booking_by_day_raw:
if firstDate:
currentDate = key
months = []
dow = []
bookingDate = key
for i in range(tau):
months.append(bookingDate.month)
dow.append(bookingDate.weekday())
bookingDate = bookingDate + oneDay
booking_by_day[key] = (booking_by_day_raw[key], months, dow)
firstDate = False
else:
while key != currentDate:
months = []
dow = []
bookingDate = currentDate
for i in range(tau):
months.append(bookingDate.month)
dow.append(bookingDate.weekday())
bookingDate = bookingDate + oneDay
booking_by_day[currentDate] = ([0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0],
months, dow)
currentDate = currentDate + oneDay
months = []
dow = []
bookingDate = key
for i in range(tau):
months.append(bookingDate.month)
dow.append(bookingDate.weekday())
bookingDate = bookingDate + oneDay
booking_by_day[key] = (booking_by_day_raw[key], months, dow)
currentDate = currentDate + oneDay
with open('./Output/' + fileName + 'Train.csv', mode='w') as train_file:
with open('./Output/' + fileName + 'Test.csv', mode='w') as test_file:
fieldnames = ['BookDateYear', 'BookDateMonth', 'BookDateDayOfMonth', 'Bookings', 'Month', 'DOW']
trainWriter = csv.DictWriter(train_file, fieldnames=fieldnames)
trainWriter.writeheader()
testWriter = csv.DictWriter(test_file, fieldnames=fieldnames)
testWriter.writeheader()
entryCount = 0
trainCount = int(len(booking_by_day.keys()) * 0.7)
for key in booking_by_day.keys():
if entryCount < trainCount:
trainWriter.writerow({'BookDateYear': key.year, 'BookDateMonth': key.month, 'BookDateDayOfMonth': key.day, 'Bookings': booking_by_day[key][0], 'Month': booking_by_day[key][1], 'DOW': booking_by_day[key][2]})
else:
testWriter.writerow({'BookDateYear': key.year, 'BookDateMonth': key.month, 'BookDateDayOfMonth': key.day, 'Bookings': booking_by_day[key][0], 'Month': booking_by_day[key][1], 'DOW': booking_by_day[key][2]})
entryCount += 1
print("Done") |
# -*- coding: utf-8 -*-
import re
import string
def remove_punctuation(text):
return re.sub(ur"\p{P}+", "", text)
def remove_punctuation(to_translate, translate_to=u''):
not_letters_or_digits = u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~'
translate_table = dict((ord(char), translate_to) for char in not_letters_or_digits)
return to_translate.translate(translate_table)
s = u'аьаьавыдалоываБЮЁ№!"№!"№"!ЮБ,бю.,'
print remove_punctuation(s) |
# ------------------------->Tuples<------------------------------
veg = ("onion", "potato", "tomato", "pepper", "carrot")
Fruits = ("orange", "banana", "apples", "grapes")
print(veg)
print(type(veg))
print(len(veg))
print(veg[1])
print(veg[-2])
print(veg[2:4])
b = list(veg)
b[2:4] = "pea", "cabbage"
veg = tuple(b)
print(veg)
b.append("tomato")
veg = tuple(b)
print(veg)
b.remove("cabbage")
veg = tuple(b)
print(veg)
# del veg -> print(veg) tuple is deletd due to this it cause an error.
# unpacking of tuple
print("onion")
print("potato")
print("tomato")
print("pepper")
print("carrot")
# joining and multiplying of tuples
print(veg + Fruits)
print(veg*3)
# ------------------------->Sets<------------------------------
# sets are unchangeable, Unindexed and unordered
nida_friends = {"Aadila", "Mahnoor", "Tasneem", "Sumaira"}
print(nida_friends)
print(type(nida_friends))
print(len(nida_friends))
# by using set constructor
my_friends = set(("Aadila", "Mahnoor", "Khadija", "Sumaira", "Nida"))
# access the set item
print(my_friends)
for x in my_friends:
print(x)
print("Mahnoor" in my_friends)
# add items in a set.
my_friends.add("Sehrish")
print(my_friends)
my_friends.update(nida_friends) # we can add list in a set by using update() method.
print(my_friends)
# joining of sets
print(my_friends.union(nida_friends)) # update() also used to join the sets.
nida_friends.intersection_update(my_friends)
print(nida_friends)
print(my_friends.intersection(nida_friends))
# Remove item from set
my_friends.remove("Nida")
print(my_friends)
my_friends.discard("Sehrish")
print(my_friends)
a = nida_friends.pop()
print(a)
nida_friends.clear()
print(nida_friends)
# del method removes the whole set and it causes error.
#del my_friends
#print(my_friends)
#------------------------>Booleans<--------------------------
print(nida_friends > my_friends)
print(my_friends == nida_friends)
print(my_friends >= nida_friends)
if my_friends > nida_friends:
print("Tasneem's friends are greater than Nida's friends.")
else:
print("Nida's friends are greater than Tasneem's friends.")
|
def gcd(a,b):
if a<b: a,b=b,a
if b==0: return a
return gcd(b,a%b)
def plus(a,b):
c=a[0]*b[1]+b[0]*a[1]
d=a[1]*b[1]
return [c/gcd(c,d),d/gcd(c,d)]
n=100
def dfs(x):
if x==n:return [1,0]
if x==0:
return plus([2,1],dfs(x+1)[::-1])
if x%3!=2: return plus([1,1],dfs(x+1)[::-1])
else: return plus([(int(x/3)+1)*2,1],dfs(x+1)[::-1])
e=dfs(0)
print e
f=0
while e[0]>0:
f+=e[0]%10
e[0]/=10
print f
|
import time
import datetime
t = time.time()
print (t) #原始时间数据
print (int(t)) #秒级时间戳
print (int(round(t * 1000))) #毫秒级时间戳
nowTime = lambda:int(round(t * 1000))
print (nowTime()); #毫秒级时间戳,基于lambda
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) #日期格式化
dt = '2019-07-24 16:19:45'
ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
print (dt,ts,sep="=")
|
Nba_Players = {"Jordan Bell", 7, "Stephen Curry", 30, "Kevon Looney", 5, "Nico Mannion", 2, "Mycal", 15}
def largestJerseyNumber(NBA_Players) :
largestJerseyNumber = 0
print (Nba_Players ["Stephen Curry"])
print (largestJerseyNumber)
# read in 1st Jersey Number,
#compare to 2nd jersey Number
#if 1st > 2nd
#largestJerseyNumber = 1st
|
# findAll - return a list when there is zero or ONE groups
# findAll - returns a list of tuples when there is two or more groups
# [] - Custom character class
# Use {} to specify occurrence in a patterns - {2} -> two vowels 'ao'in a row
# ------------------------------
# Caret has two behaviours : when within character class, it performs negate
# Caret at beginning
# [^ ] - Negate condition
# Caret (^) at the beginning of regEx means "starts With"
# Dollar($) at the end of the regEx means "Ends With"
# Presence of both Caret(^) and Dollar($) indicates "Exact match
import re
def find_all_as_a_list(text_pattern):
find_regex = re.compile(r'\d{3}')
list_match = find_regex.findall(text_pattern)
print(list_match)
def find_all_as_tuples(text_pattern):
find_tuple_regex = re.compile(r'(\d)-(\d\d)-(\d\d\d)')
tuple_match = find_tuple_regex.findall(text_pattern)
print(tuple_match)
def custom_class_find_vowels(text_pattern):
custom_regex = re.compile(r'[aeiouAEIOU]{2}')
list_of_matches = custom_regex.findall(text_pattern)
print(list_of_matches)
def custom_class_alphabet_seq(text_pattern):
custom_alpha = re.compile(r'[a-f]')
list_of_matches = custom_alpha.findall(text_pattern)
print(list_of_matches)
## Print negation using Caret(^)
custom_does_not_contain = re.compile(r'[^a-f]')
list_of_does_not_contain = custom_does_not_contain.findall(text_pattern)
print(list_of_does_not_contain)
def find_exact_match(text_pattern):
exact_match_regex = re.compile(r'^Hello\sWorld$')
match_found = exact_match_regex.search(text_pattern)
if match_found != None:
print(match_found.group())
else:
print("No Match found!")
def all_digits(text_pattern):
all_digits_regex = re.compile(r'^\d+$')
match_found = all_digits_regex.search(text_pattern)
print(match_found.group())
def find_words_that_contain(text_pattern):
find_words_regex = re.compile(r'.at')
word_list = find_words_regex.findall(text_pattern)
print(word_list)
whole_words_regex = re.compile(r'.{1,2}at')
whole_word_list = whole_words_regex.findall(text_pattern)
print(whole_word_list)
## Demo time!!
find_all_as_a_list("The three musketeers : 1022, 303, 678 and 890")
find_all_as_tuples(
"The number pattern goes like this : 1-12-123, 2-23-234, 3-34-345")
custom_class_find_vowels(
"The string will print vowels in umbrella And EGG plus chicken coop")
custom_class_alphabet_seq(
"The alphabet sequence has many permutations and combinations")
find_exact_match("Hello World")
all_digits("123456788")
find_words_that_contain("The cat in the hat lost his flat and he sat on a mat") |
'''
# Inheritance allows us to define a class that inherits all the methods and properties from another class.
# Parent class is the class being inherited from, also called base class.
# Child class is the class that inherits from another class, also called derived class.
'''
class User():
def sign_in(self):
print('Logged In.')
class Wizerd(User):
def __init__(self, name, power):
self.name = name
self.power = power
def attack(self):
print(f'{self.name} attack with the power of {self.power}.')
class Archer(User):
def __init__(self, name, no_of_archer):
self.name = name
self.no_of_archer = no_of_archer
def attack(self):
print(f'{self.name} attack with archer: archer left - {self.no_of_archer}.')
wizerd1 = Wizerd('Marlin', 50)
print(wizerd1)
print(wizerd1.sign_in()) # Here we can see,though sign_in() is not a method of Wizerd class. We still can access it.
wizerd2 = Wizerd('Tanvir', 100)
print(wizerd2.sign_in())
print(wizerd2.attack())
archer1 = Archer('Tan', 200)
print(archer1.sign_in())
print(archer1.attack())
print('\n')
'''
# Python gives us useful tools to check whether anything is an instance of a class or not.
# Syntax - isinstance(instance, class)
'''
print(isinstance(wizerd1, Wizerd))
print(isinstance(wizerd2, User)) # As Wizerd class is a sub class of User.
print(isinstance(wizerd2, object)) # As everything in Python is an object. So everything in python inherite from
# object base class. That's why it gives us true value.
print('\n')
'''
# Another example - Single Inheritance.
'''
class Vehicle():
def __init__(self, name, cost, mileage):
self.name = name
self.cost = cost
self.mileage = mileage
def show_vehicle_details(self):
print(f'Vehicle Brand: {self.name}.')
print(f'Cost of the vehicle: {self.cost} $.')
print(f'Mileage of the vehicle: {self.mileage} kmpl.')
class Car(Vehicle):
def show_car_details(self):
print(f'My brand name is {self.name}.')
car1 = Car('Mercedez', 20000, 20)
print(car1.show_vehicle_details())
print('\n')
'''
# Overriding the __init__ method or creating child class constructor.
'''
class Vehicle():
def __init__(self, name, cost, mileage):
self.name = name
self.cost = cost
self.mileage = mileage
def show_vehicle_details(self):
print(f'Vehicle Brand: {self.name}.')
print(f'Cost of the vehicle: {self.cost} $.')
print(f'Mileage of the vehicle: {self.mileage} kmpl.')
class Bus(Vehicle):
def __init__(self, name, cost, mileage, tyres, hp):
super().__init__(name, cost, mileage)
self.tyres = tyres
self.hp = hp
def show_bus_details(self):
print(f'My brand name is {self.name}.')
print(f'My number of tyres are: {self.tyres}.')
print(f'My engine HorsePower is: {self.hp}.')
bus1 = Bus('Mercedez', 20000, 20, 10, 2000)
print(bus1.show_bus_details(), bus1.show_vehicle_details())
print('\n')
'''
# Now demonstrating Multiple Inheritance.
'''
class Parent1():
def assign_string_one(self, str1):
self.str1 = str1
def show_string_one(self):
return self.str1
class Parent2():
def assign_string_two(self, str2):
self.str2 = str2
def show_string_two(self):
return self.str2
class Child(Parent1, Parent2):
def assign_string_three(self, str3):
self.str3 = str3
def show_string_three(self):
return self.str3
child1 = Child()
child1.assign_string_one('I am string of Parent 1.')
child1.assign_string_two('I am string of Parent 2.')
child1.assign_string_three('I am string of Child.')
print(child1.show_string_one())
print(child1.show_string_two())
print(child1.show_string_three())
print('\n')
'''
# Now demonstrating Multilevel Inheritance.
'''
class Parent():
def assign_name(self, name):
self.name = name
def show_name(self):
return self.name
class Child(Parent):
def assign_age(self, age):
self.age = age
def show_age(self):
return self.age
class GrandChild(Child):
def assign_gender(self, gender):
self.gender = gender
def show_details(self):
return self.name, self.age, self.gender
grandchild = GrandChild()
grandchild.assign_name('Tanvir.')
grandchild.assign_age(25)
grandchild.assign_gender('Male')
print(grandchild.show_details()) |
'''
# What is Polymorphism : The word polymorphism means having many forms. In programming, polymorphism means same
function name (but different signatures) being uses for different types.
'''
class User():
def sign_in(self):
print('Logged In.')
def attack(self):
print('Do nothing.')
class Wizard(User):
def __init__(self, name, power):
self.name = name
self.power = power
def attack(self):
# User.attack(self)
print(f'{self.name} attacking with power of {self.power}.')
return 'Attack Successful.'
class Archer(User):
def __init__(self, name, no_of_arrow):
self.name = name
self.no_of_arrow = no_of_arrow
def attack(self):
print(f'{self.name} attacking with arrow. Arrows left: {self.no_of_arrow}.')
return 'Attack Successful.'
'''
# Here we can see we have methods with same name in our all class. Yet they gives us different output.
'''
wizard1 = Wizard('Tan', 100)
archer1 = Archer('Tanvir', 30)
print(wizard1.attack())
print(archer1.attack() + '\n')
'''Here User's attack function is not executing as it is being override by the attack method of Wizard and Archer class.
We can also make a default function to call this method.
Let's say we also want to access attack method in our super class. Then we need mention that method using class as
shown in line 21.
'''
def call_attack(char):
char.attack()
call_attack(wizard1)
call_attack(archer1)
print('\n')
# We can also do the same using a for loop.
for char in [wizard1, archer1]:
char.attack()
print('\n')
'''
# Now demonstrating some example from some websites.
'''
# Example of inbuilt polymorphic functions :
# len() being used for a string
print(len("geeks"))
# len() being used for a list
print(len([10, 20, 30]))
# Examples of used defined polymorphic functions :
# A simple Python function to demonstrate Polymorphism
def add(x, y, z=0):
return x + y + z
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
# Polymorphism with class methods:
class Bangladesh():
def capital(self):
print('Capital of Bangladesh is Dhaka.')
def language(self):
print('Bangla is used as national language.')
class India():
def capital(self):
print('Capital of India is Delhi.')
def language(self):
print('Hindi is used as national language.')
bd = Bangladesh()
ind = India()
for country in (bd, ind):
country.capital()
country.language()
'''
# Polymorphism with Inheritance and Polymorphism with a Function and objects is already shown in our first example.
''' |
'''
# Encapsulation in Python - The process of wrapping up variables and methods into a single entity is known as
Encapsulation. It is one of the underlying concepts in object-oriented programming (OOP). It acts as a protective
shield that puts restrictions on accessing variables and methods directly, and can prevent accidental or
unauthorized modification of data. Encapsulation also makes objects into more self-sufficient, independently
functioning pieces.
# Access modifiers - Access modifiers limit access to the variables and functions of a class. Python uses three types
of access modifiers; they are - private, public and protected.
--> Public members are accessible anywhere from the class. All the member variables of the class are by default public.
--> Protected members are accessible within the class and also available to its sub-classes. To define a protected
member, prefix the member name with a single underscore “_”.
--> Private members are accessible within the class. To define a private member, prefix the member name with a double
underscore “__”.
'''
class PlayerCharacter:
def __init__(self, name, age, sex):
self.name = name # Public
self._age = age # Private
self.__sex = sex # Protected
def speak(self):
print(f'My name is {self.name}, I am {self._age} years old and I am {self.__sex} ')
return 'Done'
player1 = PlayerCharacter('Tanvir', 25, 'Male')
print(player1.speak())
print(player1.name)
print(player1._age)
print(player1._PlayerCharacter__sex)
#print(player1.__sex) # This line will give us an error as __sex is a private attribute. So we need to access this in
# a specific way given up.
print('\n')
'''
# Now demonstrating a better example where we can access the attributes using set and get method.
'''
class Car:
def __init__(self, speed, color):
self.speed = speed
self.color = color
ford = Car(200, 'Red')
print(ford.speed)
ford.speed = 300
print(ford.speed) # As speed is a public attribute, we can modify this using assign new value. So we can prevent this
# using encapsulation.
print('\n')
class Vehical:
def __init__(self, name, speed, color):
self.__name = name
self.__speed = speed
self.__color = color
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_speed(self, speed):
self.__speed = speed
def get_speed(self):
return self.__speed
def set_color(self, color):
self.__color = color
def get_color(self):
return self.__color
car = Vehical('Ford', 300, 'Red')
print(f'Car Name: {car._Vehical__name}, Car Speed: {car._Vehical__speed}, Car Color: {car._Vehical__color}')
car.set_name('Mercedes')
car.set_speed(400)
car.set_color('Black')
print(f'Car Name: {car.get_name()}, Car Speed: {car.get_speed()}, Car Color: {car.get_color()}') |
#Escreva um programa que leia uma string e imprima quantas vezes cada caractere aparece nessa string
string = input('Digite uma string: ')
count = {}
for i in string:
count[i] = count.get(i,0) + 1
for chave, valor in count.items():
print(f'{chave}: {valor}x')
print() |
#Write a function called is_abecedarian that returns True
#if the letters in a word appear in alphabetical order (double letters are ok).
#How many abecedarian words are there?
def is_abecedarian(word):
index = 0
while index < len(word) -1:
if word[index] > word[index+1]:
return False
else:
index +=1
return True
fin = open('words.txt')
count = 0
for line in fin:
word = line.strip()
if is_abecedarian(word):
count += 1
print('There are {} abecedarian words.'.format(count)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.