text
stringlengths
37
1.41M
#!/usr/bin/env python3 """ Name: Andrew Krubsack Email: [email protected] Description: Midterm Jurassic Park script """ print("Name: Andrew Krubsack") password_database = {} password_database = {"Username":"dnedry","Password":"please"} command_database = {} command_database = {"reboot":"OK. I will reboot all park systems."} command_database["shutdown"] = "OK. I will shut down all park systems." command_database["done"] = "I hate all this hacker stuff." white_rabbit_object = 0 counter = 0 while white_rabbit_object == 0 and counter < 3: counter += 1 print("Username:") input_user = input("->") print("Password:") input_password = input("->") # == UserName and Password Logic ====== if (input_user == password_database["Username"]) and \ (input_password == password_database["Password"]): white_rabbit_object = 1 print("Hi, Dennis. You're still the best hacker in Jurassic Park.") print("Enter a command") print("1. reboot") print("2. shutdown") print("3. done") # == Command Logic ============ command = input("->") if command in command_database.keys(): print(command_database[command]) else: print("The Lysine Contingency has been put into effect.") else: if counter < 3: print("You didn't say the magic word. {count}") else: repeat = "You didn't say the magic word.\n" * 25 print(repeat)
class Person: def __init__(self, name, base_attack, base_deff, base_hp): self.name = name self.base_deff = base_deff self.base_attack = base_attack self.base_hp = base_hp def __str__(self): return self.name def set_things(self, things): for thing in things: self.equip_thing(thing) def equip_thing(self, item): print(f'{self.name} получил {item.thing_name}') if item.t_attack is not None: self.base_attack = self.base_attack + item.t_attack if item.t_deff is not None: self.base_deff = self.base_deff + item.t_deff if item.t_hp is not None: self.base_hp = self.base_hp + item.t_hp print(f'Боец {self.name} получает бонусы:' f'|Атака:+{item.t_attack}| |Защита:+{item.t_deff}|' f' |Хп:+{item.t_hp}|') class Paladin(Person): def __init__(self, name, base_attack, base_deff, base_hp): super().__init__(name, base_attack, base_deff, base_hp) self.base_hp = base_hp * 2 self.base_deff = base_deff * 2 print(f'Боец {self.name} из ордена паладинов прибыл.') class Warrior(Person): def __init__(self, name, base_attack, base_deff, base_hp): super().__init__(name, base_attack, base_deff, base_hp) self.base_attack = base_attack * 2 print(f'Боец {self.name} из касты войнов прибыл.')
""" Complexity: O(n log n) Evey iteration of input values takes O(log n) time as inputs gets half in size for every function call Formula: - create two subarrys of half size of input array - merge the subarrys """ def merge_sort(n): """ >>> merge_sort([2, 3, 1, 4, 2, 5, 6]) [1, 2, 2, 3, 4, 5, 6] """ k = len(n)//2 if len(n) == 1: return n a = merge_sort(n[:k]) b = merge_sort(n[k:]) return merge(a, b) def merge(a, b): r = [] while a and b: if a[0] < b[0]: r.append(a[0]) del a[0] else: r.append(b[0]) del b[0] if a: r.extend(a) if b: r.extend(b) return r if __name__ == "__main__": import sys r = merge_sort([int(i) for i in sys.argv[1:]]) print(r)
#!/usr/bin/python # to syntax check run # python -m py_compile <filename> # import socket library to help us scan for ports import socket # the import below is python3 and above from termcolor import colored # creating a socket object and assigning it to sock, # and we are going to use the AF_INET which says it is going # to be an IPv4 address host that we are going to connect to # and the SOCK_STREAM represents we are going to use TCP sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # give a 'false' value back after 3 seconds if no response # is recieved from the ip/port socket.setdefaulttimeout(3) # what is the host to connect to #host = "109.64.40.173" # what is the port you want to scan #port = 111 # get user input instead of hard coding the IP or the port # raw_input for python2 and input for python3 host = input("Please type the IP address you want to scan: ") # we have to wrap it in an int because it is going to be pure numbers # that the sock.connect_ex is going to do #port = int(raw_input("Please type the port you want to scan: ")) def portscanner(port): if sock.connect_ex((host,port)): # adding colours so we can see the difference print(colored("port %d is closed" % (port), 'red')) else: print(colored("port %d is open" % (port), 'green')) # port_scanning the first 1000 ports for the # give ip address for port in range(1, 1000): portscanner(port);
class PalindromeChecker: @staticmethod def check_palindrome(word): result = False odd_letter_set = set() for letter in word: if letter in odd_letter_set: odd_letter_set.remove(letter) else: odd_letter_set.add(letter) if len(odd_letter_set) <= 1: result = True return result
import constants MAIN_MENU = """ BASKETBALL TEAM STATS TOOL ---- MENU---- Here are your choices: 1) Display Team Stats 2) Quit Enter an option >""" def clean_data(source_data): """ Takes in the PLAYERS constant Map the contents of the constant (sorted by experience) into a new dictionary list, cleaning the data as we go. Returns the new dictionary list of cleaned and sorted data """ return [{ 'name':player.get('name'), 'guardians':player.get('guardians').split(' and '), 'experience':player.get('experience') == 'YES', 'height':int(player.get('height').split()[0]) } for player in sorted(source_data, key=lambda k: k['experience'])] def balance_teams(source_teams, players): """ Takes list of cleaned and sorted players and the TEAMS constant Populates a dictionary with an entry for each team with the team name and an empty players list We keep cycling through the teams and step through the players allocating players to team until all players are assigned a team Returns the populated teams dictionary """ teams = [] for team in constants.TEAMS: teams.append({'team': team, 'players':[]}) player_index = 0 while player_index < len(players): for team in teams: team["players"].append(players[player_index]) player_index += 1 return(teams) def show_team_menu(): """ Prints list of teams with indexes Prompts users to choose which teams stats to display """ team_menu_choice = True while team_menu_choice: print("\n") menu_index = 1 for team in teams: print(f"{menu_index}) {team['team']}") menu_index += 1 try: team_menu_choice = int(input("\nEnter an option >")) if team_menu_choice > 0 and team_menu_choice <= len(teams): show_team_stats(team_menu_choice - 1) break else: raise ValueError() except ValueError: print("Invalid choice, try again") def show_team_stats(team_index): team = teams[team_index] #team name print(f"\nTeam: {team['team']} Stats") print("--------------------") #total players total_players = len(team["players"]) print(f'Total players: {total_players}') total_experienced_players = 0 total_inexperienced_players = 0 for player in team["players"]: if player['experience'] == True: total_experienced_players += 1 else: total_inexperienced_players += 1 #total experienced players print(f'Total experienced: {total_experienced_players}') #total inexperienced players print(f'Total inexperienced: {total_inexperienced_players}') #average height total_player_height = 0 for player in team["players"]: total_player_height = total_player_height + player['height'] average_player_height = round(total_player_height / total_players, 1) print(f'Average height: {average_player_height}') #List of players player_names = [player['name'] for player in team["players"]] print("\nPlayers on Team:") print(" " + ", ".join(player_names)) #list of guardians list_of_guardians = [] list_of_list_of_guardians = [player['guardians'] for player in team["players"]] for guardians in list_of_list_of_guardians: for guardian in guardians: list_of_guardians.append(guardian) print("\nGuardians:") print(" " + ", ".join(list_of_guardians)) input("\nPress ENTER to continue...") if __name__ == "__main__": players = clean_data(constants.PLAYERS) teams = balance_teams(constants.TEAMS, players) main_menu_choice = True while main_menu_choice: main_menu_choice = input(MAIN_MENU) if main_menu_choice == '1': show_team_menu() elif main_menu_choice == '2': main_menu_choice = False else: print("You did not make a valid selection")
a=int(input("Informe o primeiro número: ")) b=int(input("Informe o segundo número: ")) numero = a+b if numero > 1: for i in range (2, numero): if (numero % i) == 0: print ("O número",numero,"não é primo.") break if (i == (numero - 1)): print ("O número",numero,"é primo.") else: print ("O número",numero,"não é primo.")
from matplotlib import pyplot as plt import numpy as np import random # https://blog.csdn.net/your_answer/article/details/79259063 # 遗传算法 def coordinate_init(size): # 产生坐标字典 coordinate_dict = {} coordinate_dict[0] = (-size, 0) # 起点是(-size,0) up = 1 for i in range(1, size + 1): # 顺序标号随机坐标 x = np.random.uniform(-size, size) if np.random.randint(0, 2) == up: y = np.sqrt(size ** 2 - x ** 2) else: y = -np.sqrt(size ** 2 - x ** 2) coordinate_dict[i] = (x, y) coordinate_dict[size + 1] = (-size, 0) # 终点是(-size,0),构成一个圆 return coordinate_dict def distance_matrix(coordinate_dict, size): # 生成距离矩阵 d = np.zeros((size + 2, size + 2)) for i in range(size + 1): for j in range(size + 1): if (i == j): continue if (d[i][j] != 0): continue x1 = coordinate_dict[i][0] y1 = coordinate_dict[i][1] x2 = coordinate_dict[j][0] y2 = coordinate_dict[j][1] distance = np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) if (i == 0): d[i][j] = d[size + 1][j] = d[j][i] = d[j][size + 1] = distance else: d[i][j] = d[j][i] = distance return d def path_length(d_matrix, path_list, size): # 计算路径长度 length = 0 for i in range(size + 1): length += d_matrix[path_list[i]][path_list[i + 1]] return length def shuffle(my_list): # 起点和终点不能打乱 temp_list = my_list[1:-1] np.random.shuffle(temp_list) shuffle_list = my_list[:1] + temp_list + my_list[-1:] return shuffle_list def product_len_probability(my_list, d_matrix, size, p_num): len_list = [] pro_list = [] path_len_pro = [] for path in my_list: len_list.append(path_length(d_matrix, path, size)) max_len = max(len_list) + 1e-10 gen_best_length = min(len_list) gen_best_length_index = len_list.index(gen_best_length) mask_list = np.ones(p_num) * max_len - np.array(len_list) sum_len = np.sum(mask_list) for i in range(p_num): if (i == 0): pro_list.append(mask_list[i] / sum_len) elif (i == p_num - 1): pro_list.append(1) else: pro_list.append(pro_list[i - 1] + mask_list[i] / sum_len) for i in range(p_num): path_len_pro.append([my_list[i], len_list[i], pro_list[i]]) return my_list[gen_best_length_index], gen_best_length, path_len_pro def choose_cross(population, p_num): jump = np.random.random() if jump < population[0][2]: return 0 low = 1 high = p_num mid = int((low + high) / 2) # 二分搜索 while (low < high): if jump > population[mid][2]: low = mid mid = int((low + high) / 2) elif jump < population[mid - 1][2]: high = mid mid = int((low + high) / 2) else: return mid def veriation(my_list, size): # 变异 ver_1 = np.random.randint(1, size + 1) ver_2 = np.random.randint(1, size + 1) while ver_2 == ver_1: # 直到ver_2与ver_1不同 ver_2 = np.random.randint(1, size + 1) my_list[ver_1], my_list[ver_2] = my_list[ver_2], my_list[ver_1] return my_list size = 50 p_num = 100 # 种群个体数量 gen = 2000 # 进化代数 pm = 0.1 # 变异率 coordinate_dict = coordinate_init(size) # 距离矩阵 d = distance_matrix(coordinate_dict, size) # 初始点列表 path_list = list(range(size + 2)) population = [0] * p_num # 种群矩阵 # 建立初始种群,随机打乱初始点列表 for i in range(p_num): population[i] = shuffle(path_list) gen_best, gen_best_length, population = product_len_probability(population, d, size, p_num) # print(population) # 这个列表的每一项中有三项,第一项是路径,第二项是长度,第三项是使用时转盘的概率 son_list = [0] * p_num best_path = gen_best # 最好路径初始化 best_path_length = gen_best_length # 最好路径长度初始化 every_gen_best = [] every_gen_best.append(gen_best_length) for i in range(gen): # 迭代gen代 son_num = 0 while son_num < p_num: # 产生p_num数量子代,杂交与变异 # 通过二分查找,随机选取父索引和母索引 father_index = choose_cross(population, p_num) mother_index = choose_cross(population, p_num) father = population[father_index][0] mother = population[mother_index][0] # print("father {}".format(father)) # print("mother {}".format(mother)) son1 = father.copy() son2 = mother.copy() prduct_set = np.random.randint(1, p_num + 1) print("father index {}".format(len(father))) print(prduct_set) # 随机选取父列表,母列表的索引值 father_cross_set = set(father[1:prduct_set]) mother_cross_set = set(mother[1:prduct_set]) # print("father cross set {}".format(father_cross_set)) # print("mother cross set {}".format(mother_cross_set)) cross_complete = 1 for j in range(1, size + 1): # 如果父的子列表元素存在母列表中,使用母元素替换父的子元素 # 操作目的,将父的子列表中的元素按照母列表中的顺序进行排列 if son1[j] in mother_cross_set: son1[j] = mother[cross_complete] cross_complete += 1 if cross_complete > prduct_set: break if np.random.random() < pm: # 变异 son1 = veriation(son1, size) son_list[son_num] = son1 son_num += 1 if son_num == p_num: break cross_complete = 1 for j in range(1, size + 1): if son2[j] in father_cross_set: son2[j] = father[cross_complete] cross_complete += 1 if cross_complete > prduct_set: break if np.random.random() < pm: # 变异 son2 = veriation(son2, size) son_list[son_num] = son2 son_num += 1 gen_best, gen_best_length, population = product_len_probability(son_list, d, size, p_num) if (gen_best_length < best_path_length): best_path = gen_best best_path_length = gen_best_length every_gen_best.append(gen_best_length) x = [] y = [] for point in best_path: x.append(coordinate_dict[point][0]) y.append(coordinate_dict[point][1]) # print(gen_best) # 最后一代最优路径 # print(gen_best_length) # 最后一代最优路径长度 # print(best_path) # 史上最优路径 # print(best_path_length) # 史上最优路径长度 # plt.figure(1) # plt.subplot(211) # plt.plot(every_gen_best) # plt.subplot(212) # plt.scatter(x, y) # plt.plot(x, y) # plt.grid() # plt.show()
#3과5가 출력된다. #if True : #if False: #print("1") #print("2") #else: #print("3") #else : #print("4") #print("5") #위 코드를 보면, "사실인 상태에서, 거짓이라면 1과 2를 출력하라 아니라면 3을 출력하라" 라고 되어있다. #그렇다면 거짓이 아닌 사실인 상태이기 때문에 1과 2는 출력되지 않으며, 거짓이 아니기 때문에 3이 출력된다. #if false의 조건문이 종료된다. if true의 조건문이 유지된 상태, 즉 사실인 상태가 아니라면 4를 출력하라 라고 되어있다. # 하지만 사실인 상태이기 때문에 4가 출력되지 않으며, if true의 조건문이 종료된다. #아무런 조건이 걸리지 않은 채 5를 출력하라 라고 되어있으나, 5가 출력된다. # 따라서 3과 5가 출력되는 값이 보일 것 이다.
nums = [1,2,3,4,5] avg=sum(nums)/len(nums) print(avg) # list의 평균값= list의 모든 원소들의 합/ list의 모든 원소의 갯수 #list의 평균값을 avg로 정의함 #list인 nums안에있는 원소들의 합을 구하기 위해 sum 함수를 사용 # 원소의 갯수로 나눠줘야 하기 때문에 원소갯수를 구하는 len 함수를 사용한 뒤 나눠줌 # avg로 정의한 평균값을 출력한다.
import abc import random class Tombola(abc.ABC): @abc.abstractmethod def load(self, iterable): """Add items from an iterable""" @abc.abstractmethod def pick(self): """Remove item at random""" def loaded(self): return bool(self.inspect()) def inspect(self): items = [] while True: try: items.append(self.pick()) except LookupError: break self.load(items) return tuple(sorted(items)) class Fake(Tombola): def pick(self): return 13 class Struggle: def __len__(self): return 23 class BingoCage(Tombola): def __init__(self, items): self._randomizer = random.SystemRandom() self._items = [] self.load(items) def load(self, items): self._items.extend(items) self._randomizer.shuffle(self._items) def pick(self): try: return self._items.pop() except IndexError: raise LookupError('pick from empty BingoCage') def __call__(self): self.pick() class LotteryBlower(Tombola): def __init__(self, iterable): self._balls = list(iterable) def load(self, iterable): self._balls.extend(iterable) def pick(self): try: position = random.randrange(len(self._balls)) except ValueError: raise LookupError('pick from empty BingoCage') return self._balls.pop(position) def loaded(self): return bool(self._balls) def inspect(self): return tuple(sorted(self._balls)) @Tombola.register class TomboList(list): def pick(self): if self: position = random.randrange(len(self)) return self.pop(position) else: raise LookupError('pop from empty TomboList') load = list.extend def loaded(self): return bool(self) def inspect(self): return tuple(sorted(self)) from collections import abc print('isinstance(Struggle(), abc.Sized)\n{}\n----------'.format(isinstance(Struggle(), abc.Sized))) print('issubclass(Struggle, abc.Sized)\n{}\n----------'.format(issubclass(Struggle, abc.Sized))) Tombola.register(TomboList) print('issubclass(TomboList, Tombola)\n{}\n----------'.format(issubclass(TomboList, Tombola))) t = TomboList(range(100)) print('isinstance(t, Tombola)\n{}\n----------'.format(isinstance(t, Tombola))) print('TomboList is not inherited from Tombola -- TomboList.__mro__\n{}\n----------'.format(TomboList.__mro__)) TEST_FILE = 'tombola_tests.rst' TEST_MSG = '{0:16} {1.attempted:2} tests, {1.failed:2} failed - {2}' import doctest def main(argv): verbose = '-v' in argv real_subclasses = Tombola.__subclasses__() virtual_subclasses = list(Tombola._abc_registry) print(real_subclasses + virtual_subclasses) for cls in real_subclasses + virtual_subclasses: test(cls, verbose) def test(cls, verbose=False): print("*******************"*10 + cls.__name__) res = doctest.testfile(TEST_FILE, globs={'ConcreteTombola': cls}, verbose=verbose, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE) tag = 'FAIL' if res.failed else 'OK' print(TEST_MSG.format(cls.__name__, res, tag)) if __name__ == '__main__': import sys main(sys.argv) # python3 tombola.py -v
from collections import abc my_dict = {} print('-'*20) print("instance of abc {}".format(isinstance(my_dict, abc.Mapping))) print('-'*20) tt = (1,2,(30,40)) print("tuple is hashable {}".format(hash(tt))) tf = (1,2,frozenset([30,40])) print("frozen set is hashable {}".format(hash(tf))) print('-'*20) a = dict(one=1,two=2,three=3) print("building dict {}".format(a)) b = {'one' : 1, 'two': 2, 'three' : 3} print("building dict {}".format(b)) c = dict(zip(['one', 'two', 'three'], [1,2,3])) print("building dict {}".format(c)) d = dict([('two', 2), ('one', 1), ('three', 3)]) print("building dict {}".format(d)) e = dict({'three':3, 'one': 1, 'two': 2}) print("building dict {}".format(e)) print("equal dict {}".format(a==b==c==d==e)) print('-'*20) DIAL_CODES = [ (86, 'China'), (91, 'India'), (1, 'United States'), (62, 'Indonesia'), (55, 'Brazil'), (92, 'Pakistan'), (880, 'Bangladesh'), (234, 'Nigeria'), (7, 'Russia'), (81, 'Japan'), ] country_code = {country: code for code, country in DIAL_CODES} print("country_code {}".format(country_code)) print("another code {}".format({code: country.upper() for country, code in country_code.items() if code < 66})) print('-'*20) class StrKeyDict0(dict): def __missing__(self, key): if isinstance(key, str): raise KeyError(key) return self[str(key)] def get(self, key, default=None): try: return self[key] except KeyError: return default def __contains__(self, key): return key in self.keys() or str(key) in self.keys() d = StrKeyDict0([('2','two'), ('4','four')]) print("StrKeyDict0 d['2'] {}".format(d['2'])) print("StrKeyDict0 d[4] {}".format(d[4])) # below will raise exception # print("StrKeyDict0 d[1] {}".format(d[1])) print("StrKeyDict0 d.get('2') {}".format(d.get('2'))) print("StrKeyDict0 d.get(4) {}".format(d.get(4))) print("StrKeyDict0 d.get(1, 'N/A') {}".format(d.get(1, 'N/A'))) print("StrKeyDict0 2 in d {}".format(2 in d)) print("StrKeyDict0 1 in d {}".format(1 in d)) print('-'*20) import builtins from collections import ChainMap pylookups = ChainMap(locals(), globals(), vars(builtins)) print("builtins {}".format(pylookups)) from collections import Counter ct = Counter('abracadabra') print("counter {}".format(ct)) ct.update('aaaaazzz') print("counter {}".format(ct)) print("most common {}".format(ct.most_common(2))) print('-'*20) import collections class StrKeyDict(collections.UserDict): def __missing__(self, key): if isinstance(key, str): raise KeyError(key) return self[str[key]] def __contains__(self, key): return str(key) in self.data def __setitem__(self, key, item): self.data[str(key)] = item d = StrKeyDict([(2,'two'), (4,'four')]) # print("StrKeyDict d[2] {}".format(d[2])) print("StrKeyDict d['2'] {}".format(d['2'])) print('-'*20) from types import MappingProxyType d = {1: 'A'} d_proxy = MappingProxyType(d) print("d_proxy {}".format(d_proxy)) print("d_proxy[1] {}".format(d_proxy[1])) d[2] = 'B' #any changes will be reflect print("d_proxy[2] {}".format(d_proxy[2]))
def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ input_len = len(input_list) input_freq = [0] * 10 pivot = 1 merge_opt1 = [] merge_opt2 = [] if input_len == 0 or input_len == 1: return [-1, -1] if input_len % 2 != 0: pivot = 2 for num in input_list: input_freq[num] += 1 for item in range((len(input_freq) - 1), -1, -1): while input_freq[item]: if pivot: merge_opt1.append(str(item)) pivot -= 1 else: pivot += 1 merge_opt2.append(str(item)) input_freq[item] -= 1 return [int(''.join(merge_opt1)), int(''.join(merge_opt2))] def test_function(test_case): output = rearrange_digits(test_case[0]) solution = test_case[1] if sum(output) == sum(solution): print("Pass") else: print("Fail") # Normal Cases test_function([[1, 2, 3, 4, 5], [542, 31]]) # Pass test_function([[4, 6, 2, 5, 9, 8], [964, 852]]) # Pass test_function([[1, 2, 3], [31, 2]]) # Pass # Edge Cases test_function([[0, 1, 2, 5, 6, 7], [752, 167]]) # Fail test_function([[1, 9, 1], [10, 1]]) # Fail test_function([[], []]) # Fail
class Group(object): def __init__(self, _name): self.name = _name self.groups = [] self.users = [] def add_group(self, group): self.groups.append(group) def add_user(self, user): self.users.append(user) def get_groups(self): return self.groups def get_users(self): return self.users def get_name(self): return self.name def is_user_in_group(user, group): """ Return True if user is in the group, False otherwise. Args: user(str): user name/id group(class:Group): group to check user membership against """ if user == "" or user is None: return "Set values for user" if group == "" or group is None: return "Set values for group" if not isinstance(group, Group): return "Invalid group input!" if user in group.get_users(): # User found return True else: if len(group.get_groups()) == 0: # Keep searching return False else: for sub_group in group.get_groups(): found = is_user_in_group(user, sub_group) return found parent = Group("parent") child = Group("child") sub_child = Group("subchild") sub_child_user = "sub_child_user" sub_child.add_user(sub_child_user) child.add_group(sub_child) parent.add_group(child) # Test print(is_user_in_group(user="parent_user", group=parent)) #False print(is_user_in_group(user="child_user", group=parent)) #False print(is_user_in_group(user="sub_child_user", group=parent)) # True # Edge Case print(is_user_in_group(user="other_group", group=parent)) # False print(is_user_in_group(user="", group=parent)) # Set values for user and group print(is_user_in_group(user="sub_child_user", group=sub_child_user)) # Invalid group input!
friends = ["Peter", "Pete", "Pet", "Hun", "Jade"] print(friends) print(friends[1]) friends[1] = "Julie" print(friends[1:]) lucky_numbers = [4, 3, 2, 7, 13, 23] #friends.extend(lucky_numbers) friends.append("Ralph") friends.insert(1, "Pony") friends.remove("Pet") friends.pop() print(friends) friends.index("Pony") friends.sort() lucky_numbers.reverse() friends2 = friends.copy() print(friends2)
# tuple is a kind of data structure, similar to a list but with a couple or more differences as below; # tuples are immutable(cannot modify) coordinates = (4, 5) print(coordinates[1]) # coordinates[1] = 10 expected output: TypeError: 'tuple' object does not support item assignment coordinates_list = [(3, 4), (21, 3), (1, 12)]
"""CSC110 Fall 2020 Final Project, Extraction File Copyright and Usage Information =============================== This file is provided solely for the personal and private use of Professors and TA's teaching CSC110 at the University of Toronto St. George campus. All forms of distribution of this code, whether as given or with any changes, are expressly prohibited. For more information on copyright for CSC110 materials please consult the owners. This file is Copyright (c) 2020 Carson, Kowan, Girish, Howard """ import csv from typing import List, Tuple, Dict def get_data(filename: str) -> Dict[str, List[Tuple[int, float]]]: """ Return a dictionary of of country to tuple. The tuple has two values, a year and carbon emission amount Preconditions: - files are csv files - files follow the format as Canada_-_CO2_emissions.csv file format - filename is a filepath that leads to a valid csv file outlined above """ with open(filename) as file: reader = csv.reader(file) # get header for dates headers = next(reader) data = next(reader) country = data[3] # format data and return it country_data = {country: [(int(headers[pos]), float(data[pos])) for pos in range(4, len(headers))]} return country_data def get_gdp(filename: str) -> List[float]: """ Return a list of a countries gdp from 1970 to 2018 The list is ordered from 1970 to 2018 values Preconditions: - files are csv files - files follow the format as Canada_GDP.csv file format - filename is a filepath that leads to a valid csv file outlined above """ gdp_so_far = [] reversed_gdp_so_far = [] with open(filename) as file: reader = csv.reader(file) # skip header next(reader) data = next(reader) while 1970 <= int(data[0]) <= 2018: gdp_so_far.append(data[1]) data = next(reader) # flip the list so the last item is the first item while gdp_so_far != []: reversed_gdp_so_far.append(gdp_so_far.pop()) return reversed_gdp_so_far if __name__ == '__main__': import python_ta python_ta.check_all(config={ 'max-line-length': 100, 'extra-imports': ['python_ta.contracts', 'csv'], 'allowed-io': ['get_gdp', 'get_data'], 'disable': ['R1705'] }) import python_ta.contracts import doctest doctest.testmod()
class Product(object): def __init__(self, price, item_name, weight, brand, cost): self.price = price self.item_name = item_name self.weight = weight self.brand = brand self.cost = cost self.status = "for sale" def sell(self): self.status = "sold" return self def addTax(self,num): self.price = self.price + (self.price * num) return self def return_reason(self,reason): if reason == "defective": self.status = "defective" self.price = 0 elif reason == "like new": self.status = "for sale" elif reason == "open": self.status = "used" self.price = self.price - (self.price * 0.20) return self def displayInfo(self): print "Price:", self.price print "Name:", self.item_name print "Weight:", self.weight print "Brand:", self.brand print "Cost:", self.cost print "Status:", self.status
class Animal(object): def __init__(self, name, health): self.name = name self.health = health def walk(self,rep): self.health -= 1 * rep return self def run(self,rep): self.health -= 5*rep return self def displayHealth(self): print "Health:", self.health return self # animal1 = Animal("cat", 20) # animal1.walk(3).run(2).displayHealth() class Dog(Animal): def __init__(self): self.health = 150 def pet(self): self.health +=5 return self # dog1 = Dog() # dog1.walk(3).run(2).pet().displayHealth() class Dragon(Animal): def __init__(self): self.health = 170 def fly(self): self.health -= 10 return self def displayHealth(self): super(Dragon, self).displayHealth() print "I am a Dragon" return self # dragon1 = Dragon() # dragon1.fly().displayHealths() class Cat(Animal): def __init__(self): self.health = 10 cat1 = Cat() cat1.displayHealth()
# Main Class # Rahul Shrestha # CMPS 470-Spring 2016 # Dr. John W. Burris # https://github.com/rahulShrestha89/470-Assignment1 # This program implements the DECISION_TREE_LEARNING algorithm. # Input Description: # First line: (N) Number of examples # Second line: (X) Number of attributes (Not including goal predicate) # Third line: The name of each of the X attributes on a single line, separated by comma. # Following N lines contain X+1 values containing the data set, separated by comma. import os import math # generator function to map key-value pair # and holds values respective to attributes # i.e. attributes with respective example values in a dictionary def get_examples(examples, attributes): for value in examples: yield dict(zip(attributes, value.strip().replace(" ", "").split(','))) # get the list of Goal Predicate from the examples # extracted from the input file def get_goal_predicates(): return [d['Predicate'] for d in examples] # get the total distribution of goal predicates # for instance: total number of yes/no def get_goal_predicate_frequency(goal_predicate_list): # holds total number of occurrence of goal predicates frequency = [] # holds the predicate,respective occurrence value in dictionary goal_predicate_distribution = {} # count the occurrence and store in the list for i in range(len(goal_predicate_list)): frequency.append(get_goal_predicates().count(goal_predicate_list[i])) # hold the values as (key,value) zip_pair = zip(goal_predicate_list, frequency) # assign values to the dictionary for goal_predicate_list, frequency in zip_pair: goal_predicate_distribution[goal_predicate_list] = frequency return goal_predicate_distribution # get the unique example values of each attribute in a list def get_unique_example_values(): # stores the unique values of an attribute in a list of lists unique_example = [] # reads the attributes and its respective example values for i in range(len(name_of_attributes)-1): unique_example.append(list(set([d[name_of_attributes[i]] for d in examples]))) return unique_example # get the frequency of examples # i.e. occurrence of an attribute value in an example # get the total distribution of goal predicates # for instance: total number of yes/no def get_example_frequency(): # stores the unique values of an attribute in a list of lists unique_example = get_unique_example_values() # hold attribute_frequency_dict as a list # stores as [{ },{ },...{ }] attribute_frequency_list = [] for i in range(len(unique_example)): for j in range(len(unique_example[i])): # stores as { "attribute": value, "predicate_value[0]": occurrence, "predicate_value[1]": occurrence} attribute_frequency_dict = {name_of_attributes[i]: unique_example[i][j]} for k in range(len(goal_predicate_list)): frequency = len([x for x in examples if x['Predicate'] == goal_predicate_list[k] and x[name_of_attributes[i]] == unique_example[i][j]]) attribute_frequency_dict[goal_predicate_list[k]] = frequency attribute_frequency_list.append(attribute_frequency_dict) return attribute_frequency_list # using entropy to calculate the homogeneity of a sample. # Entropy is the sum of p(x)log(p(x)) across all the different possible results # If the sample is completely homogeneous the entropy is zero and # if the sample is an equally divided it has entropy of one. # it is based on the overall distribution of predicate # gets the entropy of the target i.e. the goal predicate def get_goal_predicate_entropy(): # store the entropy value predicate_entropy = 0 # store the sum of frequencies sum_of_frequencies = 0 # store the dictionary with predicate and its frequency frequency_values = get_goal_predicate_frequency(goal_predicate_list) for key in frequency_values.keys(): sum_of_frequencies += frequency_values[key] for key in frequency_values.keys(): predicate_entropy += (-frequency_values[key]/sum_of_frequencies) \ * math.log(frequency_values[key]/sum_of_frequencies, 2) return predicate_entropy # gets the entropy of the examples based on their frequency def get_entropy(attribute, value): # holds all the info for attributes and its respective goal predicate frequency data = get_example_frequency() # finds the dictionary with attribute == value dic = next(item for item in data if item.get(attribute) == value) # remove the attribute and value from dictionary dic.pop(attribute, None) # stores the entropy value entropy = 0 # stores the sum of all frequency of an attribute example total_sum = sum(dic.values()) for i in range(len(goal_predicate_list)): # check if the frequency is 0 if (dic[goal_predicate_list[i]]) == 0: entropy += 0 else: entropy += (-(dic[goal_predicate_list[i]]/total_sum)) * math.log((dic[goal_predicate_list[i]])/total_sum, 2) return entropy # Entropy using the frequency table of two attributes # It is the product of Probability and Entropy value of the attribute def get_entropy_of_two_attributes(attribute,index): unique_examples = get_unique_example_values() # holds the entropy value entropy = 0 # loop until sub list has values for k in range(len(unique_examples[index])): entropy += ((int([d[attribute] for d in examples].count(unique_examples[index][k]))) / (len(examples))) * (get_entropy(attribute, unique_examples[index][k])) return entropy # information gain is based on the decrease in entropy after a data set is split on an attribute # gain = entropy(goal predicate) - entropy(attribute along with the predicate) def get_information_gain(): # stores as { "attribute_1": entropy_value_1, "attribute_2": entropy_value_2 } information_gain_dict = {} # stores the difference between entropy of predicates in a dictionary # loop starts with the first attribute for i in range(len(name_of_attributes)-1): information_gain_dict[name_of_attributes[i]] = (get_goal_predicate_entropy() - get_entropy_of_two_attributes(name_of_attributes[i], i)) return information_gain_dict # find the best attribute based on information gain # attribute with the largest information gain is the decision node. def find_best_attribute(): # find key with the highest entropy value best_attribute = max(get_information_gain(), key=get_information_gain().get) return best_attribute # TODO: # find the most common value for an attribute def majority(): return 0 # TODO: def get_values(): return 0 def make_tree(data, attributes, target, recursion): recursion += 1 # Returns a new decision tree based on the examples given data = data[:] vals = [record[attributes.index(target)] for record in data] default = majority(attributes, data, target) # If the data set is empty or the attributes list is empty, return the # default value. When checking the attributes list for emptiness, we # need to subtract 1 to account for the target attribute. if not data or (len(attributes) - 1) <= 0: return default # If all the records in the data set have the same classification, # return that classification. elif vals.count(vals[0]) == len(vals): return vals[0] else: # Choose the next best attribute to best classify our data best = find_best_attribute() # Create a new decision tree/node with the best attribute and an empty # dictionary object--we'll fill that up next. tree = {best: {}} # Create a new decision tree/sub-node for each of the values in the # best attribute field for val in get_values(data, attributes, best): # Create a subtree for the current value under the "best" field example = get_example_frequency(data, attributes, best, val) new_attr = attributes[:] new_attr.remove(best) subtree = make_tree(examples, new_attr, target, recursion) # Add the new subtree to the empty dictionary object in our new # tree/node we just created. tree[best][val] = subtree return tree # get the file name from the user file_name = input("Enter the input file name: ") # look for file in the directory try: fo = open(file_name, "r") except IOError: print("Error: can\'t find file or read data.") else: print("File found.") # check if the file is empty if os.stat(file_name).st_size <= 0: print("Not enough data in the input file.") else: # read and stores the number of examples, attributes. # as well as the name of attributes, and all examples with open(file_name, 'r') as file: number_of_examples = int(file.readline()) number_of_attributes = int(file.readline()) # replace the spaces and use , as delimiter name_of_attributes = [n for n in (file.readline().strip().replace(" ", "")).split(",")] name_of_attributes.append("Predicate") # store all the unfiltered examples as list all_examples = file.readlines() # holds all the examples as a list of dictionary # for instance: dic=[{'name_attributes': respective_example_value_from_the_file},...{}] examples = list(get_examples(all_examples, name_of_attributes)) # get the values of Predicate from the examples # set - unordered collection of unique elements goal_predicate_list = list(set(get_goal_predicates())) # invoke get_entropy_of_attributes function get_goal_predicate_entropy() # gets the best attribute for the tree print('Finding the best attribute....') print() print(' The best attribute for the root node is ' + find_best_attribute()) print() print('Still a work in progress to get the TRESS!')
import random class GameController: """ 2048游戏算法代码 """ __list_2048 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] def move_zero(self): """ 将一行列表的零元素移动到末尾 :return: """ for i in range(len(list_row) - 1, -1, -1): if list_row[i] == 0: del list_row[i] list_row.append(0) def add_adjoin(self): """ 每行相邻相同数字相加 :return: """ self.move_zero() for i in range(len(self.__list_2048) - 1): if list_row[i] == list_row[i + 1]: list_row[i] *= 2 del list_row[i + 1] list_row.append(0) def left_shift(self): """ 左移指令算法 :return: """ global list_row for line in self.__list_2048: list_row = line self.add_adjoin() def right_shift(self): """ 右移指令算法 :return: """ global list_row for item in self.__list_2048: list_row = item[::-1] self.add_adjoin() item[::] = list_row[::-1] def matrix_transpose(self): """ 矩阵转置函数 :return: """ for r in range(len(self.__list_2048) - 1): for c in range(r + 1, len(self.__list_2048)): self.__list_2048[c][r], self.__list_2048[r][c] = self.__list_2048[r][c], self.__list_2048[c][r] def up_shift(self): """ 上移指令算法 :return: """ self.matrix_transpose() self.left_shift() self.matrix_transpose() def down_shift(self): """ 下移指令算法 :return: """ self.matrix_transpose() self.right_shift() self.matrix_transpose() def print_interface_of_game(self): """ 打印界面函数 :return: """ for item in self.__list_2048: print(item[0], item[1], item[2], item[3], sep='\t', end='\n') def add_2_to_list_2048(self): """ 每次移动都在0的位置添加一个新的2元素 :return: """ list_index_of_0 = [] for r in range(len(self.__list_2048)): for c in range(len(self.__list_2048)): if self.__list_2048[r][c] == 0: # 0元素的坐标(r,c) list_index_of_0.append((r, c)) index_of_0 = random.choice(list_index_of_0) # 随机找到列表中的一个元素 self.__list_2048[index_of_0[0]][index_of_0[1]] = 2 # 添加新的2元素
""" Turbulence gradient temporal power spectra calculation and plotting :author: Andrew Reeves :date: September 2016 """ import numpy from matplotlib import pyplot def calc_slope_temporalps(slope_data): """ Calculates the temporal power spectra of the loaded centroid data. Calculates the Fourier transform over the number frames of the centroid data, then returns the square of the mean of all sub-apertures, for x and y. This is a temporal power spectra of the slopes, and should adhere to a -11/3 power law for the slopes in the wind direction, and -14/3 in the direction tranverse to the wind direction. See Conan, 1995 for more. The phase slope data should be split into X and Y components, with all X data first, then Y (or visa-versa). Parameters: slope_data (ndarray): 2-d array of shape (..., nFrames, nCentroids) Returns: ndarray: The temporal power spectra of the data for X and Y components. """ n_frames = slope_data.shape[-2] # Only take half result, as FFT mirrors tps = abs(numpy.fft.fft(slope_data, axis=-2)[..., :n_frames/2, :])**2 # Find mean across all sub-aps mean_tps = (abs(tps)**2).mean(-1) return mean_tps def get_tps_time_axis(frame_rate, n_frames): """ Parameters: frame_rate (float): Frame rate of detector observing slope gradients (Hz) n_frames: (int): Number of frames used for temporal power spectrum Returns: ndarray: Time values for temporal power spectra plots """ t_vals = numpy.fft.fftfreq(n_frames, 1./frame_rate)[:n_frames/2.] return t_vals def plot_tps(slope_data, frame_rate): """ Generates a plot of the temporal power spectrum/a for a data set of phase gradients Parameters: slope_data (ndarray): 2-d array of shape (..., nFrames, nCentroids) frame_rate (float): Frame rate of detector observing slope gradients (Hz) Returns: """ n_frames = slope_data.shape[-2] tps = calc_slope_temporalps(slope_data) t_axis_data = get_tps_time_axis(frame_rate, n_frames) fig = pyplot.figure() ax = fig.add_subplot(111) # plot each power spectrum for i_ps, ps in enumerate(tps): ax.semilogy(t_axis_data, ps, label="Spectrum {}".format(i_ps)) ax.legend() ax.set_xlabel("Frequency (Hz)") ax.set_ylabel("Power (arbitrary units)") pyplot.show() def fit_tps(tps, axis): """ Parameters: tps: The temporal power spectrum to fit axis: fit parallel or perpendicular to wind direction Returns: """
from collections import Counter input = open("input.txt", "r", encoding="utf-8").read() phrases = [phrase.split() for phrase in input.splitlines()] # Part 1 def validPhrases(phrases): valids = [] for phrase in phrases: if len(phrase) == len(set(phrase)): valids.append(phrase) return len(valids) print(validPhrases(phrases)) # Part 2 def isAnagram(w1, w2): cnt1 = Counter() cnt2 = Counter() for c in w1: cnt1[c] += 1 for c in w2: cnt2[c] += 1 if cnt1 == cnt2: return True return False def validPhrases2(phrases): valids = [] for phrase in phrases: valid = True for i in range(len(phrase)): for j in range(len(phrase)): if i != j: if isAnagram(phrase[i], phrase[j]): valid = False break if not valid: break if valid: valids.append(phrase) return len(valids) print(validPhrases2(phrases))
import re input = open("input.txt", "r", encoding="utf-8").read() rows = input.splitlines() rs = [row.split("->") for row in rows] leaves = [elem for elem in rs if len(elem) == 1] nodes = [elem for elem in rs if len(elem) == 2] name = re.compile("[a-z]+") non_roots = [name.findall(node[1]) for node in nodes] non_roots_flat = [elem for list in non_roots for elem in list] candidates = [name.search(node[0]).group() for node in nodes] roots = [elem for elem in candidates if not elem in non_roots_flat] # part 1 print(roots) root = roots[0] # part 2: # Can be modelled as a graph problem where we fill a field tw (tower weight) for each node and determine wheter # a given node is balanced base on the tw-values of its children. V is the set of nodes, and adj is the adjacency list of our graph V = [row.split()[0] for row in rows] leaves = [name.search(leaf[0]).group() for leaf in leaves] number = re.compile("\d+") adj = dict.fromkeys(V) w = dict.fromkeys(V) tw = dict.fromkeys(V) # Filling out weights and adjacency list for row in rows: names = name.findall(row) v = names[0] w[v] = int(number.search(row).group()) children = [elem for elem in names if elem != names[0]] adj[v] = children #Bottom up filling of tw def balanced(v): if v in leaves: tw[v] = w[v] return True tw_ = w[v] child_tws = set() count = {} for u in adj[v]: balanced(u) child_tws.add(tw[u]) if tw[u] in count: count[tw[u]] = count[tw[u]] + 1 else: count[tw[u]] = 1 tw_ += tw[u] tw[v] = tw_ if len(child_tws) != 1: # We found a node where children dont have same tower-weight. We print what the weight of the "odd-child-out" should be. print(v + " was not balanced") bad_node = [u for u in adj[v] if count[tw[u]] == min(count.values()) ][0] matchweight = [x for x in child_tws if count[x]==max(count.values())][0] correct = w[bad_node] + (matchweight-tw[bad_node]) print(bad_node + " should have weight " + str(correct) +" but has weight " + str(w[bad_node])) return False return True balanced(root)
num = int(input("Введите целое: ")) mult = 1 while (num != 0): mult = mult * (num % 10) num = num // 10 print("Произведение цифр равно: ", mult)
from math import* def funct(p,n,m): i=15 s=p*(1+(i/100)/(m/12))**(m/(12*n)) print("Стоимость =",s) p = int(input("сумма вклада =")) n = int(input("количество лет=")) m = int(input("количество начислений процентов в год =")) funct(p, n, m)
n=int(input("Enter the n: ")) a=[[0 for i in range(n)]for j in range(n)] for i in range(n): for j in range(n): print(a[i][j],end=" ") print("\r") ''' lis=[[3, 5, 9], [6, 4, 7], [9, 1, 0]] print(lis) print(lis[1][1]) '''
#pattern 1 using while ''' i=1 while(i<=5): print('*'*i) i=i+1 ''' #pattern 1 using for '''' n=int(input("Enter the number: ")) for i in range(1,n+1): for j in range(i): print(i,end=" ") print() ''' #patern 2 using for ''' n=int(input("Enter the number: ")) for i in range(n,0,-1): for j in range(i): print('*',end=" ") print() ''' #pattern 3 using for ''' n=int(input("Enter the number: ")) for i in range(1,n+1): for j in range(1,i+1): print(j,end=" ") print() ''' #pattern 4 using for ''' n=int(input("Enter the number: ")) for i in range(n,0,-1): for j in range(i): print(i,end=" ") print() ''' #pattern 5 using for ''' n=int(input("Enter the number: ")) for i in range(1,n+1): for j in range(n+1-i,0,-1): print(j,end=" ") print() ''' #pattern 6 using for ''' n=int(input("Enter the number: ")) a=0 for i in range(n,0,-1): for j in range(i): a+=1 print(a,end=" ") print() ''' #patter 7 using for ''' n=int(input("Enter the number: ")) a=0 k=1 for i in range(1,n+1): for j in range(k): a+=1 print(a,end=" ") k+=2 print() ''' #pattern 8 using for ''' n=int(input("Enter the number: ")) a=0 for i in range(1,n+1): for j in range(i): a+=1 print(a,end=" ") print() '''
#Leap Year ''' y=int(input("Enter the Year: ")) if y%4==0: if y%100==0: if y%400==0: print("Leap Year") else: print("Not a Leap Year") else: print("Not a Leap Year") else: print("Not a Leap Year") ''' #prime number ''' a=[] sum1=0 for i in range(1,100): if i>1: for j in range(1,i): if j>1: if i%j==0: break else: a.append(i) if sum1<50: sum1=sum1+i if sum1< 50: k=sum1 print(k,a) ''' # ''' a=list(input("Enter the string: ").split(" ")) b=[] print("Task One: ",a) for i in a: for j in i: b.append(j) print(b) print("".join(b)) ''' # ''' v=['a','e','i','o','u'] a=list(input("Enter the String: ") print(a) for i in a: for j in i: if j in v: j=chr(ord(j)+1) print(('').join(j),end="") else: print(('').join(j),end="") print(end=" ") ''' # ''' n=input("Enter the String: ").split() print(n) n[0],n[-1]=n[-1],n[0] print(n) print(" ".join(n)) ''' # ''' s="abcd" n=int(input()) print(s[n::]+s[0:n]) '''
# select only special character in given input ''' a=input("Enter the statement with special character and numerics: ") for i in a: if i.isalpha()==False: if i.isdigit()==False: print(i,end="") ''' # select only alphabet in given input ''' a=input("Enter the statement with special character and numerics: ").split(" ") for i in a: for j in i: if j.isalpha(): print(j,end="") print() ''' ''' a=input("Enter the statement with special character and numerics: ") for i in a: if i.isalpha(): print(i,end="") ''' #select only digit in given input ''' a=input("Enter the statement with special character and numerics: ") for i in a: if i.isdigit(): print(i,end="") ''' # Give the target and multiply then check the number palindrome then print the highest ''' i=int(input("Enter the target number: ")) t=0 for n1 in range(i): for n2 in range(i): p=str(n1*n2) r=p[::-1] if(r==p): if(int(t)<int(p)): t=p a,b=n1,n2 print(a,b,t) '''
# -*- coding: utf -8 -*- from math import sin x =float(input("Lietotāj, lūdzu ievadi argumentu (x): ")) y = sin(x) print ("sin(%.2f) = %.2f"%(x,y)) k = 0 a = (-1)**0*x**1/(1) S = a print ("a0 = %6.2f S0 = %6.2f"%(a,S)) k = k +1 a = a * (-1)*x*x/((2*k)*(2*k + 1)) S= S + a print ("a%d = %6.2f S%d = %6.2f"%(k,a,k,S)) k = k +1 a = a * (-1)*x*x/((2*k)*(2*k + 1)) S =S + a print ("a%d = %6.2f S%d = %6.2f"%(k,a,k,S)) k = k + 1 a = (-1)*x*x/((2*k)*(2*k + 1)) S = S + a print ("a%d = %6.2f S%d = %6.2f"%(k,a,k,S))
from sklearn.cluster import KMeans import numpy as np import matplotlib.pyplot as plt def read_data(filename): ''' Parameters ---------- filename : string file storing comma separated data Returns ------- numpy array of data stored in filename. file rows are converted to rows in the np array. The first element of each row is cast to an int. All other elements are cast to floats ''' data = [] with open(filename, 'r') as f: for x in f: entry = [float(i) for i in x.split(',')] entry[0] = int(entry[0]) #first element of each line is the class label data.append(entry) return np.array(data) class KMeansClustering(KMeans): def __init__(self, data, k): super().__init__(n_clusters=k, random_state=0) self.fit(data) def get_centroids(self): 'return np array of shape (n_clusters, n_features) representing the cluster centers' return self.cluster_centers_ def get_labels(self, data): 'Predict the closest cluster each sample in data belongs to. returns an np array of shape (samples,)' return self.predict(data) def total_inertia(self): 'returns the total inertia of all clusters, rounded to 4 decimal points' return round(self.inertia_, 4) def plot_try_k_clusters(avg_purities, inertias): ''' plots the results of try_k_clusters assumes avg_purities and inertias are lists of equal length and follow the docstring of try_k_clustesrs ''' assert type(avg_purities) is list and type(inertias) is list assert len(avg_purities) == len(inertias) x=np.arange(len(avg_purities)) + 1 avg_purities = [x*100 for x in avg_purities] plt.plot(x, avg_purities, 'bo') plt.title("Average Purity of clusters") plt.xlabel("Num Clusters") plt.ylabel("% Purity") plt.show() plt.plot(x, inertias, 'rx''') plt.title("Total Inertia of Clusters") plt.xlabel("Num Clusters") plt.ylabel("Total Inertia") plt.show() ##### END HELPER CODE ##### def prep_dataset(raw_data): ''' Prepares the raw dataset for clustering. Separate the raw data into sample features and labels Parameters ---------- raw_data : np array A np array of shape (num_samples, num_features + 1) The first element of each row is the class label for that sample. The remaining elements are the sample features Returns ------- Tuple of (data, labels) data : np array of shape (num samples, num_features) labels : np array of shape (num_samples, ). labels for the data set samples ''' data = raw_data[:,1:] labels = raw_data[:,0] return (data,labels) def kmeans(data, k): ''' Run the kmeans clustering algorithm with k clusters on data. Use the KMeansClustering class provided to run the clustering algorithm. Parameters ---------- data : a numpy array with shape (N,X), where N is the number of wines and X is the number of features per wine k : int, number of clusters for kMeans Returns ------- a tuple of (labels, inertia) labels: a size N 1-d numpy array, representing the cluster labels for each data point inertia: float, the total intertia for the clusters ''' cluster = KMeansClustering(data,k) labels = cluster.get_labels(data) inertia = cluster.total_inertia() return (labels,inertia) def scale_data(data): ''' Scale data features using a MinMax scaling. Each feature should be transformed such that: f_scaled = (f - f_min) / (f_max - f_min) where f is the unscaled feature, f_min is the minimum value of that feature across all samples, and f_max is the maximum value of that feature across all samples. Note that, for f = f_max, f_scaled = 1. For f = f_min, f_scaled = 0. Parameters ---------- data : np array of shape (num samples, num features) Returns ------- scaled : np array of shape (num samples, num features). Each feature should be individually scaled to the range [0,1]. ''' scaled = (data - data.min(0)) / (data.max(0) - data.min(0)) return scaled def cluster_purity(clusters, labels): ''' Find the purity of the clusters. Purity is defined as the proportion of a cluster that is taken up by the most represented class label within that cluster. If multiple class labels are represented equally, return the percent composition of either label. Round purity values to the 4 decimal points Parameters ---------- clusters : np array of shape (num_samples,) with each element being an int representing the sample's cluster. Values of clusters will be in the range [0,num_clusters] labels : np array of shape (num_samples,). The class labels for each sample Returns ------- purities : list of length num_clusters, purity values for each cluster ''' num_clusters = len(set(clusters)) dict_clusters = {} for i in range(num_clusters): dict_clusters[i] = {} num_labels = set(labels) for i in num_labels: for r in dict_clusters: dict_clusters[r][i] = 0 for i in range(len(clusters)): dict_clusters[clusters[i]][labels[i]] += 1 purities = [] for i in dict_clusters: total = sum(dict_clusters[i].values()) top = max(dict_clusters[i].values()) purity = round(top/total,4) purities.append(purity) return purities #result = ps6.cluster_purity(clusters, labels) def try_k_clusters(data, labels, ks): ''' Try kmeans clustering with num_clusters = 1,2,...ks. Return the average cluster purity Parameters ---------- data : np array of shape (num samples, num features) labels : np array of shape (num_samples,). The class labels for each sample ks : int indicating the k values to try. all integer k values will be tried in the range [1,ks] Returns ------- A tuple of (avg_purities, inertias) avg_purities: a list of floats, length ks. The average purity value of all clusters from kmeans clustering for all k-values in range [1,ks]. Round the average purity values to 4 decimal points. avg_purities[i] = average purity score of the i+1 clusters from kmeans clustering with k=i+1. inertias: a list of floats, length ks. The total inertia values from kmeans clustering for all k-values in range [1,ks]. Round the total inertia values to 4 decimal points. inertias[i] = total inertia of the i+1 clusters from kmeans clustering with k=i+1. ''' avg_purities = [] inertias = [] for k in range(ks): clusters, inertia = kmeans(data,k+1) purities = cluster_purity(clusters,labels) avg_purity = sum(purities)/len(purities) avg_purities.append(avg_purity) inertias.append(inertia) return (avg_purities,inertias) if __name__ == "__main__": pass #OPTIONAL: Plot average purity and inertia # file = "wine.data" # raw_data = read_data(file) # data, labels = prep_dataset(raw_data) # scaled_features = scale_data(data) # k = 10 # avg_purity, inertia = try_k_clusters(scaled_features, labels, k) # plot_try_k_clusters(avg_purity, inertia)
#file for testing python staff like tokenization and so on... string = " asdasd asd asd " string1 = "asdm,asdasdj,asdasd asd asd asd,ssdadasd ad " string = "".join(string.split()) print (string)
def isFactor(number, factor): return number % factor == 0 def smallestFactorOf(number): for i in range(2,number): if(isFactor(number, i)): return i
#Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. sum_of_squares = 0 problem_range = range(1, 101) for i in problem_range: sum_of_squares += i*i print(sum_of_squares) sum_of_range = sum(problem_range) square_of_sum = sum_of_range*sum_of_range difference = square_of_sum - sum_of_squares print(difference)
def is_leap(year): leap = False if( (year % 4 == 0 and year % 100 != 0) or (year % 100 == 0 and year % 400 == 0)): leap = True return leap if __name__ == '__main__': year = is_leap(1992) print year
#!/usr/bin/python3 def divisible_by_2(my_list=[]): if my_list: list = my_list[:] for i in range(len(list)): if (my_list[i] % 2 == 0): list[i] = True else: list[i] = False return list
#!/usr/bin/python3 for i in range(0, 100): dizaine = i // 10 unite = i % 10 if (unite > dizaine): if (i == 1): print("{:02d}".format(i), end="") else: print(", {:02d}".format(i), end="") print()
#!/usr/bin/python3 """ Python Network Project """ def find_peak(list): """ finds a peak in a list of unsorted integers """ peaks = [] if list: m = list[0] mpos = 0 for i, elem in enumerate(list): if elem > m: m = elem mpos = i return list[mpos]
from tkinter import * import math # x=column # y=row def clear(): valueA.delete(0, 'end') valueB.delete(0, 'end') valueC.delete(0, 'end') def calculate(): a=int(valueA.get()) b=int(valueB.get()) c=int(valueC.get()) #x1=((-(b))+ math.sqrt((math.pow(b,2) * (-4) * a * c))) /(2*a) #x2=((-(b))- math.sqrt((math.pow(b,2) * (-4) * a * c))) /(2*a) x1 = (-(b) + math.sqrt((b*b)-4*a*c))/(2*a) x2 = (-(b) - math.sqrt((b*b)-4*a*c))/(2*a) #x1=(-(b)+(math.sqrt((math.pow(b,2))*-4*a*c)))/2(a) #x2=(-(b)-(math.sqrt((math.pow(b,2))*-4*a*c)))/2(a) lblsolution.config(text=f"Solution: X={round(x1,3)} , X={round(x2,3)}") win=Tk() win.title("My first Python GUI ") win.minsize(width=500,height=500) lbltitel=Label(text="Quadratic Equation Solver") lbltitel.place(x=170,y=0) lblA=Label(text="A Value:") lblA.place(x=30,y=30) valueA=Entry() valueA.place(x=90,y=30) lblB=Label(text="B Value:") lblB.place(x=30,y=60) valueB=Entry() valueB.place(x=90,y=60) lblC=Label(text="C Value:") lblC.place(x=30,y=90) valueC=Entry() valueC.place(x=90,y=90) but_slove=Button(text="Slove",command=calculate) but_slove.place(x=100,y=120) but_clear=Button(text="Clear",command=clear) but_clear.place(x=150,y=120) lblsolution=Label(text="Solution:") lblsolution.place(x=0,y=150) win.mainloop()
''' 功能:用openpyxl读写excel Created on 2019年1月21日 @author: Vostory ''' # coding=utf-8 import openpyxl filename = r'D:\\PracFolder\\Data\\111.xlsx' wb = openpyxl.load_workbook(filename) # 读文件 sheets = wb.sheetnames # 获取读文件中所有的sheet,通过名字的方式 print('worksheets is %s' % sheets, type(sheets)) ws = wb[sheets[0]] # 获取第一个sheet内容 # ws = workbook.sheet_by_name(u'Sheet1') # 通过工作表名称获取 # ws= workbook.sheets()[0] # 通过索引顺序获取 # ws= workbook.sheet_by_index(0) # 通过索引顺序获取 print(ws.title) # 获得sheet名称 # 遍历sheet1中所有行row num_rows = ws.max_row print(num_rows) for curr_row in range(num_rows): for cell1 in list(ws.rows)[curr_row]: print(cell1.value) print('row is %s' % curr_row) # 遍历sheet1中所有列col num_cols = ws.max_column print(num_cols) for curr_col in range(num_cols): for cell2 in list(ws.columns)[curr_col]: print(cell2.value) print('col is %s' % curr_col) # 遍历sheet1中所有单元格cell for rown in range(num_rows): # 默认开始下标为0 for coln in range(num_cols): # 默认开始下标为0 cell3 = ws.cell(rown + 1, coln + 1) # 下标必须从1开始 print(cell3) print('数据读取结束!') # 写入数据 outwb = openpyxl.Workbook() # 打开一个将要写的excel文件 Sheet1 = outwb.create_sheet('Sheet1') # 在将写的文件创建sheet,且命名为mySheet print(outwb.sheetnames) # 输出目前所有的工作表名称 ws = outwb.active # 获取当前正在操作的表对象 ws.append(['电影名', '年份', '地区', '剧情类型', '导演', '主演', '评分', '评论人数', '简介']) saveExcel = "D:\\PracFolder\\Data\\test.xlsx" outwb.save(saveExcel) # 一定要记得保存 print('数据写入结束!')
# Напишите программу, которая будет разрезать большую прямоугольную область на N \times NN×N одинаковых прямоугольных областей. # Области задаются четырьмя координатами: минимальной широтой, минимальной долготой, максимальной широтой, максимальной долготой. # # При выводе области должны быть упорядочены по возрастанию минимальной широты, а в случае равных широт - по возрастанию минимальной долготы. # # Гарантируется, что все числа во входных данных положительны. data_str = input().split() data = [float(x) for x in data_str] n = int(input()) d_sh = (data[2] - data[0]) / n d_dol = (data[3] - data[1]) / n for i in range(0, n): for j in range(0, n): min_sh = data[0] + d_sh * i max_sh = data[0] + d_sh * (i + 1) min_dol = data[1] + d_dol * j max_dol = data[1] + d_dol * (j + 1) print(min_sh, min_dol, max_sh, max_dol)
# В качестве ответа введите все строки наибольшей длины из входного файла, не меняя их порядок. # # В данной задаче удобно считать список строк входного файла целиком при помощи метода readlines(). # # Ссылка на входной файл: https://stepik.org/media/attachments/lesson/258920/input.txt with open('input6.txt') as file: text = file.readlines() maxlen = max(len(line) for line in text) print(*filter(lambda line: len(line) == maxlen, text))
# Ученые нашли табличку с текстом на языке племени Мумба-Юмба. # Определите, сколько различных слов содержится в этом тексте. # Словом считается последовательность непробельных символов идущих подряд, слова разделены одним или большим числом пробелов или символами конца строки. # Большие и маленькие буквы считаются различными. # # В этой и последующих задачах этого занятия вам нужно скачать файл по ссылке, запустить свой скрипт на собственном компьютере и ввести только ответ конкретно для этого файла. #79936 # Ссылка на входные данные https://stepik.org/media/attachments/lesson/258915/input.txt data = open('input.txt', 'r') words = set() for line in data: words.update(line.split()) print(len(words))
# Выведите в обратном порядке содержимое всего файла полностью. # Для этого считайте файл целиком при помощи метода read(). # # Ссылка на входной файл: https://stepik.org/media/attachments/lesson/258921/input.txt data = open('input7.txt', 'r') u = data.read() print(u[::-1])
from func import delFinish three = "three " str_1 = delFinish(three + three + three) str_2 = delFinish(three * 3) print(str_1) print(str_2)
#Ex.0025 - Crie um programa que leia um nome e diga se existe 'silva' no mesmo nome = str(input('Escreva seu nome:')) print('Existe Silva no nome: {}'.format('SILVA' in nome.upper()))
#Faça um programa que leia um número inteiro e mostre na tela o sucessor e seu antecessor. n = int(input('Digite um valor:')) print('Analisando o valor de {}, seu antecessor é {} e o seu sucessor é {}'.format(n, (n-1), (n+1)))
#Ex.0017 - Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um Triângulo Retângulo calcule e mostre o comprimento da Hipotenusa #Incluindo importação from math import hypot o = float(input('Digite o cateto oposto:')) a = float(input('Digite o cateto adjacente:')) h = hypot(a, o) print('resultado:{:.1f}'.format(h))
import itertools import numpy as np def minimum_distance_v(v1, v2): vdiff = v2 - v1 if abs(vdiff) < 0.5: return vdiff elif v1 > 0.5: return 1 - abs(vdiff) else: return -1 + abs(vdiff) def minimum_distance_point(p1, p2): return [minimum_distance_v(v1, v2) for (v1, v2) in zip(p1, p2)] def max_pair_distance(points): if len(points) == 1: return 0.0 pairs = np.array([minimum_distance_point(p1, p2) for p1, p2 in itertools.combinations(points, 2)]) distances = (pairs ** 2).sum(axis=1) ** 0.5 return max(distances)
#!/usr/bin/python3 ''' Author: Aastha Shrivastava PRN: 19030142001 Date modified: 27th JULY 2019 7th August 2019: added exception handling Description: Program reads file supplied by user, takes an intger value n from user and writes the file contents in new file without every nth character on each line. ''' try: #opening connection to file which user entered inp_file = open(input("Enter file name")) out_file = open("tempout.txt", "w") skip_char = int(input("Enter character number to skip")) #reading file line by line for line in inp_file: start = 0 end = skip_char - 1 #writing the contents to output file and skipping the nth character while (start <= len(line)): out_file.write(line[start:end]) start = end + 1 end += skip_char #possible exceptions program may encounter except FileNotFoundError: print("File not found please check the file name and try executing program again") except TypeError: print("Character number must be an integer please execute the program again and enter a valid value") except PermissionError: print("Permission denied to read/write file") except FileExistsError: print("tempout.txt already exists and cannot be overwritten") except IsADirectoryError: print("Requested file is a directory") #closing the file finally: try: inp_file.close() out_file.close() except AttributeError: pass
# A simple hangman game written in python import random print("Welcome to HangMan") #List of words word_list = ["Youva","Jupyter","Speed","Function"] # Choosing a random word from the list word = list(random.choice(word_list)) guess_word = ['*']*len(word) guess_count = len(word)+2 score = 0 # Running game loop till user guesses the correct word or run out of guesses while(('*' in guess_word) and guess_count>0): print("Word:%s \tscore:%d \tguesses left:%d"%(''.join(guess_word),score,guess_count)) letter = input("Enter next character:") guess_count-=1 if(letter in word): score += word.count(letter) for idx in range(len(word)): if word[idx] == letter: guess_word[idx] = letter if('*' not in guess_word): print("Congratulations!! you guessed the word:%s correctly!"%(''.join(guess_word))) break else: print("Sorry you ran out of guesses :(( word was:%s"%(''.join(word)))
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: '''Function to create binary search tree from its preorder of elements ''' def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if len(preorder) == 0: return None root = TreeNode(preorder[0]) for i in preorder[1:]: temp = root added = False while(not added): if(i<temp.val): if(temp.left == None): newNode = TreeNode(i) temp.left = newNode added = True break temp = temp.left continue else: if(temp.right == None): newNode = TreeNode(i) temp.right = newNode added = True break temp = temp.right continue return root
''' Description: Program to display a simple slideshow using Tkinter. ''' from tkinter import * import time images=["DSC_0511","DSC_0512"] def slide(): #while True: for i in images: image = PhotoImage(file=i+".JPG.png") label = Label(image=image) #label.place(x=0,y=0) label.pack(fill=BOTH,expand=2) #time.sleep(5) fr = Tk() btn=Button(fr,text="start",command=slide) btn.pack() fr.mainloop()
from .base import Shape class Circle(Shape): def __init__(self, radius, **kwargs): super().__init__(**kwargs) self.radius = radius def draw(self, turtle): turtle.penup() turtle.goto(self.center_x, self.center_y - self.radius) # From docs: The center is radius units left of the turtle; turtle.pendown() turtle.color(self.color) turtle.circle(self.radius)
people = [{'name': "Мария", 'gender': "female", }, {'name': "Калоян", 'gender': "male", }, ] def print_person(person: dict): print("{} ({}) is interested in {}".format( person['name'], person['age'], ', '.join(person['interests']) )) def print_people(people: list): for person in people: print_person(person) try: print_people(people) except KeyError as e: print("Unhandled KeyError exception: " + str(e))
# today we are going to learn about lists and for loops and while loops # Yesterday, we learned about conditions and comparisons. # today, we will learn about: # lists # string # in/not in # loops # hopefully function! ''' Lists are pretty cool. It's something you could maybe put a high score in. you create a new list with no content by: l = list() You can create a list with content in it by: l = ['a', 'b', 'c'] A list can hold many different types. You can access and modify list by using this kind of syntax: a[1] x = a[0] you can get the length of the array by: len(a) Here are some list methods: list.append(elem) => add element to end list.insert(index, elem) => addd elements at the index, shift elements to right) list.extend(list2) -> adds element of list2 to the end of the list. list.index(elem) -> searches for the given element from start of list list.remove(elem) -> removes the element list.sort() -> sort in place list.reverse() -> reverse the list in place list.pop(index) -> removes and return element. if index omitted, opposite of append Exercise 1: Create a new list called high score. Ask the user for a high score to insert 5 times. After adding all of it, sort it, then reverse it, then print it. ''' highscore = list() ''' Exercise 2: Create a list of vocabs. Show the list of vocab to memorize. Add one more vocab to the list. Then remove the second vocab in the list. Show me what is in the first index of the vocab list. ''' ''' Strings are actaully just a list of something called a character. So we can do many lists operations on strings. We already know a few String operations + (concat) * (duplicate) There are some more: s.lower()/upper() -> lowercase or uppercase of string s.strip() -> remove whitespace start and end s.startwith('')/endwith('') s.find('') -> returns first index of where it is found; otherwise -1 s.replace('old', 'new') -> return a string where all occurrences of 'old' have been replaced s.split('delim') -> splits the string into an array by the delimeter s.join(list) -> joins items in list into one string with s as its delimeter. You can also access the string using list like syntax. You can also find the length of the string like lists # Exercise 1: take in 2 3-digit number and 1 4-digit number. Create a phone number out of it in this format: 123-456-7890 Make sure you verify that it is in that format. Hint: len, s.isdigit() # Exercise 2: Take in a name with the following format: Kevin Myungki Kang and change it to KANG, KEVIN MYUNGKI so that it can work for driver's license. ''' ''' in/not in in and not in is very useful for string and lists. You can asks python to check if a part of a string is in the bigger string or an element is in the list as follows: "a" in "cat" => True "b" in "cat" => False 3 in [1, 2, 3] => True 4 in [1, 2, 3] => False Not in just basically does the opposite. ''' ''' for loops: in python, we do loops with a list. the most common way to do it is by using a function called range. range(2) => [0, 1] range(1, 5) => [1, 2, 3, 4] range(1, 14, 7) => [1, 8] we iterate through this list by: for i in range(2): print(i) Similarly, with a string, we can: for c in "abcd": print(c) this extacts all characters. Again similarly, with an array, we can: for e in [1, 2, 3]: print(e) Exercise: Using TrumpTwitter.py, extract all of the Trump's friends and print out the name of the friends of Trump's with Trump in their names. # python3 -i TrumpTwitter.py '''
# today we are going to learn about lists and for loops and while loops # Yesterday, we learned about conditions and comparisons. # today, we will learn about: # lists # string # in/not in # loops # hopefully function! ''' in/not in in and not in is very useful for string and lists. You can asks python to check if a part of a string is in the bigger string or an element is in the list as follows: "a" in "cat" => True "b" in "cat" => False 3 in [1, 2, 3] => True 4 in [1, 2, 3] => False Not in just basically does the opposite. ''' # Let's try in and not in out! "a" in "cat" "ca" in "cat" "ca" not in "cat" 3 in [1, 2, 3] 5 in [1, 2, 3] 8 not in [1, 3, 5] # Where can this be useful? # in the phone book we built, maybe we wanna parse by the area code. # or maybe we wanna check if a person's name is in the phone book. # it is also VERY useful for loops. ''' for loops: in python, we do loops with a list. the most common way to do it is by using a function called range. range(2) => [0, 1] range(1, 5) => [1, 2, 3, 4] range(1, 14, 7) => [1, 8] we iterate through this list by: for i in range(2): print(i) Similarly, with a string, we can: for c in "abcd": print(c) this extacts all characters. Again similarly, with an array, we can: for e in [1, 2, 3]: print(e) # python3 -i TrumpTwitter.py ''' # out of all the loops, for loops are one of the most common. # we use range most often. # loops in python basically iterates through lists. # for i in range(5) # ^ after every loop, i will be set to 0, then 1, 2, 3, and 4. # THIS IS VERY USEFUL FOR GOING THROUGH LISTS that we make. # we can also do this: # for i in [1, 3, 5] # often we want to go through lists, so we would just: # for i in list # for phone books, we have 2 lists... # so we can try: for n, num in zip(names, numbers)... # this will iterate names and numbers together. # in the phonebook, you can notice we have something called a while loop with a 1. # how while loop works is: # while(cond): # the reason I did while(1) is that anything other than 0 is actually translated to True. # cuz 0 is false. ''' Exercise: Using TrumpTwitter.py, extract all of the Trump's friends and print out the name of the friends of Trump's with Trump in their names. ''' ''' Exercise 2: '''
def fib(n): tail = [0, 1] for i in range(1, n): tail.append(sum(tail[-2:])) return tail[-1] if __name__ == '__main__': print(fib(4))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None import sys class Solution: max_sum = -sys.maxsize-1 def maxPathSum(self, root: TreeNode) -> int: self.max_gain(root) return self.max_sum def max_gain(self, node: TreeNode): if node is None: return 0 left_max = max(0, self.max_gain(node.left)) right_max = max(0, self.max_gain(node.right)) self.max_sum = max(self.max_sum, left_max + right_max + node.val) return max(left_max, right_max) + node.val
# When a person has a disease, they infect exactly R other people but only on the very next day. No # person is infected more than once. We want to determine when a total of more than P people have # had the disease. p = int(input()) # total people to be infected n = int(input()) # day 0 r = int(input()) # value of r total = n runs = 0 while total <= p: next = n * r n = next total += next runs += 1 print(runs) # n people on day 0 infect r people on day 1 # those people infect r people on day 2
list1 = [6, 19, 23, 49, 8, 41, 20, 53, 56, 87] def find_max(itemlist): if len(itemlist) == 1: return itemlist[0] op1 = itemlist[0] op2 = find_max(itemlist[1:]) if op1 > op2: return op1 else: return op2 print(find_max(list1))
''' Question: Define a class which has at least five methods: getInteger: to get two integers from console input printIntegers: to print integers. addInteger: to add two integers together subtractInteger: to subtract two integers powerInteger: to get the power of the first integer to the power of second intger Also please include simple test function to test the class methods. Hints: Use __init__ method to construct some parameters ''' from math import pow class InputIntegerOut(): def __init__(self): self.num1 = 0 self.num2 = 0 def getInteger(self): self.num1 = int(input("Enter your first integer: ")) self.num2 = int(input("Enter your second integer: ")) def printInteger(self): print("First integer is", self.num1) print("Second integer is", self.num2) def addInteger(self): print("The sum of these two integers is", self.num1 + self.num2) def subtractInteger(self): print("The difference between these two integers is", abs(self.num1-self.num2)) def powerInteger(self): print("The result of the first integer to the power of the second integer is", pow(self.num1,self.num2)) intSample = InputIntegerOut() intSample.getInteger() intSample.printInteger() intSample.addInteger() intSample.subtractInteger() intSample.powerInteger()
''' Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 60. H is 10. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma separated input sequence is given to the program: 100,200,300 The output of the program should be: 11,15,19 Hints: If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26) In case of input data being supplied to the question, it should be assumed to be a console input. ''' from math import * def formula(): C = 60 H = 10 consoleInput = input("Enter your integers: ").split(',') lst = [] print(consoleInput) for D in consoleInput: Q = round(sqrt(2*C*int(D)/H)) lst.append(str(Q)) print(','.join(lst)) formula()
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # The following code reads all the Gapminder data into Pandas DataFrames. You'll # learn about DataFrames next lesson. path = '/datasets/ud170/gapminder/' employment = pd.read_csv(path + 'employment_above_15.csv', index_col='Country') female_completion = pd.read_csv(path + 'female_completion_rate.csv', index_col='Country') male_completion = pd.read_csv(path + 'male_completion_rate.csv', index_col='Country') life_expectancy = pd.read_csv(path + 'life_expectancy.csv', index_col='Country') gdp = pd.read_csv(path + 'gdp_per_capita.csv', index_col='Country') # The following code creates a Pandas Series for each variable for the United States. # You can change the string 'United States' to a country of your choice. employment_us = employment.loc['United States'] female_completion_us = female_completion.loc['United States'] male_completion_us = male_completion.loc['United States'] life_expectancy_us = life_expectancy.loc['United States'] gdp_us = gdp.loc['United States'] # Uncomment the following line of code to see the available country names print employment.index.values # Use the Series defined above to create a plot of each variable over time for # the country of your choice. You will only be able to display one plot at a time # with each "Test Run". gdp_us.plot() employment_us.plot() female_completion_us.plot() male_completion_us.plot() life_expectancy_us.plot()
list5 = [1, 2.5, 3, 4.25, 6, 7, 9.5] res = [] res = list(x for x in list5 if x%2!=0) # for i in list5: # if i%2 != 0: # res.append(i) print(res)
while True: try: num1 = input("enter number") if (len(num1) == 4): print("enter number is four digit only") break except ValueError: print("Enter number with only four digits")
import math input_values = input("Enter the values in a comma-separated sequence:") split_values = input_values.split(',') C = 50 H = 30 for i in split_values: D = int(i) Q = math.sqrt((2 * C * D) / H) print("For D Value of {} result is {}".format(D, Q))
#Answer: Yes we can assign a diffterent data type in Python as its dynamic programming. a = 25.3 print(a) a = 'Hello' print(a)
lucky_number = 9 counter = 5 while counter > 0: number = eval(input("Guess the lucky number:")) if number == lucky_number: print("Good Guess!") break else: if counter > 1: print("Try again!") counter -= 1 if counter == 0: print("Sorry but that was not very successful!")
""" This program creates a network out of a formatted text file and finds the path of least resistance (lowest weight edges). To achieve this it uses Kruskal's minimum spanning tree algorithm together with a breadth first search algorithm. NETWORK : contains the nodes or "cities" as well as the edges (roads). PARENT : contains each node's parent node. Used for checking for cycles in the network. RANK : contains each node's rank. Also used for checking for cycles. """ NETWORK = { 'cities': [] } PARENT = dict() RANK = dict() def get_max_altitude(mst, path): """retrieves the highest altitude in the path""" mst.sort(key=lambda x: x[2], reverse=True) for road in mst: if road[0] in path and road[1] in path: return road[2] def create_adjacency_list(roads): """ To make path finding easier this function gets the minimum spanning tree as an input and returns an an adjacency list. """ adj_list = {} for road in roads: adj_list[road[0]] = [] # initializing the keys of the adjacency list adj_list[road[1]] = [] for road in roads: # adds all the adjacency's for each key adj_list[road[0]].append(road[1]) adj_list[road[1]].append(road[0]) return adj_list def breadth_first(mst, destination): """ This function gets as an input the minimum spanning tree constructed earlier, as well as the destination it we want to get to. It finds the path between city 1 and the destination by utilising the breadth first search algorithm. """ adj_list = create_adjacency_list(mst) # returns a reformatted version of the MST explored = [] queue = [[1]] while queue: path = queue.pop(0) city = path[-1] if city not in explored: neighbours = adj_list[city] # gets neighbouring nodes for each city for neighbour in neighbours: # and loops through them while forming new_path = list(path) # paths for each of them new_path.append(neighbour) queue.append(new_path) if neighbour == destination: # When the algorithm stumbles upon the return new_path # destination city it returns the shortest path explored.append(city) return "There is no path to city: ", destination def make_set(city): """This function is used to initialize each city's values in the PARENT and RANK dictionaries""" PARENT[city] = city RANK[city] = 0 def find(city): """Finds a city's parent and returns it""" if PARENT[city] != city: PARENT[city] = find(PARENT[city]) return PARENT[city] def union(city1, city2): """Combines the sets containing cities 1 and 2 if they don't have common parents""" root1 = find(city1) root2 = find(city2) if root1 != root2: if RANK[root1] > RANK[root2]: PARENT[root2] = root1 else: PARENT[root1] = root2 if RANK[root1] == RANK[root2]: RANK[root2] += 1 def kruskal(): """ Kruskal's MST algorithm. First it sorts the set NETWORK['roads'] by weight before utilizing the find() and union() functions to combine unconnected nodes until every possible node is connected. """ roads = list(NETWORK['roads']) minimum_spanning_tree = set() for city in NETWORK['cities']: # initializes every city's dictionary values make_set(city) roads.sort(key=lambda x: x[2]) # sorts roads by elevation for road in roads: city1, city2, altitude = road if find(city1) != find(city2): # Checks if city1 and city2 have common parents. union(city1, city2) # If none found it does a union for their sets minimum_spanning_tree.add(road) # before adding the road to the MST return sorted(minimum_spanning_tree) def add_city(city): """ adds a city to the NETWORK dictionary """ NETWORK['cities'].append(city) def add_roads(roads): """ gets an array containing roads to be added to the NETWORK dictionary """ roads_array = [] for i in range(len(roads)): city1 = int(roads[i][0]) # Gets the values from their predetermined city2 = int(roads[i][1]) # indexes in each sub-array. altitude = int(roads[i][2]) roads_array.append((city1, city2, altitude)) # And appends them to a temporary array before pushing NETWORK['roads'] = roads_array # it back up to the NETWORK dictionary. def read_network_file(path): """ Reads a formatted .txt file, appends it to a list called network_info, gets the number of cities and roads as well as the destination city from the first and last lines of the document respectively. After this it slices them away and returns the remaining list to create the network itself. """ network_info = [] # useful info about the network if path.endswith(".txt"): file = open(path, "r") for line in file: line = line.rstrip() # strips trailing newlines network_info.append(line.split(' ')) # splits the line into chunks, cities = int(network_info[0][0]) # so it can add it into network_info for later access. roads = int(network_info[0][1]) destination = int(network_info[roads + 1][0]) network_info = network_info[1:-1] # Now that the useful info has been extracted we can slice it return cities, roads, destination, network_info # off only the roads remain. else: print("Not a .txt file")
""" greedy_3_tree.py Module that contains the Greedy 3 Tree heuristics definition. """ import network import sys import utils import numpy as np def Greedy3Tree(topology: network.Network): mid_points = MinDistance3Connected(topology) mid_point_pairs = MidPoint6Connected(topology, mid_points) MidPoint12Connected(topology, mid_point_pairs) MidPointAllConnected(topology, mid_points) return topology def MinDistance3Connected(net): mid_points = [] visited_nodes = [False] * len(net.get_network_graph().nodes) closest = sys.maxsize second_closest = sys.maxsize closest_index = -1 for node_v in net.get_network_graph().nodes(data="coords"): if not visited_nodes[node_v[0]]: closest = sys.maxsize closest_index = -1 second_closest_index = -1 for node_e in net.get_network_graph().nodes(data="coords"): if node_v[0] is not node_e[0] and not visited_nodes[node_e[0]]: dist = utils.euclidean_distance(node_v[1], node_e[1]) if dist < closest: second_closest_index = closest_index second_closest = closest closest_index = node_e[0] closest = dist else: if dist < second_closest: second_closest_index = node_e[0] second_closest = dist if closest_index != -1: net.add_edge(node_v[0], closest_index, weight=1) visited_nodes[closest_index] = True visited_nodes[node_v[0]] = True if second_closest_index != -1: net.add_edge(node_v[0], second_closest_index, weight=1) visited_nodes[second_closest_index] = True mid_points.append(node_v) return mid_points def MidPoint6Connected(net, mid_points): mid_point_pairs = [] visited_nodes = [False] * len(net.get_network_graph().nodes) closest = sys.maxsize closest_index = -1 for mid_point in mid_points: if not visited_nodes[mid_point[0]]: for node in net.get_node_connected_component(mid_point[0]): visited_nodes[node] = True closest_index = -1 closest = sys.maxsize for node in mid_points: if mid_point[0] != node[0] and not visited_nodes[node[0]]: dist = utils.euclidean_distance(mid_point[1], node[1]) if dist < closest: closest = dist closest_index = node[0] if closest_index != -1: net.add_edge(mid_point[0], closest_index, weight=1) for node in net.get_node_connected_component(mid_point[0]): visited_nodes[node] = True mid_point_pairs.append((mid_point[0], closest_index)) return mid_point_pairs def MidPoint12Connected(net, mid_point_pairs): visited_nodes = [False] * len(net.get_network_graph().nodes) coords = net.get_node_coords() closest = sys.maxsize closest_index = (-1, -1) for pair in mid_point_pairs: if not visited_nodes[pair[0]]: closest = sys.maxsize closest_index = (-1, -1) for pair_2 in mid_point_pairs: if pair[0] != pair_2[0] and not visited_nodes[pair_2[0]]: dist = utils.euclidean_distance( coords.get(pair[0]), coords.get(pair_2[0])) + \ utils.euclidean_distance( coords.get(pair[1]), coords.get(pair_2[1])) if dist < closest: closest = dist closest_index = pair_2 if closest_index != (-1, -1): net.add_edge(pair[0], closest_index[0], weight=1) net.add_edge(pair[1], closest_index[1], weight=1) for node in net.get_node_connected_component(pair[0]): visited_nodes[node] = True def MidPointAllConnected(net, mid_points): visited_nodes = [[False] * len(net.get_network_graph().nodes) for _ in range(len(net.get_connected_subnetwork()))] for i, subgraph in enumerate(net.get_connected_subnetwork()): for node in subgraph: visited_nodes[i][node] = True for i, subgraph in enumerate(net.get_connected_subnetwork()): for node in subgraph.nodes: if len(net.get_node_neighbors(node)) < 3: for mid_point in mid_points: if not visited_nodes[i][mid_point[0]]: net.add_edge(node, mid_point[0], weight=1) while len(net.get_node_neighbors(node)) < 3: coords = net.get_node_coords() closest = sys.maxsize closest_index = -1 neighbors = list(net.get_node_neighbors(node)) nc_list = np.setdiff1d( list(net.get_network_graph().nodes), neighbors) for n in nc_list: if node != n: dist = utils.euclidean_distance(coords.get(node), coords.get(n)) if dist < closest: closest = dist closest_index = n if closest_index != -1: net.add_edge(node, closest_index, weight=1)
# 字符串 str1 = "hello python" str2 = 'hello world' print(str1) print(str1[2]) print(str2) print(str2[3]) for char in str2: print(char) print(len(str2))
""" 1. 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] https://leetcode-cn.com/problems/two-sum/ """ class Solution: def twoSum(self, nums, target: int): dictionary = {} for i, n in enumerate(nums): if target - n in dictionary: return [dictionary[target - n], i] dictionary[n] = i nums = [2,7,11,15] target = 9 s = Solution() print(s.twoSum(nums,target))
# 异常 def excption1(): try: # 不能确定正确执行的代码 num = int(input("请输入一个整数:")) except: # 错误的处理代码 print("请输入正确的整数") print("-" * 50) def excption2(): """捕捉错误类型""" try: # 提示用户输入一个整数 num = int(input("输入一个整数:")) # 使用 8 除以用户输入的整数并且输出 result = 8 / num print(result) except ZeroDivisionError: print("除0错误") except ValueError: print("请输入正确的整数") def excption3(): """捕捉未知异常""" try: # 提示用户输入一个整数 num = int(input("输入一个整数:")) # 使用 8 除以用户输入的整数并且输出 result = 8 / num print(result) except ValueError: print("请输入正确的整数") except Exception as result: print("未知错误 %s" % result) def excption4(): """完整异常的写法""" try: # 提示用户输入一个整数 num = int(input("输入一个整数:")) # 使用 8 除以用户输入的整数并且输出 result = 8 / num print(result) except ValueError: print("请输入正确的整数") except Exception as result: print("未知错误 %s" % result) else: print("尝试成功") finally: print("无论是否出现错误都会执行的代码") def excption5(): return int(input("输入整数:")) def excption6(): return excption5() def excption7(): # 利用异常的传递性,在主程序捕获异常 try: print(excption6()) except Exception as result: print("未知错误 %s" % result) def excption8(): """主动抛出异常""" # 1. 提示用户输入密码 pwd = input("请输入密码:") # 2. 判断密码长度 >= 8,返回用户输入的密码 if len(pwd) >= 8: return pwd # 3. 如果 < 8 主动抛出异常 print("主动抛出异常") # 1> 创建异常对象 - 可以使用错误信息字符串作为参数 ex = Exception("密码长度不够") # 2> 主动抛出异常 raise ex def excption9(): # 提示用户输入密码 try: print(excption8()) except Exception as result: print(result) excption9()
""" 给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。 假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。 注意:每次拼写时,chars 中的每个字母都只能用一次。 返回词汇表 words 中你掌握的所有单词的 长度之和。 示例 1: 输入:words = ["cat","bt","hat","tree"], chars = "atach" 输出:6 解释: 可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。 示例 2: 输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr" 输出:10 解释: 可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。   提示: 1 <= words.length <= 1000 1 <= words[i].length, chars.length <= 100 所有字符串中都仅包含小写英文字母 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters """ words = ["cat", "bt", "hat", "tree"] chars = "atach" # 53 1 def count_characters(words, chars): know = 0 for word in words: keep_chars = chars[:] for i in word: if i in keep_chars: keep_chars = keep_chars.replace(i, "", 1) else: break else: know += len(word) return know print(count_characters(words, chars)) # 53 2 import collections def count_characters_2(words, chars): ans = 0 # Counter类计数器 # Counter({'a': 2, 't': 1, 'c': 1, 'h': 1}) cnt = collections.Counter(chars) for w in words: # Counter({'c': 1, 'a': 1, 't': 1}) c = collections.Counter(w) # all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。 if all([c[i] <= cnt[i] for i in c]): ans += len(w) return ans print(count_characters_2(words, chars)) #============================ 2520 ms 13.9 MB 跟53的相比差了20多倍,我太菜了 ============== def count_characters_3(words, chars): length = 0 tup_c = tuple(chars[:]) for word in words: tup_w = tuple(word[:]) count = 0 word_length = len(word) for w in word: if(tup_c.count(w) >= tup_w.count(w)): count += 1 if(count == word_length): length += word_length return length print(count_characters_3(words, chars)) # 先统计各个字符才个数,再比较 比53大佬慢4倍左右 408 ms 13.7 MB def count_characters_4(words, chars): length = 0 dictionary_char = get_dictionary(chars) for word in words: dictionary_word = get_dictionary(word) count = 0 word_length = len(word) for w in word: if(dictionary_char.get(w,0) >= dictionary_word.get(w,0)): count += 1 if(count == word_length): length += word_length return length def get_dictionary(chars): dictionary_char = {} for c in chars: count = dictionary_char.get(c,0) if(count == 0) : dictionary_char[c] = 1 else: count += 1 dictionary_char[c] = count return dictionary_char; print(count_characters_4(words, chars))
import string file_name = input('Enter the file name (ex. palindromes.txt)> ') unwanted = string.punctuation + ' ' def is_palindrome(str): # Remove the unwanted chars new_str = filter(lambda x: x not in unwanted, str.lower()) if new_str == new_str[::-1]: return True with open(file_name, 'r') as f: for line in f: # Here I used rstrip to remove the newline (\n) at the end of the line if is_palindrome(line.rstrip()): print (line.rstrip())
#Write your code below this line 👇 #Hint: Remember to import the random module first. 🎲 import random print("Welcome. This is a coin toss programme.") coin_side_chosen = int(input("Type 0 for Heads and 1 for Tails.")) if coin_side_chosen == 0: print("You chose Heads.") else: print("You chose Tails.") comp_coin_side_chosen = random.randint(0, 1) if comp_coin_side_chosen == 0: print("Computer chose Heads.") else: print("Computer chose Tails.") if coin_side_chosen == comp_coin_side_chosen: print("You Won.") else: print("You Lose.")
import pygame # Add your favorite background color background_colour = (0, 0, 255) # Set the width and the height of the window (width, height) = (300, 200) # set the screen fro pygame to the width and height tuple defined above screen = pygame.display.set_mode((width, height)) # set the name of the pygame project at the top of the window pygame.display.set_caption('Tutorial 1') screen.fill(background_colour) pygame.display.flip() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit()
class Toy(): def __init__(self,color,age): self.color= color self.age= age self.my_dict= { 'name':'Yoyo', 'has_pets':False } def __str__(self): return f'{self.color}' def __len__(self): return 5 def __call__(self): return('yes??') def __getitem__(self, i): return self.my_dict[i] action_figure=Toy("Red",0) print(action_figure.__str__()) print(str(action_figure)) print(len(action_figure)) print(action_figure()) print(action_figure['name'])
# 4.3 ## 4.3.1 Intro to network analysis import networkx as nx # create an undirected graph G = nx.Graph() # add node: G.add_node(1) G.add_nodes_from([2,3]) G.add_nodes_from(['u','v']) # view nodes G.nodes() NodeView((1, 2, 3, 'u', 'v')) # adding edges takes 2 args, the nodes G.add_edge(1,2) G.add_edge('u','v') # you can add edges from nodes that dont exist - Networkx adds those nodes G.add_edges_from([(1,3),(1,4),(1,5),(1,6)]) G.add_edge('u','w') G.edges() EdgeView([(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), ('u', 'v'), ('u', 'w')]) # removing nodes G.remove_node(2) G.nodes() NodeView((1, 3, 'u', 'v', 4, 5, 6, 'w')) G.remove_nodes_from([4,5]) G.nodes() NodeView((1, 3, 'u', 'v', 6, 'w')) # removing edges G.remove_edge(1,3) G.edges() EdgeView([(1, 6), ('u', 'v'), ('u', 'w')]) G.remove_edges_from([(1,2), ('u','v')]) G.edges() EdgeView([(1, 6), ('u', 'w')]) G.nodes() NodeView((1, 3, 'u', 'v', 6, 'w')) # get number of nodes or edges G.number_of_nodes() 6 G.number_of_edges() 2 ## 4.3.3 Graph Visualistaion with NetworkX ## using a built in data set called Karate Club graph G = nx.karate_club_graph() # to visualise, import matplot import matplotlib.pyplot as plt nx.draw(G) nx.draw(G, with_labels=True, node_color='lightblue', edge_color='gray') plt.show() nx.show() ----------------------------------------------------------------- rror Traceback (most recent call last) nput-142-4f04236f4dc5> in <module>() .show() rror: module 'networkx' has no attribute 'show' nx.draw(G, with_labels=True, node_color='lightblue', edge_color='gray') plt.savefig('karate_graph.pdf') plt.show() # Nx stores degrees of nodes in a dict where keys are node IDs and vals are degrees G.degree() DegreeView({0: 16, 1: 9, 2: 10, 3: 6, 4: 3, 5: 4, 6: 4, 7: 4, 8: 5, 9: 2, 10: 3, 11: 1, 12: 2, 13: 5, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 3, 20: 2, 21: 2, 22: 2, 23: 5, 24: 3, 25: 3, 26: 2, 27: 4, 28: 3, 29: 4, 30: 4, 31: 6, 32: 12, 33: 17}) # to find specific nodes degrees: G.degree()[33] 17 # or using this notation where the arg is the node: G.degree(33) 17 # note this fn degree is different and distinguished by the interpreter by the way it is called # the first degree has no args, the second 1 ard ### 4.3.4 Random Graphs # simplest random graph model for network is the Erdos-Renyi or the ER graph model # there are two parameters for a random graph model, N and p. # N is the number of nodes and p is the probability for any two nodes to be connected by an edge # so to implement you would go through every possible pair of nodes and with probabiliyt p insert an edge between them. # consider eaxh pair of nodes once, independently of any other pair and, for example, flip a coin to see if they are connected. # If the value of p is small typical graphs tend to be sparse having few edges # large values of p mean the graph is densely connected # the Nx lib includes an ER graph generator but we will write our own. # The we would be able to implement a more complex network model of the kind not included in the Nx lib # to implement the coin flip part we will import a fn from scipy stats ### pseudocode for the random graph generator #number of nodes, N = 20 #probability of edge, p = 0.2 #create empty graph #add all nodes in the graph #loop over all pairs of nodes # add edge with probability p N = 20 p = 0.2 G = nx. Graph() G.add_nodes_from(range(N)) for node1 in G.nodes(): for node2 in G.nodes(): # True == 1 #if bernoulli.rvs(p=p) == True: is the same as: if bernoulli.rvs(p=p): G.add_edge(node1, node2) G.nodes() NodeView((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)) G.number_of_nodes() 20 G.number_of_edges() 72 # Edges seems v high when probability is only 0.2 nx.draw(G) plt.savefig("random_nx_1") plt.show <function matplotlib.pyplot.show(*args, **kw)> plt.show() # yep has far to many edges - why? # We have considered each pair twice - because we consider node1 being 10 and #node2 being 1 BUT ALSO node1 being 1 and node2 being 10. G = nx. Graph() G.add_nodes_from(range(N)) for node1 in G.nodes(): for node2 in G.nodes(): # will also work if use > if node1 < node2 and bernoulli.rvs(p=p): G.add_edge(node1, node2) nx.draw(G) plt.savefig('random_nx_2') plt.show() G.number_of_nodes() 20 G.number_of_edges() 37 # turn into fn: def er_graph(N, p): """ Generate a random ER Network Graph """ G = nx. Graph() G.add_nodes_from(range(N)) for node1 in G.nodes(): for node2 in G.nodes(): if node1 < node2 and bernoulli.rvs(p=p): G.add_edge(node1, node2) return G # Test by calling directly from nx.draw: nx.draw(er_graph(50, 0.08)) nx.draw(er_graph(50, 0.08), node_size=40, node_color='gray') plt.savefig('er_final') plt.show()
#Exercise 1 #A cipher is a secret code for a language. In this case study, we will explore a cipher that is reported by contemporary Greek historians to have been used by Julius Caesar to send secret messages to generals during times of war. #The Caesar cipher shifts each letter of a message to another letter in the alphabet located a fixed distance from the original letter. If our encryption key were 1, we would shift h to the next letter i, i to the next letter j, and so on. If we reach the end of the alphabet, which for us is the space character, we simply loop back to a. To decode the message, we make a similar shift, except we move the same number of steps backwards in the alphabet. #Over the next five exercises, we will create our own Caesar cipher, as well as a message decoder for this cipher. In this exercise, we will define the alphabet used in the cipher. #The string library has been imported. Create a string called alphabet consisting of the lowercase letters of the space character space ' ', concatenated with string.ascii_lowercase at the end. import string alphabet = ' ' + string.ascii_lowercase #alphabet has already defined from the last exercise. Create a dictionary with keys consisting of the characters in alphabet, and values consisting of the numbers from 0 to 26. #Store this as positions. positions = dict(zip(alphabet, range(27))) #alphabet and positions have already been defined from previous exercises. Use positions to create an encoded message based on message where each character in message has been shifted forward by 1 position, as defined by positions. Note that you can ensure the result remains within 0-26 using result % 27 #Store this as encoded_message. message = "hi my name is caesar" def encode(message, step): encoded_message = "" for i in message: ind = positions[i] cod = alphabet[ind+step] encoded_message += cod return encoded_message encoded_message = encode(message, 1) print(encoded_message) #alphabet, position and message remain defined from previous exercises. In addition, sample code for the previous exercise is provided below. Modify this code to define a function encoding that takes a message as input as well as an int encryption key key to encode a message with the Caesar cipher by shifting each letter in message by key positions. #Your function should return a string consisting of these encoded letters. #Use encode to encode message using key = 3, and save the result as encoded_message. #Print encoded_message #supplied code encoding_list = [] for char in message: position = positions[char] encoded_position = (position + key) % 27 encoding_list.append(alphabet[encoded_position]) encoded_string = "".join(encoding_list) # I basically did this in my previous piece of code :) def encode(message, key): encoding_list = [] for char in message: position = positions[char] encoded_position = (position + key) % 27 encoded = alphabet[encoded_position] encoding_list.append(encoded) encoded_string = "".join(encoding_list) return encoded_string encoded_message = encode(message, 3) print(encoded_message) # this works but mine was nicer #Note that encoding and encoded_message are already loaded from the previous problem. Use encoding to decode encoded_message using key = -3. #Store your decoded message as decoded_message. #Print decoded_message. Does this recover your original message? #### NOTE that they saved the encoder as ENCODING this time not encode ;) decoded_message = encoding(encoded_message, -3) print(decoded_message)
import usuarios.conexion as conexion connect = conexion.conectar() # variable connect llamar metodo conectar que esta dentro de coexion database = connect[0] #indice cero donde eeta la base de datos cursor = connect[1] #indice uno donde esta el cursor class Producto: def __init__(self,codigo_producto,id_TipoPro, nombreProducto,familia,DNI_provedor,descripcion,cantidad_stock,precio_venta,precio_provedor): self.codigo_producto = codigo_producto self.id_TipoPro = id_TipoPro self.nombreProducto = nombreProducto self.familia = familia self.DNI_provedor = DNI_provedor self.descripcion = descripcion self.cantidad_stock = cantidad_stock self.precio_venta = precio_venta self.precio_provedor = precio_provedor def guardar (self): sql = "INSER INTO productos VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,NOW())" producto =(self.codigo_producto,self.id_TipoPro,self.nombreProducto,self.familia,self.DNI_provedor,self.descripcion,self.cantidad_stock,self.precio_venta,self.precio_provedor) cursor.execute(sql,producto) database.commit() return[cursor.rowcount,self] #consulta producto existe def identificar_producto (self): #metodo identificar sql = "SELECT * FROM tipoproducto WHERE id_TipoPro = %s OR nombreProducto = %s" #DATOS PARA CONSULTA PRODUCTO producto = (self.id_TipoPro, self.nombreProducto) #CONSULTA cursor.execute(sql, producto) result = cursor.fetchone() return result
# # Global settings # # Step size for calculation step = 1/12. nyears = 14 nstep = int(nyears/float(step)) # Step size for temperature (determines roughly the granularity of reported sensor temperatures) ts_step = 5 # steps per degree # time_step_list is a list of each step through the years, for plotting purposes maybe. # It is size nstep+1 time_step_list = [] time_step_list.append(0) for i in range(nstep) : time_step_list.append( time_step_list[-1] + step ) # Used to live in NominalPower nomsensorT = 0 # Temperature kelvin / celsius conversion def kelvin(celsius) : return 273.15 + celsius
import unittest from problem_two import * class TestPrintDepth(unittest.TestCase): def test_output(self): """ Tests if the value returned from the print_depth function matchs the expected value. """ var1 = { "key1":1, "key2":{ "key3":1, "key4":{ "key5":4, "user":person_b, } } } var2 = {"user1": person_a} self.assertDictEqual(print_depth(var1), {'key1': 1, 'key2': 1, 'key3': 2, 'key4': 2, 'key5': 3, 'user': 3, 'first_name': 5, 'last_name': 5, 'father': 5}) self.assertDictEqual(print_depth(var2), {'user1':1, 'first_name':2, 'last_name':2, 'father':2}) self.assertDictEqual(print_depth({}), {}) def test_input_data(self): """ Raises a TypeError if the input data is not a dictionary """ self.assertRaises(TypeError, print_depth, []) self.assertRaises(TypeError, print_depth, 1) self.assertRaises(TypeError, print_depth, 'test')
def get_salary(hours: int) -> int: res = hours * 84 if hours > 120: res += (hours - 120) * 84 * 0.15 if hours < 60: res -= 700 return res if __name__ == "__main__": try: hours = int(input("Pls input the hours of work:")) print(f"Salary is {get_salary(hours)}") except Exception as e: print("The type of input is not integer,and the error is ", e)
print("To je program za pretvarjanje enot") kilometri = int(raw_input("Vnesi stevilo kilometrov: ")) conv_fac = 0.621371 milje = kilometri * conv_fac print("To je " + str(milje) +" milj") while True: answer = raw_input("Zelis narediti novo pretvorbo? (yes/no)") if answer == "yes": kilometri = int(raw_input("Vnesi stevilo kilometrov: ")) conv_fac = 0.621371 milje = kilometri * conv_fac print("To je " + str(milje) + " milj") elif answer == "no": print ("adijo") break else: print("napaka, odgovori z yes ali no")
#! /usr/bin/env python # -*- coding: utf-8 -*- # 「Introduction to Computation and Programming Using Python」の§3.3の例題2 def isIn(short_string, long_string): m = len(long_string) n = len(short_string) for i in range(m): if long_string[i] == short_string[0]: flag = True for j in range(n): if long_string[i+j] != short_string[j]: flag = False break if flag: return True return False if isIn('test', 'Test test'): print 'True' else: print 'False'
#! /usr/bin/env python # -*- coding: utf-8 -*- # 「Introduction to Computation and Programming Using Python」の§4.1.2の例題 def printName(firstName, lastName, reverse=False): if reverse: print lastName + ', ' + firstName else: print firstName, lastName printName('Olga', 'Puchajerova') printName('Olga', 'Puchajerova', True) printName('Olga', 'Puchajerova', False) printName('Olga', 'Puchajerova', reverse=False) printName('Olga', lastName='Puchajerova', reverse=False) printName(lastName='Puchajerova', firstName='Olga', reverse=False)
def manhattanDistance(p1, p2): return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) with open("6.txt", "r") as f: coordinates = [] for line in f.readlines(): current = line.rstrip("\n").split(",") coordinates.append((int(current[0]), int(current[1]))) areaOwned = {c: [0, False] for c in coordinates} minX = min(coordinates, key=lambda c: c[0])[0] maxX = max(coordinates, key=lambda c: c[0])[0] minY = min(coordinates, key=lambda c: c[1])[1] maxY = max(coordinates, key=lambda c: c[1])[1] xRange = range(minX, maxX + 1) yRange = range(minY, maxY + 1) def isInfinite(p): print(p) return p[0] == minX or p[0] == maxX or p[1] == minY or p[1] == maxY matrix = [[[((x, y), c, manhattanDistance((x,y),c)) for c in coordinates] for x in xRange] for y in yRange] for y in range(len(xRange)): for x in range(len(yRange)): matrix[x][y].sort(key=lambda p: p[2]) if not areaOwned[matrix[x][y][0][1]][1]: areaOwned[matrix[x][y][0][1]][1] = isInfinite(matrix[x][y][0][0]) if matrix[x][y][0][2] != matrix[x][y][1][2]: areaOwned[matrix[x][y][0][1]][0] += 1 print(areaOwned) print(max(filter(lambda v: not v[1], areaOwned.values())))
import pygame import math pygame.init() BLACK = (0,0,0) WHITE = (255,255,255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0,0,255) PI = 3.141592653 done = False clock = pygame.time.Clock() size = (700,500) screen = pygame.display.set_mode(size) pygame.display.set_caption("Mr Duguid's Cool Game") screen.fill(WHITE) pygame.display.flip() width = 0 while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: print("Key Pressed") width = width +1 screen.fill(WHITE) pygame.draw.line(screen, GREEN, [0,0], [100,100],width) y_offset = 0 while y_offset < 100: pygame.draw.line(screen,RED,[0,10+y_offset],[100,110+y_offset],5) y_offset = y_offset + 10 for i in range(200): radians_x = i / 20 radians_y = i / 6 x = int(75 * math.sin(radians_x)) + 200 y = int(75 * math.cos(radians_y)) + 200 pygame.draw.line(screen, BLACK, [x,y], [x+5,y], 5) pygame.draw.rect(screen,BLACK,[20,20,250,100],2) pygame.draw.ellipse(screen, BLACK, [20,20,250,100], 2) pygame.draw.arc(screen, GREEN, [100,100,250,200],PI/2, PI, 2) pygame.draw.arc(screen, BLACK, [100,100,250,200],0, PI/2, 2) pygame.draw.arc(screen, RED, [100,100,250,200],2*PI/2, 2*PI, 2) pygame.draw.arc(screen, BLUE, [100,100,250,200],PI, 3*PI/2, 2) pygame.draw.polygon(screen, BLACK, [[200,350], [0,400], [200,450], [400,400]],5) font = pygame.font.SysFont('Calibri',25,True,False) text = font.render("Some Text",True,GREEN) screen.blit(text, [500,250]) pygame.display.flip() clock.tick(60) print("Got Here") pygame.quit()
from turtle import Turtle class GameBar(Turtle): def __init__(self): super().__init__() self.speed(0) self.penup() self.color('white') self.hideturtle() self.goto(0, 260) def set_points(self, tray_left, tray_right): self.clear() self.write(f"Player {tray_left.game_color}: {tray_left.score} " f"Player {tray_right.game_color}: {tray_right.score}", align="center", font=("Calibri", 15, "normal")) class EndGameBar(Turtle): def __init__(self): super().__init__() self.speed(0) self.penup() self.color('red') self.hideturtle() self.goto(0, 50) def end_game(self, tray): self.clear() self.write(f"Player {tray.game_color} won with {tray.score} points", align="center", font=("Calibri", 30, "italic"))
#!/bin/python3 import math import os import random import re import sys # Complete the caesarCipher function below. def caesarCipher(s, k): q="abcdefghijklmnopqrstuvwxyz" w = q.upper() t = "" for i in s: if i not in q and i not in w: t=t+i else: if i not in q: ind = (w.index(i)+k)%len(q) t=t+w[ind] else: ind = (q.index(i)+k)%len(q) t=t+q[ind] return t if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) s = input() k = int(input()) result = caesarCipher(s, k) fptr.write(result + '\n') fptr.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- # Development environment: # - Python 2.7.5 (32-bit) # - Windows 7 64-bit machine import json from pprint import pprint def getMovieRatings(jsonFile): """ Reads movie ratings from json file and returns an object """ with open(jsonFile) as ratingsFile: ratings = json.load(ratingsFile) return ratings # Calculate similarity score # Two methods: 1. Euclidean distance and 2. Pearson correlation def calcSimilarityEuclidean(ratings, critic1, critic2): """ Calculates similarity score using Euclidean distance method """ return 0 def calcSimilarityPearson(ratings, critic1, critic2): """ Calculates similarity score using Pearson correlation coefficient method """ pass def movieRecommendations(): """ Movie recommendation program based on ratings of critics """ ratings = getMovieRatings("movie_ratings.json") for critic in ratings: print critic for movie in ratings[critic]: print ratings[critic][movie] sim = calcSimilarityEuclidean(ratings, "Mick LaSalle", "Toby") print sim def main(): movieRecommendations() if __name__ == '__main__': main()
# #3. Delete Operation on Array # number_array = [4, 5, 2, 7, 9, 13]; # Lets delete the item in the 3rd position of the original array [4, 5, 2, 7, 9, 13]; print("=========== Initial Array =========") for idex, item in enumerate(number_array): print(" Array [", idex , "] ", item) print("=========== Initial Array =========") m = 3; #delete the item at the 5th position n = len(number_array); #assign the array length j = m #define a variable in the size index to remove while( j < n) : number_array[j-1] = number_array[j]; j = j + 1; n = n - 1; # length will reduce due to the deletion print("========= Updated Array ============") for i in range(n): print(" Array [", i , "] ", number_array[i]) print("========== Updated Array ===========") # Initial array before insertion: [4, 5, 2, 7, 9, 13]; # result array after insertion: [4, 5, 2, 9, 13];
import datetime class User: def __init__(self, name, birthday): self.name = name self.birthday = birthday def age(self): today = datetime.date(2021, 5, 18) yyyy = int(self.birthday[0:4]) mm = int(self.birthday[4:6]) dd = int(self.birthday[6:8]) dob = datetime.date(yyyy, mm, dd) age_in_day = (today - dob).days age_in_year = age_in_day / 365 return int(age_in_year) user = User('ashu', '19970416') print('Hello', user.name, 'You are ', user.age(),'years old !')
# method to format the list of users # prints user's title, fan count, likes, and userID def print_user_data( user_list ): i = 0 for user in user_list: print(str(i) + ': ' + user['title'] + " FANS:" + str(user['extraInfo']['fans']) + " LIKES:" + str( user['extraInfo']['likes']) + " ID:" + str(user['extraInfo']['userId'])) i += 1 # print user data from the hashtag list def print_user_objects( user_list): i = 0 for user in user_list: print(user['userInfo']['user']['nickname'] + " FOLLOWERS:" + str(user['userInfo']['stats']['followerCount']) + " LIKES:" + str(user['userInfo']['stats']['heart']) + " ID:" + str(user['userInfo']['user']['id'])) i += 1 # gather average, max, and min number of followers from list of users def hashtag_user_stats( users ): sum = 0 min = 0 max = 0 for i in range(len(users)): user=users[i] follow = user['userInfo']['stats']['followerCount'] sum = sum + follow if i == 0: min = follow max = follow elif follow < min: min = follow elif follow > max: max = follow avg = sum / len(users) return [avg, max, min] # prints the hashtag data, title and number of views def print_hashtag( tag_list ): for tag in tag_list: print( tag['cardItem']['title'] + ' VIEWS: ' + str( tag['cardItem']['extraInfo']['views'])) # prints the dictionary of TikToks. All data output def print_tiktoks( tiktok_list): for tiktok in tiktok_list: print(tiktok) # prints the TikTok found, formatted def print_tiktoks_format( tiktok_list, api): for tiktok in tiktok_list: username = tiktok['author']['uniqueId'] print(username + ' UserID: ' + str(tiktok['author']['id'])) user = api.get_user( username ) print(user) # from a given list of tiktoks, return all user objects def get_userobj_from_list( tiktok_list, api ): users = [] for tiktok in tiktok_list: username = tiktok['author']['uniqueId'] user = api.get_user( username ) users.append(user) return users # Collect userIDs from a list of TikTok users def get_seeds( user_list ): seed_ids = [] for user in user_list: seed_ids.append(user['extraInfo']['userId']) return seed_ids # Check for unique elements def is_unique( seed_list, item ): for value in seed_list: if item == value: return False return True
import sqlite3 #enable control of an sqlite database import csv #facilitates CSV I/O f="discobandit.db" db = sqlite3.connect(f) #open if f exists, otherwise create c = db.cursor() #facilitate db ops #========================================================== fObj1 = open("peeps.csv") fObj2 = open("courses.csv") d1=csv.DictReader(fObj1) d2=csv.DictReader(fObj2) #Q: What can you print here to make each line show only # a name and its ID? # eg, # sasha, 3 q = "CREATE TABLE students (name TEXT, age INTEGER, id INTEGER)" c.execute(q) #run SQL query for key in d1: field1 = key['name'] field2 = key['age'] field3 = key['id'] q = "INSERT INTO students VALUES('" + field1 + "','" +field2 + "','"+ field3+ "');" c.execute(q) q = "CREATE TABLE courses (code TEXT, id INTEGER, mark INTEGER)" c.execute(q) for key in d2: field1 = key['code'] field2 = key['id'] field3 = key['mark'] q = "INSERT INTO courses VALUES('" + field1 + "','" + field2 + "','" + field3 + "');" c.execute(q) #========================================================== db.commit() #save changes db.close() #close database
#!/usr/bin/python # -*- coding:utf-8 -*- from perceptron import Perceptron f = lambda x:x class LinearUnit(Perceptron): def __init__(self,input_num): Perceptron.__init__(self,input_num,f) def get_training_dataset(): input_vecs = [[5],[3],[8],[1.4],[10.1]] labels = [5500,2300,7600,1800,11400] return input_vecs,labels def train_linear_unit(): lu = LinearUnit(1) input_vecs,labels = get_training_dataset() lu.train(input_vecs,labels,10,0.01) return lu if __name__ == '__main__': linear_unit = train_linear_unit() print linear_unit print 'work 3.4 year,mothly salary = %.2f'%linear_unit.predict([3.4]) print 'work 13.4 year,mothly salary = %.2f'%linear_unit.predict([13.4])
import time from threading import Thread COUNT = 500_000_000 def countdown(n): while n > 0: n -= 1 start = time.time() t1 = Thread(target=countdown, args=(COUNT//2,)) t2 = Thread(target=countdown, args=(COUNT//2,)) t1.start() t2.start() t1.join() t2.join() end = time.time() print("Tempo em segundos:", round((end-start), 2))