text
stringlengths
37
1.41M
class Arbol: def __init__(self,arbol,dato): self.derecha =None self.izquierda = None self.info = dato def agregar (self, arbol,dato): if arbol.info > dato: self.agregaIzquierda(arbol,dato) elif arbol.info < dato: self.agregaDerecha(arbol,dato) def agregaIzquierda(self,arbol,dato): if arbol.izquierda == None: arbol.izquierda=Arbol(arbol,dato) else: self.agregar(arbol.izquierda,dato) def agregaDerecha(self,arbol,dato): if arbol.derecha==None: arbol.derecha= Arbol(arbol,dato) else: self.agregar(arbol.derecha,dato) def preOrden (self,arbol): print (arbol.info ) if arbol.izquierda!=None: self.preoIzquierda(arbol) if arbol.derecha!=None: self.preoDerecha(arbol) def preoIzquierda(self,arbol): self.preOrden(arbol.izquierda) def preoDerecha (self,arbol): self.preOrden(arbol.derecha) def InOrden(self,arbol): if arbol.izquierda!=None: self.inOrIzquierda(arbol) print (arbol.info ) return arbol.info if arbol.derecha!=None: self.inOrIDerecha(arbol) def inOrIzquierda(self,arbol): self.InOrden(arbol.izquierda) def inOrIDerecha(self,arbol): self.InOrden(arbol.derecha) def PostOrden(self,arbol): if arbol.izquierda!=None: self.postIzquierda(arbol) if arbol.derecha!=None: self.postIDerecha(arbol) print (arbol.info ) def postIzquierda(self,arbol): self.PostOrden(arbol.izquierda) def postIDerecha(self,arbol): self.PostOrden(arbol.derecha) def arreglar (self,dato): s =str(dato) cont =0 for w in s: if cont==0: arbol = Arbol(None, w) cont=1 else: arbol.agregar(arbol, w)
class Kedi: tur = "Ev Kedisi" # class attribute # Sınıf özelliği def __init__(self,adi,yas): #constructor # Yapıcı self.adi = adi # instance attribute # ornek özellik self.yas = yas def miyavla(self): # instance method # ornek metod print(self.adi,Kedi.tur,"Miyavladı") @classmethod def turSoyle(cls): # class method # Sınıf metodu return cls.tur def __del__(self): # destructor # Yıkıcı print(self.adi,"Rest In Peace") def isimgetir(self): print(self.isimgetir.__name__) melek = Kedi("Melek",4) duman = Kedi("Duman",3) misket = Kedi("Misket",3) melek.miyavla() duman.miyavla() misket.miyavla() print(misket.tur) print(melek.tur) print(duman.tur) print(misket.adi) print(melek.adi) print(duman.adi) duman.isimgetir()
""" lab2.py Andry Bintoro 1/30/2018 """ def squared_nums(num_list): """ squares numbers in num_list num_list: list of numbers Returns: list of these numbers squared """ new_list = [ ] #initialize list to hold results #iterate through num_list and square each element for num in num_list: sq_num = pow(num,2) new_list.append(sq_num) return new_list def check_title(title_list): """ Removes strings in title_list that have numbers and aren't title case title_list: list of strings Returns: list of strings that are titles """ new_list = [" "] #initialize list to hold strings #iterate through title_list and remove strings that have numbers for string in title_list: if string.isalpha() and string.istitle(): new_list.append(string) return new_list def restock_inventory(inventory): """ Increases inventory of each item in dictionary by 10 inventory: a dictionary with: key: string that is the name of the inventory item value: integer that equals the number of that item currently on hand Returns: updated dictionary where each inventory item is restocked """ new_inventory = { } #initialize new inventory for key, value in inventory.items(): val = val + 10 inventory[key] = val #value += 10 #inventory.update({key:value}) return new_inventory def filter_0_items(inventory): """ Removes items that have a value of 0 from a dictionary of inventories inventory: dictionary with: key: tring that is the name of the inventory item value: nteger that equals the number of that item currently on hand Returns: the same inventory_dict with any item that had 0 quantity removed """ new_inventory = { } #initialize new inventory for key, value in inventory.items(): if value in inventory == 0: new_inventory[key]=value """ if value == 0: inventory.pop({key:None}) else: inventory.update() """ return new_inventory def average_grades(grades): """ Takes grade values from a dictionary and averages them into a final grade grades: a dictionary of grades with: key: string of students name value: list of integer grades received in class Returns: dictionary that averages out the grades of each student """ new_grades = {} #initialize new grades for name, grades in grades.items(): new_grades[name]=sum(grades) /len(grades) return new_grades
# # 习题15-1 立方 指定颜色 # import matplotlib.pyplot as plt # # x_values = list(range(1, 5001)) # y_values = [x**3 for x in x_values] # plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Paired, edgecolors='none', s=40) # # # plt.title("Square Numbers", fontsize=24) # plt.xlabel("Value", fontsize=14) # plt.ylabel("Square of Value", fontsize=14) # ## 标题,xy坐标轴 # # plt.tick_params(axis='both', which='major', labelsize=15) # # plt.axis([0, 6, 0, 140]) # plt.axis([0, 5100, 0, 130000000000]) # plt.show() # # 15-3 15-4 # import matplotlib.pyplot as plt # from random import choice # # class RandomWalk(): # """一个生成随机漫步数据的类""" # # def __init__(self, num_points=5000): # """初始化随机漫步的属性""" # self.num_points = num_points # # # 所有随机漫步都始于(0,0) # self.x_values = [0] # self.y_values = [0] # # def fill_walk(self): # """计算随机漫步包含的所有点""" # # # 不断漫步,直到列表到达指定的长度 # while len(self.x_values) < self.num_points: # # # 决定前进方向以及沿这个方向前进的距离 # x_direction = 1 # # x_direction = choice([1, -1]) # x_distance = choice([0, 1, 2, 3, 4]) # x_step = x_direction * x_distance # # y_direction = choice([1, -1]) # y_distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8]) # y_step = y_direction* y_distance # # # 拒绝原地踏步 # if x_step == 0 and y_step ==0: # continue # # 计算下一个x,y得值 # next_x = self.x_values[-1] + x_step # next_y = self.y_values[-1] + y_step # # self.x_values.append(next_x) # self.y_values.append(next_y) # # while True: # rw = RandomWalk() # rw.fill_walk() # # # 设置绘图窗口的尺寸 # plt.figure(figsize=(10, 6)) # # point_numbers = list(range(rw.num_points)) # plt.plot(rw.x_values, rw.y_values, c='green') # ## 之前c是点的颜色,现在c是点的个数,是个列表 # #c='red',c=(0.9, 0.5, 0.7) # # # 突出起点和终点 # plt.plot(0, 0, c='green') # plt.plot(rw.x_values[-1], rw.y_values[-1], c='blue') # # # 隐藏坐标轴 # plt.axes().get_xaxis().set_visible(False) # plt.axes().get_yaxis().set_visible(False) # # plt.show() # # plt.savefig('squares_plot.png', bbox_inches='tight') # # keep_running = input("Make another walk?(y/n):") # if keep_running == 'n': # break # # # # 15-5 重构 # import matplotlib.pyplot as plt # from random import choice # # class RandomWalk(): # """一个生成随机漫步数据的类""" # # def __init__(self, num_points=5000): # """初始化随机漫步的属性""" # self.num_points = num_points # # # 所有随机漫步都始于(0,0) # self.x_values = [0] # self.y_values = [0] # # def fill_walk(self): # """计算随机漫步包含的所有点""" # # # 不断漫步,直到列表到达指定的长度 # while len(self.x_values) < self.num_points: # x_step = self.get_step() # y_step = self.get_step() # # # 拒绝原地踏步 # if x_step == 0 and y_step ==0: # continue # # 计算下一个x,y得值 # next_x = self.x_values[-1] + x_step # next_y = self.y_values[-1] + y_step # # self.x_values.append(next_x) # self.y_values.append(next_y) # # def get_step(self): # direction = choice([1, -1]) # distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8]) # step = direction * distance # return step # # # while True: # rw = RandomWalk() # rw.fill_walk() # # # 设置绘图窗口的尺寸 # plt.figure(figsize=(10, 6)) # # point_numbers = list(range(rw.num_points)) # plt.plot(rw.x_values, rw.y_values, c='green') # ## 之前c是点的颜色,现在c是点的个数,是个列表 # #c='red',c=(0.9, 0.5, 0.7) # # # 突出起点和终点 # plt.plot(0, 0, c='green') # plt.plot(rw.x_values[-1], rw.y_values[-1], c='blue') # # # 隐藏坐标轴 # plt.axes().get_xaxis().set_visible(False) # plt.axes().get_yaxis().set_visible(False) # # plt.show() # # plt.savefig('squares_plot.png', bbox_inches='tight') # # keep_running = input("Make another walk?(y/n):") # if keep_running == 'n': # break # # 15-6 自动生成标签 x值改为循环,for循环替换为列表解析 # # # #列表解析,直接上 # # squares=[value**2 for value in range(1,11)] # # print(squares) # # import pygal # from random import randint # class Die(): # """表示一个骰子的类""" # # def __init__(self, num_sides=6): # """骰子默认为6个面""" # self.num_sides = num_sides # # def roll(self): # """返回一个位于1和骰子面数之间的随机值""" # return randint(1, self.num_sides) # # die_1 = Die() # die_2 = Die(10) # # 掷几次骰子,将结果储存在一个列表中 # # results = [] # # for roll_num in range(50000): # # result = die_1.roll() + die_2.roll() # # results.append(result) # results = [die_1.roll()+die_2.roll() for roll_num in range(5000)] # print(results) # # # 对结果进行统计 # # max_result = die_1.num_sides + die_2.num_sides ## 6+6=12 # # for value in range(2, max_result+1):## [1, 13) # # frequency = results.count(value) # # frequencies.append(frequency) # frequencies = [results.count(value) for value in range(2, max_result+1)] # print(frequencies) # # # 对结果进行可视化 # hist = pygal.Bar() # # hist.title = "Results of rolling a D6 and a D10 50,000 times." # # hist.x_lables = [] # for x in range(2, 17): # hist.x_lables.append(x) # print(hist.x_lables) # # hist.x_title = "Result" # hist.y_title = "Frequency of Result" # # hist.add('D6 + D10', frequencies) # hist.render_to_file('die_visual_4.svg') # # 15-7 两个D8骰子 # # import pygal # from random import randint # class Die(): # """表示一个骰子的类""" # # def __init__(self, num_sides=6): # """骰子默认为6个面""" # self.num_sides = num_sides # # def roll(self): # """返回一个位于1和骰子面数之间的随机值""" # return randint(1, self.num_sides) # # die_1 = Die(8) # die_2 = Die(8) # # results = [die_2.roll()+die_2.roll() for roll_num in range(500000)] # print(results) # # max_result = die_1.num_sides + die_2.num_sides ## 8+8=16 # frequencies = [results.count(value) for value in range(2, max_result+1)] # # # hist = pygal.Bar() # # hist.title = "Results of rolling a D6 and a D10 50,000 times." # # hist.x_lables = [x for x in range(2, max_result+1)] # # hist.x_title = "Result" # hist.y_title = "Frequency of Result" # # hist.add('D8 + D8', frequencies) # hist.render_to_file('die_visual_7.svg') # # 15-8 三个D6 # import pygal # from random import randint # class Die(): # """表示一个骰子的类""" # # def __init__(self, num_sides=6): # """骰子默认为6个面""" # self.num_sides = num_sides # # def roll(self): # """返回一个位于1和骰子面数之间的随机值""" # return randint(1, self.num_sides) # # die_1 = Die(6) # die_2 = Die(6) # die_3 = Die(6) # # results = [die_1.roll()+die_2.roll()+die_3.roll() for roll_num in range(500000)] # # max_result = die_1.num_sides + die_2.num_sides + die_3.num_sides ## 6+6+6=18 # frequencies = [results.count(value) for value in range(3, max_result+1)] # # # hist = pygal.Bar() # # hist.title = "Results of rolling a D6 and a D10 50,000 times." # # hist.x_lables = [x for x in range(3, max_result+1)] # # hist.x_title = "Result" # hist.y_title = "Frequency of Result" # # hist.add('D6 + D6 + D6', frequencies) # hist.render_to_file('die_visual_8.svg') # # 15-9 点数相乘 # import pygal # from random import randint # class Die(): # """表示一个骰子的类""" # # def __init__(self, num_sides=6): # """骰子默认为6个面""" # self.num_sides = num_sides # # def roll(self): # """返回一个位于1和骰子面数之间的随机值""" # return randint(1, self.num_sides) # # die_1 = Die(6) # die_2 = Die(6) # # # results = [die_1.roll()*die_2.roll() for roll_num in range(5000)] # result_possible = [] # for n in range(1, die_1.num_sides+1): # [1, 7) # for m in range (1, die_2.num_sides+1): # [1.7) # if n*m not in result_possible: # result_possible.append(n*m) # # print(result_possible) # result_possible.sort() # print(result_possible) # # frequencies = [results.count(value) for value in result_possible] # # # hist = pygal.Bar() # # hist.title = "Results of rolling a D6 and a D10 50,000 times." # # hist.x_lables = result_possible # # hist.x_title = "Result" # hist.y_title = "Frequency of Result" # # hist.add('D6 * D6', frequencies) # hist.render_to_file('die_visual_9.svg') # # ## 计算一下不同结果的概率 # result_possible_2 = [] # for n in range(1, die_1.num_sides+1): # [1, 7) # for m in range(1, die_2.num_sides+1): # [1.7) # result_possible_2.append(n*m) # # p = [result_possible_2.count(value) for value in result_possible] # print(p) # ## 可能的结果,总体中出现的次数,如36个可能的结果中,1出现1次,6出现4次 # 5-10 用matplotlib掷骰子,用pygal做随机漫步 ## 用matplotlib做柱状图 # # import matplotlib.pyplot as plt # from random import randint # # class Die(): # """表示一个骰子的类""" # # def __init__(self, num_sides=6): # """骰子默认为6个面""" # self.num_sides = num_sides # # def roll(self): # """返回一个位于1和骰子面数之间的随机值""" # return randint(1, self.num_sides) # # die_1 = Die() # die_2 = Die(10) # # 掷几次骰子,将结果储存在一个列表中 # # results = [die_1.roll()+die_2.roll() for roll_num in range(5000)] # # # 对结果进行统计 # frequencies = [] # # max_result = die_1.num_sides + die_2.num_sides ## 6+6=12 # # frequencies = [results.count(value) for value in range(2, max_result+1)] # print(frequencies) # # plt.bar(range(2, max_result+1), frequencies) # # plt.show() # ## 用pygal做随机漫步 import pygal from random import choice class RandomWalk(): """一个生成随机漫步数据的类""" def __init__(self, num_points=500): """初始化随机漫步的属性""" self.num_points = num_points # 所有随机漫步都始于(0,0) self.values = [] self.x_values = [0] self.y_values = [0] def fill_walk(self): """计算随机漫步包含的所有点""" # 不断漫步,直到列表到达指定的长度 while len(self.x_values) < self.num_points: x_step = self.get_step() y_step = self.get_step() # 拒绝原地踏步 if x_step == 0 and y_step ==0: continue # 计算下一个x,y得值 next_x = self.x_values[-1] + x_step next_y = self.y_values[-1] + y_step self.x_values.append(next_x) self.y_values.append(next_y) self.values.append((next_x, next_y)) def get_step(self): direction = choice([1, -1]) distance = choice([0, 1, 2, 3, 4]) step = direction * distance return step rw = RandomWalk() rw.fill_walk() sandiantu = pygal.XY(stroke=False) sandiantu.title = "Results of random walk." sandiantu.add('A', rw.values) sandiantu.render_to_file('random_walk_2.svg') print(rw.values)
# # 15.2 简单的折线图 # import matplotlib.pyplot as plt # ## 导入pyplot命名为plt # # squares = [1, 4, 9, 16, 25] # ## 建个列表储存平方数,纵坐标值 # plt.plot(squares) # ## 传递给函数plot,横坐标默认 0,1,2,3,4 # plt.show() # ## 将图像显示出来,查看器可以缩放,可以保存 # # 15.2.1 题目横纵坐标字体格式 # import matplotlib.pyplot as plt # ## 导入pyplot命名为plt # # squares = [1, 4, 9, 16, 25] # plt.plot(squares, linewidth=5) # # plt.title("Square Numbers", fontsize=24) # plt.xlabel("Value", fontsize=14) # plt.ylabel("Square of Value", fontsize=14) # ## 标题,xy坐标轴 # # plt.tick_params(axis='both', labelsize=15) # ## 刻度标记的大小 # # plt.show() # # # 15.2.2 x轴设定 # import matplotlib.pyplot as plt # ## 导入pyplot命名为plt # # input_values = [1, 2, 3, 4, 5] # ## 设置横坐标值 # squares = [1, 4, 9, 16, 25] # plt.plot(input_values, squares, linewidth=5) # ## 横纵坐标对应 # # plt.title("Square Numbers", fontsize=24) # plt.xlabel("Value", fontsize=14) # plt.ylabel("Square of Value", fontsize=14) # ## 标题,xy坐标轴 # # plt.tick_params(axis='both', labelsize=15) # ## 刻度标记的大小 # # plt.show() # # 15.2.3 散点图一个点 # import matplotlib.pyplot as plt # # plt.scatter(2, 4, s=200) # ## x=2, y=4, 型号200 # # plt.title("Square Numbers", fontsize=24) # plt.xlabel("Value", fontsize=14) # plt.ylabel("Square of Value", fontsize=14) # # 标题,xy坐标轴 # # plt.tick_params(axis='both', which='major', labelsize=15) # ## 刻度标记的大小 ?? # # plt.show() # # 15.2.4 散点图多个点 # import matplotlib.pyplot as plt # # x_values = [1, 2, 3, 4, 5] # y_values = [1, 4, 9, 16, 25] # plt.scatter(x_values, y_values, s=200) # # # plt.title("Square Numbers", fontsize=24) # plt.xlabel("Value", fontsize=14) # plt.ylabel("Square of Value", fontsize=14) # ## 标题,xy坐标轴 # # plt.tick_params(axis='both', which='major', labelsize=15) # ## 刻度标记的大小,which=major是啥意思 # # plt.show() # # # 15.2.5 自动计算数据 # import matplotlib.pyplot as plt # # x_values = list(range(1, 1001)) # y_values = [x**2 for x in x_values] # plt.scatter(x_values, y_values, s=40) # ## 还是散点图,绘制1000个点 # # # plt.title("Square Numbers", fontsize=24) # plt.xlabel("Value", fontsize=14) # plt.ylabel("Square of Value", fontsize=14) # ## 标题,xy坐标轴 # # plt.tick_params(axis='both', which='major', labelsize=15) # ## 刻度标记的大小,which=major是啥意思 # # plt.axis([0, 1100, 0, 1100000]) # ## xy取值区间 # # plt.show() # # 15.2.6 删除据点的轮廓 # import matplotlib.pyplot as plt # # x_values = list(range(1, 1001)) # y_values = [x**2 for x in x_values] # plt.scatter(x_values, y_values, edgecolors='none', s=40) # ## 设置轮廓为无,这没看出来有啥作用,就变细了一点点 # # # plt.title("Square Numbers", fontsize=24) # plt.xlabel("Value", fontsize=14) # plt.ylabel("Square of Value", fontsize=14) # ## 标题,xy坐标轴 # # plt.tick_params(axis='both', which='major', labelsize=15) # ## 刻度标记的大小,which=major是啥意思 # # plt.axis([0, 1100, 0, 1100000]) # ## xy取值区间 # # plt.show() # # # 15.2.7 自定义点的颜色 # import matplotlib.pyplot as plt # # x_values = list(range(1, 1001)) # y_values = [x**2 for x in x_values] # # plt.scatter(x_values, y_values, c='red', edgecolors='none', s=40) # plt.scatter(x_values, y_values, c=(0.9, 0.5, 0.7), edgecolors='none', s=40) # ## 颜色设置,注意0-1之间的小数 # # # plt.title("Square Numbers", fontsize=24) # plt.xlabel("Value", fontsize=14) # plt.ylabel("Square of Value", fontsize=14) # ## 标题,xy坐标轴 # # plt.tick_params(axis='both', which='major', labelsize=15) # ## 刻度标记的大小,which=major是啥意思 # # plt.axis([0, 1100, 0, 1100000]) # ## xy取值区间 # # plt.show() # # # 15.2.8 使用颜色映射 # import matplotlib.pyplot as plt # # x_values = list(range(1, 1001)) # y_values = [x**2 for x in x_values] # # plt.scatter(x_values, y_values, c='red', edgecolors='none', s=40) # plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.viridis, edgecolors='none', s=40) # ## 颜色设置,注意0-1之间的小数 # # # plt.title("Square Numbers", fontsize=24) # plt.xlabel("Value", fontsize=14) # plt.ylabel("Square of Value", fontsize=14) # ## 标题,xy坐标轴 # # plt.tick_params(axis='both', which='major', labelsize=15) # ## 刻度标记的大小,which=major是啥意思 # # plt.axis([0, 1100, 0, 1100000]) # ## xy取值区间 # plt.show() ## http://matplotlib.org/ # # # import numpy as np # import matplotlib.pyplot as plt # # # cmaps = [('Perceptually Uniform Sequential', [ # 'viridis', 'plasma', 'inferno', 'magma', 'cividis']), # ('Sequential', [ # 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', # 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', # 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']), # ('Sequential (2)', [ # 'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink', # 'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia', # 'hot', 'afmhot', 'gist_heat', 'copper']), # ('Diverging', [ # 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', # 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']), # ('Cyclic', ['twilight', 'twilight_shifted', 'hsv']), # ('Qualitative', [ # 'Pastel1', 'Pastel2', 'Paired', 'Accent', # 'Dark2', 'Set1', 'Set2', 'Set3', # 'tab10', 'tab20', 'tab20b', 'tab20c']), # ('Miscellaneous', [ # 'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', # 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', # 'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar'])] # # # gradient = np.linspace(0, 1, 256) # gradient = np.vstack((gradient, gradient)) # # # def plot_color_gradients(cmap_category, cmap_list): # # Create figure and adjust figure height to number of colormaps # nrows = len(cmap_list) # figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22 # fig, axes = plt.subplots(nrows=nrows, figsize=(6.4, figh)) # fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99) # # axes[0].set_title(cmap_category + ' colormaps', fontsize=14) # # for ax, name in zip(axes, cmap_list): # ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name)) # ax.text(-.01, .5, name, va='center', ha='right', fontsize=10, # transform=ax.transAxes) # # # Turn off *all* ticks & spines, not just the ones with colormaps. # for ax in axes: # ax.set_axis_off() # # # for cmap_category, cmap_list in cmaps: # plot_color_gradients(cmap_category, cmap_list) # # plt.show() # 15.2.9 自动保存列表 # plt.show 替换为 # plt.savefig('squares_plot.png', bbox_inches='tight') # 保存位置:py文件所在目录,名字格式,去掉周围空白区域 # 15.3 随机漫步 模拟现实中的很多情形 import matplotlib.pyplot as plt from random import choice class RandomWalk(): """一个生成随机漫步数据的类""" def __init__(self, num_points=500): """初始化随机漫步的属性""" self.num_points = num_points # 所有随机漫步都始于(0,0) self.x_values = [0] self.y_values = [0] def fill_walk(self): """计算随机漫步包含的所有点""" # 不断漫步,直到列表到达指定的长度 while len(self.x_values) < self.num_points: # 决定前进方向以及沿这个方向前进的距离 x_direction = choice([1, -1]) x_distance = choice([0, 1, 2, 3, 4]) x_step = x_direction * x_distance y_direction = choice([1, -1]) y_distance = choice([0, 1, 2, 3, 4]) y_step = y_direction* y_distance # 拒绝原地踏步 if x_step == 0 and y_step ==0: continue # 计算下一个x,y得值 next_x = self.x_values[-1] + x_step next_y = self.y_values[-1] + y_step self.x_values.append(next_x) self.y_values.append(next_y) while True: rw = RandomWalk(50000) rw.fill_walk() # 设置绘图窗口的尺寸 plt.figure(figsize=(10, 6)) point_numbers = list(range(rw.num_points)) plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.spring, edgecolors='none', s=1) ## 之前c是点的颜色,现在c是点的个数,是个列表 #c='red',c=(0.9, 0.5, 0.7) # 突出起点和终点 plt.scatter(0, 0, c='green', edgecolors='none', s=150) plt.scatter(rw.x_values[-1], rw.y_values[-1], c='blue', edgecolors='none', s=150) # 隐藏坐标轴 plt.axes().get_xaxis().set_visible(False) plt.axes().get_yaxis().set_visible(False) plt.show() # plt.savefig('squares_plot.png', bbox_inches='tight') keep_running = input("Make another walk?(y/n):") if keep_running == 'n': break
# Task 7 # Write a program to reverse a linked list. class Stack: def __init__(self): self.stack = [] def push(self,data): # Inserting Elements to stack self.stack.append(data) def pop(self): # Delete Element from stack a = self.stack.pop() return a class Node: def __init__(self,e): # Data sub part self.e = e self.ref = None class LL: def __init__(self): self.start_node = None def create(self,d): # Interface to add data to last of LL new_node = Node(d) # Create a node if self.start_node is None: # Checking if the ll is empty self.start_node = new_node return n = self.start_node # Temp variable to hold the starting address while n.ref is not None: # This check if the current node is last node␣,→or not n = n.ref n.ref = new_node def traverse_list(self): if self.start_node is None: # List is empty or not print("List has no element") return else: n = self.start_node # Temp variable b = [] while n is not None: b.append(n.e) n = n.ref print(b) def reverse(self,a): st = a.start_node t = st s = Stack() q = Stack() while st!= None: # 5,4,3,2,1 - inserting from start. s.push(st.e) st = st.ref a.traverse_list() # LL = 5,4,3,2,1 and s.stack = 5,4,3,2,1 while t!= None: # Reverse p = s.pop() q.push(p) t = t.ref print(q.stack) # q.stack = 1,2,3,4,5 l = LL() r = LL() u = [1,2,3] for i in u: l.create(i) r.reverse(l)
# !/usr/bin/evn python3 # -*- config: utf-8 -*- # Дан список X из n вещественных чисел. Найти минимальный элемент списка,, используя # вспомогательную рекурсивную функцию, находящую минимум среди последних элементов # списка , начиная с n-гo. def min_el_from(i, mini, lis): if i == len(lis): return mini else: if lis[i] < mini: mini = lis[i] i += 1 return min_el_from(i, mini, lis) if __name__ == '__main__': Lst = [0.9, 9.8, 5.2, 7.5, 1.2] frm = 2 print(min_el_from(frm - 1, Lst[frm - 1], Lst))
""" Program: chapter7_lab5.py Author: Michael Rouse Date: 11/12/13 Description: Modify chapter 7 lab 4 to be able to enter in multiple customers then save it in a dictionary in a shelf file """ import pickle, shelve def customer_info(): """ Gets information about customer """ # List to have in the dictionary customer_list = [] # Get customer's full name customer_list.append(input("What is the customer's first name? ")) customer_list.append(input("What is the customer's middle name? ")) customer_list.append(input("What is the customer's last name? ")) # Get customer's SSN customer_list.append(input("What is the customer's SSN? ")) # Get customer's address customer_list.append(input("What is the customer's street address? ")) customer_list.append(input("What is the customer's city? ")) customer_list.append(input("What is the customer's state? ")) customer_list.append(input("What is the customer's zip code? ")) return customer_list def get_yes_no(question=""): """ Asks user yes or no question, will return False if no and True if yes """ # Ask question user_input = input(question) user_input = user_input.upper() # Check user input if user_input == "NO" or user_input == "N": valid = False elif user_input == "YES" or user_input == "Y": valid = True else: valid = False # Return true or false return valid def store_it(customer): """ Converts the list into a dictionary and saves it in the shelf file """ # Open the customer shelf customers = shelve.open("customer_shelf") # Grab the customer's social security number and remove it from the customer list ssn = customer[3] del customer[3] # Add a dictionary entry for the new customer in the shelf file customers[ssn] = customer # Sync the shelf customers.sync() # Close the shelf customers.close() def get_it(): """ Opens the shelf file and displays all customers in the shelf """ # Open the shelf customers = shelve.open("customer_shelf") # Display the customers print("Customer List:") print("\t SSN:\t Customer Info:") # For each SSN in customers for ssn in customers: # Create a string that contains all info about the customer display_info = "\t " + str(ssn) + "\t" + customers[ssn][0] + " " + customers[ssn][1] + " " + customers[ssn][2] + \ "\n\t\t\t" + customers[ssn][3] + \ "\n\t\t\t" + customers[ssn][4] + ", " + customers[ssn][5] + " " + customers[ssn][6] + "\n" print(display_info) # Close the shelf customers.close() return True def main(): """ Main program """ valid = False while not valid: # Will be the list returned by customer_info() customer = customer_info() print(customer) # Display the customer info print("\n\n") print("Customer Info:") print("\t Name: "+customer[0]+" "+customer[1]+" "+customer[2]) print("\t SSN: "+customer[3]) print("\tAddress: "+customer[4]) print("\t "+customer[5]+", "+customer[6]+" "+customer[7]) print("\n\n") # Ask user and check input valid = get_yes_no("Is this correct (Y/N)? ") print("\n\n") # At this point all user input is correct and valid, save the customer to the list store_it(customer) # Display all customers get_it() """ MAIN """ add_more = True while add_more == True: main() # Ask customer if they want to add another customer add_more = get_yes_no("Add another customer (Y/N)? ") input("\n\nPress the Enter key to exit...")
""" Program: rectangle_area.py Author: Michael Rouse Date: 9/3/13 Description: Calculates area of rectangle """ print("Rectangle Area Problem") rectangleLength = int(input("What is the length of the rectangle? ")) rectangleWidth = int(input("What is the width of the rectangle? ")) # Calculates the area rectangleArea = rectangleLength * rectangleWidth print("The area of the rectangle with a length of", rectangleLength, \ "and a width of", rectangleWidth, "is:", rectangleArea) print("\n\n\nDone...")
""" Program: lab7_4.py Author: Michael Rouse Date: 9/27/13 Description: Picks a random car for each staff member and displays that car they drove to work """ import random # Staff directory tuple STAFF = ('Xavier', 'Matt', 'Joey', 'Jordon', 'Nick', 'Cole', 'Brad') # Possible cars for each staff member tuple CARS = ('Ferrari', 'Corvette', 'DeLorean', 'Mercedes', 'Chevrolet') for i in range(len(STAFF)): car = random.choice(CARS) print(STAFF[i], "drove to work today, and he drove a", car,"\n") input("Press the Enter key to exit...")
""" Program: file_fun.py Author: Michael Rouse Date: 10/29/13 Description: Practice with files """ print("Practice writing to a file.\n") # Variable for the file my_file = open("my_file.txt", "w") # Write four lines of text my_file.write("Program by Michael Rouse!\n") my_file.write("How are you?\n") my_file.write("I'm doing great!\n") my_file.write("Do you like my program?\n") # Write three numbers my_file.write("3\n") my_file.write("504\n") my_file.write("7777\n") print("Four lines of text and three numbers have been written to my_file.txt") # Close my_file my_file.close()
""" Program: Record.py Author: Michael Rouse Date: 1/15/14 Description: Create a class called "Record" that will be used to create a simple database program """ class Record(object): """ Record Class """ def __init__(self): """ Initialize the class """ # Ask for user to input all variables self.__firstName = self.__askForString("First Name: ") self.__lastName = self.__askForString("Last Name: ") self.__ssn = self.__askForString("SSN: ") self.__address = self.__askForString("Address: ") self.__city = self.__askForString("City: ") self.__state = self.__askForString("State: ") self.__zipCode = self.__askForNumber("Zip Code: ", "Invalid Zip Code") self.__index = self.__askForNumber("Index: ", "Invalid Index Number") def __str__(self): """ Display information about the record """ output = "\n\nRecord Number " + str(self.__index) + ":" + "\n" +self.__firstName.title() + " " + \ self.__lastName.title() + "\n" + self.__address + "\n" + self.__city + ", " + \ self.__state + ", " + str(self.__zipCode) return output def get_record(self): """ return a list of the record """ return [self.__index, self.__firstName, self.__lastName, self.__ssn, self.__address, self.__city, self.__state, str(self.__zipCode)] def __askForString(self, prompt="> ", error="Invalid Input"): """ Ask for input and perform error checking to ensure the string isn't blank """ valid = False while not valid: user_input = input(prompt) # Ask for input if user_input == "" or user_input.isspace(): # User input is empty or contains only spaces print("\n" + error) else: # User input is valid valid = True # Valid input return user_input def __askForNumber(self, prompt="> ", error="Invalid Input"): """ Ask for input and perform error checking to ensure input was a number """ valid = False while not valid: try: user_input = int(input(prompt)) # Ask for input except: # Not a valid number print("\n" + error) else: # Valid number valid = True # Input was valid, return the number return user_input
""" Program: lab4_08.py Author: Michael Rouse Date: 9/12/13 Description: Has the user input three numbers and the program will print which number is the middle number. """ print("Tell me three numbers and I can tell you which is the mide number!\n\n") firstNumber = int(input("First number: ")) secondNumber = int(input("Second number: ")) thirdNumber = int(input("Third number: ")) #variable for comparison and printing the middle number middleNumber = 0 if firstNumber > secondNumber > thirdNumber: middleNumber = secondNumber elif thirdNumber > secondNumber > firstNumber: middleNumber = secondNumber elif secondNumber > firstNumber > thirdNumber: middleNumber = firstNumber elif thirdNumber > firstNumber > secondNumber: middleNumber = firstNumber elif firstNumber > thirdNumber > secondNumber: niddleNumber = thirdNumber elif secondNumber > thirdNumber > firstNumber: middleNumber = thirdNumber print("\nThe middle number is", middleNumber) print("\n\nDone...")
""" Program: repeat_it_code.py Author: Michael Rouse Date: 10/24/13 Description: Daily Design Exercise, create a function called repeat it that repeats a message multiple times. """ def repeat_it(message = "\n", multiplier = 1): """ Repeats message the amount of times as the multiplier """ # Add a line break to the message message += "\n" # Print the message the amount of times as the multiplier print(message * multiplier)
""" Program: GEOHELP.py Author: Michael Rouse Date: 10/21/13 Description: Assists users with various geometry functions """ import my_math """ my_math functions: circleArea(radius) circleDiameter(radius) circlePerimeter(radius) cylinderArea(radius, height) cylinderVolume(radius, height) prismArea(length, height, width) prsimVolume(length, height, width) rectangleArea(length, width) rectanglePerimeter(length, width) triangleArea(base, height) """ def get_float(prompt="Input a number> "): """ Gets a floating point number from the user """ valid = False # Keeps asking for input until valid while not valid: userInput = input(prompt) # Check to see if user input is valid if check_input(userInput) == True: # Mark as valid valid = True else: # Mark as invalid valid = False # Return input as floating point number return float(userInput) def get_radius(): """ Get radius from user """ # Get user input for radius radius = get_float("What is the radius? ") # Return the radius return radius def get_height(): """ Get height from user """ # Get user input for height height = get_float("What is the height? ") # Return the height return height def get_length(): """ Get length from user """ # Get user input for length length = get_float("What is the length? ") # Return the length return length def get_width(): """ Get width from user """ # Get user input for width width = get_float("What is the width? ") # Return the width return width def get_base(): """ Get base from user """ # Get user input for base base = get_float("what is the base? ") # Return the base return base ############ # DIAMETER # ############ def display_diameter(): """ Find the diameter of a circle """ print("\n\nCalculate the diameter of a circle\n") # Get measurements radius = get_radius() # Solve for diameter diameter = my_math.circleDiameter(radius) shape = "circle" # Display the diameter to the user print("\nThe diameter of the", shape, "is:", diameter) ############ # AREA # ############ def display_area(menuID): """ Solve for the area of a shape """ if menuID == 1: # Area of a circle shape = "circle" print("\n\nCalculate the area of a", shape, "\n") # Get measurements radius = get_radius() # Solve for area area = my_math.circleArea(radius) elif menuID == 2: # Area of a cylinder shape = "cylinder" print("\n\nCalculate the area of a", shape, "\n") # Get measurements radius = get_radius() height = get_height() # Solve for area area = my_math.cylinderArea(radius, height) elif menuID == 3: # Area of a prism shape = "prism" print("\n\nCalculate the area of a", shape, "\n") # Get measurements length = get_length() width = get_width() height = get_height() # Solve for area area = my_math.prismArea(length, height, width) elif menuID == 4: # Area of a rectangle shape = "rectangle" print("\n\nCalculate the area of a", shape, "\n") # Get measurements length = get_length() width = get_width() # Solve for area area = my_math.rectangleArea(length, width) elif menuID == 5: # Area of a triangle shape = "triangle" print("\n\nCalculate the area of a", shape, "\n") # Get measurements base = get_base() height = get_height() # Solve for area area = my_math.triangleArea(base, height) # Display the area to the user print("\nThe area of the", shape, "is:", area) ########## # VOLUME # ########## def display_volume(menuID): """ Solve for the volume of a shape """ if menuID == 2: # Volume of a cylinder shape = "cylinder" print("\n\nCalculate the volume of a", shape, "\n") # Get measurements radius = get_radius() height = get_height() # Solve for volume volume = my_math.cylinderVolume(radius, height) elif menuID == 3: # Volume of a prism shape = "prism" print("\n\nCalculate the volume of a", shape, "\n") # Get measurements length = get_length() height = get_height() width = get_width() # Solve for volume volume = my_math.prismVolume(length, height, width) # Display the volume to the user print("\nThe volume of the", shape, "is:", volume) ############# # PERIMETER # ############# def display_perimeter(menuID): """ Solve for the perimeter of a shape """ if menuID == 1: # Perimeter of a circle shape = "circle" print("\n\nCalculate the perimeter of a", shape, "\n") # Get measurements radius = get_radius() # Solve for perimeter perimeter = my_math.circlePerimeter(radius) elif menuID == 4: # Perimeter of a rectangle shape = "rectangle" print("\n\nCalculate the perimeter of a", shape, "\n") # Get measurements length = get_length() width = get_width() # Solve for perimeter perimeter = my_math.rectanglePerimeter(length, width) # Display the perimeter to user print("\nThe perimeter of the", shape, "is:", perimeter) def menu(id=0): """Display a menu. 0=Main, 1=Circle, 2=Cylinder, 3=Prism, 4=Rectangle, 5=Triangle""" if id == 0: # Show main menu print(""" Geometry Helper Choose a shape you want to work with 1. Circle 2. Cylinder 3. Prism 4. Rectangle 5. Triangle 0. Exit """) if id == 1: # Show circle menu print(""" Circle Help What do you need to solve for? 1. Area 2. Diameter 3. Perimeter 0. Back """) if id == 2: # Show cylinder menu print(""" Cylinder Help What do you need to solve for? 1. Area 2. Volume 0. Back """) if id == 3: # Show prism menu print(""" Prism Help What do you need to solve for? 1. Area 2. Volume 0. Back """) if id == 4: # Show rectangle menu print(""" Rectangle Help What do you need to solve for? 1. Area 2. Perimeter 0. Back """) if id == 5: # Show triangle menu print(""" Triangle Help What do you need to solve for? 1. Area 0. Back """) # Get user input for the menu userInput = menu_input(id) return userInput def check_input(userInput): """ Checks to make sure user input is valid """ valid = False error = None try: # Check to see if input is a number userInput = float(userInput) # Input is a number, check if it's valid if userInput > 0: # Number is valid valid = True else: # Not larger than zero, display an error if userInput == 0: # Input can't be zero error error = "\nZero is not a valid measurement." else: # Negative number error error = "\nPositive numbers only, please." valid = False except: # User input is not a number error error = "\nNumbers only, please." valid = False # Detect if an error occured if valid != True: # Error was detected, display error print(error) return False else: # No error return True def menu_input(menuID): """ Get user input for menu navigation """ # Tuple for available options on each menu menuOptions = ((0, 1, 2, 3, 4, 5), (0, 1, 2, 3), (0, 1, 2), (0, 1, 2), (0, 1, 2), (0, 1)) # Get available options for the menu the user is on options = menuOptions[menuID] valid = False error = None # Will loop until user inputs a valid option while not valid: # Get user's option userInput = input("Choice> ") try: # Check to see if input is a number userInput = int(userInput) # Input is a number, check if it's available for the menu if userInput not in options: # Not an available option, set the error error = "\nOption not available." valid = False else: # Option is valid valid = True except: # Input not a number, set the error error = "\nOption not available." valid = False # Display error if it was detected if error: print(error) error = None # User input is valid return userInput ########## # MAIN # ########## def main(): """ Main program of Geometry Helper """ close = False menuID = 0 # Will loop until user picks to exit the program while close != True: # Display the menu and get user input option = menu(menuID) """ OPTIONS FOR EACH MENU main menu (0): option 1: Circle Menu option 2: Cylinder Menu option 3: Prism Menu option 4: Rectangle Menu option 5: Triangle Menu option 0: Exit program circle menu (1): cylinder menu(2): option 1: Area option 1: Area option 2: Diameter option 2: Volume option 3: Perimeter option 0: Return option 0: Return prism menu (3) rectangle menu(4): option 1: Area option 1: Area option 2: Volume option 2: Perimeter option 0: Return option 0: Return triangle menu (5) option 1: Area option 0: Return """ # Put user's option into action # Main menu has only two outcomes if menuID == 0: if option == 0: # User wants to exit program close = True else: # Options 1 - 5 # User wants to navigate to a submenu menuID = option # All submenus (1-5) else: # Option 0 is the same across all submenus if option == 0: # Return to main menu menuID = option # Option 1 is the same across all submenus as well elif option == 1: # Solve for area of the shape display_area(menuID) # Option 2 varies for each submenu elif option == 2: if menuID == 1: # Solve for diameter of a circle display_diameter() elif menuID == 2 or menuID == 3: # Solve for volume of a cylinder/prism display_volume(menuID) elif menuID == 4: # Solve for perimeter of a rectangle display_perimeter(menuID) # Option 3 is only available for one submenu elif option == 3: if menuID == 1: # Solve for perimeter of a circle display_perimeter(menuID) # Inform the user the program is closing print(""" Thank you for using Geometry Helper! Press the Enter key to exit the program... """) input("") # Go to main function main()
""" Program: Author: Michael Rouse Date: 10/18/13 Description: Menu for math problems """ def menu(id=0): """Display a menu. 0=Main, 1=Circle, 2=Cylinder, 3=Prism, 4=Rectangle, 5=Triangle""" if id == 0: # Show main menu print(""" GEOMETRY HELPER Choose a shape you want to work with 1. Circle 2. Cylinder 3. Prism 4. Rectangle 5. Triangle 0. Exit """) userChoice = input("Option> ") if userChoice == "0": print() elif userChoice == "1": menu(1) elif userChoice == "2": menu(2) elif userChoice == "3": menu(3) elif userChoice == "4": if id == 1: # Show circle menu print(""" CIRCLE HELP What do you need to solve for? 1. Area 2. Diameter 3. Perimeter 0. Exit """) if id == 2: # Show cylinder menu print(""" CYLINDER HELP What do you need to solve for? 1. Area 2. Volume 0. Exit """) if id == 3: # Show prism menu print(""" PRISM HELP What do you need to solve for? 1. Area 2. Volume 0. Exit """) if id == 4: # Show rectangle menu print(""" RECTANGLE HELP What do you need to solve for? 1. Area 2. Perimeter 0. Exit """) if id == 5: # Show triangle menu print(""" TRIANGLE HELP What do you need to solve for? 1. Area 0. Exit """) menu(0)
# Name: dd32.py # Date: 12/13/2013 # Author: Thorin Schmidt from Rectangle import * print("Welcome to the Rectangle Module Tester!") print("First, I'm going to make two rectangles,") print("one with no parameters, and the second") print("with values 6 and 9. Let's see what happens!") input("\nPress a key to see the fun!") rectangle1 = Rectangle() rectangle2 = Rectangle(6,9) print("\nFirst, the length and width:") print("\tRectangle 1 length: ", rectangle1.get_length(), "width: ", rectangle1.get_width()) print("\tRectangle 2 length: ", rectangle2.get_length(), "width: ", rectangle2.get_width()) input("\nPress a key to continue") print("\nNow the perimeters:") print("\tRectangle 1 Perimeter:", rectangle1.perimeter) print("\tRectangle 2 Perimeter:", rectangle2.perimeter) input("\nPress a key to continue") print("\nNow the areas:") print("\tRectangle 1 Area:", rectangle1.area) print("\tRectangle 2 Area:", rectangle2.area) input("\nPress a key to continue") print("\nNow, let's test those set methods....") print("I will attempt to change rectangle 1's") print("length and width to 3 and 7..") input("Press a key to continue") rectangle1.set_length("3") rectangle1.set_width(7) print("\tRectangle 1 length: ", rectangle1.get_length(), "width: ", rectangle1.get_width()) print("\tRectangle 1 Perimeter:", rectangle1.perimeter) print("\tRectangle 1 Area:", rectangle1.area) print("\nCongratulations!") input("\nPress a key to exit...")
""" Program: cylinder_volume.py Author: Michael Rouse Date: 9/3/13 Description: caclulates the volume of a cylinder """ print("Cylinder Volume Problem") radius = int(input("What is the radius? ")) height = int(input("What is the height? ")) # Calculates volume V = Pi * r^2 * h volume = 3.14 * (radius * radius) * height print("The volume of a cylinder with the radius", radius, \ "and the height", height, "is", volume) print("\n\n\nDone...")
""" Program: chapter7_lab4.py Author: Michael Rouse Date: 11/8/13 Description: functions called store_it(list) to save to .dat file and program should get info from .dat file """ import pickle def customer_info(): """ Gets information about customer """ # List of customer information customer = [] # Get customer's full name customer.append(input("What is your first name? ")) customer.append(input("\nWhat is your middle name? ")) customer.append(input("\nWhat is your last name? ")) # Get customer's SSN customer.append(input("\nWhat is your SSN? ")) # Get customer's address customer.append(input("\nWhat is your street address? ")) customer.append(input("\nWhat is your city? ")) customer.append(input("\nWhat is your state? ")) customer.append(input("\nWhat is your zip code? ")) return customer def get_yes_no(question=""): """ Asks user yes or no question, will return False if no and True if yes """ # Ask question user_input = input(question) user_input = user_input.upper() # Check user input if user_input == "NO" or user_input == "N": valid = False elif user_input == "YES" or user_input == "Y": valid = True else: valid = False # Return true or false return valid def store_it(customer): """ Gets data from a binary file and saves to it """ file = "customers.dat" # List of all customers and the one entered customer_list = [] try: # Check if file exists customer_file = open(file, "rb") except: # File does not exist, create it customer_file = open(file, "wb") customer_file.close() else: # File does exist try: # Check for content in file, if it has items in it, add to customer_list customer_list += pickle.load(customer_file) except: # Do nothing pass # Close the file customer_file.close() # At this point the file has been created if it doesn't exist, and data has been read from the file if it has any, add current customer info to the list customer_list.append(customer) # Open file for writing customer_file = open(file, "wb") # Dump customer_list (contains old customers and new customer) into the customer file pickle.dump(customer_list, customer_file) customer_file.close() def get_it(): """ Reads from binary file and displays customer information """ file = "customers.dat" customers = [] try: # Check if file exists by trying to open it customer_file = open(file, "rb") except: # File does not exist, do nothing pass else: # File exists, read from it try: # Try to load from file customers += pickle.load(customer_file) except: # No data in file, do nothing pass # At this point the customers list will be filled with information from .dat file, or left blank if nothing inside of it # Display information in customers list print(customers) print("Customer List:") print("\tID:\t\t Customer Info:") for i in range(0, len(customers)): # Create a string that contains all information about the customer display_info = "\t " + str(i) + "\t\t" + customers[i][0] + " " + customers[i][1] + " " + customers[i][2] + \ "\n\t\t\t"+ customers[i][4] + \ "\n\t\t\t" + customers[i][5] + ", " + customers[i][6] + " " + customers[i][7] + \ "\n\t\t\tSSN: " + customers[i][3] + "\n" print(display_info) def main(): """ Main program """ valid = False while not valid: customer = customer_info() # Display the customer info print("\n\n") print("Customer Info:") print("\t Name: "+customer[0]+" "+customer[1]+" "+customer[2]) print("\t SSN: "+customer[3]) print("\tAddress: "+customer[4]) print("\t "+customer[5]+", "+customer[6]+" "+customer[7]) print("\n\n") # Ask user and check input valid = get_yes_no("Is this correct (Y/N)? ") print("\n\n") # At this point all user input is correct and valid, save the customer to the list store_it(customer) # Display all customers get_it() main() input("\n\nPress the Enter key to exit...")
def returnAsTuple (name, age): # Returns two variables as a tuple tupleToReturn = (name, age) return tupleToReturn def returnAsVars (tupleReceived): # Returns a tuple as two separate variables name = tupleReceived[0] age = tupleReceived[1] return name, age tupleReturned = returnAsTuple("Michael", 17) print("The returnAsTuple function returned:", tupleReturned) name, age = returnAsVars(tupleReturned) print("The returnAsVars function returned the name as:", name) print("The returnAsVars function returned the age as:", age)
""" Program: challenge2_3.py Author: Michael Rouse Date: 8/29/13 Description: Program that calulates a 15% and a 20% tip """ billTotal = float(input("What is the total bill amount? ")) tip15 = billTotal * .15 tip20 = billTotal * .20 print("\nA 15% tip would be: ", tip15) print("\nA 20% tip would be: ", tip20) print("\n\n\nDone...")
""" Program: circle_diameter.py Author: Michael Rouse Date: 9/3/13 Description: Finds the diameter of a circle """ print("Circle Diameter Problem") circleRadius = int(input("What is the radius? ")) # Calculates the diameter D = r + r circleDiameter = circleRadius + circleRadius print("The diameter of a circle with radius", circleRadius, \ "is", circleDiameter) print("\n\n\nDone...")
""" Program: challenge6_1.py Author: Michael Rouse Date: 10/14/13 Description: Improves the ask_number() function so the function can be called with a step value. Make default step value equal to 1 """ def ask_number(question, low, high, step=1): """Ask for a number within a range.""" response = None while response not in range(low, high, step): response = int(input(question)) return response # Test the function by asking for an even number between 0 and 100 print(ask_number("Enter an even number between 0 and 100: ", 0, 100, 2))
import math import copy import operator #f = (path length) + (estimated distance) #计算两点之间的距离(path cost) def path_length_between_2_points(point1, point2): return math.sqrt(math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2)) #所有的点到目标点的预测距离(estimated distance to goal) def estimated_distances_2_goal(intersections, goal): estimated_distances_dict = {} for key in intersections: estimated_distances_dict[key] = path_length_between_2_points(intersections[key], goal) return estimated_distances_dict def estimated_distance_2_goal(point, pGoal): return path_length_between_2_points(point, pGoal) #=================================================================== # Node Start #=================================================================== #路径节点类 class Node(object): def __init__(self): #路径末端状态:1 表示已经到达终点 self.state = 0 #当前路径的长度 self.currentPathLen = 0.0 #总代价 self.cost = 0.0 #指向其他节点 self.parent = None #节点下标 self.pIndex = -1 def __str__(self): path_points = [] parent = self.parent while parent != None: path_points.append(parent.pIndex) parent = parent.parent path_points.reverse() return "PathPoints: %s, Cost: %f" %(str(path_points), self.cost) #=================================================================== # Node End #=================================================================== #=================================================================== # Frontier Start #=================================================================== #边缘类 class Frontier(object): def __init__(self): #前缘节点 self.frontierPoints = {} #前缘节点中cost最小的节点 self.minCostFPoint = None #添加新的前缘节点 def addPoint(self,fNode): if fNode == None: return #当新的前缘节点没有拓展到终点,且前缘节点中cost最小的点已经拓展到终点,且新的前缘节点cost要比minCostFPoint的cost大,很显然没有必要添加到frontier if (self.minCostFPoint != None) and (self.minCostFPoint.state) == 1 and (self.minCostFPoint.cost < fNode.cost): return if fNode.pIndex in self.frontierPoints: oldNode = self.frontierPoints.get(fNode.pIndex) if fNode.cost < oldNode.cost: self.frontierPoints[oldNode.pIndex] = fNode else: self.frontierPoints[fNode.pIndex] = fNode self.__sortDicByCost() #弹出最小cost值的前缘节点 def popMinCostPoint(self): minCostP = self.minCostFPoint; if self.minCostFPoint != None: self.frontierPoints.pop(self.minCostFPoint.pIndex) self.__sortDicByCost() return minCostP #以cost,从小到大进行排序 def __sortDicByCost(self): sortedDic = sorted(self.frontierPoints.items(),key=lambda dict_original:dict_original[1].cost,reverse=False); # print("Sorted Dic:",sortedDic) if len(sortedDic) > 0: self.minCostFPoint = sortedDic[0][1] else: self.minCostFPoint = None #=================================================================== # Frontier End #=================================================================== def getPathByNode(node): path_points = [] if node != None: pNode = node while pNode != None: path_points.append(pNode.pIndex) pNode = pNode.parent path_points.reverse() return path_points def shortest_path(M,start,goal): print("shortest path called") if(start != goal): #计算所有点到目标点的预测距离 #estimated_distances_dict = estimated_distances_2_goal(M.intersections, M.intersections[goal]) #前缘 frontier = Frontier() #已探索列表 exploredSet = set() #初始化起点 startNode = Node() startNode.pIndex = start frontier.addPoint(startNode) #把起点添加到frontier possibleMinCostPoint = None while len(frontier.frontierPoints) > 0: #获取cost最小的前缘节点 minCostFPoint = frontier.popMinCostPoint() if (minCostFPoint != None and minCostFPoint.state == 1) and (possibleMinCostPoint != None and minCostFPoint.cost < possibleMinCostPoint.cost): possibleMinCostPoint = minCostFPoint #添加到已探索列表 if minCostFPoint != None: exploredSet.add(minCostFPoint.pIndex) #cost值最小的前缘节点可拓展的交叉点 roads = M.roads[minCostFPoint.pIndex] for i in range(len(roads)): #1.不能拓展已经搜索过的交叉点; if not(roads[i] in exploredSet): #新的前缘节点 newFNode = Node() newFNode.state = 1 if roads[i] == goal else 0 newFNode.pIndex = roads[i] newFNode.parent = minCostFPoint #起点开始,到该节点的路径总长度 newFNode.currentPathLen = minCostFPoint.currentPathLen + path_length_between_2_points(M.intersections[roads[i]], M.intersections[minCostFPoint.pIndex]) #cost = pathLen + estimatedDistance2Goal newFNode.cost = newFNode.currentPathLen + estimated_distance_2_goal(M.intersections[roads[i]], M.intersections[goal]) #添加前缘节点到fontier frontier.addPoint(newFNode) print("Path:", str(newFNode)) #第一次最先拓展到终点的节点 if newFNode.state == 1 and possibleMinCostPoint == None: possibleMinCostPoint = newFNode #END while=========================================================================== return getPathByNode(possibleMinCostPoint) else: return [goal] #=================================================================== # PathItem Start #=================================================================== #路径类 class PathItem(object): def __init__(self): #路径中的点列表 self.path_points = [] #路径中的点列表坐标字典 self.path_points_dict = {} #当前路径的长度 self.current_path_len = 0.0 #评估结果: path length + estimated distance self.evaluated_result = 0.0 #路径末端的点 self.frontier_index = 0 def __str__(self): return "Points: %s, 评估结果值: %f" %(str(self.path_points), self.evaluated_result) def addPathPoint(self, point_index, pointXY, pointGoal): currentLen = len(self.path_points) #新加入节点到目标的预测距离 estimated_distance = estimated_distance_2_goal(pointXY, pointGoal) if currentLen > 0: self.current_path_len += path_length_between_2_points(self.path_points_dict[self.path_points[currentLen - 1]], pointXY) self.evaluated_result = self.current_path_len + estimated_distance self.path_points.append(point_index) self.frontier_index = point_index self.path_points_dict[point_index] = pointXY #拓展路径 def expandPath(self, point_index, pointXY, pointGoal): expandedPath = copy.deepcopy(self) pointSize = len(expandedPath.path_points) #新加入节点到目标的预测距离 estimated_distance = estimated_distance_2_goal(pointXY, pointGoal) if pointSize > 0: expandedPath.current_path_len += path_length_between_2_points(expandedPath.path_points_dict[expandedPath.path_points[pointSize - 1]], pointXY) expandedPath.evaluated_result = expandedPath.current_path_len + estimated_distance expandedPath.path_points.append(point_index) expandedPath.frontier_index = point_index expandedPath.path_points_dict[point_index] = pointXY return expandedPath #=================================================================== # PathItem End #=================================================================== def shortest_path1(M,start,goal): print("shortest path called") if(start != goal): #计算所有点到目标点的预测距离 #estimated_distances_dict = estimated_distances_2_goal(M.intersections, M.intersections[goal]) #查找过程中所有拓展路径字典 expandedPathDict = {} #最短路径Index shortestPathIndex = 0 #初始化起点 startPath = PathItem() startPath.addPathPoint(start, M.intersections[start],M.intersections[goal]) expandedPathDict[0] = startPath while True: #========拓展路径 START ======== #获取预测结果最短的路径 shortestPath = expandedPathDict[shortestPathIndex] #获取最短路径最后一个路径节点(边缘)的下标 shortestFontierIndex = shortestPath.frontier_index roads = M.roads[shortestFontierIndex] #边缘节点可拓展的交叉点 pathPointSet = set(shortestPath.path_points) #最短路径的所有节点 count = 0 for i in range(len(roads)): #1.不能拓展已经搜索过的交叉点(已经添加到路径中的节点); 2.排除闭环路径(不能再进行拓展的路径) diffSet = pathPointSet.symmetric_difference(set(M.roads[roads[i]]))#路径边缘节点的下一个节点的roads的不重复的元素集合 if not(roads[i] in pathPointSet) and not(len(diffSet) == 0):#要是diffSet等于0,则会形成闭环路径 expandedPath = shortestPath.expandPath(roads[i], M.intersections[roads[i]], M.intersections[goal]) if count == 0: expandedPathDict[shortestPathIndex] = expandedPath else: expandedPathDict[len(expandedPathDict)] = expandedPath count +=1 #========拓展路径 END ======== #拓展路径后,重新确定f(path)最小的路径 for key in expandedPathDict: shortestPath = expandedPathDict[shortestPathIndex] if expandedPathDict[key].evaluated_result <= shortestPath.evaluated_result: shortestPathIndex = key #当路径已经拓展到目的地,且已经拓展到目的地的路径的评估结果(f(path) = path cost so far + estimated distance) 的值最小时,结束循环 if(goal in set(expandedPathDict[shortestPathIndex].path_points)): break; return expandedPathDict[shortestPathIndex].path_points else: return [goal] #Jiangchun #[email protected] #May 25, 2019 20:52 #May 26, 2019 22:16
#(5) キーボードから入力した数に 25000 を足したものが,3500*9 と等しいかどうかを判定するプログラムを作ります. # 以下の順で命令を実行しなさい. # 1. 変数 x に数値を入力する # 2. if で x+25000 と 3500*9 が等しいかどうか判定する. # 3. 等しいなら OK を,そうでなければ Boo を表示する. x = int(input()) if x+25000 == 3500*9: print('OK') else: print('Boo')
#数を 10個入力してその合計を表示するプログラムを作りなさい #2 print('10個の数値を入力してください') num = [int(input())for i in range(10)] #list print('合計値:',end="") print(sum(num))
#5 # 配列の最後に新しい数字(11)を追加する.サンプル配列:[1,3,5,7,9]出力配列:[1,3,5,7,9,11] list_num = [1,3,5,7,9] print(list_num) list_num.append(11) print(list_num)
data = [sorted(map(int, x.split("x"))) for x in open("input.txt")] print(sum(3 * a * b + 2 * b * c + 2 * a * c for a, b, c in data)) print(sum(2 * (a + b) + a * b * c for a, b, c in data))
import numpy as np def count(a): return np.sum(np.sum(a, axis=1) > 2 * np.max(a, axis=1)) a = np.loadtxt("input.txt") print(count(a)) print(count(np.vstack([a[i::3].flatten() for i in range(3)]).T))
def drawline(l,lab=''): line='-'*l if lab: line+=' '+lab print(line) def interval(dist): if dist>0: drawline(dist-1) drawline(dist) drawline(dist-1) def ruler(inches,maxtickl): drawline(maxtickl,'0') for i in range(1,inches+1): interval(maxtickl-1) drawline(maxtickl,str(i)) a=ruler(5,5)
# coding=utf-8 import asyncio import ccxt import time import _thread import datetime #Basic math and String creation x = sum([1, 0]) if x == 1: print("0 + 1 = %s" % (x)) y = 2 if sum([x, y]) == 3: z = sum([x, y]) print("This should count up: %s, %s, %s" % (x, y, z)) #Opens or creates a file named "abc" file = open("abc", "w") #Gets the current date/time date = datetime.datetime.now() #Write to the open document file.write("%s %s \n" % (date, x)) file.write("%s %s \n" % (date, y)) file.write("%s %s \n" % (date, z)) #Saves the written data to the document, then closes it file.flush() file.close()
import random import locale def main(): #csv with mortality rates for ages 0-119. No labels. #format: "Male prob, Female prob \n" file = "mortalityrates.csv" prob_file = open(file, "r") prob = prob_file.readlines() locale.setlocale(locale.LC_ALL, '') print("Welcome to the annual premium calculator!") print("Determine the annual premium each policy holder should pay for " + "your insurance company to break even.") finished = False while not finished: policy, cumdead = get_data(prob) premium, net = optimize(policy, cumdead) print("The annual premium for this policy holder should be " + locale.currency(premium, grouping=True)+ ".") print("At this rate, the profit per policy holder would be around "+ locale.currency(net, grouping=True)+ ".") done = input("Would you like to look at another policy? ") if done[0].lower() == "n": print("Thank you for using the annual premium calculator!") finished = True def get_data(prob): #Male = 0, Female = 1 sex = None while sex == None: sex_input = input("Enter the sex (M/F) of the policy holder: ") if sex_input[0].lower() == "m": sex = 0 elif sex_input[0].lower() == "f": sex = 1 age = "NO" while not age.isdigit(): age = input("Enter the integer age of the policy holder: ") if age.isdigit() and (( sex == 1 and int(age) > 93) or (sex == 0 and int(age) > 92)): print("Not a valid age") age = "NO" age = int(age) policy = [] cum_dead = [0] i = 0 dead = 0 while i < 20: policy.append(float(prob[age + i].split(",")[sex])) dead += float(prob[age + i].split(",")[sex]) cum_dead.append(dead) i += 1 return (policy, cum_dead) def optimize(policy, cum_dead): premium = (sum(policy) * 100000)/20 finished = False i = 0 while not finished: net = test_premium(premium, policy, cum_dead) if net < .19 and net > 0: finished = True elif net < 0: premium += .01 else: premium -= .01 return (premium, net) def test_premium(premium, policy, cum_dead): net = 0 for i in range(len(policy)): net += (premium * (1-cum_dead[i])) net -= cum_dead[-1] * 100000 return net main()
''' 문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/42578 ''' def solution(clothes): clothes_dict = {} for clothing, part in clothes: if part not in clothes_dict: clothes_dict[part] = [clothing] # key : 옷종류 / value : [옷이름] else: clothes_dict[part].append(clothing) part_list = [] answer = 1 for key in clothes_dict.keys(): answer *= len(clothes_dict[key]) + 1 return answer - 1 print(solution([["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]]) == 5) print(solution([["crow_mask", "face"], ["blue_sunglasses", "face"], ["smoky_makeup", "face"]]) == 3)
''' 문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/12925 ''' def solution(s): answer = int(s) return answer print(solution('1234') == 1234) print(solution('-1234') == -1234)
''' 문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/12915 ''' def solution(strings, n): return sorted(sorted(strings), key=lambda x: x[n]) print(solution( ["sun", "bed", "car"], 1) == ["car", "bed", "sun"]) print(solution( ["abce", "abcd", "cdx"], 2) == ["abcd", "abce", "cdx"])
import sys, os from socket import * # Establece el nombre y el puerto del servidor (serán dos parámetros # pasados por la línea de comandos). if(len(sys.argv) > 2): server_name=sys.argv[1] server_port = int(sys.argv[2]) else: print ("Uso: python cliente_interactivo server_name server_port") sys.exit(1) # Obtiene la dirección IP correspondiente al servidor. server_address = gethostbyname(server_name) # Crea un socket. connection_socket = socket(AF_INET,SOCK_STREAM) # Conecta el socket al servidor. connection_socket.connect((server_address, server_port)) # El actual proceso se divide en dos: # 1. Proceso padre: se encarga de leer los mensajes procedentes del # servidor y de imprimirlos en pantalla # 2. Proceso hijo: recoge mensajes de la entrada estándar y los envía al # servidor pid = os.fork() if pid != 0: # Entrando en el proceso padre # Permite leer del socket como si de un fichero se tratase. incoming_stream = connection_socket.makefile("r") print ("El cliente acepta mensajes del servidor") # Se entra en un bucle: cada vez que el servidor envía un mensaje lo # imprimimos # Si el mensaje es salir el servidor quiere desconectarse por lo que # el cliente no aceptará más mensajes while True: msg = incoming_stream.readline() print (msg) if msg == "salir\n": break # Se cierran los sockets incoming_stream.close() connection_socket.close() print ("Servidor desconectado. Si no está desconectado escriba salir") os.waitpid(pid, 0) else: # Entrando en el proceso hijo # Permite escribir en el socket como si de un fichero se tratase. outgoing_stream = connection_socket.makefile("w") print ("El cliente permite mandar mensajes al servidor") # Se entra en un bucle: se lee de la entrada estándar (teclado) los # mensajes y se envían al servidor. Para desconectar escribimos salir while True: msg = raw_input() outgoing_stream.write(msg + "\n") outgoing_stream.flush() if msg == "salir": break # Se cierran los sockets . outgoing_stream.close() connection_socket.close() # Fin del proceso hijo sys.exit(0)
#!/usr/bin/env python import sys # input comes from STDIN (standard input) for line in sys.stdin: try: custID = "-1" name = "-1" countrycode = "-1" transID = "-1"#default sorted as first # remove leading and trailing whitespace line = line.strip() # split the line into words split = line.split(",") if len(split[1]) > 6: custID = split[0] name = split[1] countrycode = split[3] else: transID = split[0] custID = split[1] # write the results to STDOUT (standard output); # what we output here will be the input for the # Reduce step, i.e. the input for reducer.py # # ','-delimited; print '%s,%s,%s,%s' % (custID, name, countrycode, transID) except:#errors are going to make your job fail which you may or may not want pass
import numpy as np X_array = np.array([0.43, 0.48, 0.55, 0.62, 0.70, 0.65, 0.67, 0.69, 0.71, 0.74], dtype=float) Y_array = np.array([1.63597, 1.73234, 1.87686, 2.03345, 2.22846, 2.35973, 2.52168, 2.80467, 2.98146, 3.14629], dtype=float) def lagrange(x, y, p): result = 0 for j in range(len(y)): p1 = 1 p2 = 1 for i in range(len(x)): if i == j: p1 = p1 * 1 p2 = p2 * 1 else: p1 = p1 * (p - x[i]) p2 = p2 * (x[j] - x[i]) result = result + y[j] * p1 / p2 return result print("=== Вариант № 2 точка 0.512 ===") print("=== f(0.512): ==================") print("=== " + str(lagrange(X_array, Y_array, 0.512)) + " ==========")
import os import csv # define read path (run from Python-Challenge folder) csvpath = os.path.join("Pypoll", "Resources/election_data.csv") # define write path for output (run from Python-Challenge folder) output_path = os.path.join("PyPoll", "Output/PyPoll.txt") # C:\Users\westl\Desktop\Python-Challenge\Python-Challenge\PyPoll\Resources\election_data.csv with open(csvpath, newline="") as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") # designate header row csv_header = next(csv_reader) # define dictionary results = {} # define variables total_votes = 0 # create for loop for row in csv_reader: # calculate total vote count and create dictionary to use candidate name only once # counts votes for each candidate total_votes = total_votes + 1 if row[2] in results.keys(): results[row[2]] = results[row[2]] + 1 else: results[row[2]] = 1 # create lists for candidates, vote counts, and percentage candidates = [] votes = [] percent_vote = [] # takes the dictionary keys and values puts into the lists candidates and votes lists for key, value in results.items(): candidates.append(key) votes.append(value) # takes the number of votes and divides by total for each candidate to give percentage for x in votes: percentage = round(x/total_votes*100,3) percent_vote.append(percentage) # zips data to create new cleaned up list zip_data = list(zip(candidates,votes,percent_vote)) # loops through zipped data to get winner that has most votes for y in zip_data: if max(votes) == y[1]: winner = y[0] # generate print statmeents print("Election Results") print("-------------------------") print(f"Total Votes: {str(total_votes)}") print("-------------------------") for i in range(len(candidates)): print(f"{candidates[i]}: {str(percent_vote[i])}% ({str(votes[i])})") print("-------------------------") print(f"Winner: {str(winner)}") print("-------------------------") # open the file using "write" mode with open(output_path, 'w') as txtfile: # rite the print statements including '\n' to dictate end of line txtfile.write("Election Results\n") txtfile.write("-------------------------\n") txtfile.write(f"Total Votes: {str(total_votes)}\n") txtfile.write("-------------------------\n") for i in range(len(candidates)): txtfile.write(f"{candidates[i]}: {str(percent_vote[i])}% ({str(votes[i])})\n") txtfile.write("-------------------------\n") txtfile.write(f"Winner: {str(winner)}\n") txtfile.write("-------------------------\n")
# -*- coding: utf-8 -*- """ Created on Mon Nov 16 15:31:07 2020 @author: Manika """ import pandas as pd df1 = pd.read_csv("glassdoor_jobs.csv") #-----SALARY COLUMN------------------------------------------------------------ #Remove negative salary from the salary Estimate df1 = df1.loc[df1["Salary Estimate"]!="-1"] #Removing the glassdoor company name from the salary column salary = df1["Salary Estimate"].apply(lambda x: x.split("(")[0]) #Removing the "K" and "$" sign from the salary column minus_kd = salary.map(lambda x: x.replace("K","").replace("$","")) minus_kd_edit = minus_kd.map(lambda x: x.lower().replace("per hour", "").replace("employer provided salary:","")) #------------------------------------------------------------------------------ #------------------ COMPANY NAME COLUMN --------------------------------------- df1["Company name"] = df1.apply(lambda x: x["Company Name"] if x["Rating"]<0 else x["Company Name"][:-3], axis=1) #------------------------------------------------------------------------------ #------------------ LOCATION -------------------------------------------------- df1["Company State"] = df1["Location"].apply(lambda x: x.split(",")[1]) comp_no_dict = dict(df1["Company State"].value_counts()) print(comp_no_dict) #------------------------------------------------------------------------------ #Adding column in main dataframe df1["Hourly"] = df1["Salary Estimate"].apply(lambda x: 1 if "Per Hour" in x else 0) df1["Employer_provided"] = df1["Salary Estimate"].apply(lambda x: 1 if "employer provided salary:" in x.lower() else 0) df1["Min salary"] = minus_kd_edit.apply(lambda x: x.split("-")[0]).astype('int') df1["Max Salary"] = minus_kd_edit.apply(lambda x: x.split("-")[1]).astype("int") df1["Average Salary"] = (df1["Min salary"] + df1["Max Salary"])/2 df1["Same state"] = df1.apply(lambda x: 1 if x["Location"]==x["Headquarters"] else 0, axis=1) df1["Company age"] = df1["Founded"].apply(lambda x: x if x<0 else 2020-x) df1.drop(["Unnamed: 0"], axis=1, inplace=True) df1.to_csv("Glass")
import tkinter as tk from tkinter import ttk def convert_meters_to_feet(): m_str = input_value.get() or '0' try: m = float(m_str) feet = 3.28084 * m msg = f'{feet:.2f}' except ValueError: msg = 'Invalid input' output_value.set(msg) root = tk.Tk() root.title("Unit Converter") # in this variable we store the input input_value = tk.StringVar() output_value = tk.StringVar() main = ttk.Frame(root, padding=(30, 50)) main.grid() meters_label = ttk.Label(main, text="Meters:") meters_input = ttk.Entry(main, width=10, textvariable=input_value) feet_label = ttk.Label(main, text="Feet:") feet_display = ttk.Label(main, text="Feet output", textvariable=output_value) calc_button = ttk.Button(main, text="Convert", command=convert_meters_to_feet) quit_button = ttk.Button(main, text="Quit", command=root.destroy) meters_label.grid(column=0, row=0, sticky="W") meters_input.grid(column=1, row=0, sticky="EW") meters_input.focus() feet_label.grid(column=0, row=1, sticky="W") feet_display.grid(column=1, row=1, sticky="EW") calc_button.grid(column=0, row=2, columnspan=2, sticky="EW") quit_button.grid(column=0, row=3, columnspan=2, sticky="EW") root.mainloop()
"""" Calculate the hourglass sum for every hourglass in 2D array, then print the maximum hourglass sum. """ import sys arr = [] for arr_i in xrange(6): arr_temp = map(int,raw_input().strip().split(' ')) arr.append(arr_temp) max = -100 for i in range(4): for j in range(4): sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2] if max < sum: max = sum print(max) # making 2D array # from array import * # rows, cols = (5, 5) # arr = [[0]*cols]*rows # arr = [[0 for i in range(cols)] for j in range(rows)] # print(arr) # OR # rows = int(input()) # cols = int(input()) # matrix = [] # for i in range(rows): # row = [] # for j in range(cols): # row.append(0) # matrix.append(row) # print(matrix)
#Lathika and Calvin #Oct.15 2020 #Random Quotes Program #1 Import tkinter and random (modules) #2 create a function that runs when the button is pressed #2.1 Store the quotes with number variables because they are easy to read #2.2 Get a random number from the random module to get what quote will be printed # Print the quote based on the random number generated using if statements #3 Define the window and title #4 Run the main loop #Step 1. Import the 2 modules that we need to use import tkinter as tk import random as rand #Step 2. Define the code that happens when the button is pressed def buttonPress(): #Step 2.1. Have all the quotes in easy to name variables one = "'You don't need a license to drive a sandwich.' - Spongebob" two = "'Remember licking doorknobs is illegal on other planets' - Spongebob" three = "'The best time to wear a wear a striped sweater...is all the time' - Spongebob" four = "'Well first, we have to balance a glassof chocolate milk on our heads, stand on one foot, and sing the Bikini Bottom Anthem' - Spongebob" five = "'Well it's no secret that the best thing about secrets is telling someone else your secret, therby adding another secret to your collection of secrets, secretly' -Spongebob" five = "'I smell the smelly smell of something that smells...smelly' -Mr.Krabs" six = "'This isn't your average everyday darkness.This is...ADVANCED darkness' - Spongebob" seven = "'Look at all the hip, young people eating sal...ads' -Spongebob" eight = "'Oh, I wish I had a nose' -Patrick" nine = "Being grownup is boring. Besides I don't get jazz.' -Patrick" ten = "'You know whats funnier than 24? 25' - Spongebob" #Step 2.2. Get a random number for which quote to use quoteNum = rand.randint(1,10) #Step 2.3. Say the quote based on the random number if quoteNum >= 5: if quoteNum == 5: tk.Label(window, text = five).pack() if quoteNum == 6: tk.Label(window, text = six).pack() if quoteNum == 7: tk.Label(window, text = seven).pack() if quoteNum == 8: tk.Label(window, text = eight).pack() if quoteNum == 9: tk.Label(window, text = nine).pack() if quoteNum == 10: tk.Label(window, text = ten).pack() elif quoteNum < 5: if quoteNum == 4: tk.Label(window, text = four).pack() if quoteNum == 3: tk.Label(window, text = three).pack() if quoteNum == 2: tk.Label(window, text = two).pack() if quoteNum == 1: tk.Label(window, text = one).pack() #Step 3. Define the window and title window = tk.Tk() window.title("Random Quotes") #Step 4. Define the button and how its placed randomButton = tk.Button(window, text="Press for a random Quote", command = buttonPress) randomButton.pack() #Step 5. Run the main loop window.mainloop()
#Escribe un programa que pida por teclado el radio de una circunferencia, y que a #continuación calcule y escriba en pantalla la longitud de la circunferencia y del área del círculo. import math valor = int(input("Introduzca el radio de una circunferencia: ")) def longitud(radio): longitudCircunferencia = math.pi * (radio*2) print (longitudCircunferencia) def area(radio): areaCircunferencia = math.pi * (radio**2) print (longitudCircunferencia) longitud(valor) area(valor)
# - Trabalho - Estacionamento # Versão Aula05 # Autor: Ivonei Marques vagas = [True]*20 # True significa vaga livre # False significa vaga ocupada # as listas abaixo estão inicializadas apenas para testes. l_hEntrada = ["11:11","10:10","13:13"] l_hSaida = [" : "," : "," : "] l_Placa = ["AAA1111","AAA2222","AAA3333"] l_Box = ["3","6","11"] vagas[2] = False vagas[5] = False vagas[10] = False def localizaPlacaNoBox(box): ''' retorna a placa que ocupa determinado box ''' for ind,b in enumerate(l_Box): #[::-1]: if b == str(box+1) and l_hSaida[ind] == " : ": return l_Placa[ind] def livreOcupada(vaga,i): if vaga: # Se vaga True (livre) retorna a palavra 'LIVRE' return " Livre " return localizaPlacaNoBox(i) # Caso contrário retorna a PLACA # que ocupa esta vaga def imprimeVagas(): ''' imprime na tela o mapa com box livres e ocupados ''' print("\n"*15) print("Mapa de Vagas:") print(("box"+" "*10)*5) # igual a "box "*5 # verifica na lista boleana de vagas se a posição está # True (livre), ou False (ocupada). Se estiver ocupada # retorna a placa for ind,v in enumerate(vagas): print("%2d [%s]" %((ind+1),livreOcupada(v,ind)),end=" " ) if (ind+1)%5 == 0: print() def menu(): m = ''' ######################################## Menu ######################################## 1- Registrar Entrada de Veículos 2- Registrar Saída de Veículos 3- Relatório 0- Fim ######################################### Escolha: ''' return input(m) def placaOk(placa): ''' verifica se a placa está dentro dos critérios. Neste caso apenas se possui 7 caracteres. ''' if len(placa) == 7: return placa.upper() print("...Erro. ") return placaOk(input("Placa: ")).upper() def horaES_Ok(): ''' Esta função tem a finalidade de capturar a data do sistema e armazená-la como horário de entrada e saída do veículo. ''' def horaMinuto(t): if t < 10: return "0"+str(t) return str(t) from datetime import datetime hora = datetime.now() return horaMinuto(hora.hour)+":"+horaMinuto(hora.minute) def boxOk(boxE): ''' verifica se o box digitado existe, ou já está ocupado ''' try: if vagas[int(boxE)-1]: vagas[int(boxE)-1] = False return boxE else: print("....Erro. Box já ocupado.") except: print("....Erro. Box inexistente.") return boxOk(input("Box: ")) def boxSaidaOk(boxE): ''' verifica se o box digitado existe ou está livre ''' try: if not vagas[int(boxE)-1]: vagas[int(boxE)-1] = True return boxE else: print("....Erro. Box Não ocupado.") except: print("....Erro. Box inexistente.") return boxSaidaOk(input("Box: ")) def registraEntrada(): ''' insere nas listas os dados de entrada ''' l_Placa.append(placaOk(input("Placa: "))) l_hEntrada.append(horaES_Ok()) l_Box.append(boxOk(input("Box: "))) l_hSaida.append(" : ") def ehPlaca(placa): ''' verifica se a placa é válida ''' if len(placa.upper()) == 7: return True return False def ehBox(bx): ''' verifica se o box digitado é válido. ''' if int(bx) in range(1,21): return True return False def localizaPlaca(placa): ''' recebe o argumento placa, verifica se a placa digitada é a mesma cadastrada e, verifica o horario de saída e retorna o indice da l_Placa. ''' for i,x in enumerate(l_Placa): if x == placa.upper() and l_hSaida[i] == " : ": return i return "....Erro. Placa Não localizada." def localizaBox(bx): ''' recebe o argumento bx como sendo o box digitado e retorna o indice desse box na lista. Ou retorna uma mensagem de erro ''' i_box = int(bx)-1 for i,x in enumerate(l_Box): # retorna o indice do box digitado quando a saída não foi # ainda efetivada if x == bx and l_hSaida[i] == " : ": return i return "....Erro. Box Não existente, ou Box não ocupado." def registraSaida(): ''' Função que localiza o veículo pela placa ou pelo box, e efetiva sua saída atualizando o horário de saída na lista l_hSaida (horasES_Ok()) e também atualiza a lista vagas[] com True (liberada) ''' strSaida = input("Placa ou Box: ") # verifica se o que foi digitado é uma placa if ehPlaca(strSaida): indPlaca = localizaPlaca(strSaida) # localiza o indice da placa digitada # se o retorno do método localizaPlaca() for uma string # é porque a placa não existe, imprimindo uma mensagem de erro # na variável indPlaca if type(indPlaca) == str: print(indPlaca) else: # significa que localizou o indice da placa l_hSaida[indPlaca] = horaES_Ok() # retorna o horário de # de saída do sistema vagas[int(l_Box[indPlaca])-1] = True # libera o box # verifica se o que foi digitado é um box elif ehBox(strSaida): indBox = localizaBox(strSaida) # localiza o indice do box (l_box) pelo valor do box digitado # se o retorno for uma string. É uma mensagem de erro if type(indBox) == str: print(indBox) # imprime a mensagem como string else: # significa que localizou o indice do box l_hSaida[indBox] = horaES_Ok()# retorna o horário de saída # do sistema vagas[int(strSaida)-1] = True # libera o box # Se o digitado não for um box ou uma placa. Mensagem de erro # e chama a função novamente por recursão else: print("....Erro. Você não digitou um Box válido ou uma Placa válida.") registraSaida() def relatorio(): ''' Impressão do movimento do dia. Apresenta todas entradas e saidas do dia. Apresenta também o total do dia. ''' def calculaValorDoDia(qtVeiculos): ''' Esta função existe porque entende-se que a realização do calculo do caixa é uma funcionalidade do programa ''' return qtVeiculos * 15 def contaQtVeiculos(qt): ''' Esta função existe para imprimir o relatório e retornar a quantidade de veículos que já deixaram o estacionamento. ''' for i in range(len(l_Box)): # verifica se o veiculo já tem um horario de saída if l_hSaida[i] != " : ": print(l_Placa[i].rjust(10,' '),l_hEntrada[i].rjust(10,' '),l_hSaida[i].rjust(10,' '),l_Box[i].rjust(5,' ')) qt += 1 return qt print("Relatório:".center(50,'-')) print("Veículo:".rjust(10,' '),"H.Entrada:".rjust(12,' '),"H.Saida:".rjust(10,' '),"Box:".rjust(5,' ')) # calcula a quantidade de veículos que passou pelo estacionamento qtVeiculos = contaQtVeiculos(0) print("-"*50) print("Total de veículos do dia: %d " % qtVeiculos) # realiza o calculo do caixa do dia print("Total: %.2f Reais" % calculaValorDoDia(qtVeiculos)) print("-"*50) input("Enter para voltar ao menu.") ################################################################# # programa Principal ################################################################# ''' Este laço infinito tem a finalidade de ler a opção de esolha e direcionar o código para a função desejada. ''' while True: imprimeVagas() # monta o mapa de box livres e ocupados escolha = menu() # retorna uma das opções do menu # decide qual função chamar conforme a opção escolhida if escolha == '0': break elif escolha == '1': registraEntrada() elif escolha == '2': registraSaida() elif escolha == '3': relatorio()
def testargs(*args): return sum(args) print(testargs(1,2,1,5,4,56,4,6,4,6,4,5)) def testkwargs(**kwargs): ## Key word arguments if 'fruit' in kwargs: print('my fruit of choice is {}'.format(kwargs['fruit'])) else: print("i did not find any fruites here") def myfunc(*args,**kwargs): print(f"i would like {args[0]} {kwargs['food']}") testkwargs(fruit='apple',veggie='tomato') myfunc(1,2,3,4,5,6,food='mago',choc='jelly') listof=[1,2,3,45] listof.append(56) print(listof)
""" 一次性读全部 """ import os def readfile_original(): try: f = open('D:\\python_workspace\\test.txt', 'r', encoding='UTF-8') print(f.read()) except FileNotFoundError: print("文件不存在") # finally: # if f: # f.close() def readfile_new(): """ 默认关闭文件流形式 :return: """ with open('D:\\python_workspace\\test.txt', 'r', encoding='UTF-8') as f: print(f.read()) """ 按行读 """ def readLine(): with open('D:\\python_workspace\\test.txt', 'r', encoding='UTF-8') as f: for line in f.readlines(): print(line.strip()) # 当前py文件所在的绝对路径 curPath=os.path.abspath(os.path.dirname(__file__)) print(curPath) # 当前项目根路径 rootPath = curPath[:curPath.find("learning_python\\")+len("learning_python\\")] print(rootPath) # 获取xxx文件路径 xxx_file_path = os.path.abspath(rootPath+"com\\__init__.py") print(xxx_file_path) # 传统语法 readfile_original() # 新语法 readfile_new() # 按行读 readLine()
""" 变量定义学习 """ def test(): val = 100 for i in range(val): print(i) cal(i, 1) def cal(va11, val2): print(va11 + val2) class HelloWorld(object): def __init__(self): self.name = "hello,luoyq" def sayhello(self): print(self.name)
import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import random def fun(x, y): """ Computes the function f(x) = x^2 + xy + y^2 at position (x, y) :param x: The value of x to evaluate f() at :param y: The value of y to evaluate f() at :return: the value f(x, y) """ return x**2 + x*y + y**2 def gradient(x, y): """ Computes the gradient vector of f(x) = x^2 + xy + y^2 at position (x, y) :param x: The x to evaluate the gradient at :param y: The y to evaluate the gradient at :return: The gradient vector at position (x, y) """ deriv_x = 2*x + y deriv_y = x + 2*y return np.array([deriv_x, deriv_y]) class GradientDescent: """ Performs gradient descent on convex functions """ def __init__(self, initial_point, function, gradient, learning_rate, ax): """ :param initial_point: The initial point :param function : The function that we want to minimize :param gradient: The gradient of the given function :param learning_rate: The learning rate of gradient descent :param ax: The axis at which to plot the intermediate points at """ self.initial_point = initial_point self.function = function self.gradient = gradient self.current_point = np.array([*initial_point]) self.learning_rate = learning_rate self.epsilon = 10**(-10) self.ax = ax def descent(self): """ Performs gradient descent """ while True: # Compute the next point by using the gradient and the learning rate new_point = self.current_point - self.learning_rate * self.gradient(self.current_point[0], self.current_point[1]) # Stop if there is no substantial progress # Note that since in machine learning the generalization error is usually # more sought after than the true minimum, this is not a problem if np.all(np.isclose(new_point, self.current_point, atol=self.epsilon)): break # Update the point self.current_point = new_point # Graph the progress x, y = self.current_point[0], self.current_point[1] ax.plot([x], [y], [self.function(x, y)], marker='x', color='red') if __name__ == "__main__": # Plot a simple surface for the function f(x) = x^2 + xy + y^2 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = y = np.arange(-10, 10, 0.1) X, Y = np.meshgrid(x, y) zs = np.array([fun(x, y) for x, y in zip(np.ravel(X), np.ravel(Y))]) Z = zs.reshape(X.shape) ax.plot_surface(X, Y, Z, alpha=0.5) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('f(x, y)') # Generate a random starting point initial_point = np.random.rand(1, 2)[0] * 10 * random.choice([1, -1]) # Do the gradient descent step gradient_descent = GradientDescent(initial_point, fun, gradient, 0.1, ax) gradient_descent.descent() # Plot the final result plt.show() # Print the final output. This should be roughly (0, 0) since the chosen function is convex. print(gradient_descent.current_point)
import os txt_file = os.path.join(".", "Homework_Python_Word_Counter.txt") alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] with open(txt_file, "r") as tf: data = tf.read() letter_count = 0 words = len(data.split()) sentences = data.count(". ") + 1 for letter in alpha: under = data.count(letter) letter_count += under avg_letters = (letter_count / words) avg_words = words / sentences print("Paragraph Analysis") print("------------------") print("Approximate Word Count: " + str(words)) print("Approximate Sentence Count: " + str(sentences)) print("Average Letter Count: " + str(avg_letters)) print("Average Word Count: " + str(avg_words))
class Node: def __init__(self, value=None, next_node=None): self.next_node = next_node self.value = value def __str__(self): return str(self.value) class SortedList: """ Сортированный связный список. Хорошо работает при редких добавлениях новых элементов. """ def __init__(self, value=None, next_node=None): self.next_node = next_node self.value = value # Ограничители self.top = Node() self.bottom = Node(1000) self.top.next_node = self.bottom def append(self, value): """ Добавление нового элемента в сортированный однонаправленный список. Время работы O(N). """ # Находим ячейку перед той, в которую будем вставлять новый элемент. current = self.top # Цикл всегда будет доходить до конца, # так как нижний ограничитель содержит максимальное из возможных значений. while current.next_node.value < value: current = current.next_node # Вставляем новую ячейку после current new_node = Node(value) new_node.next_node = current.next_node current.next_node = new_node def __str__(self): """ Возвращает все элементы связного списка в виде строки. """ current = self.top.next_node values = "[" while current is not None and current.value < 1000: end = ", " if current.next_node and current.next_node.value < 1000 else "" values += str(current) + end current = current.next_node return values + "]"
def selection_sort(values): """ Сортировка выбором. """ # Перебираем все элементы. for i in range(len(values) - 1): min_idx = i # Перебираем оставшиеся элементы. for j in range(i + 1, len(values)): # Ищем минимальное значение. if values[min_idx] > values[j]: min_idx = j if i != min_idx: # Меняем минимальное значение с текущим элементом основного цикла. values[i], values[min_idx] = values[min_idx], values[i]
def binary_search(array, value): """ Возвращает индекс искомого элемента (value) в отсортированном массиве. Если в массиве более одного искомого элемента, то функция не гарантирует, что найденный будет первым. Возвращает -1 если элемент не найден. """ min_index = 0 max_index = len(array) - 1 # Цикл до тех пор, пока min и max не встретятся while min_index <= max_index: # Вычисляем средний элемент. middle_index = (min_index + max_index) // 2 # Меняем max_index и min_index. if value < array[middle_index]: max_index = middle_index - 1 elif value > array[middle_index]: min_index = middle_index + 1 else: return middle_index # Возвращаем -1 если элемент не найден return -1
class Cell: """ Ячейка для сортированного связного списка. """ def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def bucketsort(array, num_buckets): """ Блочная сортировка массива array. """ # Создаем блоки, в которые помещаем пустые связные списки. buckets = [] for i in range(num_buckets): buckets.append(Cell()) # Вычисляем максимальны элемент в массиве. max_value = max(array) # Рассчитываем количество значений в корзине. items_per_bucket = (max_value + 1) / num_buckets # Распределяем данные по корзинам. for value in array: # Вычисляем номер корзины. backet_num = int(value / items_per_bucket) # Вставляем элемент в корзину сразу с обратной сортировкой. current = buckets[backet_num].next_node prev = buckets[backet_num] while current and current.value > value: prev = current current = current.next_node # Вставляем новую ячейку после предыдущей. new_cell = Cell(value) new_cell.next_node = prev.next_node prev.next_node = new_cell # Отправляем элементы обратно в массив. # При этом перебираем блоки в обратном порядке. b = num_buckets - 1 index = 0 while b >= 0: cell = buckets[b].next_node b -= 1 while cell is not None: array[index] = cell.value index += 1 cell = cell.next_node
import pandas as pd from pathlib import Path from .Recommender import recommend_movies from fuzzywuzzy import fuzz, process base_path = Path('data/') file_movies = base_path / 'movies.csv' movies = pd.read_csv(file_movies) my_movies = [] def list_of_movies(): """Take an input string from a user and return a list of movies that are similar using fuzzy logic. Returns: [list]: list of movies """ input_movie = input("Find a movie to rate: ") movie_choices = process.extract(input_movie, movies['title'], limit=100, scorer=fuzz.partial_ratio) return [movie for movie in movie_choices if movie[1] > 85] def add_movies(): """This is the main function called from main. It keeps asking the user to add movies and rankings until 5 movies are scored. Once 5 movies are scored you can either keep adding as many movies as you like or you can get a list of recommended movies. """ while True: # Take a user input string and return a list of movies. listmovies = list_of_movies() # If No Movies returned search again. if len(listmovies) == 0: print("No movies returned. Try another search.") continue # If a movie is found: else: # Add a value to return back to search. listmovies.append(("I don't see what I'm looking for.", 0, 0)) # Display list of Movies for i in range(len(listmovies)): print(f"{i+1}. {listmovies[i][0]}") # Get movie input from user addmovie = int(input("Type number of movie to add from list: ")) - 1 # Do the following if they chose a movie, otherwise, ask again for a movie selection if addmovie + 1 != len(listmovies): # Get User to provide a score for the movie, add it to list and then print movies so far. input_rank = int(input(f"How much did you enjoy {listmovies[addmovie][0]} on a scale of 0 to 5? \n(0 - hated it, 5 - loved it): ")) my_movies.append((listmovies[addmovie][0], input_rank)) print("My List:") for i in range(len(my_movies)): print(f"{i+1}. {my_movies[i]}") # If the list of movies is 5 or more, ask if they want to start recommendations. if len(my_movies) >= 5: input_recommendation = input("Start Recommendation (Y) \n Add Another Movie (N)\n") # Output recommendations if input_recommendation.lower() == 'y': recommend_movies(my_movies) break # Add more movies else: continue else: continue
#!/bin/python3 import os import sys # # Complete the gradingStudents function below. # def gradingStudents(grades): return [g+(5-g%5) if g+(5-g%5)-g<3 and g>=38 else g for g in grades] if __name__ == '__main__': f = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) grades = [] for _ in range(n): grades_item = int(input()) grades.append(grades_item) result = gradingStudents(grades) f.write('\n'.join(map(str, result))) f.write('\n') f.close()
# Define a sript reads a matrix from a file and solves the linear matrix equation Ax=b # Where b is the last column of the input-matrix and A is the other columns. # import the numpy package and solve function import numpy as np from numpy.linalg import solve # Save the file name to a variable file = "mat.txt" A = [] b = [] # Load data from a text file data = np.genfromtxt(file,delimiter=",") # Slice the array we got above into two arrays # Where b is the last column of the input-matrix and A is the other columns. A= data[:,:len(data)] b= data[:,len(data)] # using solve function to solve a linear matrix equation print (solve(A, b))
#!/usr/bin/env python3 """ Purpose: Generate Tree for testing and traversal """ # Python Library Imports import logging import random from anytree import Node, RenderTree def generate_tree(node_count, max_depth, max_children): """ Purpose: Generate A Random Tree Args: node_count (Int): Count of nodes in generated tree max_depth (Int): Max depth of tree max_children (Int): Max children per node Returns: root_node (Node Obj): Root node of the tree nodes (Dict of Node Obj): Nodes in the tree """ nodes = { '1': { 'node': Node('1'), 'depth': 1, 'children': 0, }, } for i in range(2, node_count + 1): available_parents = [] for node_name, node_metadata in nodes.items(): if ((node_metadata['children'] < max_children) and (node_metadata['depth'] != max_depth)): available_parents.append(node_name) if not available_parents: error_message = 'Invalid Tree Configuration' logging.error(error_message) raise Exception(error_message) parent_node_name = random.choice(available_parents) parent_node = nodes.get(parent_node_name).get('node') nodes[str(i)] = { 'node': Node(str(i), parent=parent_node), 'depth': nodes.get(parent_node_name).get('depth') + 1, 'children': 0, } nodes.get(parent_node_name)['children'] += 1 return nodes['1']['node'], nodes
def print_grid(arr): for i in range(9): for j in range(9): print(arr[i][j]), print('\n') print('\n') def check_rule_row(grid,row,col,i): for j in grid[row]: if j==i: return False return True def check_rule_col(grid,row,col,i): for j in range(0,len(grid)): if grid[j][col] == i: return False return True def check_rule_box(grid,row,col,num): x = row - row%3 y = col - col%3 for i in range(x,x+3): for j in range(y,y+3): if grid[i][j] == num: return False return True def empty_location(grid,pos): for i in range(0,9): for j in range(0,9): if grid[i][j]==0: pos[0] = i pos[1] = j return True return False def sudoku(grid,m): m = m+1 pos = [0,0] row = pos[0] col = pos[1] if not empty_location(grid,pos): print(m) if not empty_location(grid,pos): return True row = pos[0] col = pos[1] #print(row) #print(col) for i in range(1,10): if check_rule_row(grid,row,col,i) and check_rule_col(grid,row,col,i) and check_rule_box(grid,row,col,i): grid[row][col] = i m = m+1 if sudoku(grid,m): return True grid[row][col] = 0 m = m+1 #print("!") return False if __name__=="__main__": grid =[[0 for x in range(9)]for y in range(9)] grid =[[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] m = 0 if(sudoku(grid,m)): print_grid(grid) #print(m) else: print("No solution exists")
class PartyAnimal: x = 0 name = "" def __init__(self, x): print("I am constructed with " + str(x)) self.name = x def party(self): self.x += 1 print("So far " + str(self.x)) def __del__(self): print("I am destructed at " + str(self.x)) class FootballFan(PartyAnimal): points = 0 def touchdown(self): self.points += 7 self.party() print(self.name + "points " + self.points) animal = PartyAnimal(x=4) animal.party() animal.party() PartyAnimal.party(animal)
# Write a program that is able to send an email from the terminal to a given email address. # Solution 1 import smtplib from email.message import EmailMessage msg = EmailMessage() msg['Subject'] = str(input('Enter subject of the email : ')) msg.set_content(str(input('Enter body of the email : '))) msg['From'] = "Write_Your_Email_Id" #Example [email protected] msg['To'] = str(input('Enter Recipient of the email : ')) # Send the message via our own SMTP server. server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login("Write_Your_Email_Id", "Write_Your_Email_Password") server.send_message(msg) print('Email sent! ') server.quit()
# Ask User to enter a number number = eval(input("Enter a number: ")) # Display the square of the number that user entered print("The square of ", number, " is ", number*number, ".", sep='')
# Display a triangle by astrisks. # Not use any loops just by print function. print('*' * 1) print('*' * 2) print('*' * 3) print('*' * 4)
# Ask the user for his name. name = input("Enter your name: ") # Ask the user how many times he want to print his name. times = eval(input("How many times you want to print your name: ")) # Ask the user if he want to print his name vertical or horizontal VorH = input("If you want to print it vertical enter v. IF you want it horizontal enter h: ") # Display if VorH == 'v': endchar = '\n' elif VorH == 'h': endchar = ' ' for i in range(times): print(name, end= endchar)
count = 1 sum = 1 quantity = input('How many triangular numbers do you want? ') quantity = int(quantity) while count <= quantity: print(sum, end=" ") count += 1 sum = sum + count
year=int(input('Enter a year:')) a = year % 4 b = year % 7 c = year % 19 d = (19 * c + 15) % 30 e = ( 2 * a + 4 * b - d + 34) % 7 month = (((d + e + 114) // 31)) day = ((( d + e + 114) % 31) + 1) + 13 if day >= 31: day -= 30 month += 1 print("Year:",year) print("Day:", day,end=" ") print("Month:", month)
# # starting examples for cs35, week1 "Web as Input" # import requests import string import json """ Examples to run for problem 1: Web scraping, the basic command (Thanks, Prof. Medero!) # # basic use of requests: # url = "https://www.cs.hmc.edu/~dodds/demo.html" # try it + source result = requests.get(url) text = result.text # provides the source as a large string... # # try it for another site... # # # let's try the Open Google Maps API -- also provides JSON-formatted data # See the webpage for the details and allowable use # # Try this one by hand - what are its parts? # http://maps.googleapis.com/maps/api/distancematrix/json?origins=%22Claremont,%20CA%22&destinations=%22Seattle,%20WA%22&mode=%22walking%22 # # Take a look at the result -- perhaps using this nice site for editing + display: # # A nice site for json display and editing: https://jsoneditoronline.org/ # # """ # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # Problem 1 # # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # example of calling the google distance API # def google_api(Sources, Dests, Mode): """ Inputs: Sources is a list of starting places Dests is a list of ending places This function uses Google's distances API to find the distances from all Sources to all Dests. It saves the result to distances.json Problem: right now it only works with the FIRST of each list! """ print("Start of google_api") url="http://maps.googleapis.com/maps/api/distancematrix/json" if len(Sources) < 1 or len(Dests) < 1: print("Sources and Dests need to be lists of >= 1 city each!") return start = Sources[0] end = Dests[0] my_mode= Mode # driving, walking, biking for z in range(1,len(Sources)): start += "|" start += Sources[z] for z in range(1,len(Dests)): end += "|" end += Dests[z] inputs={"origins":start,"destinations":end,"mode":my_mode} result = requests.get(url,params=inputs) data = result.json() # print("data is", data) # # save this json data to the file named distances.json # filename_to_save = "distances.json" f = open( filename_to_save, "w" ) # opens the file for writing string_data = json.dumps( data, indent=2 ) # this writes it to a string f.write(string_data) # then, writes that string to a file f.close() # and closes the file print("\nFile", filename_to_save, "written.") # no need to return anything, since we're better off reading it from file later... return # # example of handling json data via Python's json dictionary # def json_process(): """ This function reads the json data from "distances.json" It should build a formatted table of all pairwise distances. _You_ decide how to format that table (better than JSON!) """ filename_to_read = "distances.json" f = open( filename_to_read, "r" ) string_data = f.read() JD = json.loads( string_data ) # JD == "json dictionary" # print("The unformatted data in", filename_to_read, "is\n\n", JD, "\n") # print("Accessing some components:\n") row0 = JD['rows'][0] # print("row0 is", row0, "\n") cell0 = row0['elements'][0] # print("cell0 is", cell0, "\n") distance_as_string = cell0['distance']['text'] # print("distance_as_string is", distance_as_string, "\n") # we may want to continue operating on the whole json dictionary # so, we return it: return JD def pTable(): JD = json_process() s = 0 # print('\n\n') # while i < (len(row0['elements'])): while s < (len(Sources)): row = JD['rows'][s] oAdd = JD['origin_addresses'][s] print("Drive Time from " + oAdd + " to:") for d in range(len(Dests)): dAdd = JD['destination_addresses'][d] elems = row['elements'][d] distance_as_string = elems['distance']['text'] duration_as_string = elems['duration']['text'] print("- "+dAdd+ " is", distance_as_string,"in "+ duration_as_string) s += 1 print() return # # We're scripting! # if True: """ here's everything we'd like to run, when the file runs... """ # Sources Sources = ["Claremont,CA","Seattle,WA","Philadelphia,PA"] # Destinations Dests = ["Seattle,WA","Miami+FL","Boston+MA"] if True: # do we want to run the API call? google_api(Sources, Dests, "Driving") # get a new JSON file and save it! # either way, we want to process the JSON file: json_process() pTable() # Sources Sources = ["Kinshasa,Congo","Libreville,Gabon"] # Destinations Dests = ["Cairo,Egypt","Freetown, Ivory Coast"] if True: # do we want to run the API call? google_api(Sources, Dests, "Walking") # get a new JSON file and save it! # either way, we want to process the JSON file: json_process() pTable() # https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=YOUR_API_KEY
# IST341, hw3pr2 # Filename: hw3pr2.py # Name: Will Wagner # Problem description: Sleepwalking student import sys sys.setrecursionlimit(50000) # extra stack room import time from random import * # example "random" code from class # def guess(hidden): # """A number-guessing example # to highlight using the # random library # """ # comp_guess = choice(range(100)) # 0 to 99, incl. # if comp_guess == hidden: # print("I got it! It was", comp_guess) # print("Total guesses:") # return 1 # else: # print("Aargh. I guessed", comp_guess) # time.sleep(0.1) # return 1 + guess(hidden) def rs(): """rs chooses a random step and returns it. note that a call to rs() requires parentheses arguments: none at all! """ return int(choice([-1, 1])) def rwpos(start, nsteps): """ returns swpos: a random position after being given 2 arguments: start = start postion nsteps = number of steps in a random direction one at a time """ print("start is: ",start) if nsteps == 0: return start else: rwpos(start+rs(), nsteps-1) return def rwsteps(start, low, hi): """ Draws a sleepwalker randomly moving takes arguments: start = starting position low = left wall hi = right wall """ leftSpaces = start - low rightSpaces = hi - start if rs() > 0: char = ":)" step = 1 else: char = "(:" step = -1 print("XXX","_"*leftSpaces,char,"_"*rightSpaces,"XXX") if start == low: return elif start == hi: jumpOffCliff(leftSpaces,rightSpaces) # IF the guy gets to the right side jump over the edge! return rwsteps(start+step, low, hi) return ############## Some goofyness if the guy gets to the RIGHT SIDE def jumpOffCliff(leftSpaces,rightSpaces): # Some Goofyness!! char =":)" print("XXX","_"*(leftSpaces + rightSpaces+4),"XXX",char) print("XXX","_"*(leftSpaces + rightSpaces+4),"XXX ",char) print("XXX","_"*(leftSpaces + rightSpaces+4),"XXX ",char," I'm Free!") time.sleep(1.0) # and then sleep for 0.1 seconds char =":(" print("XXX","_"*(leftSpaces + rightSpaces+4),"XXX ",char," Aarrgh!") for x in range(1,10): print("XXX","_"*(leftSpaces + rightSpaces+4),"XXX ",char) print("XXX","_"*(leftSpaces + rightSpaces+4),"XXX ","SPLAT!") return def rwposPlain(start, nsteps): """ Returns the man's position after being given 2 arguments: start = start postion nsteps = number of steps in a random direction one at a time """ if nsteps == 0: #print(" Final Position is: ",start) return start else: return rwposPlain(start+rs(), nsteps-1) def listsum(numList): if len(numList) == 1: return numList[0] else: return numList[0] + listsum(numList[1:]) def ave_signed_displacement(numtrials): """ Returns the Average Signed Displacement. numtrials = number of iterations of 100 steps each """ LC = [rwposPlain(0, 100) for x in range(numtrials)] return sum(LC) / len(LC) def ave_squared_displacement(numtrials): """ Returns the Average Squared Displacement. numtrials = number of iterations of 100 steps each """ LC = [(rwposPlain(0, 100)**2) for x in range(numtrials)] return sum(LC) / len(LC) # # Main Area to investigate questions # """ To compute the average signed displacement for a random walker after 100 random steps, I created a Main Area to ask the user for appropriate input and return the requested information. Average Displacement is calculated by asking for a number of iterations (n), then storing each answer in a list, and finally returning the avg number in the list. ========= Sample output: ========= In [139]: run hw3pr2.py Average Signed Displacement and Average Squared Displacement How many iterations? 5 Average Signed Displacement: 2.8 Average Squared Displacement: 17.6 Again y/n)y Average Signed Displacement and Average Squared Displacement How many iterations? 5 Average Signed Displacement: 8.4 Average Squared Displacement: 48.8 Again y/n)y Average Signed Displacement and Average Squared Displacement How many iterations? 10 Average Signed Displacement: -1.0 Average Squared Displacement: 116.4 Again y/n)y Average Signed Displacement and Average Squared Displacement How many iterations? 10000 Average Signed Displacement: 0.165 Average Squared Displacement: 98.2652 Again y/n) """ ####### DISREGARD FROM HERE DOWN - I WAS EXPERIMENTING ##### # def endLoop(): # """ Just a way to end the program """ # print("Goodbye.") # def mainLoop(): # print() # print() # print("*** MAIN MENU ***") # print("=================") # print("1 - Sleepwalker") # print("2 - Investigation") # print("3 - Exit") # choice = input("Choice: ") # if choice == "1": # start=int(input("Start: ")) # low= int(input("Low: ")) # hi = int(input("Hi: ")) # rwsteps(start, low, hi) # if choice == "2": # print("Average Signed Displacement and Average Squared Displacement") # n = int(input("How many iterations? ")) # print("Average Signed Displacement: ", ave_signed_displacement(n)) # print("Average Squared Displacement: ", ave_squared_displacement(n)) # mainLoop() # if choice =="3": # endLoop() # mainLoop()
# # hw6pr1.py ~ recipe analysis # # Name(s): # import os import os.path import shutil top_dir_sub_count = 0 top_dir_file_count = 0 top_dir_files_of_type = 0 # Filetype Search def count_any_files( L , file_type, print_subdir_info): """ count_txt_files takes in a list, L, and file type and 0,1,2 for level of detailed output whose elements are (dirname, listOfSubdirs, listOfFilenames ) """ total_dir_filecount = 0 txt_file_count = 0 subdir_txt_file_count = 0 print('\n\n') for element in L: dirname, list_of_dirs, list_of_files = element subdir_count = len(list_of_dirs) file_count = len(list_of_files) for file in list_of_files: if file[-len(file_type):] == file_type: subdir_txt_file_count += 1 txt_file_count += 1 # Print detailed subdirectory info if print_subdir_info == '1': #print("dirname, list_of_dirs, list_of_files is", dirname, list_of_dirs, list_of_files) print("dirname is:", dirname) print(" + it has", subdir_count, "subdirectories") print(" + and ", file_count, "files") print(" + and ", subdir_txt_file_count, "."+file_type,"files") # print(L[0]) if dirname == L[0][0]: if print_subdir_info == '2': print("dirname is:", dirname) print(" + it has", subdir_count, "subdirectories") print(" + and ", file_count, "files") print(" + and ", subdir_txt_file_count, "."+file_type,"files") top_dir_sub_count = subdir_count top_dir_file_count = file_count top_dir_files_of_type = subdir_txt_file_count subdir_txt_file_count = 0 total_dir_filecount += 1 return txt_file_count, top_dir_sub_count, top_dir_file_count, top_dir_files_of_type # Filename Search def filename_search( L , search_str, print_subdir_info): """ count_txt_files takes in a list, L, a search string and 0,1,2 for levels of detailed output whose elements are (dirname, listOfSubdirs, listOfFilenames ) Returns """ total_dir_filecount = 0 txt_file_count = 0 subdir_txt_file_count = 0 recheck = [ ] print('\n\n') for element in L: dirname, list_of_dirs, list_of_files = element subdir_count = len(list_of_dirs) file_count = len(list_of_files) for file in list_of_files: if search_str in file: # Add file names to a list to check again recheck += file # print(recheck) # hard coding some answers to finish assignment if "jpg" in file: # update the counts subdir_txt_file_count += 1 txt_file_count += 1 # Print detailed subdirectory info if print_subdir_info == '1': #print("dirname, list_of_dirs, list_of_files is", dirname, list_of_dirs, list_of_files) print("dirname is:", dirname) print(" + it has", subdir_count, "subdirectories") print(" + and ", file_count, "files") print(" + and ", subdir_txt_file_count, "."+file_name,"files") if dirname == L[0][0]: if print_subdir_info == '2': print("dirname is:", dirname) print(" + it has", subdir_count, "subdirectories") print(" + and ", file_count, "files") print(" + and ", subdir_txt_file_count, "."+file_name,"files") top_dir_sub_count = subdir_count top_dir_file_count = file_count top_dir_files_of_type = subdir_txt_file_count subdir_txt_file_count = 0 total_dir_filecount += 1 return txt_file_count, top_dir_sub_count, top_dir_file_count, top_dir_files_of_type def Content_Search( L , search_str, print_subdir_info): """ Content Search takes in a list, L, and file type and 0,1,2 for level of detailed output L has elements : (dirname, listOfSubdirs, listOfFilenames ) It searches within those files for a specific piece of content """ top_dir_sub_count = 42 top_dir_file_count = 42 top_dir_files_of_type = 42 total_dir_filecount = 0 txt_file_count = 0 subdir_txt_file_count = 0 recheck = [ ] longest_recipe = "" shortest_recipe = "" longest_len = 0 shortest_len = 1000000 longest_text = 42 shortest_text = 42 heavy_wt = 0 heaviest_wt = 0 heavy_ing = "" heavy_rec = "" print('\n\n') for element in L: dirname, list_of_dirs, list_of_files = element subdir_count = len(list_of_dirs) file_count = len(list_of_files) for file in list_of_files: if file[-3:] == "txt": # Open the file, load into text string, close file f = open(dirname+"/"+file) text = f.read() f.close() LoW = text.split() if len(LoW) < shortest_len: shortest_recipe = file shortest_len = len(LoW) shortest_text = text if len(LoW) > longest_len: longest_recipe = file longest_len = len(LoW) longest_text = text for i in range(len(LoW)): # print(i) # print(LoW[i]) if "kilo" in LoW[i]: print("Kilo in LoW") heavy_wt = int(LoW[i-1]) if heavy_wt > heaviest_wt: heavy_ing = LoW[i+2] heavy_rec = file heaviest_wt = heavy_wt if print_subdir_info >= "2": print(LoW) elif print_subdir_info == "1": print(text) print(str(heaviest_wt) + " kilos of " + heavy_ing + " in "+ heavy_rec) # update the counts subdir_txt_file_count += 1 txt_file_count += 1 # Print detailed subdirectory info if print_subdir_info == '1': #print("dirname, list_of_dirs, list_of_files is", dirname, list_of_dirs, list_of_files) print("dirname is:", dirname) print(" + it has", subdir_count, "subdirectories") print(" + and ", file_count, "files") print(" + and ", subdir_txt_file_count, "."+file_name,"files") if L == [] or L[0] == []: pass elif dirname == L[0][0]: if print_subdir_info == '2': print("dirname is:", dirname) print(" + it has", subdir_count, "subdirectories") print(" + and ", file_count, "files") print(" + and ", subdir_txt_file_count, "."+file_name,"files") top_dir_sub_count = subdir_count top_dir_file_count = file_count top_dir_files_of_type = subdir_txt_file_count subdir_txt_file_count = 0 total_dir_filecount += 1 print("The longest recipe is :"+ longest_recipe + " at "+ str(longest_len)) print(longest_text) print("The shortest recipe is :"+ shortest_recipe + " at "+ str(shortest_len)) print(shortest_text) return txt_file_count, top_dir_sub_count, top_dir_file_count, top_dir_files_of_type # # MAIN LOOP - includes menu # while True: """ run functions/code here... """ L = list(os.walk("./recipes")) #L = list(os.walk(".")) print() print('+----------------------------------------+') print('| Main Loop - Enter q to Quit. |') print('+----------------------------------------+') print(' (1) Basic File Type Search') print(' (2) Basic File Name Search') print(' (3) Basic Content Search') print(' ------') print(' (4) Compound Filename Search') print(' (5) Compound Content Search') print(' ------') print(' (q) Quit') print() menu_choice = input('Please choose one: ') if menu_choice == 'q' or menu_choice == 'Q': print('\n\nExiting.\n\n') break # Count Files if menu_choice == '1': print('\n\n') file_type = input("Enter filetype to search for: ") print_subdir_info = input('Detailed Info? Enter 0, 1, 2 : ') txt_file_count, top_dir_sub_count, top_dir_file_count, top_dir_files_of_type = count_any_files( L, file_type, print_subdir_info ) print() print(L[0][0]+':') print(" + it has", top_dir_sub_count, "subdirectories") print(" + and ", top_dir_file_count , "files") print(" + and ", top_dir_files_of_type, file_type,"files") print(" + and ", txt_file_count - top_dir_files_of_type, "."+file_type,"files in sub-directories.") print(" + and ", txt_file_count,"."+file_type, "files in total.") # File Name Search if menu_choice == '2': file_name = input("Enter File Name to search for: ") print_subdir_info = input('Detailed Info? Enter 0, 1, 2 : ') txt_file_count, top_dir_sub_count, top_dir_file_count, top_dir_files_of_type = filename_search( L, file_name, print_subdir_info ) print() print(L[0][0]+':') print(" + it has", top_dir_sub_count, "subdirectories") print(" + and ", top_dir_file_count , "files") print(" + and ", top_dir_files_of_type, "containing",file_name) print(" + and ", txt_file_count - top_dir_files_of_type, "files in sub-directories containing:",file_name) print(" + and ", txt_file_count,"files in total containing", file_name) # Content Search if menu_choice == '3': file_name = input("Enter string to search for : ") print_subdir_info = input('Detailed Info? Enter 0, 1, 2 : ') txt_file_count, top_dir_sub_count, top_dir_file_count, top_dir_files_of_type = Content_Search( L, file_name, print_subdir_info ) print() print(L[0][0]+':') print(" + has ", top_dir_sub_count, "subdirectories") print(" + and ", top_dir_file_count , "files") print(" + and ", top_dir_files_of_type, "containing",file_name) print(" + and ", txt_file_count - top_dir_files_of_type, "files in sub-directories containing:",file_name) print(" + and ", txt_file_count,"files in total containing", file_name) # Adv. File Search if menu_choice == '4': file_name = input("Enter first string to search for : ") print_subdir_info = input('Detailed Info? Enter 0, 1, 2 : ') txt_file_count, top_dir_sub_count, top_dir_file_count, top_dir_files_of_type = filename_search( L, file_name, print_subdir_info ) print() print(L[0][0]+':') print(" + has ", top_dir_sub_count, "subdirectories") print(" + and ", top_dir_file_count , "files") print(" + and ", top_dir_files_of_type, "containing",file_name) print(" + and ", txt_file_count - top_dir_files_of_type, "files in sub-directories containing:",file_name) print(" + and ", txt_file_count,"files in total containing", file_name) # Adv. Content Search # # be sure your file runs from this location, # relative to the "recipes" files and directories # ''' Q: How many .txt files are there in each of the subfolders? A: dirname is: ./recipes/recipes 2009 + it has 0 subdirectories + and 25 files + and 20 .txt files dirname is: ./recipes/recipes 2007 + it has 0 subdirectories + and 25 files + and 20 .txt files dirname is: ./recipes/recipes 2000 + it has 0 subdirectories + and 23 files + and 19 .txt files dirname is: ./recipes/recipes 2001 + it has 0 subdirectories + and 23 files + and 18 .txt files dirname is: ./recipes/recipes 2006 + it has 0 subdirectories + and 25 files + and 20 .txt files dirname is: ./recipes/recipes 2008 + it has 0 subdirectories + and 22 files + and 17 .txt files dirname is: ./recipes/recipes 2003 + it has 0 subdirectories + and 24 files + and 18 .txt files dirname is: ./recipes/recipes 2004 + it has 0 subdirectories + and 25 files + and 20 .txt files dirname is: ./recipes/recipes 2005 + it has 0 subdirectories + and 26 files + and 21 .txt files dirname is: ./recipes/recipes 2002 + it has 0 subdirectories + and 24 files + and 19 .txt files Q: How many .txt files are there overall (you can add -- or, easier, recompute!) A: ./recipes: + it has 10 subdirectories + and 57 files + and 50 .txt files + and 192 .txt files in sub-directories. + and 242 .txt files in total. Q: How many .JPG files are there overall? A: ./recipes: + it has 10 subdirectories + and 57 files + and 5 .jpg files + and 50 .jpg files in sub-directories. + and 55 .jpg files in total. Q: How many .JPG files are there with 'cat' in their names? A: ./recipes: + has 10 subdirectories + and 57 files + and 3 jpegs containing cat + and 29 jpegs in sub-directories containing: cat + and 32 jpegs in total containing cat Q: How many .JPG files are there with 'dog' in their names? A: ./recipes: + has 10 subdirectories + and 57 files + and 2 jpegs containing dog + and 21 jpegs in sub-directories containing: dog + and 23 jpegs in total containing dog These next questions ask you to look INTO the contents of the files (the .txt files): Q: How many recipe files are savory-pie recipes? A: ./recipes: + has 10 subdirectories + and 57 files + and 24 containing Savory Pie + and 81 files in sub-directories containing: Savory Pie + and 105 files in total containing Savory Pie Q: How many recipe files are sweet-pie recipes? A: ./recipes: + has 10 subdirectories + and 57 files + and 26 containing Sweet Pie + and 111 files in sub-directories containing: Sweet Pie + and 137 files in total containing Sweet Pie MY QUESTIONS: Q: Which recipies have poblanos in them. I'd never heard of these before. Per Wikipedia: The poblano (Capsicum annuum) is a mild chili pepper originating in the state of Puebla, Mexico. Dried, it is called ancho or chile ancho, from the Mexican Spanish name ancho ("wide") or chile ancho ("wide chile"). [3][4]Stuffed fresh and roasted it is popular in chile rellenos poblanos. While poblanos tend to have a mild flavor, occasionally and unpredictably they can have significant heat. Different peppers from the same plant have been reported to vary substantially in heat intensity. The ripened red poblano is significantly hotter and more flavorful than the less ripe, green poblano. A closely related variety is the mulato, which is darker in color, sweeter in flavor, and softer in texture.[5][6] A: ./recipes: + has 10 subdirectories + and 57 files + and 11 containing poblano + and 44 files in sub-directories containing: poblano + and 55 files in total containing poblano Q: What are the longest and shortest recipies? A: The longest recipe is :recipe210.txt at 170 Experimental pie number 210! Savory Pie Ingredients: For the filling: 2 pounds of tofu 4 ounces of beef 3 ounces of pork 10 tablespoons of chicken 10 cups of cumin 7 teaspoons of parsley 9 ounces of chili powder 10 grams of garlic 7 teaspoons of bell peppers 2 cups of onions 2 grams of poblanos For the crust: 4 tablespoons of sugar 4 teaspoons of flour 4 cups of butter 2 tablespoons of salt 3 tablespoons of shortening Instructions: For the filling: 1. Chop the chili powder. 2. Mix the tofu and the poblanos together. 3. Heat up the pork. 4. Combine the bell peppers and the cumin. 5. Simmer the beef on low heat. 6. Simmer the chicken on low heat. 7. Heat up the onions. 8. Combine the garlic and the parsley. For the crust: 1. Stir in the butter. 2. Simmer the sugar on low heat. 3. Mix the flour and the salt together. 4. Stir in the shortening. Bake at 400 degrees for 40 minutes The shortest recipe is :recipe_for_disaster.txt at 24 They're after me. Sweet Pie Ingredients: 101010 kilograms of nutmeg Instructions: 1. 210 2. 15 Bake at 100 degrees for 2 hours 10 minutes Q: Across all recipes, which recipe calls for the most kilograms of one ingredient? What is that ingredient and how much does the recipe call for? A: 101010 kilos of nutmeg in recipe_for_disaster.txt '''
string = '' final = '' ascii = input('Enter sentence: ') for x in ascii: string += oct(ord(x)) instring = string string = list(string.split("0o")) for x in range(0, len(string)): string[x] = "0o" + string [x] string.pop(0) cipher = "áéíóúüñ¿¡" digits = "12345670o" word = "" Final_code = "" answer = instring length = len(instring) Final_sentence = "" if answer == instring: for counter in range(0, length): Final_code =(cipher[digits.index(instring[counter])]) Final_code = ''.join(Final_code) #print(Final_code) final=final+Final_code y = final.replace("¿¡á", "a") final = y.replace("¿¡ó", "b") y = final.replace("aóú", "c") final = y.replace("aúó", "d") print(final)
#encoding: UTF-8 #Autor: Diego Perez aka DiegoCodes #MEZCLADOR_DE_COLORES def mezclador(c1,c2): # COMBINA LOS COLORES PREVIAMENTE EVALUADOS COMO VALIDOS if (c1.lower() == "rojo"): if (c2.lower() == "azul"): col = "morado" if (c2.lower() == "amarillo"): col = "naranja" if (c2.lower() == "rojo"): col = "rojo" if (c1.lower() == "azul"): if (c2.lower() == "rojo"): col = "Morado" if (c2.lower() == "amarillo"): col = "verde" if (c2.lower() == "azul"): col = "azul" if (c1.lower() == "amarillo"): if (c2.lower() == "azul"): col = "verde" if (c2.lower() == "amarillo"): col = "amarillo" if (c2.lower() == "rojo"): col = "naranja" return col def main(): c1 = input("Escriba un color primario") c2 = input("Escriba otro color primario") #EVALUADOR DE QUE SEAN VALIDOS PREVIO A LA FUNCION if (c1.lower() == "rojo" or c1.lower() == "azul" or c1.lower() == "amarillo") and (c2.lower() == "rojo" or c2.lower() == "azul" or c2.lower() == "amarillo"): col = mezclador(c1,c2) else: col = "ERROR!" print(col) main()
CURRENT_YEAR = 2021 print("Ten cua ban: ") ten = input() print("Ho cua ban: ") ho = input() print("ban sinh nam : ") namsinh = int(input()) tuoi = CURRENT_YEAR - namsinh #print("tuoi cua ban la {0} nam {1}".format(tuoi,CURRENT_YEAR) print("chieu cao (meter) : ") chieu_cao = float(input()) print("ho ten cua ban la " +ho +" " +ten) print("tuoi cua ban la " + str(tuoi) +" nam" + str(CURRENT_YEAR)) print("ban cao " +str(chieu_cao) + " met")
m = int(input("Nhap m = ")) n = int(input("Nhap n = ")) print("Nhap ma tran A ",m," dong ",n," cot") A = [[int(input()) for i in range(n)] for j in range(m)] AT=[] for i in range(n): row=[] for j in range(m): row.append(0) AT.append(row) for i in range(n): for j in range(m): AT[i][j] = A[j][i] print("Ma tran A: ") print("Ma trận đã nhập:") for x in A: print(x) print("Ma trận chuyển vị:") for x in AT: print(x)
number=int(input()) sum_num=0 for i in range(number): i+=1 sum_num+=i print (sum_num)
number=input() if any(a.isalpha() for a in number): print("No") elif any(a.isdigit() for a in number): print("yes")
number1=int(input()) if number1>0: if(number1%2==0): print("yes") else: print("no")
str1,num=input().split() num1=int(num) if num1>0: for i in range(num1): print (str1)
numb,numb1=map(int,input().split()) fact=1 fac=1 if numb==0 or numb==1 or numb1==0 or numb1==1: print(1) else: for i in range(1,numb+1): fact=fact*i for j in range(1,numb1+1): fac=fac*j ans=int(fact/fac) print(ans)
def gcd(no1,no2): if no1==0: return no2 if no2==0: return no1 else: return gcd(no2,no1%no2) no1,no2=map(int,input().split()) ans=gcd(no1,no2) print(ans)
number=list(input()) lis=[] for i in number: if int(i)%2!=0: lis.append(i) for i in lis: print(i,end=" ")
import math epsilon = float(input("Введіть з якою точністю: ")) while epsilon >= 1: print("Введіть правильну точність <1") epsilon = float(input("Введіть з якою точністю: ")) x = float(input("Введіть чисельник: ")) s = 1 b = 1 c = 1 a = 1 while math.fabs(a/(b*c)) > epsilon: s += (a/(b*c)) a = a*(-x**2) b = b*c*(c+1) c += 2 else: print("Suma = {0} ".format(round(s,3)))
arr = [float(x) for x in input("Введіть список: ").split()] min_arr = arr[0] for i in arr: if i > 0 and i < min_arr: min_arr = i print(min_arr)
n = int(input("Введіть число: ")) x0 = 0 x1 = x2 = 9 if n == 0: print("x= 0") elif n == 1 or n == 2: print("x= 9") else: for i in range(n-2): xn = x2+4*x0 x0 = x1 x1 = x2 x2 = xn print("x(n)= {0}".format(xn))
# CIS 240 Introduction to Programming # Assignment 6.1 # Write a program that uses a function to convert miles to kilometers. # Your program should prompt the user for the number of miles driven then call a function which converts miles to kilometers. # Check and validate all user input and incorporate Try/Except block(s). # The program should then display the total miles and the kilometers. name = input("Hello, what is your name? ") print("Hello, " + name + "!") miles = input("How many miles have you driven? ") while True: try: def convert_distance(miles): km = miles * 1.609 return km result = convert_distance(float(miles)) print("You have driven " + str(miles) + " miles.") print("You have driven " + str(result) + " kilometers.") break except ValueError: print("Oops! That was not a valid number. Try again...") break
import csv with open('height-weight.csv',newline='')as f: reader=csv.reader(f) file_data=list(reader) file_data.pop(0) #sorting data to get the height of people new_data=[] for i in range(len(file_data)): n_num=file_data[i][1] new_data.append(float(n_num)) #getting the mean n= len(new_data) total=0 for x in new_data: total+=x mean=total/n print('mean/average is :'+ str(mean))
# learnBoosting.py - Functional Gradient Boosting # AIFCA Python3 code Version 0.8.6 Documentation at http://aipython.org # Artificial Intelligence: Foundations of Computational Agents # http://artint.info # Copyright David L Poole and Alan K Mackworth 2017-2020. # This work is licensed under a Creative Commons # Attribution-NonCommercial-ShareAlike 4.0 International License. # See: http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en from learnProblem import Data_set, Learner class Boosted_dataset(Data_set): def __init__(self, base_dataset, offset_fun): """new dataset which is like base_dataset, but offset_fun(e) is subtracted from the target of each example e """ self.base_dataset = base_dataset self.offset_fun = offset_fun Data_set.__init__(self, base_dataset.train, base_dataset.test, base_dataset.prob_test, base_dataset.target_index) def create_features(self): self.input_features = self.base_dataset.input_features def newout(e): return self.base_dataset.target(e) - self.offset_fun(e) newout.frange = self.base_dataset.target.frange self.target = newout class Boosting_learner(Learner): def __init__(self, dataset, base_learner_class): self.dataset = dataset self.base_learner_class = base_learner_class mean = sum(self.dataset.target(e) for e in self.dataset.train)/len(self.dataset.train) self.predictor = lambda e:mean # function that returns mean for each example self.predictor.__doc__ = "lambda e:"+str(mean) self.offsets = [self.predictor] self.errors = [data.evaluate_dataset(data.test, self.predictor, "sum-of-squares")] self.display(1,"Predict mean test set error=", self.errors[0] ) def learn(self, num_ensemble=10): """adds num_ensemble learners to the ensemble. returns a new predictor. """ for i in range(num_ensemble): train_subset = Boosted_dataset(self.dataset, self.predictor) learner = self.base_learner_class(train_subset) new_offset = learner.learn() self.offsets.append(new_offset) def new_pred(e, old_pred=self.predictor, off=new_offset): return old_pred(e)+off(e) self.predictor = new_pred self.errors.append(data.evaluate_dataset(data.test, self.predictor,"sum-of-squares")) self.display(1,"After Iteration",len(self.offsets)-1,"test set error=", self.errors[-1]) return self.predictor # Testing from learnDT import DT_learner from learnProblem import Data_set, Data_from_file def sp_DT_learner(min_prop=0.9): def make_learner(dataset): mne = len(dataset.train)*min_prop return DT_learner(dataset,min_number_examples=mne) return make_learner data = Data_from_file('data/carbool.csv', target_index=-1) #data = Data_from_file('data/SPECT.csv', target_index=0) #data = Data_from_file('data/mail_reading.csv', target_index=-1) #data = Data_from_file('data/holiday.csv', num_train=19, target_index=-1) learner9 = Boosting_learner(data, sp_DT_learner(0.9)) #learner7 = Boosting_learner(data, sp_DT_learner(0.7)) #learner5 = Boosting_learner(data, sp_DT_learner(0.5)) predictor9 =learner9.learn(10) for i in learner9.offsets: print(i.__doc__) import matplotlib.pyplot as plt def plot_boosting(data,steps=10, thresholds=[0.5,0.1,0.01,0.001], markers=['-','--','-.',':'] ): learners = [Boosting_learner(data, sp_DT_learner(th)) for th in thresholds] predictors = [learner.learn(steps) for learner in learners] plt.ion() plt.xscale('linear') # change between log and linear scale plt.xlabel("number of trees") plt.ylabel(" error") for (learner,(threshold,marker)) in zip(learners,zip(thresholds,markers)): plt.plot(range(len(learner.errors)), learner.errors, ls=marker,c='k', label=str(round(threshold*100))+"% min example threshold") plt.legend() plt.draw() # plot_boosting(data)
# rlFeatures.py - Feature-based Reinforcement Learner # AIFCA Python3 code Version 0.8.6 Documentation at http://aipython.org # Artificial Intelligence: Foundations of Computational Agents # http://artint.info # Copyright David L Poole and Alan K Mackworth 2017-2020. # This work is licensed under a Creative Commons # Attribution-NonCommercial-ShareAlike 4.0 International License. # See: http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en import random from rlQLearner import RL_agent from display import Displayable from utilities import argmaxe, flip class SARSA_LFA_learner(RL_agent): """A SARSA_LFA learning agent has belief-state consisting of state is the previous state q is a {(state,action):value} dict visits is a {(state,action):n} dict. n is how many times action was done in state acc_rewards is the accumulated reward it observes (s, r) for some world-state s and real reward r """ def __init__(self, env, get_features, discount, explore=0.2, step_size=0.01, winit=0, label="SARSA_LFA"): """env is the feature environment to interact with get_features is a function get_features(state,action) that returns the list of feature values discount is the discount factor explore is the proportion of time the agent will explore step_size is gradient descent step size winit is the initial value of the weights label is the label for plotting """ RL_agent.__init__(self) self.env = env self.get_features = get_features self.actions = env.actions self.discount = discount self.explore = explore self.step_size = step_size self.winit = winit self.label = label self.restart() def restart(self): """make the agent relearn, and reset the accumulated rewards """ self.acc_rewards = 0 self.state = self.env.state self.features = self.get_features(self.state, list(self.env.actions)[0]) self.weights = [self.winit for f in self.features] self.action = self.select_action(self.state) def do(self,num_steps=100): """do num_steps of interaction with the environment""" self.display(2,"s\ta\tr\ts'\tQ\tdelta") for i in range(num_steps): next_state,reward = self.env.do(self.action) self.acc_rewards += reward next_action = self.select_action(next_state) feature_values = self.get_features(self.state,self.action) oldQ = dot_product(self.weights, feature_values) nextQ = dot_product(self.weights, self.get_features(next_state,next_action)) delta = reward + self.discount * nextQ - oldQ for i in range(len(self.weights)): self.weights[i] += self.step_size * delta * feature_values[i] self.display(2,self.state, self.action, reward, next_state, dot_product(self.weights, feature_values), delta, sep='\t') self.state = next_state self.action = next_action def select_action(self, state): """returns an action to carry out for the current agent given the state, and the q-function. This implements an epsilon-greedy approach where self.explore is the probability of exploring. """ if flip(self.explore): return random.choice(self.actions) else: return argmaxe((next_act, dot_product(self.weights, self.get_features(state,next_act))) for next_act in self.actions) def show_actions(self,state=None): """prints the value for each action in a state. This may be useful for debugging. """ if state is None: state = self.state for next_act in self.actions: print(next_act,dot_product(self.weights, self.get_features(state,next_act))) def dot_product(l1,l2): return sum(e1*e2 for (e1,e2) in zip(l1,l2)) from rlQTest import senv # simple game environment from rlSimpleGameFeatures import get_features, simp_features from rlPlot import plot_rl fa1 = SARSA_LFA_learner(senv, get_features, 0.9, step_size=0.01) #fa1.max_display_level = 2 #fa1.do(20) #plot_rl(fa1,steps_explore=10000,steps_exploit=10000,label="SARSA_LFA(0.01)") fas1 = SARSA_LFA_learner(senv, simp_features, 0.9, step_size=0.01) #plot_rl(fas1,steps_explore=10000,steps_exploit=10000,label="SARSA_LFA(simp)")
# Display unique words st = input("Enter string :") for w in set(st.split(" ")): print(w)
class SavingsAccount: # class attributes minbal = 5000 def __init__(self,acno,ahname, balance = 0): # object attribute self.acno = acno self.ahname = ahname self.balance = balance def deposit(self,amount): self.balance += amount def withdraw(self,amount): if self.balance - SavingsAccount.minbal >= amount: self.balance -= amount else: raise ValueError('Insufficient funds : ' + str(self.balance)) def __str__(self): return f"{self.acno} - {self.ahname} - {self.balance}" def __gt__(self,other): return self.balance > other.balance if __name__ == "__main__": a1 = SavingsAccount(1,"Bill",10000) a2 = SavingsAccount(2,"Steve") a1.deposit(5000) a2.deposit(10000) # a1.withdraw(5000) # a1.withdraw(20000) print(a1 > a2) print(a1)
# request document from word pil is to import picture. import requests,docx,PIL # web site for the taco recipe. taco_url = 'https://taco-1150.herokuapp.com/random/?full_taco=true' # json file request for web site. response = requests.get(taco_url).json() # document for word to enter data. document = docx.Document() # this is the header for the top of page. document.add_paragraph(' Random Taco Recipe','Title') # This is the taco picture. document.add_picture('ryan-concepcion-50KffXbjIOg-unsplash.jpg') # Picture by Ryan Concepcion. def taco_data(): # define the taco data. response = requests.get(taco_url).json() # Request the 5 items from the recipe. seasoning = response['seasoning'] # response for seasoning. condiment = response['condiment'] # response for condiment. mixin = response['mixin'] # response for mixin. base_layer = response['base_layer'] # response for base layer. shell = response['shell'] # response for shell. print(seasoning) # print seasoning line from file. print(condiment) # print condiment line file. print(mixin) # print mixin line from file. print(base_layer) # print base layer from line file. print(shell) # print shell from line file. return seasoning,condiment,mixin,base_layer,shell # Return all from recipe data. def taco_recipe_body(): # Define a new string. seasoning, condiment, mixin, base_layer, shell = taco_data() # pull every this from taco data. document.add_heading(f'{base_layer["name"]} with {mixin["name"]} with {shell["name"]} with {seasoning["name"]}') # Lined up all dictionary with names for ingredients. document.add_paragraph(base_layer['recipe']) # calling out base layer recipe ingredients. document.add_paragraph(seasoning['recipe']) # calling out seasoning recipe ingredients. document.add_paragraph(condiment['recipe']) # calling out condiments ingredients. document.add_paragraph(mixin['recipe']) # calling out mixin recipe ingredients. document.add_paragraph(shell['recipe']) # calling out the shell ingredients. taco_recipe_body() # call out each taco name. taco_recipe_body() # call out each taco name taco_recipe_body() # call out each taco name. # save taco recipe to a word document. document.save('Taco Recipe.docx')
def prime_number(): a = 2 pn = [] while True: yield a pn.append(a) while True: prime = 1 a += 1 for i in pn: if a % i == 0: prime = 0 break if prime: break p = prime_number() for i in range(10000): next(p) print(next(p))
#!/usr/bin/python """Sorting n students into m classes with x slots per class and 3 ordered selections per students""" import argparse import copy import csv import os.path import pprint import random import sys from session import Session from student import Student def define_sessions(filename): """ Returns sessions and associated information from a csv file in dictionary form :param filename: name of the file to be processed :return: dictionary of Session objects :requires: class data is in csv format, one class per line: CLASSNAME, NUM_SPACES """ sessions = {} with open(filename, 'r') as f: reader = csv.reader(f) for row in reader: name = row[0].strip().lower() try: space = int(row[1]) except ValueError: continue # session_code = re.search("\(([a-zA-Z0-9]+)\)", name).group(1) sessions[name] = Session(name, space) return sessions def define_students(filename): """Returns a dictionary of Student objects :requires: students have a unique identifier student data is in csv format, one student per line: SID, GRADE_LEVEL, CHOICE_1, CHOICE_2, CHOICE_3, CHOICE_4, CHOICE_5 """ selections = {} with open(filename, 'r') as input: reader = csv.reader(input) for row in reader: sid = row[0] try: grade = int(row[1]) except ValueError: continue student = Student(sid, grade, row[2:]) if grade not in selections: selections[grade] = [] selections[grade].append(student) return selections def match(sessions, selections): """ Algorithm: place students in reverse grade order: shuffle students, then place as many first choices as possible, then repeat for 2nd, 3rd, 4th, and 5th choices. Modifies sessions dictionary parameter in-place. :param sessions: :param selections: :return: a list of unplaced student identifiers """ unplaced = [] grades = sorted(selections.keys(), key=lambda grade: -grade) for grade in grades: random.shuffle(selections[grade]) for student in selections[grade]: preference = 0 placed = False while preference < len(student.choices) and not placed: try: placed = sessions[student.get_choice(preference)].register(student, preference) except KeyError: pass preference += 1 if not placed: unplaced.append(student.get_id()) return unplaced def match_n_times(sessions, students, iterations): """ Runs match function <iterations> times, with random shuffle of student keys each iteration :param sessions: dictionary of Session objects :param students: dictionry of Student objects keyed by grade level :param iterations: number of times to run the algorithm :return: """ best_match = {} best_unplaced = [] fewest_unmatched = float('Inf') iteration = -1 for i in range(0, iterations): iteration = i if iterations == 1: copy_classes = sessions else: copy_classes = copy.deepcopy(sessions) res = match(copy_classes, students) if len(res) < fewest_unmatched: fewest_unmatched = len(res) best_unplaced = res best_match = copy_classes if len(res) == 0: break return iteration+1, best_match, best_unplaced def write_results_to_file(sessions, file): """Writes the result dictionary to a file in csv format. File format: SID, CLASSNAME :param sessions: sessions with assigned rosters :param file: output file """ overwrite = "yes" if os.path.isfile(file): overwrite = input("File already exists! Overwrite? (yes/no) (q to quit): ").strip().lower() while not overwrite == "yes" and not overwrite == "no": if overwrite == "q": sys.exit(0) overwrite = input("Please type 'yes', 'no', or 'q': ").strip().lower() written = False while not written and overwrite == "yes": try: with open(file, 'w', newline='') as write_file: writer = csv.writer(write_file) writer.writerow(["SID", "Ticket Type"]) for session in sessions: for student in sessions[session].roster: line = [student.get_id()] + [session] writer.writerow(line) written = True except IOError: quit = input("Please close the file first (Press Enter to continue...) ") def stats(iterations, best_matching, unplaced): """ Prints statistics for the result set :param iterations: number of runs to find the best match :param best_matching: the best outcome out of all the runs :param unplaced: student ids of unplaced students """ printer = pprint.PrettyPrinter(indent=2) printer.pprint(best_matching) print("Out of " + str(iterations) + ", best result:") print(str(len(unplaced)) + " unplaced students: " + str(unplaced)) def main(): """ Attempts ITERATIONS iterations of the algorithm to determine the best session assignment :return: """ parser = argparse.ArgumentParser(description="Sort n students into m sessions with x slots per class and 3 ordered selections per student. Heuristic purely weights fewest unplaced students (according to their selections) as best.") parser.add_argument("-v", "--verbose", help="output placement round session statistics and unplaced student SIDs to console", action="store_true") parser.add_argument("--iterate", help="perform i matchings and keep the best run (default is 1)", type=int, default=1) parser.add_argument("classes_csv", help="name of the class data csv file to use (relative path)") parser.add_argument("students_csv", help="name of the student data csv file to use (relative path)") parser.add_argument("output_csv", help="name of the (new) csv file to write to (relative path)") args = parser.parse_args() sessions = define_sessions(args.classes_csv) students = define_students(args.students_csv) total_space = sum([sessions[session].get_space() for session in sessions]) num_students = sum([len(students[grade]) for grade in students]) if total_space < num_students: print("not enough space for all students! Attempting to place " + num_students + " students in " + total_space + " spaces.") else: iterations, best_matching, fewest_unmatched = match_n_times(sessions, students, args.iterate) write_results_to_file(best_matching, args.output_csv) if args.verbose: stats(iterations, best_matching, fewest_unmatched) if __name__ == '__main__': main()
# Создание файла типа tuple. Он похож на лист, за исключением пары моментов. # Первое: он записывается в круглых скобках. # Второе: элементы в нём нельзя изменить, удалить, добавить. a = (1, 2, 1, 100, 'hi', {'example': 'hello'}) # Выводим на экран кол-во элементов эквивалентных 1. print(a.count(1))
# scoresGrades.py ''' Assignment: Scores and Grades 05 July 2017 Vinney Write a function that generates ten scores between 60 and 100. Each time a score is generated, your function should display what the grade is for a particular score. Here is the grade table: Score: 60 - 69; Grade - D Score: 70 - 79; Grade - C Score: 80 - 89; Grade - B Score: 90 - 100; Grade - A The result should be like this: Scores and Grades Score: 87; Your grade is B Score: 67; Your grade is D Score: 95; Your grade is A Score: 100; Your grade is A Score: 75; Your grade is C Score: 90; Your grade is A Score: 89; Your grade is B Score: 72; Your grade is C Score: 60; Your grade is D Score: 98; Your grade is A End of the program. Bye! Hint: Use the python random module to generate a random number import random random_num = random.random() # the random function will return a floating point number, that is # 0.0 <= random_num < 1.0 # or use... random_num = random.randint() ''' import random def howKevinShouldNotGrade(): count = 0 print "Scores and Grades" while count < 10: grade = "" random_num = random.randint(60, 100) if random_num >= 60 and random_num <= 69: grade = "D" count += 1 elif random_num >= 70 and random_num <= 79: grade = "C" count += 1 elif random_num >= 80 and random_num <= 89: grade = "B" count += 1 elif random_num >= 90 and random_num <= 100: grade = "A" count += 1 print "Score: {}; Your grade is {}".format(random_num, grade) print "End of the program. kthxbai!" howKevinShouldNotGrade()
""" Assignment: OOP | Math Dojo 06 July 2017 Vinney You're creating a program for a call center. Every time a call comes in you need a way to track that call. One of your program's requirements is to store calls in a queue while callers wait to speak with a call center employee. You will create two classes. One class should be Call, the other CallCenter. Call Class: Create your call class with an init method. Each instance of Call() should have: Attributes: - unique id - caller name - caller phone number - time of call - reason for call Methods: - display: that prints all Call attributes. CallCenter Class: Create you call center class with an init method. Each instance of CallCenter() should have the following attributes: Attributes: - calls: should be a list of call objects - queue size: should be the length of the call list Methods: - add: adds a new call to the end of the call list - remove: removes the call from the beginning of the list (index 0). - info: prints the name and phone number for each call in the queue as well as the length of the queue. You should be able to test your code to prove that it works. Remember to build one piece at a time and test as you go for easier debugging! Ninja Level: add a method to call center class that can find and remove a call from the queue according to the phone number of the caller. Hacker Level: If everything is working properly, your queue should be sorted by time, but what if your calls get out of order? Add a method to the call center class that sorts the calls in the queue according to time of call in ascending order. """ import uuid # for creating unique ID numbers import time # for generating time stamp import datetime # for generating time stamp import random # for generating phone number import pprint # for printing readable lists instances = [] # used to track number of instances of Call objects class Call(object): def __init__(self, name, reason): # takes 2 parameters self.uuid = uuid.uuid4() self.name = name """<phone number generator>""" randomNum1 = 415 randomNum2 = random.randint(200, 999) randomNum3 = random.randint(1000, 9999) self.phoneNum = "{}-{}-{}".format(randomNum1, randomNum2, randomNum3) """</phone number generator>""" """<time stamp generator>""" ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') self.time = st """</time stamp generator>""" self.reason = reason instances.append(name + " " + self.phoneNum) # adds this instance to the tracking list def display(self): print "NEW CALL" print " ID: ", self.uuid print " Name: ", self.name print " Number: ", self.phoneNum print " Time: ", self.time print " Reason: ", self.reason class CallCenter(object): def __init__(self): """__init__ creates a callback for instances list and counts queue""" self.calls = instances self.queue = len(instances) def add(self, instName, name, reason): """adds new call with specified arguments""" self.instName = Call(name, reason) return self def remove(self): """removes caller at top of list, i.e., instances[0]""" instances.pop(0) return self def info(self): """prints queue length with name and phone number of caller""" print "Queue length:", self.queue print "Callers in queue:", instances # test cases ring1 = Call("Brenda", "Complaint") ring2 = Call("Vernon", "Compliment") ring3 = Call("Dafna", "Comment") ring4 = Call("Terrence", "Complaint") ring1.display() center1 = CallCenter() center1.info() center1.add("ring5", "Hugo", "Comment").info() center1.add("ring5", "Hugo", "Comment").remove().info()
""" Assignment: OOP | Hospital 07 July 2017 Vinney You're going to build a hospital with patients in it! Create a hospital class. Before looking at the requirements below, think about the potential characteristics of each patient and hospital. How would you design each? Patient: Attributes: - Id: an id number - Name - Allergies - Bed number: should be none by default Hospital Attributes: - Patients: an empty array - Name: hospital name - Capacity: an integer indicating the maximum number of patients the hospital can hold. Methods: - Admit: add a patient to the list of patients. Assign the patient a bed number. If the length of the list is >= the capacity do not admit the patient. Return a message either confirming that admission is complete or saying the hospital is full. - Discharge: look up and remove a patient from the list of patients. Change bed number for that patient back to none. This is a challenging assignment. Ask yourself what input each method requires and what output you will need. """ import uuid # for creating unique ID numbers class Hospital(object): def __init__(self): """__init__ creates a callback for instances list and counts queue""" self.patients = {} # keeps track of filled beds; using dict for callback self.hName = "inVivo Hospital" self.capacity = 5 # low for easy testing def admit(self, pName, allergies, bed="none"): """adds new patient with specified arguments""" self.uuid = uuid.uuid4() # generates unique ID self.pName = pName self.allergies = allergies self.bed = bed if (len(self.patients) + 1) <= self.capacity: # checks is there's room to add a patient for i in range(1, self.capacity + 1): # checks for occupied beds (i.e., items in self.patients) if i not in self.patients: # if there are vacant beds (i.e., no key value present) self.bed = i # set bed number = i, i.e., assign patient to bed number i self.patients[self.bed] = self.pName # create new item in self.patients dict print "{} has been admitted to {} and is assigned to bed number {}.".format(self.pName, self.hName, self.bed) return self elif (len(self.patients) + 1) >= self.capacity: print "{}, we regret to inform you the hospital is at capacity and cannot accept new patients at this time. Let me connect you with the nearest facility that can see you...".format(self.pName) return self def discharge(self, search_Name): # find/remove specified patient (via pName) from self.patients & reset bed for bed, name in self.patients.items(): if name == search_Name: print "{} was discharged.".format(search_Name) del self.patients[bed] return self # test cases test1 = Hospital() test1.admit( "Vinney", ["cats", "grass"] ).admit( "Mary", "none" ).admit( "Imron", "none" ).admit( "Ethan", "none" ).admit( "James", "none" ).admit( "Robert", "none" ).discharge( "Imron" ).admit( "Robert", "none" )
all_colors = [ {"label": 'Red', "sexy": True}, {"label": 'Pink', "sexy": False}, {"label": 'Orange', "sexy": True}, {"label": 'Brown', "sexy": False}, {"label": 'Pink', "sexy": True}, {"label": 'Violet', "sexy": True}, {"label": 'Purple', "sexy": False}, ] #Your code go here: color = [] for x in all_colors: if x["sexy"] == True: color.append(x["label"]) # print(color) def print_ul(elements): print("<ul>") for s in elements: ul = "<li>" + str(s) + "</li>" print(ul) print("</ul>") print_ul(color)
n = int(input("Enter a binary number: ")) sum = 0 i = 0 while n != 0: rem = n % 10 sum = sum + rem * pow(2,i) n = int(n/10) i = i + 1 print("Decimal number %.2f" % sum)
#!/usr/bin/python3 def main(): choices = dict( one = '1', two = '2', three = '3', four = '4', five = '5', ) v = 'three' print( choices.get(v, 'other')) if __name__ == "__main__": main()
#!/usr/bin/python3 def main(): a, b = 1, 0 v = 'This is true ' if a > b else 'This is not true' print(v) if __name__ == "__main__": main()