text
stringlengths
37
1.41M
def Add(num1,num2): while(num2!=0): carry = num1 & num2 num1 = num1^num2 num2 = carry<<1 return num1 def recursive_Add(x,y): if (y==0): return x else: return recursive_Add(x^y,(x&y) << 1) print(recursive_Add(32,61))
def fibonacci(n): if n<0: print("Incorrect input") elif n == 0: return 0 elif n == 1: return 1 else: return fibonocci(n-1)+fibonocci(n-2) #print(fibonacci(5)) def fibonacci(n): f = [0,1] for i in range(2,n): f.append(f[i-1]+f[i-2]) return f[n] #print(fibonacci(9)) def fibonacci(n): first = 0 second = 1 if n<0: print("Incorrect input") elif n == 0: return first elif n == 1: return second else: for i in range(2,n+1): c = first + second first = second second = c return second #print(fibonacci(9)) def fibonacci_sum(n): f = [0,1] fib_sum = 0 for i in range(2,n+1): f.append(f[i-1]+f[i-2]) for i in range(len(f)): fib_sum = fib_sum +f[i] return fib_sum #print(fibonacci_sum(5)) def fib_Sum(n): if n == 0: return 0 Sum = 0 a,b = 1,1 Sum += a while b<=n: Sum += b a,b = b,a+b return Sum print(fib_Sum(5))
def simple_reverse(string): new_string = [] for i in range(len(string)-1,-1,-1): new_string.append(string[i]) return ''.join(new_string) string = "Hello" #print(simple_reverse(string)) def swap(string,a,b): string = list(string) temp = string[a] string[a] = string[b] string[b] = temp return ''.join(string) def smarter_reverse(string): for i in range(len(string)//2): string = swap(string,i,len(string)-i-1) return string #print(smarter_reverse(string)) string2 = reversed(string) print(''.join(string2)) list1 = list(string) list1.reverse() print(''.join(list1))
import math # =============================================================================================================== # # THIS CLASS IS IN CHARGE OF DISPLAYING A MESSAGE FRAME, SIMILAR TO A MENU, BUT WITH NO OPTIONS class GameMessageFrame: def __init__(self, lines, padt=0, padb=0): self.lines = lines self.padt = padt self.padb = padb # =============================================================================================================== # # DRAWS A MESSAGE FRAME def get_frame(self): if len(self.lines) == 0: return frame = "" # TOP BORDER frame += "╔{:=^97}╗\n".format('') # TOP PADDING if self.padt > 0: for i in range(0, self.padt): frame += "║{:^97}║\n".format('') for line in self.lines: frame += "║{:^97}║\n".format(line) # BOTTOM PADDING if self.padb > 0: for i in range(0, self.padb): frame += "║{:^97}║\n".format('') # BOTTOM BORDER frame += "╚{:=^97}╝".format("") return frame # =============================================================================================================== # # THIS CLASS IS IN CHARGE OF DRAWING THE MENUS ON THE GAME class GameMenu: # CLASS CONSTRUCTOR def __init__(self, options, enum=False, caption=None, padt=0, padb=0, hmenu=False, loop=False): self.options = options # OPTIONS THAT WILL APPEAR ON THE MENU self.enum = enum # ENUMERATE OPTIONS self.caption = caption # CAPTION FOR THE MENU self.padt = padt # TOP PADDING (IN LINES) self.padb = padb # BOTTOM PADDING (IN LINES) self.hmenu = hmenu # SET IF MENU IS HORIZONTAL self.loop = loop # LOOPING MENU self.selected_index = 0 # INDEX OF CURRENTLY SELECTED ITEM ON THE MENU # =============================================================================================================== # # DRAWS A FRAMED MENU FROM THE LIST OF OPTIONS PROVIDED def get_menu(self): menu = "" # TOP BORDER menu += "╔{:=^97}╗\n".format('') # TOP PADDING if self.padt > 0: for i in range(0, self.padt): menu += "║{:^97}║\n".format('') # CAPTION if self.caption is not None: menu += "║{:^97}║\n".format(self.caption) menu += "║{:^97}║\n".format('') # VERTICAL MENU? if not self.hmenu: for i in range(len(self.options)): # ENUMERATED if self.enum: if i == self.selected_index: menu += '║' + str('>> {}. {} <<'.format(i+1, self.options[i])).center(97) + '║\n' else: menu += '║' + str('{}. {}'.format(i+1, self.options[i])).center(97) + '║\n' # NOT ENUMERATED else: if i == self.selected_index: menu += '║' + str('>> {} <<'.format(self.options[i])).center(97) + '║\n' else: menu += '║' + str('{}'.format(self.options[i])).center(97) + '║\n' # END VERTICAL # HORIZONTAL MENU else: col_len = 0 h_options = '' if len(self.options) > 0: col_len = int(math.floor(97 / len(self.options))) for i in range(len(self.options)): # ENUMERATED if self.enum: if i == self.selected_index: h_options += str('>> {}. {} <<'.format(i+1, self.options[i])).center(col_len) else: h_options += str('{}. {}'.format(i+1, self.options[i])).center(col_len) # NON ENUMERATED else: if i == self.selected_index: h_options += str('>> {} <<'.format(self.options[i])).center(col_len) else: h_options += str('{}'.format(self.options[i])).center(col_len) menu += '║' + h_options.center(97) + '║\n' # END HORIZONTAL MENU # BOTTOM PADDING if self.padb > 0: for i in range(0, self.padb): menu += "║{:^97}║\n".format('') # BOTTOM BORDER menu += "╚{:=^97}╝".format("") return menu # =============================================================================================================== # # SELECT THE NEXT OPTION ON THE MENU def select_next(self): # MAKE SURE WE DON'T GO OUT OF RANGE if self.loop: if self.selected_index + 1 > len(self.options) - 1: self.selected_index = 0 else: self.selected_index += 1 else: if self.selected_index + 1 > len(self.options) - 1: pass else: self.selected_index += 1 return self.get_menu() # =============================================================================================================== # # SELECT THE PREVIOUS OPTION ON THE MENU def select_previous(self): # MAKE SURE WE DON'T GO OUT OF RANGE if self.loop: if self.selected_index - 1 < 0: self.selected_index = len(self.options) - 1 else: self.selected_index -= 1 else: if self.selected_index - 1 < 0: pass else: self.selected_index -= 1 return self.get_menu() # CONSTANTS WITH PREMADE MENUS USED IN THE GAME QUIT_MENU = GameMenu(['Yes', 'No', 'Quit to Main Menu'], hmenu=True, padt=8, padb=9, caption='Really Quit?') MAIN_MENU = GameMenu(['Start', 'Credits', 'Quit'], hmenu=True) MATCH_TYPE_MENU = GameMenu(['Local Match', 'Online Match'], padt=8, padb=8, caption='Select Match Type') PLAYER1_HERO_MENU = GameMenu(['New Character', 'Load Character'], padt=8, padb=8, caption='Player 1, select your hero') PLAYER2_HERO_MENU = GameMenu(['New Character', 'Load Character'], padt=8, padb=8, caption='Player 2, select your hero') PLAYER1_CONFIRM_HERO_MENU = GameMenu(['Yes', 'No'], hmenu=True, caption='Confirm selection') PLAYER2_CONFIRM_HERO_MENU = GameMenu(['Yes', 'No'], hmenu=True, caption='Confirm selection') PRE_COMBAT_MENU = GameMenu(['PRESS <ENTER> TO BEGIN MATCH'], padt=8, padb=9, caption='The Heroes are Ready') POST_COMBAT_MENU = GameMenu(['PRESS <ENTER> TO CONTINUE'],padt=8, padb=9) SAVE_CHARACTER_PROMPT = GameMenu(['Yes', 'No'], hmenu=True, padt=8, padb=9, caption='Do you wish to save your character?') CREDITS = GameMessageFrame(['TEAM Awesome is:','','Omar Silva', 'Mike Sturdy', 'Tim Andrew'], padt=8, padb=7) if __name__ == '__main__': pass
import random # THIS FILE IS IN CHARGE OF ANYTHING TO DO WITH ROLLING THE RANDOM DICE USED IN THE GAME # ============================================================================================================= # # ROLLS A RANDOM DICE, FORMAT IS 'XdY', WHERE x IS THE AMOUNT OF DIE TO ROLL, AND Y IS THE TYPE OF DIE TO ROLL # EX. '3d6' = ROLL THREE SIX SIDED DICE ; '2d8' = ROLL TWO EIGHT SIDED DIE def roll(what): amount, type_die = what.split('d') if type_die == '4': return d4(int(amount)) elif type_die == '6': return d6(int(amount)) elif type_die == '8': return d8(int(amount)) elif type_die == '10': return d10(int(amount)) elif type_die == '12': return d12(int(amount)) elif type_die == '20': return d20(int(amount)) elif type_die == '100': return d100(int(amount)) # ============================================================================================================= # # ROLLS X AMOUNT OF 4 SIDED DIE, RETURNS RESULTS AS A LIST def d4(x): rolls = [] counter = 1 while counter <= x: rolls.append(random.randint(1, 4)) counter += 1 return rolls # ============================================================================================================= # # ROLLS X AMOUNT OF 6 SIDED DIE, RETURNS RESULTS AS A LIST def d6(x): rolls = [] counter = 1 while counter <= x: rolls.append(random.randint(1, 6)) counter += 1 return rolls # ============================================================================================================= # # ROLLS X AMOUNT OF 8 SIDED DIE, RETURNS RESULTS AS A LIST def d8(x): rolls = [] counter = 1 while counter <= x: rolls.append(random.randint(1, 8)) counter += 1 return rolls # ============================================================================================================= # # ROLLS X AMOUNT OF 10 SIDED DIE, RETURNS RESULTS AS A LIST def d10(x): rolls = [] counter = 1 while counter <= x: rolls.append(random.randint(1, 10)) counter += 1 return rolls # ============================================================================================================= # # ROLLS X AMOUNT OF 12 SIDED DIE, RETURNS RESULTS AS A LIST def d12(x): rolls = [] counter = 1 while counter <= x: rolls.append(random.randint(1, 12)) counter += 1 return rolls # ============================================================================================================= # # ROLLS X AMOUNT OF 20 SIDED DIE, RETURNS RESULTS AS A LIST def d20(x): rolls = [] counter = 1 while counter <= x: rolls.append(random.randint(1, 20)) counter += 1 return rolls # ============================================================================================================= # # ROLLS X AMOUNT OF 100 SIDED DIE, RETURNS RESULTS AS A LIST def d100(x): rolls = [] counter = 1 while counter <= x: rolls.append(random.randint(1, 100)) counter += 1 return rolls
class DoublyCircNode(object): def __init__ (self, d, n = None, p = None): self.data = d self.next = n self.prev = p def get_data(self): return self.data def set_next(self, new_next): self.next = new_next def set_prev(self, new_prev): self.prev = new_prev class DoublyCircLinkedList(object): def __init__(self, last = None): self.last = last def append(self, value): newNode = DoublyCircNode(value) if(self.last == None): self.last = newNode self.last.set_next(newNode) self.last.set_prev(newNode) return newNode.set_prev(self.last) newNode.set_next(self.last.next) self.last.next.set_prev(newNode) self.last.set_next(newNode) self.last = newNode def prepend(self, value): newNode = DoublyCircNode(value) if(self.last == None): self.append(value) return newNode.set_prev(self.last) newNode.set_next(self.last.next) self.last.next.set_prev(newNode) self.last.set_next(newNode) return def getLength(self): if(self.last != None): current = self.last i = 1 while(current.next != self.last): i+=1 current = current.next return i else: return 0 def insert(self, value, index): if(index == 0): prepend(value) return elif(index > self.getLength() or self.last == None): append(value) return else: current = self.last i = 1 while(current.next != self.last and i <index): i+=1 current = current.next newNode = DoublyCircNode(value) if(current.next == self.last): newNode.set_prev(current) newNode.set_next(current.next) current.next.set_prev(newNode) current.set_next(newNode) else: newNode.set_prev(current) newNode.set_next(current.next) current.next.set_prev(newNode) current.set_next(newNode) def deleteFirst(self, value): current = self.last if(self.last == None): return elif(self.last.next == self.last and self.last.get_data() != value): self.last = None return while(current.next != self.last and current.next.get_data() != value): current = current.next if(current.next == self.last and self.last.get_data() == value): self.last.prev.set_next(self.last.next) self.last.next.set_prev(self.last.prev) self.last = self.last.prev return elif(current.next == self.last and self.last.get_data() != value): return else: current.set_next(current.next.next) current.next.set_prev(current) return def deleteAll(self, value): if(self.last == None): return current = self.last.next while(current != self.last): if(current.get_data() == value): self.deleteFirst(value) current = current.next self.deleteFirst(value) def deleteAt(self, index): if(self.last == None or index > self.getLength()-1): return if(self.last.next == self.last): self.last = None return current = self.last i = 0 while(current.next != self.last and i < index): current = current.next i+=1 if(current == current.next.next): self.last.set_next(self.last) self.last.set_prev(self.last) elif(current.next == self.last): current.set_next(current.next.next) current.next.set_prev(current) self.last = current else: current.set_next(current.next.next) current.next.set_prev(current) def reverse(self): if(self.last == None): return current = self.last.next previous = self.last n = self.last.next while(current != self.last): n = current.next current.set_next(previous) current.set_prev(n) previous = current current = n n = current.next current.set_next(previous) current.set_prev(n) self.last = n def reverseRecursive(self, previous, current, stop): if(current == stop): n = current.next current.set_next(previous) current.set_prev(next) self.last = n return self.last n = current.next current.set_next(previous) current.set_prev(next) return (self.reverseRecursive(current, n, stop)) def get_last(self): return self.last def set_last(self, value): self.last = DoublyCircNode(value) def getValues(self): arr = [] current = self.last.next while(current != self.last): arr.append(current.get_data()) current = current.next arr.append(self.last.get_data()) return arr def main(): l = DoublyCircLinkedList() l.append(3) l.append(2) l.append(1) l.append(0) l.prepend(4) l.insert(3,3) l.deleteFirst(3) l.prepend(2) l.append(2) l.deleteAll(2) l.deleteAt(2) print(l.getValues()) l.reverse() print(l.getValues()) l.reverseRecursive(l.get_last(), l.get_last().next, l.get_last()) print(l.getValues()) if __name__ == "__main__": main()
a, b, c, = 3, 4, 5 print(a + b * c) print((a + b) * c) print("3^4 =", a ** b) print(a / b) print(a // b) print(a % b) print(b / 2) print(b // 2) print(b % 2)
""" David R. Winer [email protected] Machine Learning HW1 Implementation """ from collections import namedtuple import unicodedata import math Label = namedtuple('Label', ['label', 'firstname', 'middlename', 'lastname', 'lastname_length']) def strip_accents(s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') #### FEATURES #### # Feature 1 def firstname_longer_lastname(lb): fname = ''.join(lb.firstname.split()) # lname = ''.join(lb.lastname.split()) if len(fname) > lb.lastname_length: # if len(fname) > len(lb.lastname): return True return False # Feature 2 def has_middle_name(lb): if lb.middlename is not None: return True return False # Feature 3 def same_first_and_last_letter(lb): # fletter = unicodedata.normalize(.firstname[0].lower() if len(lb.firstname) == 1: return False if lb.firstname[0].lower() == lb.firstname[-1].lower(): return True return False # Feature 4 def firstnameletter_same_lastnameletter(lb): # last name letter is first capital letter lastnameletter = lb.lastname[0].strip().lower() for carrot in lb.lastname.split(): if carrot[0].isupper(): lastnameletter = carrot[0].lower() break if lb.firstname[0].lower() < lastnameletter: return True return False # Feature 5 def firstnameletter_is_vowel(lb): if lb.firstname[0].lower() in {'a', 'e', 'i', 'o', 'u'}: return True return False # Feature 6 def even_length_lastname(lb): if len(lb.lastname) % 2 == 0: return True return False #### EQUATIONS #### def gain(samples, feature, values): total_gain = 0 for value in values: sub_samples = [lbl for lbl in samples if feature(lbl) == value] total_gain += (len(sub_samples) / len(samples)) * entropy(sub_samples) return entropy(samples) - total_gain def entropy(samples): total = len(samples) if total == 0: return 0 sum_pos = sum(1 for lbl in samples if lbl.label is True) sum_neg = sum(1 for lbl in samples if lbl.label is False) p_pos = sum_pos / total p_neg = sum_neg / total if p_pos == 0: if p_neg == 0: return 0 return - p_neg * math.log2(p_neg) if p_neg == 0: if p_pos == 0: return 0 return -p_pos * math.log2(p_pos) return -p_pos * math.log2(p_pos) - p_neg * math.log2(p_neg) #### ID3 and DECISION TREE #### """ Nodes are nested dictionaries with 3 values, a feature, a 0 : {}, and a 1 : {} """ def num_samples_with_label(samples, target_label): return sum(1 for lbl in samples if lbl.label == target_label) def all_samples_target(samples, target_label): return len(samples) == num_samples_with_label(samples, target_label) def best_feature(samples, features, values): best = (-1, None) for feature in features: x = gain(samples, feature, values[feature]) if x > best[0]: best = (x, feature) return best[1] def most_labeled(samples, target_labels): best = (-1, None) for tlabel in target_labels: num_with_label = num_samples_with_label(samples, tlabel) if num_with_label > best[0]: best = (num_with_label, tlabel) return best[1] # ID3 without option to limit depth def ID3(samples, features, values): # if all samples have positive label for tlabel in [True, False]: if all_samples_target(samples, tlabel): return tlabel if len(features) == 0: # return most common value of remaining samples return most_labeled(samples, [True, False]) # Pick Best Feature if len(features) == 1: best_f = list(features)[0] else: best_f = best_feature(samples, features, values) children = {'feature': best_f} for best_f_value in values[best_f]: sub_samples = {lbl for lbl in samples if best_f(lbl) == best_f_value} if len(sub_samples) == 0: children[best_f_value] = most_labeled(samples, [True, False]) else: children[best_f_value] = ID3(sub_samples, set(features) - {best_f}, values) return children # ID3 with option to limit depth def ID3_depth(samples, features, values, depth): for tlabel in [True, False]: if all_samples_target(samples, tlabel): return tlabel if len(features) == 0: # return most common value of remaining samples return most_labeled(samples, [True, False]) # Pick Best Feature if len(features) == 1: best_f = list(features)[0] else: best_f = best_feature(samples, features, values) children = {'feature': best_f} for best_f_value in values[best_f]: sub_samples = {lbl for lbl in samples if best_f(lbl) == best_f_value} if len(sub_samples) == 0 or depth == 1: children[best_f_value] = most_labeled(sub_samples, [True, False]) else: children[best_f_value] = ID3_depth(sub_samples, set(features) - {best_f}, values, depth-1) return children def use_tree(tree, item): # base case, the tree is a value if type(tree) is bool: return tree # otherwise, recursively evaluate item with features result = tree['feature'](item) return use_tree(tree[result], item) def extract_name(split_line): name_part = split_line[1:] first_name = name_part[0] if len(name_part) > 2: # check if last position is title last_name = name_part[-1] middle_name = name_part[1] else: middle_name = None last_name = name_part[-1] return (first_name, middle_name, last_name) # Gets data from files and removes titles and punctuation def get_data(data_file_name): data = [] with open(data_file_name, 'rb') as training_data_file: for line in training_data_file: decoded_line = strip_accents(line.decode()) new_line = decoded_line.replace(';', ' ') new_line = new_line.replace(' Jr.', ' ') new_line = new_line.replace(' Sr.', ' ') new_line = new_line.replace(' Dr.', ' ') new_line = new_line.replace(',', ' ').replace('.', ' ') last_namelength = len(new_line.split()[-1]) # get length of name, but then remove them so that we calculate the first letter of the last name as new_line = new_line.replace(' von ', ' ').replace(' van der ', ' ').replace(' van ', ' ').replace(' de ', ' ') sp = new_line.split() if sp[0] == '+': label_value = True else: label_value = False name_parts = extract_name(sp) lb = Label(label_value, name_parts[0], name_parts[1], name_parts[2], last_namelength) data.append(lb) return data # Part 1 of the implementation hw def implementationHW(): # Set of Features, initially VALUES = {firstname_longer_lastname: [True, False], has_middle_name: [True, False], same_first_and_last_letter: [True, False], firstnameletter_same_lastnameletter: [True, False], firstnameletter_is_vowel: [True, False], even_length_lastname: [True, False]} training_data = get_data('data//updated_train.txt') dtree = ID3(training_data, list(VALUES.keys()), VALUES) num_correct = 0 for item in training_data: outcome = use_tree(dtree, item) if outcome and item.label: num_correct += 1 elif not outcome and not item.label: num_correct += 1 print('Train Acc: {}'.format(num_correct / len(training_data))) test_data = get_data('data//updated_test.txt') # dtree = ID3(test_data, list(VALUES.keys()), VALUES) num_correct = 0 for item in test_data: outcome = use_tree(dtree, item) if outcome and item.label: num_correct += 1 elif not outcome and not item.label: num_correct += 1 print('Test Acc: {}'.format(num_correct / len(test_data))) # print(dtree) def standard_dev(samples, mean): x = sum((sample-mean)**2 for sample in samples) / (len(samples)-1) return math.sqrt(x) def limit_depth(): VALUES = {firstname_longer_lastname: [True, False], has_middle_name: [True, False], same_first_and_last_letter: [True, False], firstnameletter_same_lastnameletter: [True, False], firstnameletter_is_vowel: [True, False], even_length_lastname: [True, False]} file_locations = ['data//Updated_CVSplits//updated_training0' + str(i) + '.txt' for i in range(4)] depths = [1, 2, 3, 4, 5, 6, 7, 8, 10, 15, 20] for d in depths: total = 0 avgs = [] for i in range(4): training = [] for j in range(4): if i == j: continue training.extend(get_data(file_locations[j])) test = get_data(file_locations[i]) dtree = ID3_depth(training, list(VALUES.keys()), VALUES, d) acc = 0 for item in test: result = use_tree(dtree, item) if result and item.label: acc += 1 elif not result and not item.label: acc += 1 total += acc / len(test) avgs.append(acc/len(test)) avg = total / 4 print('depth: {} \t average: {} \t std_dev: {}'.format(d, avg,standard_dev(avgs, avg))) # SECOND HALF of question: use the best depth (in this case, 6) to retrain on entire training and measure performacne on training and test data. training_data = get_data('data//updated_train.txt') dtree = ID3_depth(training_data, list(VALUES.keys()), VALUES, 6) num_correct = 0 for item in training_data: outcome = use_tree(dtree, item) if outcome and item.label: num_correct += 1 elif not outcome and not item.label: num_correct += 1 print('Train Acc: {}'.format(num_correct / len(training_data))) test_data = get_data('data//updated_test.txt') # dtree = ID3(test_data, list(VALUES.keys()), VALUES) num_correct = 0 for item in test_data: outcome = use_tree(dtree, item) if outcome and item.label: num_correct += 1 elif not outcome and not item.label: num_correct += 1 print('Test Acc: {}'.format(num_correct / len(test_data))) def superiorTech(lb): return lb.tech def enviro(lb): return lb.enviro def likesHuman(lb): return lb.likeshuman def lightYears(lb): return lb.lightyears alienLabel = namedtuple('AlienLabel', ['label', 'tech', 'enviro', 'likeshuman', 'lightyears']) def alien_test(): alienValues = {superiorTech: [True, False], enviro: [True, False], likesHuman: ['like', 'hate', 'do not care'], lightYears: [1,2,3,4]} alienData = [alienLabel(True, False, True, 'do not care', 1), alienLabel(False, False, True, 'like', 3), alienLabel(True, False, False, 'do not care', 4), alienLabel(True, True, True, 'like', 3), alienLabel(False, True, False, 'like', 1), alienLabel(True, False, True, 'do not care', 2), alienLabel(False, False, False, 'hate', 4), alienLabel(True, False, True, 'do not care', 3), alienLabel(False, True, False, 'like', 4)] print(entropy(alienData)) for feature in alienValues.keys(): print('feature: {} \t IG: {}'.format(feature.__name__, gain(alienData, feature, alienValues[feature]))) # print(feature, gain(alienData, feature, alienValues[feature])) dtree = ID3_depth(alienData, list(alienValues.keys()), alienValues, 1) print(dtree) # test_data = [alienLabel(False, True, True, 'like', 2), alienLabel(False, False, False, 'hate', 3), alienLabel(True, True, True, 'like', 4)] acc = 0 for item in test_data: result = use_tree(dtree, item) if result and item.label: acc += 1 elif not result and not item.label: acc += 1 print(1 - (acc / len(test_data))) for feature in alienValues.keys(): print(feature.__name__, majority_error_gain(alienData, feature, alienValues[feature])) dtree = ID3_depth(alienData, list(alienValues.keys()), alienValues, 8) print(dtree) def majority_error_gain(samples, feature, values): total_gain = 0 for value in values: sub_samples = [lbl for lbl in samples if feature(lbl) == value] total_gain += (len(sub_samples) / len(samples)) * majority_error(sub_samples) return majority_error(samples) - total_gain def majority_error(samples): if len(samples) == 0: return 1 p_true = num_samples_with_label(samples, True) / len(samples) p_false = num_samples_with_label(samples, False) / len(samples) if p_true > p_false: return 1 - p_true else: return 1 - p_false if __name__ == '__main__': print('David R. Winer\n') # alien_test() print('Train and Test, part 1') implementationHW() print('\nLimit Depth') limit_depth()
from array import array numbers = array("h", [-2, -1, 0, 1, 2]) memv = memoryview(numbers) print(len(memv)) print(memv[0]) memv_oct = memv.cast("B") print(memv_oct.tolist()) print(numbers) memv_oct[5] = 4 print(numbers) def calculate_element(sequence): res = {} for e in set(sequence): res[e] = sequence.count(e) return res def compare_number(x, y): if bool(int(x) - int(y)): return False return True def compare_number_2(x, y): if bool(int(x) ^ int(y)): return False return True
import argparse """ [root@ykyk argument_parse]# python ArgumentParse.py Namespace(boolean_switch=False, server='localhost') ('host = ', 'localhost') ('boolean_switch = ', False) [root@ykyk argument_parse]# python ArgumentParse.py --host 127.0.0.1 -t Namespace(boolean_switch=True, server='127.0.0.1') ('host = ', '127.0.0.1') ('boolean_switch = ', True) [root@ykyk argument_parse]# python ArgumentParse.py --help usage: ArgumentParse.py [-h] [--host SERVER] [-t] This is description optional arguments: -h, --help show this help message and exit --host SERVER connect to host -t Set a switch to True """ def _argparse(): parser = argparse.ArgumentParser(description="This is description") parser.add_argument('--host', action='store', dest='server', default='localhost', help='connect to host') parser.add_argument('-t', action='store_true', default=False, dest='boolean_switch', help='Set a switch to True') return parser.parse_args() def main(): parser = _argparse() print(parser) print("host = ", parser.server) print("boolean_switch = ", parser.boolean_switch) if __name__ == '__main__': main()
''' Python有许多内置的api,允许调用者传入参数, 以定制其行为 api在执行的时候,会通过这些钩子函数,回调函数的代码 比如list类型的sort方法接受可选的key参数,用以指定每个索引位置上的值 之间应该如果排序 ''' names = ["scorates", "archimedes", "plato", "aritotle"] names.sort(key=lambda x: len(x)) print(names) ''' 其他编程语言可能会用抽象类来定义挂钩,然而在Python中,很多钩子函数只是 无状态的函数,这些函数有明确的参数及返回值,用函数做挂钩是比较合适的,因为 他们很容易就能描述出这个挂钩的功能,而且比定义一个类要简单, python中的函数 之所以能作为钩子,原因就在于它是一级对象,也就是说,函数与方法可以像语言中的 其他值一样传递和引用 ''' def log_missing(): print('Key added') return 0 current = {'green': 12, 'blue': 3} increment = [ ("red", 5), ('blue', 17), ('orange', 9) ] result = defaultdict(log_missing, current) print("before", dict(result)) for key, amount in increment: result[key] += amount print("after", dict(result)) def increment_with_report(current, increment): added_count = 0 def missing(): nonlocal added_count added_count += 1 return 0 result = defaultdict(missing, current) for key, amount in increment: result[key] += amount return result, added_count ''' 对于连接各种Python组件的简单接口来说,通常应该给其直接传入函数, 而不是 先定义某个类,然后传入该类的实例 Python中的函数和方法都可以像以及类那样引用,因此它们与其他类型的对象一样 也能够放在表达式里面 通过名为__call__ 方法的特殊方法,可以使用该类的实例能够像普通的Python函数 那样得到调用 如果要用函数来保存状态信息,那就应该定义新的类,并令其实现__call__方法, 而不要定义带状态的闭包 '''
""" This program has a turtle that will ask you whether you would like to see a drawing or a fractal """ import turtle def draw_square(turtle): for i in range(4): turtle.forward(50) turtle.right(90) def draw_triangle(turtle): turtle.right(45) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(135) turtle.forward(135) def draw_fractal(): fractal_type = int(input("This is a fractal drawing program \n Enter a number for drawing a fractal: 1 for using a square or 2 for using a triangle")) shape_count = int(input("Enter number of shapes for fractal as a positive whole number: ")) window = turtle.Screen() window.bgcolor("orange") Gopi = turtle.Turtle() Gopi.shape("turtle") Gopi.color("red") Gopi.speed(2) for i in range(shape_count): if fractal_type == 1: Gopi.right(360/shape_count) draw_square(Gopi) elif fractal_type == 2: Gopi.right(360/shape_count) draw_triangle(Gopi) window.exitonclick() draw_fractal()
from ascii_art import logo import random EASY_LEVEL_TURNS = 12 HARD_LEVEL_TURNS = 6 def check_answer(guess, answer): if guess > answer: print("Too high") elif guess < answer: print("Too low") else: print(f"You got it. The answer was {answer}") def set_difficulty(): level = input("Choose difficulty 'easy' or 'hard': ") if level == "easy": return EASY_LEVEL_TURNS else: return HARD_LEVEL_TURNS def game(): print("Welcome to Number Guessing Game") print("Think a number between 1 to 100....") turns = set_difficulty() answer = random.randint(1, 100) # print(f"THE ANSWER IS {answer}") guess_number = 0 while guess_number != answer: if turns == 0: print(f"You lost..... The number was {answer}") return print(f"You have {turns} attempts remaining to guess the number.") guess_number = int(input("Guess a number: ")) turns -= 1 check_answer(guess_number, answer) print(logo) game()
# Uses python3 import sys def binary_search(b, y): low, high = 0, len(b) - 1 while low <= high: mid = int(low + (high - low) / 2) if y == b[mid]: return mid elif y < b[mid]: high = mid - 1 else: low = mid + 1 return -1 if __name__ == '__main__': inp = sys.stdin.read() data = list(map(int, inp.split())) n = data[0] m = data[n + 1] a = data[1:n + 1] for x in data[n + 2:]: print(binary_search(a, x), end=' ')
# Uses python3 import sys def pisano(m): previous = 0 current = 1 i = 0 while True: previous, current = current, (previous + current) % m i += 1 if previous == 0: if current == 1: return i def fib_mod(n, m): n = n % pisano(m) previous = 0 current = 1 if n < 2: return n else: for i in range(2, n + 1): previous, current = current, (previous + current) % m return current def fibonacci_sum(c): if c <= 1: return c return (fib_mod(c + 2, 10) - 1) % 10 def fibonacci_partial_sum(j, k): if j == 0: return fibonacci_sum(k) elif j == k: return fib_mod(j, 10) else: return (fibonacci_sum(k) - fibonacci_sum(j - 1)) % 10 if __name__ == '__main__': inp = sys.stdin.read() x, y = map(int, inp.split()) print(fibonacci_partial_sum(x, y))
class DynamicArray: def __init__(self, capacity=0): self.count = 0 self.capacity = capacity self.storage = [None] * self.capacity def insert(self, index, value): if index >= self.count: return ("Index out of bound!")
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: ''' use 2 pointer to find the answer in O(n^2) ''' res = [] nums.sort() lenth = len(nums) # if lenth < 3, it's impossible to find the answer if lenth<3: return [] # find the target and do 2 pointers for i in range(lenth-2): left = i+1 right = lenth-1 while(left < right): # if left + right < target, we have to let left bigger if nums[left]+nums[right] < -1*nums[i]: left+=1 while left < right and (nums[left] == nums[left-1]): left+=1 # if left + right > target, we have to let right smaller elif nums[left]+nums[right] > -1*nums[i]: right-=1 while right>left and(nums[right] == nums[right+1]): right-=1 # find answer else: res.append([nums[i],nums[left],nums[right]]) left += 1 while left < right and (nums[left] == nums[left-1]): left+=1 right -= 1 while right>left and(nums[right] == nums[right+1]): right-=1 #use set to avoid redundancy res = list(set(tuple(sorted(sub)) for sub in res)) return res
VALUE = 0 NEXT = 1 PREV = 2 def add_to_back_2(value, head, tail): #1 item = [value, None] if head is None: head = item else: tail[NEXT] = item tail = item return head, tail def add_to_the_front(value, head, tail): #2 item = [value, None] if head is None: head = tail = item else: item[NEXT] = head head = item return head, tail def print_elements_one_by_one(head): #3 while head: print(head[VALUE], end=' ') head = head[NEXT] def get_an_element_by_index(index, head): #4 i = 0 while i < index and head: head = head[NEXT] i += 1 if head is None or index < 0: return None else: return head[VALUE] def remove_an_element_from_the_end(head, tail): #5 if head and head[NEXT]: true_head = head while head[NEXT][NEXT]: head = head[NEXT] head[NEXT] = None tail = head return true_head, tail else: return None, None def remove_an_element_from_the_front(head, tail): #6 if head and head[NEXT]: head = head[NEXT] tail = head while tail[NEXT]: tail = tail[NEXT] return head, tail else: return None, None def search_for_the_value(value, head): #7 i = 0 while head and head[VALUE] != value: head = head[NEXT] i += 1 if head is None: return None else: return i head = tail = None head, tail = add_to_back_2(10, head, tail) head, tail = add_to_back_2(20, head, tail) head, tail = add_to_back_2(30, head, tail) # head, tail = add_to_the_front(10, head, tail) # head, tail = add_to_the_front(20, head, tail) # head, tail = add_to_the_front(30, head, tail) # print_elements_one_by_one(head) # print(get_an_element_by_index(2, head)) # head, tail = remove_an_element_from_the_end(head, tail) # head, tail = remove_an_element_from_the_front(head, tail) # print(search_for_the_value(20, head)) print(head, tail)
""" -------------------------------------------------------- 1. Conditionals -------------------------------------------------------- a. if: elif: else: b. while condition: c. break: d. continue: e. exit() f. for i in range(stop) // default start = 0, step = 1 for i in range(start,stop) for i in range(start,stop,step) """ # Example 1: if: elif: else: print ('1. Learning if: elif: else') name = 'Nitya' sisName = 'Nikita' if name == 'Nitya': print('correct') if sisName == 'Nikita': print('correctSis') else: print('incorrectSis') elif name == 'Usha': print('incorrect') else: print('None') # Example 2: while condition: print ('\n2. Learning while condition') age = 15 while age < 20: print(age) age += 1 # Infinite While loop # while True: # print(5) # Example 3: break: print ('\n3. Learning break statement') age2 = 15 while True: print(age2) age2 += 1 if age2 == 20: break print('Age is finally 20') # Example 4: continue: print ('\n4. Learning continue statement') age3 = 15 while True: if age3 == 16: age3 += 1 continue print(age3) age3 += 1 if age3 == 20: break print('Age is finally 20') # Example 5: sys.exit() from sys import * while True: print('Name? (Hint: Nikita') name = input() if name == 'Nikita': print('correct') exit() else: print('Retry') # Example 6: for: # For loops basically generate a list [] -> [start, stop -1] # eg. range (10) -> [0,1,2,3,4,5,6,7,8,9] # eg. range (10,11) -> [10] # eg. range (10,10) -> [] # eg. range (10,-10) -> [] // cannot start with 10 and be < -10. print ('\n5. Learning for loop') print ('print 0-9') for i in range(10): print(i) print ('sum of 0-100') sum = 0 for i in range(101): sum += i print(sum) print ('sum of 0-100 using while loop') sum1 = 0 i1 = 0 while i1 < 101: sum1 += i1 i1 += 1 print(sum1) print ('print 10-19') for j in range(10,20): print(j) print ('print 10- -18 in steps of 2') for k in range(10, -20, -2): print(k) print ('print 10-10') for k1 in range(10, 10): print(k1) print ('print 10- -10') for k2 in range(10, -10): print(k2)
################################################################# # Diagrama de Gantt Básico para Programación de la Producción # # Autor: Rodrigo Maranzana # # Contacto: https://www.linkedin.com/in/rodrigo-maranzana # # Fecha: Octubre 2020 # ################################################################# import matplotlib.pyplot as plt import numpy as np import random def crear_gantt(maquinas, ht): # Parámetros: hbar = 10 tticks = 10 nmaq = len(maquinas) # Creación de los objetos del plot: fig, gantt = plt.subplots() # Diccionario con parámetros: diagrama = { "fig": fig, "ax": gantt, "hbar": hbar, "tticks": tticks, "maquinas": maquinas, "ht": ht } # Etiquetas de los ejes: gantt.set_xlabel("Tiempo") gantt.set_ylabel("Máquinas") # Límites de los ejes: gantt.set_xlim(0, ht) gantt.set_ylim(0, nmaq*hbar) # Divisiones del eje de tiempo: gantt.set_xticks(range(0, ht, 1), minor=True) gantt.grid(True, axis='x', which='both') # Divisiones del eje de máquinas: gantt.set_yticks(range(hbar, nmaq*hbar, hbar), minor=True) gantt.grid(True, axis='y', which='minor') # Etiquetas de máquinas: gantt.set_yticks(np.arange(hbar/2, hbar*nmaq - hbar/2 + hbar, hbar)) gantt.set_yticklabels(maquinas) return diagrama # Función para armar tareas: def agregar_tarea(diagrama, t0, d, maq, nombre, color=None): maquinas = diagrama["maquinas"] hbar = diagrama["hbar"] gantt = diagrama["ax"] ht = diagrama["ht"] # Chequeos: assert t0 + d <= ht, "La tarea debe ser menor al horizonte temporal." assert t0 >= 0, "El t0 no puede ser negativo." assert d > 0, "La duración d debe ser positiva." # Color: if color == None: r = random.random() g = random.random() b = random.random() color = (r, g, b) # Índice de la máquina: imaq = maquinas.index(maq) # Posición de la barra: gantt.broken_barh([(t0, d)], (hbar*imaq, hbar), facecolors=(color)) # Posición del texto: gantt.text(x=(t0 + d/2), y=(hbar*imaq + hbar/2), s=f"{nombre} ({d})", va='center', ha='center', color='white') def mostrar(): plt.show()
class Card(object): def __init__(self, color, number = 0): self._color = color self._number = number def __repr__(self): return (self._color, self._number) def __str__(self): return self._color + ":" + str(self._number) def __cmp__(self, other): '''Comparison is first made to the color and then to the number of the card''' if self.color() < other.color(): return -1 elif self.color() == other.color(): if self.number() < other.number(): return -1 elif self.number() == other.number(): return 0 else: return 1 else: return 1 def color(self): return self._color def number(self): return self._number
import logging logging.basicConfig(format='%(asctime)s %(message)s',filename='4.log',level=logging.DEBUG) try: n=int(raw_input("Enter a number:")) logging.info("Number accepted from user") n=str(n) sum=0 for i in n: sum=sum+int(i) logging.info("sum of digits is calculated") print "The sum of digits is: " + str(sum) logging.info("Printed the sum") except ValueError: print "Only numeric digits!" logging.info("Exception : User entered a wrong value")
def countNegatives(grid): List = list() ans = 0 for i in grid: List += i for i in List: if i < 0: ans += 1 else: ans += 0 return ans grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] print(countNegatives(grid))
# List slicing in Python my_list = ['p','r','o','g','r','a','m','i','z'] # elements 3rd to 5th print(my_list[2:5]) # elements beginning to 4th print(my_list[:-5]) # elements 6th to end print(my_list[5:]) # elements beginning to end print(my_list[:]) distance = [1,2,3,4] start = 0 destination = 1 print(distance[start:destination])
paragraph = ["i", "love", "leetcode", "i", "love", "coding"] def wordcounter(paragraph): ans = [] tracker = {} for word in paragraph: if word not in tracker: tracker[word] = 1 else: tracker[word] = int(tracker.get(word)) + 1 for keyValue in tracker: ans.append([keyValue,tracker.get(keyValue)]) ans.sort(key = lambda x : (x[1],x[0]), reverse=True) print(ans) wordcounter(paragraph)
def PhoneLetterConbination(input): mapping = { '1' : 'abc', '2' : 'def', '3' : 'ghi', '4' : 'jkl', '5' : 'mno', '6' : 'pqr', '7' : 'stu', '8' : 'wxyz', '9' : '', '0' : '' } answer_combine = [' '] for digit in input: current_combine = list() for letter in mapping[digit]: for c1 in answer_combine: current_combine.append(c1 + letter) answer_combine.append(current_combine) return answer_combine print(PhoneLetterConbination('23'))
nums = [2,7,11,15] target = 9 seen = dict() for (index,key) in (enumerate(nums)): ##print(index,key) remaining = target - nums[index] if remaining not in seen: seen[key] = index else: print("1") print(seen[remaining],index)
largest = None smallest = None while True: num = input("Enter a number: ") if num == "done" : break # if "done" is introduced the program end. try: var1 = int(num) except: print("Invalid input") continue if smallest is None: smallest = var1 elif var1 < smallest: smallest = var1 if largest is None: largest = var1 elif var1 > largest: largest = var1 print("Maximum is", largest) print("Minimum is", smallest)
#python program to find the largest print('python program to find the largest: ') a=float(input("enter first number: ")) b=float(input("enter second number: ")) c=float(input("enter third number: ")) if (a>b) and (a>c): largest=a elif (b>a) and (b>c): largest=b else: largest=c print("The largest number is : ",largest) #Checking prime in python print("Checking prime in python::::") num=int(input("enter a number: ")) #prime number are greater than 1 if num>1: #check for factor for i in range(2,num): if (num%i)==0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") else: print(num,"si not a prime number")
#Temperature convertor def displayMenu(): print 'Temperature converter menu'; print '(1) Convert Fahrenheit to Celsius'; print '(2) Convert Celsius to Fahrenheit'; print '(3) Convert Celsius to Kelvin'; print '(4) Convert Kelvin to Celsius'; print '(5) Convert Fahrenheit to Kelvin'; print '(6) Convert Kelvin to Fahrenheit'; def select(): displayMenu(); choice = input('Enter your choice number:') if(choice == 1): F2C(); elif(choice == 2): C2F(); #elif(choice == 3): C2K(); #elif(choice == 4): K2C(); #elif(choice == 5): F2K(); # elif(choice == 6): K2F(); else: print"invalid choice:",choice; def C2F(): Celsius = input('Enter degrees in Celsius:'); Fahrenheit = (9.0/5.0)*Celsius+32; print Celsius,'Celsius=',Fahrenheit,'Fahrenheit'; def F2C(): Fahrenheit = input('Enter degrees in Fahrenheit:'); Celsius = ((Fahrenheit-32.0)/9.0)*5.0; print Fahrenheit,'Fahrenheit=',Celsius,'Celsius';
def add(x,y): return (x+y) def sub(x,y): return (x-y) def mul(x,y): return (x*y) def div(x,y): if (y==0): print("Undefined") else: return (x/y) print add(5,3) print sub(5,3) print mul(5,3) print div(5,0) print div(6,3)
class Person: def __init__(self, name, surname, date_of_birth, address): self.name = name self.surname = surname self.date_of_birth = date_of_birth self.address = address def __str__(self): return self.name + " " + self.surname class Employee(Person): num_of_employees = 0 def __init__(self, name, surname, date_of_birth, address, company, position, years_employed, base_salary): super(Employee, self).__init__(name, surname, date_of_birth, address) self.company = company self.position = position self.years_employed = years_employed self.base_salary = base_salary self.num_of_employees += 1 def __str__(self): return class Freelancer(Person): def __init__(self, name, surname, date_of_birth, address, skills, reviews): super(Freelancer, self).__init__(name, surname, date_of_birth, address) self.skills = skills self.reviews = reviews def __str__(self): return
#Iterative statements #if we want to execute a group of statements multiple times then we should go for iterative statements # for loop if we want to execute some action for every element in the sequence(it may be string or collection) then we should go for iterative for loop s="no one love solder untill enemy is at the border" i=0 for x in s: print("the charcter present at",i,"index is:",x) i=i+1 for t in range(10): print("surya") for x in range(11): print(x) for x in range(21): if (x%2!=0): print(x) for x in range(10,0,-1): if (x%2!=0): print(x) #to print sum of numbers present inside list d=eval(input("Enter numbers:")) sum=0 for x in d: print("the sum is",sum+x) sum=sum+x #while loop if we want to execute a group of statements iteratively untill some condition false then we should go for while loop x=1 while x<=10: print(x) x=x+1 #to display sum of first n nummbers n=int(input("Enter number:")) sum=0 i=1 while i<=n: sum=sum+i i=i+1 print("sum of",n,"numbers is:",sum)
#Exercise 9 -- Printing, Printing, Printing PTHW #Here's some new strange stuff, remember type it exactly days = "Mon Tue Wed Thu Fri Sat Sun" months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" #Affichage basique print("Here are the days: ", days) print("Here are the months: ", months) #Affichage sur plusieurs ligne sans mettre le \n print(""" There's something going on here. With the three double-quotes. We'll able to type as much as we like. Even 4 lines if we want, or 5 or 6. """)
#Exercise 16 -- Reading and Writting Files #Importation de argv from sys import argv script, filename = argv print(f"We're going to erase {filename}.") print("If you don't want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN.") #Attente pour poursuivre ou pas input('?') #ouverture du fichier target = open(filename, 'w') #Truncating print("Truncating the file. Goodbye!") target.truncate() #Receuil des phrases à écrire print("Now I'm going to ask you fo three lines.") line1 = input("line 1: ") line2 = input("line2: ") line3 = input("line 3: ") print("I'm going to write these to the file {}".format(filename)) #Ecriture de ces phrases dans le fichier target.write(line1+'\n'+line2+'\n'+line3+'\n') #Fermeture du fichier print("We closed the file.") target.close() #Lecture du fichier print(""" Do you want to read the file? Hit CTRL-C(^C) if you don't. Hit ENTER if you do want that.""") input('?') #Ouverture et affichage du fichier print("We're going to open and read the file {}".format(filename)) target = open(filename) print("Here's the content of the file:") print(target.read()) #Fermeture du fichier target.close() print("And finally, the file had been closed.")
list_from_user_str = input("Введите нескольких слов, разделённых пробелами: ").split() count = 1 # без range() для разнообразия, зато тернарный оператор! for i in list_from_user_str: print(count, i) if len(i) <= 10 else print(count, i[:10]) count += 1
months_list = ["январь", "февраль", "март", "апрель", "май", "июнь", "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"] months_dict = {1: "январь", 2: "февраль", 3: "март", 4: "апрель", 5: "май", 6: "июнь", 7: "июль", 8: "август", 9: "сентябрь", 10: "октябрь", 11: "ноябрь", 12: "декабрь" } user_month = int(input("Введите месяц в виде целого числа от 1 до 12: ")) print(months_list[user_month - 1]) print(months_dict[user_month])
n = input("Введите целое положительное число: ") my_sum = int(n) + int(n * 2) + int(n * 3) #print(my_sum)
specs = {"название": None, "цена": None, "количество": None, "eд": None} # тут мог быть список, но хотелось потренить словари) goods = [] for i in range(int(input("Введите целое положительное количество товаров: "))): item_num = i + 1 item_specs = {} for spec in specs: item_specs[spec] = input(f"{spec} товара: ") goods.append((item_num, item_specs)) print(goods) analytics = {} for spec in specs: analytics[spec] = [] for i in range(len(goods)): if goods[i][1][spec] not in analytics[spec]: # наверное, не очень правильно, что здесь в индексе циферка, а не переменная analytics[spec].append(goods[i][1][spec]) # и здесь) print(analytics)
profit = int(input("Напишите, пожалуйста, доход вашей фирмы в рублях без учёта копеек (не бойтесь, я программист!): ")) costs = int(input("Спасибо! Теперь в той же форме напишите издержки вашей фирмы: ")) real_profit = profit - costs if real_profit > 0: print("Вы молодец!") some_complicated_profit = real_profit / profit print("Компьютер только что вычислил рентабельность вашей выручки!") staff = int(input("Теперь напишите целое положительное количество сотрудников вашей фирмы: ")) each_profit = real_profit / staff print("Спасибо! До свидания! :)") else: print("Спасибо! До свидания! Идите собирать бутылки :(")
# Initialize an array containing the robot's location belief function. p = [0.2, 0.2, 0.2, 0.2, 0.2] world = ['green', 'red', 'red', 'green', 'green'] measurements = ['red', 'red'] motions = [1, 1] # Sensor accuracy pHit = 0.6 pMiss = 0.2 # Movement accuracy pExact = 0.8 pUndershoot = 0.1 pOvershoot = 0.1 def sense(belief_function, measurement): """ Produce a belief function based on a measurement. :type belief_function: list[int] :type measurement: str :rtype : list[int] """ q = [] for i in range(len(belief_function)): hit = (measurement == world[i]) q.append(belief_function[i] * (hit * pHit + (1 - hit) * pMiss)) s = sum(q) q = [i / s for i in q] return q def move(belief_function, movement): """ Produce a belief function based on a movement. :type belief_function: list[int] :type movement: int :rtype : list[int] """ q = [] for i in range(len(belief_function)): q.append(belief_function[i - movement] * pExact + belief_function[(i - (movement + 1)) % len(belief_function)] * pOvershoot + belief_function[(i - (movement - 1)) % len(belief_function)] * pUndershoot) return q # Move robot for k in range(len(measurements)): p = sense(p, measurements[k]) p = move(p, motions[k]) print p
""" --- Day 5: Binary Boarding --- First puzzle answer: 828 Second puzzle answer: """ def puzzle2(): """ puzzle 2 """ with open("input.txt") as file: seat_strings = file.read().split("\n") list_ids = [] for seat_str in seat_strings: row, seat = find_seat_id(seat_str) if 0 < row < 127: list_ids.append(row * 8 + seat) list_ids.sort() counter = 1 for num in range(list_ids[1], list_ids[-2]): if num != list_ids[counter]: return num counter += 1 def find_seat_id(seat_string): """ puzzle 1 function for figuring out the seat location based on binary seat identifier keyword --- seat: the string representation of seat location, consisting of F's, B's, L's, and R's' the 1st 7 characters are the representation of the row return value --- row, seat """ steps = [64, 32, 16, 8, 4, 2, 1, 4, 2, 1] row_range = [1, 128] seat_range = [1, 8] i = 0 #calculate the row for letter in seat_string: if letter == "F": row_range[1] -= steps[i] elif letter == "B": row_range[0] += steps[i] elif letter == "L": seat_range[1] -= steps[i] elif letter == "R": seat_range[0] += steps[i] i += 1 return row_range[0] - 1, seat_range[0] - 1 def puzzle1(): with open("input.txt") as file: seat_strings = file.read().split("\n") highest_seat_id = 0 for seat in seat_strings: row, seat = find_seat_id(seat) seat_num = row * 8 + seat if seat_num > highest_seat_id: highest_seat_id = seat_num return highest_seat_id if __name__ == "__main__": high_seat = puzzle1() print(high_seat) my_seat = puzzle2() print(my_seat)
import numpy as np from .arrays import GridBasedArrayDesign from ..utils.math import unique_rows def compute_location_differences(locations): r"""Computes all locations differences, including duplicates. Suppose ``locations`` is :math:`m \times d`, then the result will be an :math:`m^2 \times d` matrix such that ``locations[i] - locations[j]`` is stored in the ``(i + j * m)``-th row of the resulting matrix. For instance, if ``locations`` is ``[[0, 1], [1, 3]]``, then the output will be ``[[0, 0], [1, 2], [-1, -2], [0, 0]]``. Args: locations (~numpy.ndarray): An m x d array of sensor locations. """ m, d = locations.shape # Use broadcasting to compute pairwise differences. D = locations.reshape((1, m, d)) - locations.reshape((m, 1, d)) return D.reshape((-1, d)) def compute_unique_location_differences(locations, atol=0.0, rtol=1e-8): """Computes all unique locations differences. Unlike :meth:`compute_location_differences`, duplicates within the specified tolerance are removed. Args: locations: An m x d array of sensor locations. """ return unique_rows(compute_location_differences(locations), atol, rtol) class WeightFunction1D: """Creates a 1D weight function. Args: array (~doatools.model.arrays.ArrayDesign): Array design. References: [1] P. Pal and P. P. Vaidyanathan, "Nested arrays: A novel approach to array processing with enhanced degrees of freedom," IEEE Transactions on Signal Processing, vol. 58, no. 8, pp. 4167-4181, Aug. 2010. """ def __init__(self, array): if array.ndim != 1 or not isinstance(array, GridBasedArrayDesign): raise ValueError('Expecting a 1D grid-based array.') self._m = array.size self._mv = None self._build_map(array) def __call__(self, diff): """Evaluates the weight function at the given difference.""" return self.weight_of(diff) def __len__(self): """Retrieves the number of unique differences.""" return len(self._index_map) def differences(self): """Retrieves a 1D array of unique differences in ascending order. The ordering of elements returned by :meth:`differences` and the ordering of elements returned by :meth:`weights` are the same. """ return self._differences.copy() def weights(self): """Retrieves a 1D array of weights. The ordering of elements returned by :meth:`differences` and the ordering of elements returned by :meth:`weights` are the same. """ return np.array([len(self._index_map[x]) for x in self._differences]) def weight_of(self, diff): """Evaluates the weight function at the given difference.""" if diff in self._index_map: return len(self._index_map[diff]) else: return 0 def indices_of(self, diff): """Retrieves the list of indices of elements in the vectorized difference matrix that correspond to the given difference. If the given difference does not exist, an empty list will be returned. Args: diff (int): Difference. """ if diff in self._index_map: return self._index_map[diff][:] else: return [] def get_central_ula_size(self, exclude_negative_part=False): r"""Gets the size of the central ULA in the difference coarray. Args: exclude_negative_part (bool): Set to ``True`` to exclude the virtual array elements corresponding to negative differences. The central ULA part is symmetric with respect to the origin and can be represented with .. math:: \lbrack -M_\mathrm{v}+1, \ldots, -1, 0, 1, \ldots, M_\mathrm{v} \rbrack d_0 After excluding the negative part, the remaining array elements are given by .. math:: \lbrack 0, 1, \ldots, M_\mathrm{v} \rbrack d_0 Default value is ``False``. """ if self._mv is None: mv = 0 while mv in self._index_map: mv += 1 self._mv = mv return self._mv if exclude_negative_part else self._mv * 2 - 1 def get_coarray_selection_matrix(self, exclude_negative_part=False): r"""Gets the coarray selection matrix. Let the central ULA size be :math:`2M_{\mathrm{v}} - 1` and the original array size be :math:`M`. :math:`\mathbf{F}` is defined as an :math:`(2M_\mathrm{v} - 1) \times M^2` matrix that transforms the vectorized sample covariance matrix, :math:`\mathrm{vec}(\mathbf{R})`, to the virtual observation vector of the central ULA, :math:`\mathbf{z}`, via redundancy averaging: .. math:: \mathbf{z} = \mathbf{F} \mathrm{vec}(\mathbf{R}). Args: exclude_negative_part: If set to ``True``, only the nonnegative part of the central ULA (i.e., :math:`\lbrack 0, 1, \ldots, M_\mathrm{v} - 1\rbrack`) will be considered, and the resulting :math:`\mathbf{F}` will be :math:`M_\mathrm{v} \times M^2`. Default value is ``False``. Returns: The coarray selection matrix. References: [1] M. Wang and A. Nehorai, "Coarrays, MUSIC, and the Cramér-Rao Bound," IEEE Transactions on Signal Processing, vol. 65, no. 4, pp. 933-946, Feb. 2017. """ m_v = self.get_central_ula_size(exclude_negative_part=True) if exclude_negative_part: m_ula = m_v diff_range = range(0, m_v) else: m_ula = 2 * m_v - 1 diff_range = range(-m_v + 1, m_v) F = np.zeros((m_ula, self._m**2)) for i, diff in enumerate(diff_range): F[i, self.indices_of(diff)] = 1.0 / self.weight_of(diff) return F def _build_map(self, array): # Maps difference -> indices in the vectorized difference matrix index_map = {} diffs = compute_location_differences(array.element_indices).flatten() for i, diff in enumerate(diffs): if diff in index_map: index_map[diff].append(i) else: index_map[diff] = [i] # Collect all unique differences and sort them differences = np.fromiter(index_map.keys(), dtype=np.int_, count=len(index_map)) differences.sort() self._index_map = index_map self._differences = differences
""" For part III of this assignment, you'll implement a model from scratch has a vague relationship to the Weiss et al. ambiguous-motion model. The model will try to infer the direction of motion from some observations. I'll assume that a rigid motion is being observed involving an object that has two distictinctive visual features. The figure below shows a snapshot of the object at two nearby points in time. The distinctive features are the red triangle and blue square. Let's call them R and B for short. Because the features are distinctive, determining the correspondence between features at two snapshots in time is straightforward, and the velocity vector can be estimated. Assume that these measurements are noisy however, such that the x and y components of the velocity are each corrupted by independent, mean zero Gaussian noise with standard deviation σ. Thus the observation consists of four real valued numbers: Rx, Ry, Bx, and By -- respectively, the red element x and y velocities, and the blue element x and y velocities. The goal of the model is to infer the direction of motion. To simplify, let's assume there are only four directions: up, down, left, and right. Further, the motions will all be one unit step. Thus, if the motion is to the right, then noise-free observations would be: Rx=1, Ry=0, Bx=1, By=0. If the motion is down, then the noise-free observations would be: Rx=0, Ry=-1, Bx=0, By=-1. Formally, the model must compute P(Direction | Rx, Ry, Bx, By). """ from scipy.stats import norm DIRECTIONS = ['up', 'right', 'down', 'left'] def get_prior(): """ Assuming no noise in the direction Assuming the directions are up, down, left and right Prior = 1/4 :return: {float} prior over direction """ prior = 0.25 return prior def get_likelihood(direction, obs, likelihood): """ Get P( velocity | direction) :return: P( velocity | direction) for both the shapes. """ return likelihood['x_{}'.format(direction)].pdf(obs['x_red']),\ likelihood['y_{}'.format(direction)].pdf(obs['y_red']), \ likelihood['x_{}'.format(direction)].pdf(obs['x_blue']), \ likelihood['y_{}'.format(direction)].pdf(obs['y_blue']) def init_likelihood(sig): gauss_zero = norm(0, sig) gauss_one = norm(1, sig) gauss_minus_one = norm(-1, sig) likelihood = dict() likelihood['x_up'] = gauss_zero likelihood['x_right'] = gauss_one likelihood['x_left'] = gauss_minus_one likelihood['x_down'] = gauss_zero likelihood['y_up'] = gauss_one likelihood['y_down'] = gauss_minus_one likelihood['y_left'] = gauss_zero likelihood['y_right'] = gauss_zero return likelihood def task1(sig, obs): prior = get_prior() velocity_given_dir = init_likelihood(sig) posterior = {} for direction in DIRECTIONS: likelihood_x_red, likelihood_y_red, likelihood_x_blue, likelihood_y_blue = get_likelihood(direction, obs, velocity_given_dir) posterior[direction] = likelihood_x_red * likelihood_y_red * likelihood_x_blue * likelihood_y_blue * prior norm_factor = sum(posterior.values()) posterior = {key: posterior[key] / norm_factor for key in DIRECTIONS} return max(posterior, key=posterior.get) if __name__ == "__main__": print(task1(1, {'x_red': 0.75, 'y_red': -0.6, 'x_blue': 1.4, 'y_blue': -0.2})) print(task1(5, {'x_red': 0.75, 'y_red': -0.6, 'x_blue': 1.4, 'y_blue': -0.2}))
#!/usr/bin/env python import re import thread import itertools import warnings import math def _is_number(s): if s in ['0', '1', '2', '1000']: return True try: float(s) return True except ValueError: return False def _starts_with_number(s): return s[0] in ['-', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] class Bounds(object): """ :class:`Bounds` holds description of reactions constraints :param lb: Minimal amount of of flux that can go through a reaction (Lower bound). Negative numbers denote reverse direction. :param ub: Maximal amount of of flux that can go through a reaction (Upper bound). Negative numbers denote reverse direction. :return: :class:`Bounds` """ def __init__(self, lb=float("-inf"), ub=float("inf")): self.__assert_valid(lb, ub) self.__lb = lb self.__ub = ub def copy(self): """ Create a deep copy of current object :rtype: :class:`Bounds` """ return Bounds(self.__lb, self.__ub) @property def lb_is_finite(self): """ Returns inf False if lower bound is -infinity or +infinity """ return self.__lb != self.inf() and self.__lb != -self.inf() @property def lb(self): """ Minimal amount of of flux that can go through a reaction (Lower bound). Negative numbers denote reverse direction. """ return self.__lb @lb.setter def lb(self, lb): self.__assert_valid(lb, self.ub) self.__lb = float(lb) @property def ub_is_finite(self): """ Returns inf False if upper bound is -infinity or +infinity """ return self.__ub != self.inf() and self.__ub != -self.inf() @property def ub(self): """ Maximal amount of of flux that can go through a reaction (Upper bound). Negative numbers denote reverse direction. """ return self.__ub @ub.setter def ub(self, value): self.__assert_valid(self.lb, value) self.__ub = float(value) @property def direction(self): """ Suggested reaction direction. If lower bound is negative the reaction is suggested to be reversible. Otherwise irreversibility is implied. This is only a suggestion to :class:`Reaction` class and this suggestion can be broken by enabling reaction reversibility through :attr:`Reaction.direction` :rtype: :class:`Direction` """ return Direction.forward() if self.lb >= 0 else Direction.reversible() @staticmethod def inf(): """ Returns infinity :return: :class:`float` """ return float("Inf") def __assert_valid(self, lb, ub): if not isinstance(ub, (int, float)): raise TypeError("Upper bound is not a number: {0}".format(type(ub))) if not isinstance(lb, (int, float)): raise TypeError("Lower bound is not a number: {0}".format(type(lb))) if lb > ub: raise ValueError("Lower bound is greater than upper bound ({0} > {1})".format(lb, ub)) def __eq__(self, other): return type(self) == type(other) and \ self.lb == other.lb and \ self.ub == other.ub def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "[{0}, {1}]".format(self.lb, self.ub) class Metabolite(object): """ :class:`Metabolite` holds information about metabolite. Currently only supported information is metabolite name and whether metabolite satisfies boundary condition (imported/exported) :param name: Metabolite name. Metabolite name should be a non-empty string. :param boundary: Boundary condition (imported/exported - True; otherwise - false) :return: :class:`Metabolite` """ def __init__(self, name, boundary=False): self.__assert_name(name) self.__assert_boundary(boundary) self.__name = name self.__boundary = boundary self.__order_boundary = 0 def copy(self): """ Create a deep copy of current object :rtype: :class:`Metabolite` """ m = Metabolite(self.__name, self.__boundary) m.order_boundary = self.__order_boundary return m @property def name(self): """ Metabolite name. Metabolite name should be a non-empty string. """ return self.__name @name.setter def name(self, name): self.__assert_name(name) self.__name = name @property def boundary(self): """ Boundary condition (imported/exported - True; otherwise - false) """ return self.__boundary @boundary.setter def boundary(self, boundary): self.__assert_boundary(boundary) self.__boundary = boundary @property def order_boundary(self): """ Priority of displaying this metabolite. Metabolites with higher priority (lower numbers) are displayed earlier in "-External Metabolites" section """ return self.__order_boundary @order_boundary.setter def order_boundary(self, order_boundary): if not _is_number(order_boundary): raise TypeError("Display priority should be a number: {0}".format(type(order_boundary))) self.__order_boundary = order_boundary def __eq__(self, other): return type(self) == type(other) and \ self.name == other.name and \ self.boundary == other.boundary def __ne__(self, other): return not self.__eq__(other) def __assert_name(self, name): if not isinstance(name, str): raise TypeError("Metabolite name is not a string: {0}".format(type(name))) if not len(name): raise ValueError("Metabolite name is empty string") if name == "": warnings.warn("Metabolite '{0}' contains spaces".format(name), UserWarning) # TODO: Do we need this? if _starts_with_number(name) and _is_number(name): warnings.warn("Metabolite name is a number: '{0}'".format(name), UserWarning) def __assert_boundary(self, boundary): if not isinstance(boundary, bool): raise TypeError("Metabolite boundary condition is not a boolean: {0}".format(type(boundary))) def __rmul__(self, other): if isinstance(other, (float, int)): return ReactionMember(metabolite=self, coefficient=other) raise TypeError("Can only multiply by numeric coefficient") def __repr__(self): b = "*" if self.boundary else "" return "{0}{1}".format(self.name, b) class ReactionMember(object): """ :class:`Bounds` is a wrapper for :class:`Metabolite` object when used in reaction reactants or products. It contains reference to the metabolite itself and to it's coefficient in the reaction. :param metabolite: Reference to :class:`Metabolite` object :param coefficient: Multiplier associated with metabolite :return: :class:`ReactionMember` """ def __init__(self, metabolite, coefficient=1): self.__assert_metabolite(metabolite) self.__assert_coefficient(coefficient) self.__metabolite = metabolite self.__coefficient = float(coefficient) def copy(self): """ Create a deep copy of current object :rtype: :class:`ReactionMember` """ rm = ReactionMember(self.__metabolite.copy(), self.__coefficient) return rm @property def metabolite(self): """ Reference to metabolite :rtype: :class:`Metabolite` """ return self.__metabolite @metabolite.setter def metabolite(self, metabolite): self.__assert_metabolite(metabolite) self.__metabolite = metabolite @property def coefficient(self): """ Multiplier associated with metabolite """ return self.__coefficient @coefficient.setter def coefficient(self, coefficient): self.__assert_coefficient(coefficient) self.__coefficient = float(coefficient) def __add__(self, other): if isinstance(other, ReactionMember): return ReactionMemberList([self, other]) elif isinstance(other, ReactionMemberList): rml = ReactionMemberList(other) rml.insert(0, self) return rml else: raise TypeError("Can only join ReactionMember objects") def __repr__(self): return "{0:.5g} {1}".format(self.coefficient, self.metabolite) def __eq__(self, other): return type(self) == type(other) and \ self.metabolite == other.metabolite and \ self.coefficient == other.coefficient def __ne__(self, other): return not self.__eq__(other) def __assert_metabolite(self, metabolite): if not isinstance(metabolite, Metabolite): raise TypeError("Reaction member is not of type <Metabolite>: {0}".format(type(metabolite))) def __assert_coefficient(self, coefficient): if not isinstance(coefficient, (int, float)): raise TypeError("Reaction member coefficient is not a number: {0}".format(type(coefficient))) class Direction(object): """ Describe reaction directionality. Don't use this class directly! Use factory constructors :meth:`Direction.forward` and :meth:`Direction.reversible` :param type: f - Irreversible (**f** orward); r - Reversible (**r** eversible) :return: :class:`Direction` """ __lockObj = thread.allocate_lock() __forward = None __reversible = None def __init__(self, type): if not type in ["f", "r"]: raise ValueError("Invalid reaction direction type. Allowed values are: {0}".format(', '.join(type))) self.__type = type def copy(self): """ Create a deep copy of current object :rtype: :class:`Direction` """ return Direction(self.__type) @staticmethod def forward(): """ Returns irreversible directionality descriptor singleton of type :class:`Direction` :return: :class:`Direction` """ Direction.__lockObj.acquire() try: if Direction.__forward is None: Direction.__forward = Direction("f") finally: Direction.__lockObj.release() return Direction.__forward @staticmethod def reversible(): """ Returns reversible directionality descriptor singleton of type :class:`Direction` :return: :class:`Direction` """ Direction.__lockObj.acquire() try: if Direction.__reversible is None: Direction.__reversible = Direction("r") finally: Direction.__lockObj.release() return Direction.__reversible def __eq__(self, other): return type(self) == type(other) and self.__type == other.__type def __ne__(self, other): return not self.__eq__(other) def __repr__(self): if self.__type == "f": return "->" if self.__type == "r": return "<->" class ReactionMemberList(list): """ :class:`ReactionMemberList` is a list of :class:`ReactionMember` instances. :class:`ReactionMemberList` inherits from :class:`list` all the usual functions to manage a list """ def copy(self): """ Create a deep copy of current object :rtype: :class:`ReactionMemberList` """ rml = ReactionMemberList() rml.extend(rm.copy() for rm in self) return rml def find_member(self, name): """ Find metabolite by name in the list :rtype: :class:`ReactionMember` """ for mb in self: if mb.metabolite.name == name: return mb return None def __radd__(self, other): if isinstance(other, ReactionMember): rml = ReactionMemberList() rml.append(other) rml.extend(self) return rml return super(ReactionMemberList, self).__radd__(other) def __add__(self, other): if isinstance(other, ReactionMember): rml = ReactionMemberList() rml.extend(self) rml.append(other) return rml return super(ReactionMemberList, self).__add__(other) def __iadd__(self, other): if isinstance(other, ReactionMember): self.append(other) return self elif isinstance(other, ReactionMemberList): self.extend(other) return self return super(ReactionMemberList, self).__iadd__(other) def __repr__(self): return " + ".join(m.__repr__() for m in self) class Reaction(object): """ :class:`Reaction` class holds information about reaction including reaction name, members, directionality and constraints :param name: Reaction name. Reaction name should be non-empty string :param reactants: Reaction left-hand-side. Object of class :class:`ReactionMemberList`. :param products: Reaction right-hand-side. Object of class :class:`ReactionMemberList`. :param direction: Reaction direction. Object of class :class:`Direction`. :param bounds: Reaction constraints. Object of class :class:`Bounds`. :rtype: :class:`Reaction` """ def __init__(self, name, reactants=ReactionMemberList(), products=ReactionMemberList(), direction=None, bounds=None): if bounds is None and direction is None: direction = Direction.reversible() if direction is None and bounds is not None: direction = bounds.direction if bounds is None and direction is not None: bounds = Bounds(-float('inf'), float('inf')) if direction == Direction.reversible() else Bounds(0, float('inf')) self.__assert_name(name) self.__assert_members(reactants) self.__assert_members(products) self.__assert_direction(direction) self.__assert_bounds(bounds) self.__name = name self.__direction = direction self.__bounds = bounds if isinstance(reactants, ReactionMember): self.__reactants = ReactionMemberList([reactants]) else: self.__reactants = reactants if isinstance(products, ReactionMember): self.__products = ReactionMemberList([products]) else: self.__products = products def copy(self): """ Create a deep copy of current object :rtype: :class:`Reaction` """ reactants = self.__reactants.copy() products = self.__products.copy() bounds = self.__bounds.copy() r = Reaction(self.name, reactants, products, direction=self.__direction.copy(), bounds=bounds) return r @property def name(self): """ Reaction name """ return self.__name @name.setter def name(self, name): self.__assert_name(name) self.__name = name @property def reactants(self): """ Reactants :rtype: :class:`ReactionMemberList` """ return self.__reactants @reactants.setter def reactants(self, reactants): self.__assert_members(reactants) if isinstance(reactants, ReactionMember): self.__reactants = ReactionMemberList([reactants]) else: self.__reactants = reactants @property def products(self): """ Products :rtype: :class:`ReactionMemberList` """ return self.__products @products.setter def products(self, products): self.__assert_members(products) if isinstance(products, ReactionMember): self.__products = ReactionMemberList([products]) else: self.__products = products @property def direction(self): """ Reaction direction :rtype: :class:`Direction` """ return self.__direction @direction.setter def direction(self, direction): self.__assert_direction(direction) self.__direction = direction @property def bounds(self): """ Reaction constraints :rtype: :class:`Bounds` """ return self.__bounds @bounds.setter def bounds(self, bounds): self.__assert_bounds(bounds) self.__bounds = bounds def bounds_reset(self): """ Reset bounds to predefined default. For reversible reaction defaults bounds are **[-inf, +inf]**. For forward reactions it is **[0, +inf]** """ if self.direction == Direction.forward(): self.bounds = Bounds(0, Bounds.inf()) else: self.bounds = Bounds(-Bounds.inf(), Bounds.inf()) def find_effective_bounds(self): """ Find effective bounds. For example if reaction is described as irreversible but constraints are [-10, 10] the effective bounds would be [0, 10] :rtype: :class:`Bounds` """ lb = 0 if self.__direction == Direction.forward() and self.__bounds.lb < 0 else self.__bounds.lb ub = self.__bounds.ub return Bounds(lb, ub) def reverse(self): """ Reverse reactions. This functions change reactants and products places and inverses constraints so that reaction would go other way """ if self.direction != Direction.reversible(): raise RuntimeError("Reaction direction is not reversible. Only reversible reactions can be reversed") if self.bounds.lb > 0 and self.bounds.ub > 0: raise RuntimeError("Reaction effective direction is strictly forward and cannot be reversed") tmp = self.__products self.__products = self.__reactants self.__reactants = tmp self.__bounds = Bounds(-self.bounds.ub, -self.bounds.lb) def __assert_name(self, name): if not isinstance(name, str): raise TypeError("Reaction name is not a string: {0}".format(type(name))) if not len(name): raise ValueError("Reaction name is empty string") if name == "": warnings.warn("Reaction '{0}' contains spaces".format(name), UserWarning) # TODO: Do we need this? if _starts_with_number(name) and _is_number(name): warnings.warn("Reaction name is a number: '{0}'".format(name), UserWarning) def __assert_members(self, reactants): if not isinstance(reactants, (ReactionMemberList, ReactionMember)): raise TypeError("Reaction reactants is not of type ReactionMemberList or ReactionMember: {0}".format(type(reactants))) def __assert_direction(self, direction): if not isinstance(direction, Direction): raise TypeError("Reaction direction is not of type ReactionDirection: {0}".format(type(direction))) def __assert_bounds(self, bounds): if not isinstance(bounds, Bounds): raise TypeError("Reaction bounds is not of type bounds: {0}".format(type(bounds))) def __repr__(self): return "{name}{bnds}: {lhs} {dir} {rhs}".format(name=self.name, lhs=self.reactants, dir=self.direction, rhs=self.products, bnds=self.bounds) def __eq__(self, other): return type(self) == type(other) and \ self.name == other.name and \ self.reactants == other.reactants and \ self.products == other.products and \ self.bounds == other.bounds and \ self.direction == other.direction def __ne__(self, other): return not self.__eq__(other) class Operation(object): """ Object describing operation type. **Don't use this class directly! Instead use factory constructors:** * :meth:`Operation.addition` * :meth:`Operation.subtraction` * :meth:`Operation.multiplication` * :meth:`Operation.division` * :meth:`Operation.negation` (Unary operation) :param operation: String describing the operation (binary operations: ``+-/*``, unary operations: ``-``) :param is_unary: Describes what type of operation is created. Unary operations support only one argument, while binary support two. :return: :class:`Operation` """ __lockObj = thread.allocate_lock() __addition = [] __subtraction = [] __negation = [] __multiplication = [] __division = [] __unary_priority = ["-"] __binary_priority = ["*", "/", "+", "-"] def __init__(self, operation, is_unary): if not isinstance(is_unary, bool): raise TypeError("Parameter is_unary is not of type bool: {0}".format(type(is_unary))) if not is_unary and operation not in Operation.__binary_priority: raise ValueError("Invalid binary operation: {0}".format(operation)) if is_unary and operation not in Operation.__unary_priority: raise ValueError("Invalid unary operation: {0}".format(operation)) self.__is_unary = is_unary self.__operation = operation if is_unary: priority = Operation.__unary_priority.index(operation) else: priority = len(Operation.__unary_priority) priority += Operation.__binary_priority.index(operation) self.__priority = priority @staticmethod def __create_singleton(type, operation, instance): Operation.__lockObj.acquire() try: if not instance: instance.append(Operation(operation, type)) finally: Operation.__lockObj.release() return instance[0] @property def is_unary(self): """ Is operation unary. True - unary; otherwise False :return: :class:`bool` """ return self.__is_unary @property def symbol(self): """ Short description of operation * + Addition * - Subtraction * / Division * * Multiplication * - Negation :rtype: :class:`Operation` """ return self.__operation @property def priority(self): """ Operation priority. Operations with higher priority (lower numbers) are executed before lower priority operations :rtype: :class:`Operation` """ return self.__priority @staticmethod def addition(): """ Returns addition operation singleton :rtype: :class:`Operation` """ return Operation.__create_singleton(False, "+", Operation.__addition) @staticmethod def subtraction(): """ Returns subtraction operation singleton :rtype: :class:`Operation` """ return Operation.__create_singleton(False, "-", Operation.__subtraction) @staticmethod def multiplication(): """ Returns multiplication operation singleton :rtype: :class:`Operation` """ return Operation.__create_singleton(False, "*", Operation.__multiplication) @staticmethod def division(): """ Returns division operation singleton :rtype: :class:`Operation` """ return Operation.__create_singleton(False, "/", Operation.__division) @staticmethod def negation(): """ Returns negation operation (unary) singleton :rtype: :class:`Operation` """ return Operation.__create_singleton(True, "-", Operation.__negation) def __repr__(self): return self.symbol class MathExpression(object): def __init__(self, operation, operands): """ Class describing mathematical expression :param operation: Reference to :class:`Operation` :param operands: A list of operands (two for binary, one for unary). An operand can be a constant (number) or another :class:`MathExpression` :return: :class:`MathExpression` """ self.__assert_valid(operation, operands) self.__operands = operands self.__operation = operation @property def operation(self): """ Reference to :class:`Operation` :rtype: :class:`Operation` """ return self.__operation @operation.setter def operation(self, operation): self.__assert_valid(operation, self.operands) self.__operation = operation @property def operands(self): """ A list of operands (two for binary, one for unary). An operand can be a constant (number) or another :class:`MathExpression` :rtype: list of :class:`Operation` """ return self.__operands @operands.setter def operands(self, operands): self.__assert_valid(self.operation, operands) self.__operands = operands def __eq__(self, other): return type(self) == type(other) and \ self.operands == other.operands and \ self.operation == other.operation def __ne__(self, other): return not self.__eq__(other) def find_variables(self, remove_duplicates=True): vars = [] for o in self.operands: if isinstance(o, type(self)): vars.extend(o.find_variables(False)) elif not o is None: vars.append(o) if remove_duplicates: seen = set() return [x for x in vars if x not in seen and not seen.add(x)] return vars @staticmethod def format_var(var): var = "({0})".format(var) if isinstance(var, MathExpression) else var var = var.name if isinstance(var, (Reaction, Metabolite)) else var return var def __indent(self, text, indent=" "): return "\n".join([indent + l for l in text.split("\n")]) def __repr__(self, tree=False): if not tree: return " {0} ".format(self.operation).join(str(self.format_var(o)) for o in self.operands) else: operands = [] for o in self.operands: operands.append(o.__repr__(tree=True) if isinstance(o, MathExpression) else "{0}({1})".format(type(o).__name__, self.format_var(o))) return "{0}(\n{1}\n)".format( type(self).__name__, self.__indent("\n{0}\n".format(self.operation).join(operands)) ) def __assert_valid(self, operation, operands): if not isinstance(operation, (Operation, type(None))): raise TypeError("Operation is not an instance of class <Operation>: {0}".format(type(operation))) if not isinstance(operands, list): raise TypeError("Operands are not a list: {0}".format(type(operands))) # TODO: test these exceptions if operation is None: if len(operands) != 1: raise ValueError("Math expression not representing any operation (<None>) have number of operands different from one") else: if operation.is_unary and len(operands) != 1: raise ValueError("Unary operation have number of operands different from one") elif not operation.is_unary and len(operands) < 2: raise ValueError("Binary operation have less than 2 operands") class Model(object): """ BioOpt model is a main class in package. It contains list of reactions in the model and other additional information. """ def __init__(self): self.__reactions = list() self.__objective = None self.__design_objective = None @property def reactions(self): """ List of reactions in the model :rtype: list of :class:`Reaction` """ return self.__reactions @reactions.setter def reactions(self, reactions): # TODO: assert self.__reactions = reactions @property def objective(self): """ Optimization target (i.e. Biomass) :rtype: class:`MathExpression` """ return self.__objective @objective.setter def objective(self, objective): self.__assert_objective(objective) self.__objective = objective @staticmethod def __extract_expression(expression): r = next(r for r in expression.operands if isinstance(r, Reaction)) c = next(r for r in expression.operands if isinstance(r, (int, float))) return r, c @staticmethod def __extract_objective_dict(objective): coefficients = {} if objective.operation == Operation.addition(): for exp in objective.operands: r, c = Model.__extract_expression(exp) coefficients[r.name] = c elif objective.operation == Operation.multiplication(): r, c = Model.__extract_expression(objective) coefficients[r.name] = c return coefficients @property def objective_dict(self): return Model.__extract_objective_dict(self.objective) @property def design_objective_dict(self): return Model.__extract_objective_dict(self.objective) def get_objective_coefficient(self, reaction): # TODO: Implement generic operation handling self.objective model.objective.operands[2] pass @property def design_objective(self): """ Design optimization target (i.e. Ethanol) :rtype: list of :class:`MathExpression` """ return self.__design_objective @design_objective.setter def design_objective(self, design_objective): self.__assert_objective(design_objective) self.__design_objective = design_objective def find_reaction(self, names=None, regex=False): """ Searches model for reactions with specified names (patterns). If multiple reactions are found this function returns only the first one. :param names: name or list of names of reactions :param regex: If True names argument is assumed to be a regular expression :rtype: :class:`Reaction` """ r = self.find_reactions(names, regex=regex) if len(r) > 1: warnings.warn("Found {0} reactions corresponding to name '{1}'. Returning first!".format(len(r), names), RuntimeWarning) return r[0] if len(r) else None def find_reactions(self, names=None, regex=False): """ Searches model for reactions with specified names (patterns). This function is capable of returning multiple reactions. :param names: name or list of names of reactions :param regex: If True names argument is assumed to be a regular expression :rtype: list of :class:`Reaction` """ if not self.reactions: return [] import collections if names is None: return [r for r in self.reactions] elif isinstance(names, str): if regex: names = re.compile(names) return [r for r in self.reactions if names.search(r.name)] else: for r in self.reactions: if r.name == names: return [r] return [] elif isinstance(names, collections.Iterable): names = set(names) if regex: names = [re.compile(n) for n in names] return [r for r in self.reactions if any(n.search(r.name) for n in names)] else: return [r for r in self.reactions if r.name in names] else: raise TypeError("Names argument should be iterable, string or <None>") def unify_metabolite_references(self): metabolites = dict((m.name, m) for m in self.find_metabolites()) for reaction in self.reactions: for member in reaction.reactants: member.metabolite = metabolites[member.metabolite.name] for member in reaction.products: member.metabolite = metabolites[member.metabolite.name] def __unify_objective_references(self, expression, reactions): if isinstance(expression, MathExpression): for i, o in enumerate(expression.operands): if isinstance(o, MathExpression): self.__unify_objective_references(o, reactions) elif isinstance(o, Reaction): if o.name in reactions: expression.operands[i] = reactions[o.name] def unify_reaction_references(self): # TODO: What if more than one reaction with same name (Use first) reactions = dict((r.name, r) for r in self.reactions) self.__unify_objective_references(self.objective, reactions) self.__unify_objective_references(self.design_objective, reactions) def unify_references(self): """ Find metabolite with identical names which are stored as different instances and unify instances. """ self.unify_metabolite_references() self.unify_reaction_references() def __fix_math_reactions(self, expression, reactions): if isinstance(expression, MathExpression): for i, o in enumerate(expression.operands): if isinstance(o, MathExpression): self.__fix_math_reactions(o, reactions) elif isinstance(o, Reaction): expression.operands[i] = reactions[o.name] def find_metabolite(self, names=None, regex=False): """ Searches model for metabolites with specified names (patterns). If multiple metabolites are found this function returns only the first one. :param names: name or list of names of metabolites :param regex: If True names argument is assumed to be a regular expression :rtype: :class:`Metabolite` """ m = self.find_metabolites(names, regex=regex) if len(m) > 1: warnings.warn("Found {0} metabolites corresponding to name '{1}'. Returning first!".format(len(m), names), RuntimeWarning) return m[0] if len(m) else None # TODO: Test with multiple instances of the same metabolite (result should contain two instances) # TODO: Test with no reaction section. Metabolite present in ext. metabolites should be accessible def find_metabolites(self, names=None, regex=False): """ Searches model for metabolites with specified names (patterns). This function is capable of returning multiple metabolites. :param names: name or list of names of metabolites :param regex: If True names argument is assumed to be a regular expression :rtype: list of :class:`Metabolite` """ metabolites_set = set() metabolites = [] for r in self.reactions: for rm in r.reactants: if rm.metabolite.name == "atp_c": pass metabolites_set.add(rm.metabolite) for rm in r.products: if rm.metabolite.name == "atp_c": pass metabolites_set.add(rm.metabolite) #if rm.metabolite not in metabolites_set: #metabolites.append(rm.metabolite) metabolites = list(metabolites_set) import collections if names is None: return metabolites elif isinstance(names, str): if regex: names = re.compile(names) return [m for m in metabolites if names.search(m.name)] else: for m in metabolites: if m.name == names: return [m] return [] elif isinstance(names, collections.Iterable): names = set(names) if regex: names = [re.compile(n) for n in names] return [m for m in metabolites if any(n.search(m.name) for n in names)] else: return [m for m in metabolites if m.name in names] else: raise TypeError("Names argument should be iterable, string or <None>") def find_boundary_metabolites(self): """ Searches for imported/exported metabolites :rtype: list of :class:`Metabolite` """ return [m for m in self.find_metabolites() if m.boundary] def find_boundary_reactions(self): """ Searches for reactions exporting or importing metabolites :rtype: list of :class:`Reaction` """ return [r for r in self.reactions if any(m.metabolite.boundary for m in r.reactants) or any(m.metabolite.boundary for m in r.products)] def get_max_bound(self): mb = 0 for r in self.reactions: lb = math.fabs(r.bounds.lb) if lb > mb: mb = lb ub = math.fabs(r.bounds.ub) if ub > mb: mb = ub return mb @staticmethod def commune(models, model_prefix="ML{0:04d}_", env_prefix="ENV_", block=[]): """ Merge two or more models into community model. Community model allows organisms represented by models to share metabolites. Briefly, the algorithm first appends reaction and metabolite names in original models with ML****_ prefix. Then for every metabolite exported in original models boundary condition is set to :class:`False` and new export reaction is created. This export reactions allows metabolites to travel from joined models into shared environment and back. This setup allows organisms to exchange metabolites through common environment. Originally this merging framework was described in `"OptCom: A Multi-Level Optimization Framework for the Metabolic Modeling and Analysis of Microbial Communities" <http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1002363>`_ by Ali R. Zomorrodi and Costas D. Maranas. :param models: List of :class:`Model` to join :param model_prefix: Model prefix, Model prefix is added to all reaction names to avoid name collision in joined model. :param env_prefix: Prefix of metabolites in shared environment. :param block: List of names (in original models) of metabolites which should be not allowed to be exchanged between organisms. An obvious example of such metabolite is biomass. :rtype: :class:`Model` """ block = [block] if not isinstance(block, list) else block block = [re.compile(b) for b in block] boundary_metabolites = {} fwd = Direction.forward() model = Model() for i, mod in enumerate(models): env_reactions = [] for m in mod.find_boundary_metabolites(): m_in = Metabolite(model_prefix.format(i) + m.name) m_out = Metabolite(env_prefix + m.name) boundary_metabolites[m_out.name] = m_out r_out = Reaction(model_prefix.format(i) + 'OUT_' + m.name, ReactionMemberList([ReactionMember(m_in, 1)]), ReactionMemberList([ReactionMember(m_out, 1)]), Direction.forward(), Bounds(0, Bounds.inf())) r_in = Reaction(model_prefix.format(i) + 'IN_' + m.name, ReactionMemberList([ReactionMember(m_out, 1)]), ReactionMemberList([ReactionMember(m_in, 1)]), Direction.forward(), Bounds(0, Bounds.inf())) env_reactions.extend([r_out, r_in]) reactions = [] metabolites = set() for r in mod.reactions: r = r.copy() r.name = model_prefix.format(i) + r.name for m in r.reactants: metabolites.add(m.metabolite) for m in r.products: metabolites.add(m.metabolite) reactions.append(r) for m in metabolites: m.name = model_prefix.format(i) + m.name m.boundary = False for r in reactions: if not any(b.search(r.name) for b in block): model.reactions.append(r) for r in env_reactions: if not any(b.search(r.name) for b in block): model.reactions.append(r) model.unify_references() for m_name, m_out in boundary_metabolites.items(): m_ext = Metabolite("{0}xtX".format(m_name), True) r_out = Reaction(m_out.name+"xtO", ReactionMemberList([ReactionMember(m_out)]), ReactionMemberList([ReactionMember(m_ext)]), fwd) r_in = Reaction(m_out.name+"xtI", ReactionMemberList([ReactionMember(m_ext)]), ReactionMemberList([ReactionMember(m_out)]), fwd) if not any(b.search(r_out.name) for b in block): model.reactions.append(r_out) if not any(b.search(r_in.name) for b in block): model.reactions.append(r_in) return model def __assert_objective(self, objective): if not (objective is None or isinstance(objective, MathExpression)): raise TypeError("Objective is not None or <MathExpression>: {0}".format(type(objective))) def save(self, path=None, inf=1000): """ Save model on disc in bioopt format :param path: The name or full pathname of the file where the BioOpt model is to be written. :param inf: Number which would be used for constraints with infinite bounds """ ret = "-REACTIONS\n" for r in self.reactions: reactants = " + ".join("{0}{1}".format("" if abs(m.coefficient) == 1 else "{0:.5g} ".format(m.coefficient), m.metabolite.name) for m in r.reactants) products = " + ".join("{0}{1}".format("" if abs(m.coefficient) == 1 else "{0:.5g} ".format(m.coefficient), m.metabolite.name) for m in r.products) dir = "->" if r.direction == Direction.forward() else "<->" ret += "{name}\t:\t{lhs} {dir} {rhs}".format(name=r.name, lhs=reactants, dir=dir, rhs=products) + "\n" ret += "\n" ret += "-CONSTRAINTS\n" for r in self.reactions: lb = -inf if r.bounds.lb == -Bounds.inf() else r.bounds.lb ub = inf if r.bounds.ub == Bounds.inf() else r.bounds.ub if not (r.bounds.direction == Direction.forward() and r.bounds == Bounds(0)) and \ not (r.bounds.direction == Direction.reversible() and r.bounds == Bounds()): ret += "{0}\t[{1:.5g}, {2:.5g}]".format(r.name, lb, ub) + "\n" ret += "\n" ret += "-EXTERNAL METABOLITES\n" b_metabolites = self.find_boundary_metabolites() b_metabolites = sorted(b_metabolites, key=lambda x: x.order_boundary) for m in b_metabolites: ret += m.name + "\n" ret += "\n" if self.objective: ret += "-OBJECTIVE\n" ret += " ".join(str(MathExpression.format_var(o)) for o in self.objective.operands) ret += "\n\n" if self.design_objective: ret += "-DESIGN OBJECTIVE\n" ret += " ".join(str(MathExpression.format_var(o)) for o in self.design_objective.operands) ret += "\n\n" if path: f = open(path, 'w') f.write(ret) return f.close() else: return ret def __repr__(self): ret = "-REACTIONS\n{0}\n\n".format("\n".join(r.__repr__() for r in self.reactions)) ret += "-CONSTRAINTS\n{0}\n\n".format("\n".join("{0}\t{1}".format(r.name, r.bounds) for r in self.reactions)) ret += "-EXTERNAL METABOLITES\n{0}\n\n".format("\n".join(m.__repr__() for m in self.find_boundary_metabolites())) ret += "-OBJECTIVE\n{0}\n\n".format(self.objective) ret += "-DESIGN OBJECTIVE\n{0}\n\n".format(self.design_objective) return ret def __eq__(self, other): return type(self) == type(other) and \ self.reactions == other.reactions and \ self.objective == other.objective and \ self.design_objective == other.design_objective def __ne__(self, other): return not self.__eq__(other)
from copy import * from random import shuffle class Strategy: def __init__(self): self.BOARD_WIDTH = 7 self.BOARD_HEIGHT = 6 self.AI_PLAYER = 'O' self.HUMAN_PLAYER = 'X' def MiniMaxAlphaBeta(self, board, depth, player): """ A minimax algorithm[5] is a recursive algorithm for choosing the next move in an n-player game, usually a two-player game.A value is associated with each position or state of the game. This value is computed by means of a position evaluation function and it indicates how good it would be for a player to reach that position. The player then makes the move that maximizes the minimum value of the position resulting from the opponent's possible following moves. If it is A's turn to move, A gives a value to each of their legal moves. :param board: :param depth: :param player: :return: """ # get array of possible moves validMoves = self.getValidMoves(board) shuffle(validMoves) bestMove = validMoves[0] bestScore = float("-inf") # initial alpha & beta values for alpha-beta pruning alpha = float("-inf") beta = float("inf") if player == self.AI_PLAYER: opponent = self.HUMAN_PLAYER else: opponent = self.AI_PLAYER # go through all of those boards for move in validMoves: # create new board from move tempBoard = self.makeMove(board, move, player)[0] # call min on that new board boardScore = self.minimizeBeta(tempBoard, depth - 1, alpha, beta, player, opponent) if boardScore > bestScore: bestScore = boardScore bestMove = move return bestMove def minimizeBeta(self, board, depth, a, b, player, opponent): """ The algorithm continues evaluating the maximum and minimum values of the child nodes alternately until it reaches the root node, where it chooses the move with the largest value (represented in the figure with a blue arrow). This is the move that the player should make in order to minimize the maximum possible loss. :param board: :param depth: :param a: :param b: :param player: :param opponent: :return: """ validMoves = [] for col in range(7): # if column col is a legal move... if self.isValidMove(col, board): # make the move in column col for curr_player temp = self.makeMove(board, col, player)[2] validMoves.append(temp) # check to see if game over if depth == 0 or len(validMoves) == 0 or self.gameIsOver(board): return self.utilityValue(board, player) validMoves = self.getValidMoves(board) beta = b # if end of tree evaluate scores for move in validMoves: boardScore = float("inf") # else continue down tree as long as ab conditions met if a < beta: tempBoard = self.makeMove(board, move, opponent)[0] boardScore = self.maximizeAlpha(tempBoard, depth - 1, a, beta, player, opponent) if boardScore < beta: beta = boardScore return beta def maximizeAlpha(self, board, depth, a, b, player, opponent): """ The algorithm continues evaluating the maximum and minimum values of the child nodes alternately until it reaches the root node, where it chooses the move with the largest value (represented in the figure with a blue arrow). This is the move that the player should make in order to minimize the maximum possible loss. :param board: :param depth: :param a: :param b: :param player: :param opponent: :return: """ validMoves = [] for col in range(7): # if column col is a legal move... if self.isValidMove(col, board): # make the move in column col for curr_player temp = self.makeMove(board, col, player)[2] validMoves.append(temp) # check to see if game over if depth == 0 or len(validMoves) == 0 or self.gameIsOver(board): return self.utilityValue(board, player) alpha = a # if end of tree, evaluate scores for move in validMoves: boardScore = float("-inf") if alpha < b: tempBoard = self.makeMove(board, move, player)[0] boardScore = self.minimizeBeta(tempBoard, depth - 1, alpha, b, player, opponent) if boardScore > alpha: alpha = boardScore return alpha def isColumnValid(self, Board, Col): """ check if column still has place :param Board: :param Col: :return: """ if Board[0][Col] == ' ': return True return False # check the search range for rows and columns def isRangeValid(self, row, col): """ check the search range for rows and columns :param row: :param col: :return: """ if row >= 0 and col >= 0 and row < self.BOARD_HEIGHT and col < self.BOARD_WIDTH: return True return False # return all valid moves (empty columns) from the board def getValidMoves(self, Board): """ return all valid moves (empty columns) from the board :param Board: :return: """ Columns = [] for Col in range(self.BOARD_WIDTH): if self.isColumnValid(Board, Col): Columns.append(Col) return Columns # places the current move's player ['x'|'o'] in the referenced column in the board def makeMove(self, board, col, player): """ places the current move's player ['x'|'o'] in the referenced column in the board :param board: :param col: :param player: :return: """ # deepcopy is used to take a copy of current board and not affecting the original one tempBoard = deepcopy(board) for row in range(5, -1, -1): if tempBoard[row][col] == ' ': tempBoard[row][col] = player return tempBoard, row, col # check if the played move is in empty column or not def isValidMove(self, col, board): """ Check if the played move is in empty column or not :param col: :param board: :return: """ for row in range(self.BOARD_HEIGHT): if board[row][col] == ' ': return True return False # check if the board is filled with players' moves def isBoardFilled(self, board): """ check if the board is filled with players' moves :param board: :return: """ # Check the first row and Selected column if it filled or not for row in range(self.BOARD_HEIGHT): for col in range(self.BOARD_WIDTH): if board[row][col] == ' ': return False return True # find four or more of ('x'|'o') in arrow in any direction def findFours(self, board): """ find four or more of ('x'|'o') in arrow in any direction :param board: :return: """ # find four or more of ('x'|'o') in arrow in vertical direction def verticalCheck(row, col): """ find four or more of ('x'|'o') in arrow in vertical direction :param row: :param col: :return: """ fourInARow = False count = 0 for rowIndex in range(row, self.BOARD_HEIGHT): if board[rowIndex][col] == board[row][col]: count += 1 else: break if count >= 4: fourInARow = True return fourInARow, count # find four or more of ('x'|'o') in arrow in horizontal direction def horizontalCheck(row, col): """ find four or more of ('x'|'o') in arrow in horizontal direction :param row: :param col: :return: """ fourInARow = False count = 0 for colIndex in range(col, self.BOARD_WIDTH): if board[row][colIndex] == board[row][col]: count += 1 else: break if count >= 4: fourInARow = True return fourInARow, count # find four or more of ('x'|'o') in arrow in positive diagonal direction def posDiagonalCheck(row, col): """ find four or more of ('x'|'o') in arrow in positive diagonal direction / :param row: :param col: :return: """ # check for diagonals with positive slope slope = None count = 0 colIndex = col for rowIndex in range(row, self.BOARD_HEIGHT): if colIndex > self.BOARD_HEIGHT: break elif board[rowIndex][colIndex] == board[row][col]: count += 1 else: break colIndex += 1 # increment column when row is incremented if count >= 4: slope = 'positive' return slope, count # find four or more of ('x'|'o') in arrow in negative diagonal direction \ def negDiagonalCheck(row, col): """ find four or more of ('x'|'o') in arrow in negative diagonal direction \ :param row: :param col: :return: """ # check for diagonals with positive slope slope = None count = 0 colIndex = col for rowIndex in range(row, -1, -1): if colIndex > 6: break elif board[rowIndex][colIndex] == board[row][col]: count += 1 else: break colIndex += 1 # increment column when row is decremented if count >= 4: slope = 'negative' return slope, count # find four or more of ('x'|'o') in arrow in any diagonal direction def diagonalCheck(row, col): """ find four or more of ('x'|'o') in arrow in any diagonal direction :param row: :param col: :return: """ positiveSlop, positiveCount = posDiagonalCheck(row, col) negativeSlop, negativeCount = negDiagonalCheck(row, col) if positiveSlop == 'positive' and negativeSlop == 'negative': fourInARow = True slope = 'both' elif positiveSlop == None and negativeSlop == 'negative': fourInARow = True slope = 'negative' elif positiveSlop == 'positive' and negativeSlop == None: fourInARow = True slope = 'positive' else: fourInARow = False slope = None return fourInARow, slope, positiveCount, negativeCount # make the winning moves in uppercase def capitalizeFourInARow(row, col, dir): """ make the winning moves in uppercase :param row: :param col: :param dir: :return: """ if dir == 'vertical': for rowIndex in range(verticalCount): board[row + rowIndex][col] = board[row + rowIndex][col].upper() elif dir == 'horizontal': for colIndex in range(horizontalCount): board[row][col + colIndex] = board[row][col + colIndex].upper() elif dir == 'diagonal': if slope == 'positive' or slope == 'both': for diagIndex in range(positiveCount): board[row + diagIndex][col + diagIndex] = board[row + diagIndex][col + diagIndex].upper() elif slope == 'negative' or slope == 'both': for diagIndex in range(negativeCount): board[row - diagIndex][col + diagIndex] = board[row - diagIndex][col + diagIndex].upper() # initialize the variables FourInRowFlag = False slope = None verticalCount = 0 horizontalCount = 0 positiveCount = 0 negativeCount = 0 for rowIndex in range(self.BOARD_HEIGHT): for colIndex in range(self.BOARD_WIDTH): if board[rowIndex][colIndex] != ' ': # check for a vertical match starts at (rowIndex, colIndex) fourInARow, verticalCount = verticalCheck(rowIndex, colIndex) if fourInARow: capitalizeFourInARow(rowIndex, colIndex, 'vertical') FourInRowFlag = True fourInARow, horizontalCount = horizontalCheck(rowIndex, colIndex) # check for horizontal match starts at (rowIndex, colIndex) if fourInARow: capitalizeFourInARow(rowIndex, colIndex, 'horizontal') FourInRowFlag = True # check for diagonal match starts at (rowIndex, colIndex) # also, get the slope of the four if there is one fourInARow, slope, positiveCount, negativeCount = diagonalCheck(rowIndex, colIndex) if fourInARow: capitalizeFourInARow(rowIndex, colIndex, 'diagonal') FourInRowFlag = True return FourInRowFlag # gets number of the empty valid locations in the board def getEmptyLocations(self, board): """ Gets number of the empty valid locations in the board :param board: :return: """ emptyLocations = 0 for row in range(self.BOARD_HEIGHT): for col in range(self.BOARD_WIDTH): if board[row][col] == ' ': emptyLocations += 1 return emptyLocations def countSequence(self, board, player, length): """ Given the board state , the current player and the length of Sequence you want to count Return the count of Sequences that have the given length """ def verticalSeq(row, col): """Return 1 if it found a vertical sequence with the required length """ count = 0 for rowIndex in range(row, self.BOARD_HEIGHT): if board[rowIndex][col] == board[row][col]: count += 1 else: break if count >= length: return 1 else: return 0 def horizontalSeq(row, col): """Return 1 if it found a horizontal sequence with the required length """ count = 0 for colIndex in range(col, self.BOARD_WIDTH): if board[row][colIndex] == board[row][col]: count += 1 else: break if count >= length: return 1 else: return 0 def negDiagonalSeq(row, col): """Return 1 if it found a negative diagonal sequence with the required length """ count = 0 colIndex = col for rowIndex in range(row, -1, -1): if colIndex > self.BOARD_HEIGHT: break elif board[rowIndex][colIndex] == board[row][col]: count += 1 else: break colIndex += 1 # increment column when row is incremented if count >= length: return 1 else: return 0 def posDiagonalSeq(row, col): """Return 1 if it found a positive diagonal sequence with the required length """ count = 0 colIndex = col for rowIndex in range(row, self.BOARD_HEIGHT): if colIndex > self.BOARD_HEIGHT: break elif board[rowIndex][colIndex] == board[row][col]: count += 1 else: break colIndex += 1 # increment column when row incremented if count >= length: return 1 else: return 0 totalCount = 0 # for each piece in the board... for row in range(self.BOARD_HEIGHT): for col in range(self.BOARD_WIDTH): # ...that is of the player we're looking for... if board[row][col] == player: # check if a vertical streak starts at (row, col) totalCount += verticalSeq(row, col) # check if a horizontal four-in-a-row starts at (row, col) totalCount += horizontalSeq(row, col) # check if a diagonal (both +ve and -ve slopes) four-in-a-row starts at (row, col) totalCount += (posDiagonalSeq(row, col) + negDiagonalSeq(row, col)) # return the sum of sequences of length 'length' return totalCount def utilityValue(self, board, player): """ A utility function to evaluate the state of the board and report it to the calling function, utility value is defined as the score of the player who calls the function - score of opponent player, The score of any player is the sum of each sequence found for this player scaled by large factor for sequences with higher lengths. """ if player == self.HUMAN_PLAYER: opponent = self.AI_PLAYER else: opponent = self.HUMAN_PLAYER playerfours = self.countSequence(board, player, 4) playerthrees = self.countSequence(board, player, 3) playertwos = self.countSequence(board, player, 2) playerScore = playerfours * 99999 + playerthrees * 999 + playertwos * 99 opponentfours = self.countSequence(board, opponent, 4) opponentthrees = self.countSequence(board, opponent, 3) opponenttwos = self.countSequence(board, opponent, 2) opponentScore = opponentfours * 99999 + opponentthrees * 999 + opponenttwos * 99 if opponentfours > 0: # This means that the current player lost the game # So return the biggest negative value => -infinity return float('-inf') else: # Return the playerScore minus the opponentScore return playerScore - opponentScore def gameIsOver(self, board): """Check if there is a winner in the current state of the board """ if self.countSequence(board, self.HUMAN_PLAYER, 4) >= 1: return True elif self.countSequence(board, self.AI_PLAYER, 4) >= 1: return True else: return False
from src.utils import * from src.agent import * class Controller: """ The controller class handles the flow of the program - It creates the agent: The agent class contains methods for creating and revising the belief base - It contains methods for displaying general information and valid syntax examples. - It contains method for creating a new belief base, adding new belief to the belief base and checking for entailment of a belief in the belief base. """ def __init__(self): self.agent = Agent() def start_main_loop(self): while True: self.print_valid_actions() self.preform_action(int(input("Select actions: "))) def print_general_information(self): """ Displays the general information needed for running the program. Calls a print_general_information method in display_utils class, which prints the general information needed for running the program """ display_utils.print_general_information() def print_syntax_information(self): """ Displays the syntax information needed for running the program. Calls a print_syntax_information method in display_utils class, which prints the syntax information needed for running the program. """ display_utils.print_syntax_information() def print_current_belief_base(self): """ Display the current belief base. Calls a print_belief_base in agent class which prints the belief base """ self.agent.print_belief_base() def declare_new_belief_base(self): """ Contains functionality which makes the the user able to declare a new belief base. Step 1: The user inputs a sentence containing propositional logic in symbolic form Step 2: The syntax of the sentence is validated. Step 3: The satisfiability of the sentence is validated. Step 4: A new belief base is declared. If step 2 and 3 returns false a new belief base isn´t declared and the user must try again. """ # Step 1 sentence = input("Belief base: ") print("input is ", sentence) # Step 2 # # Step 3 # if not self.agent.check_satisfiability_of_sentence(sentence): # display_utils.print_unsatisfiability_information() # return # Step 4 print("controler agent. new base") self.agent.declare_new_belief_base(sentence) display_utils.print_successful_declaration_of_belief_base() def use_predefined_belief_base(self): """ Contains functionality which makes the the user able to use a predefined belief base Calls a use_predefined_belief_base method in agent class. The belief base is set as predefined list of beliefs in CNF form. """ self.agent.use_predefined_belief_base() display_utils.print_successful_declaration_of_belief_base() def add_new_belief(self): """ Contains functionality which makes the the user able to add a new belief to the belief base. Step 1: Checks if agent has a defined belief base. Step 2: The user inputs a sentence containing propositional logic in symbolic form Step 3: The syntax of the sentence is validated. Step 4: The satisfiability of the sentence is validated. Step 5: A new belief base is declared. If step 1, 2 and 3 returns false a new belief isn´t added to the belief base and the user must try again. """ # Step 1 if self.agent.defined_belief_base: display_utils.print_belief_base_not_defined() return # Step 2 sentence = input("Belief: ") # Step 3 if not validator.syntax_is_valid(sentence): display_utils.print_invalid_input_information() return # Step 4 if not self.agent.check_satisfiability_of_sentence(sentence): display_utils.print_unsatisfiability_information() return # Step 5 self.agent.add_new_belief_to_belief_base(sentence) display_utils.print_successful_addition_of_belief() def check_if_belief_is_entail_to_belief_base(self): """ Contains functionality which makes the the user able to check the entailment of a belief in the belief base. Step 1: Checks if agent has a defined belief base. Step 2: The user inputs a sentence containing propositional logic in symbolic form Step 3: The syntax of the sentence is validated. Step 4: The satisfiability of the sentence is validated. Step 5: Checks the entailment of a belief in the belief base. If step 1, 2 and 3 returns false the entailment of the belief isn´t check and the user must try again. """ # Step 1 if self.agent.defined_belief_base: display_utils.print_belief_base_not_defined() return # Step 2 sentence = input("Belief: ") # Step 3 if not validator.syntax_is_valid(sentence): display_utils.print_invalid_input_information() return # Step 4 if not self.agent.check_satisfiability_of_sentence(sentence): display_utils.print_unsatisfiability_information() return # Step 5 if self.agent.check_if_belief_is_entailed_by_belief_base(sentence): display_utils.print_entailment_valid() else: display_utils.print_entailment_invalid() def show_examples(self): print_valid_syntax() def print_valid_actions(self): print("\n--- List of actions ---") print("1: Print general menu") print("2: Print syntax information") print("3: Show Examples") print("4: Print belief base") print("5: Declare new belief base") print("6: Use predefined belief base") print("7: Add new belief to belief base") print("8: Check if belief is entailed by the belief base") def preform_action(self, i): print("\n--- Actions information ---\n") switcher = { 1: self.print_general_information, 2: self.print_syntax_information, 3: self.show_examples, 4: self.print_current_belief_base, 5: self.declare_new_belief_base, 6: self.use_predefined_belief_base, 7: self.add_new_belief, 8: self.check_if_belief_is_entail_to_belief_base, } switcher.get(i, lambda: print("Invalid input"))()
"""CSC111 Project: COVID-19 Contact Visualizer Module Description ================== Social Graph Dataclasses Module This module contains the dataclasses and their methods that represent a network of people. Copyright and Usage Information =============================== This file is Copyright (c) 2021 Simon Chen, Patricia Ding, Salman Husainie, Makayla Duffus """ from __future__ import annotations from typing import Optional import networkx as nx import colouring as colour class _Person: """ A person who undergoes contact tracing. Represents a vertex in a graph. Instance Attributes: - identifier: The unique identifier of the person. - name: The person's first and last name. - age: The person's age. - severity_level: The severity of COVID-19 the person would experience if they develop the illness. - infected: True if the person has developed COVID-19, False otherwise. - neighbours: The people in this person's social circle, and their corresponding level of contact with this person. Maps _Person object to their contact level to self. - degrees_apart: The degree of separation between this person and an infected person in Degree Mode. Representation Invariants: - self not in self.neighbours - all(self in u.neighbours for u in self.neighbours) - self.age >= 0 - 0 <= self.severity_level <= 1 """ identifier: str name: str age: int severity_level: float infected: bool neighbours: dict[_Person, float] degrees_apart: Optional[int] = None def __init__(self, identifier: str, name: str, age: int, severity_level: float) -> None: """Initialize a new person vertex with the given name, identifier, age, and severity level. """ self.identifier = identifier self.name = name self.age = age self.severity_level = severity_level self.infected = False self.neighbours = {} # BASIC METHODS def change_infection_status(self) -> None: """Reverses the current infection status of the person. >>> p1 = _Person('F5H9A8', 'L.V', 60, 0.9) >>> p1.change_infection_status() >>> p1.infected True """ self.infected = not self.infected # DEGREE CALCULATION def calculate_degrees_apart(self, curr_degree: int, visited: set, init_call: bool = True) -> None: """Update degrees_apart for all the people this person is connected to, where degrees_apart is the smallest degree apart between this person and an infected person. """ # This will ensure that degrees_apart is always calculating the smallest degree between # an infected person. if not init_call and curr_degree == 0: return # To avoid redundant calculations if self.degrees_apart is None or curr_degree < self.degrees_apart: self.degrees_apart = curr_degree visited.add(self) for person in self.neighbours: if person not in visited: person.calculate_degrees_apart(curr_degree + 1, visited.copy(), False) def get_degree(self) -> int: """Return smallest degree apart from an infected vertex. Raise ValueError if has not been calculated yet. """ if self.degrees_apart is not None: return self.degrees_apart raise ValueError def reset_degree(self, zero: Optional[bool] = False) -> None: """Resets the degrees_apart attribute to None to represent an uncalculated value. If zero is true, set it to 0 instead. """ if zero: self.degrees_apart = 0 else: self.degrees_apart = None class Graph: """ A weighted graph used to represent a network of people that keeps track of the level of contact between any two people. """ # Private Instance Attributes: # - _people: # A collection of the people in this graph. # Maps person identifier to _Person object. _people: dict[str, _Person] def __init__(self) -> None: """ Initialize an empty graph.""" self._people = {} # ACCESSOR METHODS def get_people(self) -> dict[str, _Person]: """Return a dictionary mapping a unique identifier to _Person object.""" return self._people def get_neighbours(self, item: str) -> list[_Person]: """Return the neighbours of the item""" return list(self._people[item].neighbours) def get_weight(self, person1: str, person2: str) -> float: """Return the weight between person1 and person2 >>> graph = Graph() >>> graph.add_vertex('F5H9A8', 'Bob', 60, 0.9) >>> graph.add_vertex('F7H8T6', 'Jim', 60, 0.9) >>> graph.add_edge('F5H9A8', 'F7H8T6', 0.42069) >>> graph.get_weight('F5H9A8', 'F7H8T6') 0.42069 """ return self._people[person1].neighbours[self._people[person2]] def get_names(self) -> set[str]: """Return a set containing the names of every _Person object in this graph. """ names_so_far = set() for person in self._people: names_so_far.add(self._people[person].name) return names_so_far def get_contact_level(self, identifier1: str, identifier2: str) -> float: """Return the level of contact between the given items (the weight of their edge). Return 0 if identifier1 and identifier2 are not adjacent. """ person1 = self._people[identifier1] person2 = self._people[identifier2] return person1.neighbours.get(person2, 0) # MUTATION METHODS def add_vertex(self, identifier: str, name: str, age: int, severity_level: float) -> None: """Add a vertex with the given identifier, name, age, and severity level to this graph. """ if identifier not in self._people: self._people[identifier] = _Person(identifier, name, age, severity_level) def add_edge(self, identifier1: str, identifier2: str, contact_level: float) -> None: """Add an edge between two people with the given identifiers in this graph, with the given weight, representing their level of contact. Preconditions: - identifier1 != identifier2 """ person1 = self._people[identifier1] person2 = self._people[identifier2] person1.neighbours[person2] = contact_level person2.neighbours[person1] = contact_level def set_infected(self, init_infected: set[str]) -> None: """Sets the initial infected people for the graph, given their ids. >>> graph = Graph() >>> graph.add_vertex('F5H9A8', 'L.V', 60, 0.9) >>> graph.add_vertex('F7H8T6', 'C.V', 60, 0.9) >>> graph.set_infected({'F5H9A8'}) >>> graph._people['F5H9A8'].infected True """ for identifier in init_infected: self._people[identifier].infected = True def recalculate_degrees(self) -> None: """Recalculates the degrees_apart attribute for each connected person to an infected. """ self._reset_degrees() infected_people = set() for person in self._people.values(): if person.infected: person.reset_degree(zero=True) infected_people.add(person) for infected_person in infected_people: # This method calculates it for its neighbours infected_person.calculate_degrees_apart(0, set()) def _reset_degrees(self) -> None: """ Resets all degrees_apart attributes in graph to be None """ for person in self._people.values(): person.reset_degree() # Reset all degrees to None # NETWORKX CONVERSION METHODS def to_nx(self) -> nx.Graph: """Return a networkx Graph representing self.""" graph_nx = nx.Graph() for p in self._people.values(): graph_nx.add_node(p.name, colour='rgb(155, 234, 58)') # add node for each person for u in p.neighbours: if u.name in graph_nx.nodes: graph_nx.add_edge(p.name, u.name) # add edge edge between each neighbour pair return graph_nx def to_nx_with_degree_colour(self) -> nx.Graph: """Return a networkx Graph representing self. This function also sets an additional attribute, 'colour', for each node in the networkx graph. This function is used for just a degree graph. """ graph_nx = nx.Graph() for p in self._people.values(): graph_nx.add_node(p.name) # add node for each person node_colour = colour.rgb_to_str(colour.degrees_apart_get_colour(p.degrees_apart)) graph_nx.nodes[p.name]['colour'] = node_colour for u in p.neighbours: if u.name in graph_nx.nodes: graph_nx.add_edge(p.name, u.name) # add edge edge between each neighbour pair return graph_nx def to_nx_with_simulation_colour(self) -> nx.Graph: """Return a networkx Graph representing self. This function also sets an additional attribute, 'colour', for each node in the networkx graph. This function is used for the simulations. """ graph_nx = nx.Graph() for p in self._people.values(): graph_nx.add_node(p.name) # add node for each person node_colour = colour.rgb_to_str(colour.INFECTED_COLOUR) if p.infected else 'rgb(255, ' \ '255, 255) ' graph_nx.nodes[p.name]['colour'] = node_colour for u in p.neighbours: if u.name in graph_nx.nodes: graph_nx.add_edge(p.name, u.name) # add edge edge between each neighbour pair return graph_nx if __name__ == '__main__': import doctest doctest.testmod() import python_ta.contracts python_ta.contracts.check_all_contracts() import python_ta python_ta.check_all(config={ 'extra-imports': ['networkx', 'colouring'], # the names (strs) of imported modules 'max-line-length': 100, 'disable': ['E1136'] })
# -*- coding: utf-8 -*- #d = {"k1":"v1", "k2":"v2", "k3":"v3"} #print(d) # Reihenfolge unbekannt #e = d.copy() #print(e) #d.clear() #print(d) ### Bereich II ### ### Dictionary wird kopiert ### Aber die Inhalte sind Referenzen ### Hier auf dieselbe Liste #d1 = {"key" : [1,2,3]} #d2 = d1.copy() #d2["key"].append(4) #print(d2) #print(d1) #print(d1["key"] is d2["key"]) ### Bereich III ### #d = {"k1":"v1", "k2":"v2", "k3":"v3"} #print(d.get("k2", 1234)) #print(d.get("k5", 1234)) # K-V-Pairs #for paar in d.items(): # print(paar) # Keys #for key in d.keys(): # print(key) #for key in d: # print(key) #print(list(d.keys())) ### Bereich IV ### # Holen und Entfernen #d = {"k1":"v1", "k2":"v2", "k3":"v3"} #print(d.pop("k1")) #print(d.pop("k3")) #print(d) #print(d.popitem()) #print(d) #d.setdefault("k2", 1234) #d.setdefault("k5", 1234) #print(d) #d.update({"k4" : "v4"}) #print(d) #d.update({"k1" : "Python RockZ"}) #print(d) ### VALUES ### #d = {"k1":"v1", "k2":"v2", "k3":"v3"} #for v in d.values(): # print(v) # Class dict -> static method fromkeys # erzeugt ein neues dictionary #dfk = dict.fromkeys([1,2,3], "Python") dfk = dict.fromkeys([1,2,3]) print(dfk)
#!/usr/bin/python # -*- coding: utf-8 -*- # # Python Beispiele zu # http://www.thomas-guettler.de/vortraege/python/einfuehrung.html # # (c) 2003-2012 Thomas Güttler # http://www.thomas-guettler.de/ # # Beispiel ZINSEN: # Ein Versicherungsvertreter verspricht dir, dass du einen großen # Betrag bekommst, wenn du 35 Jahre jährlich 900 Euro einzahlst. Du # willst nun wissen, wieviel Geld du hättest, wenn du keine # Rentenversicherung abschließt, sondern das Geld mit 5 Prozent # Zinsen anlegst. Vielleicht gibt es dafür eine Formel, aber iterativ # (in einer Schleife) lässt sich das auch leicht berechnen. sum=0 for i in range(35): sum*=1.05 # 5 Prozent Zinsen sum+=900 print 'Jahr %s Betrag: %s' % (i+1, sum) #--------------------------------------------------------------------- #Beispiel FIFO: #FIFO (first in first out) (Queue) #Vergleich: Autobahntunnel # l=[] # Nehme eine leere Liste for i in range(10): l.append(i) # An Liste anhängen print l while l: # Solange 'l' nicht leer ist ... print l.pop(0) # Entferne erstes Element der Liste #Ergebnis: 0, 1, 2, ... #--------------------------------------------------------------------- #Beispiel FILO: #FILO (first in last out) (Stack) #Vergleich: Stapel von Münzen # l=[] for i in range(10): l.append(i) while l: print l.pop() # Entferne letztes Element der Liste #Ergebnis: 9, 8, 7, ... #--------------------------------------------------------------------- #Beispiel ZÄHLEN for i, wort in enumerate(['null', 'eins', 'zwei']): print i, wort # 0 null, 1 eins, .... #--------------------------------------------------------------------- #Beispiel ENDE: #Das dicke Ende # file='foo.jpg' if file[-4:]=='.jpg': #unschön print 'Foto' if file.endswith('.jpg'): #besser, analog 'startswith()' print 'Foto' #--------------------------------------------------------------------- #Beispiel DIE WAHRHEIT: #Was ist wahr und was ist falsch? #Folgende Bedingungen sind wahr: # if True: print 'wahr' if 1: print 'wahr' if -1: # Alle Zahlen außer 0 sind wahr print 'wahr' if '0': # Nichtleere Zeichenkette print 'wahr' if 'False': # Nichtleere Zeichenkette print 'wahr' if [[]]: # Nichtleere Liste print 'wahr' if not False: print 'wahr' if not 0: print 'wahr' if not []: # Leere Liste print 'wahr' if not {}: # Leeres Dictionary print 'wahr' if not '': # Leere Zeichenkette print 'wahr' if not None: print 'wahr' if not bool('0'): print 'wahr' if True and True: print 'wahr' if False or True: print 'wahr' #--------------------------------------------------------------------- #Beispiel REFERENZ: #Referenz vs. Kopie # list1=[1, 2, 3, 4] list2=list1 # Zwei Referenzen zeigen auf eine Liste list2[0]=5 print list1==list2 # --> 1 list1=[1, 2, 3, 4] list2=list1[:] # Erstelle eine Kopie der ersten Liste list2[0]=5 print list1==list2 # --> 0 #--------------------------------------------------------------------- #Beispiel UNIQUE a: #Doppelte Einträge aus einer Liste entfernen: mylist=[1, 1, 7, 7, 7, 6, 2, 3, 4, 4, 4, 5] unique={} # dictionary for item in mylist: unique[item]=1 mylist=unique.keys() mylist.sort() print mylist # --> [1, 2, 3, 4, 5, 6, 7] #Beispiel UNIQUE b: #Besser mit set (Menge) mylist=[1, 1, 7, 7, 7, 6, 2, 3, 4, 4, 4, 5] myset=set(mylist) mylist=list(myset) mylist.sort() print mylist # --> [1, 2, 3, 4, 5, 6, 7] #--------------------------------------------------------------------- #Beispiel SORTDICT: #Ein Dictionary sortieren. #Da Dictionaries nicht sortiert gespeichert werden, #will man sie für die Ausgabe ggf. sortieren: mydict={'a': ['Auto', 'Ampel'], 'b': ['Bus', 'Banane'], 'c': ['Chemnitz', 'Chaos'], 'd': ['Dame', 'Diesel'], 'e': ['Esel']} print 'Unsortiert:', mydict for buchstabe, woerter in sorted(mydict.items()): print '%s: %s' % (buchstabe, woerter) #--------------------------------------------------------------------- #Beispiel SORTITEMS a: #Sortieren einer Liste von Paaren. #Die Einträge bestehen aus einer ID und einem Namen. #Die Liste soll anhand der Namen sortiert werden. # mylist=[ (1, 'Dresden'), (2, 'Chemnitz'), (3, 'Bayreuth'), (4, 'Freiburg'), (5, 'Berlin')] def mycmp(a, b): # Bsp: a==(1, 'Dresden') und b==(2, 'Chemnitz') # Diese Compare (Vergleichs) Funktion, vergleicht # jeweils die zweiten Einträge in der Liste. return cmp(a[1], b[1]) # Es wird eine Referenz auf unsere Sortierfunktion übergeben. # Analog einem Funktionspointer in C. mylist.sort(mycmp) print mylist # Erläuterung: Die built-in Funktion 'cmp' vergleicht zwei # Elemente. Sie gibt 0 zurück falls beide identisch sind, -1 falls das # erste kleiner ist, und 1 falls das erste Element größer ist. # Beispiele: # cmp( (1, 2, 3), (1, 2, 3) ) ---> 0 # cmp( (1, 2, 3), (1, 2) ) ---> 1 # cmp( (1, 100), (2, 1) ) ---> -1 # cmp( (1, 2), (1, 3) ) ---> -1 #Beispiel SORTITEMS b: #Wenn 'mycmp' auf Daten zugreifen muss, die nicht #in den Argumenten a oder b stehen, kann man mit #'Decorate Sort Undecorate' (DSU) arbeiten, das bei großen Listen #auch schneller ist als 'mycmp' #Siehe auch http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234 names={ 1: 'Dresden', 2: 'Chemnitz', 3: 'Bayreuth', 4: 'Freiburg'} decorated=[] for key, stadt in names.items(): decorated.append((stadt, key)) decorated.sort() # Es wird nach Städten sortiert ids=[] for stadt, key in decorated: ids.append(key) print ids # ids ist nun entsprechend den zugehörigen Werten in 'names' sortiert #--------------------------------------------------------------------- ##Beispiel DOWNLOAD: ##Herunterladen eine Webseite: # #import urllib2 #fd=urllib2.urlopen('http://www.python.org/') #content=fd.read() #fd.close() #print content # #--------------------------------------------------------------------- ##Beispiel WEBBROWSER: ##Anzeigen der heruntergeladene Seite in einem Browser: ##Es wird der Standard-Browser des System genommen (Netscape, Mozilla, IE, ...) # #import tempfile #import webbrowser #htmlfile=tempfile.mktemp('foo.html') #fd=open(htmlfile, 'w') #fd.write(content) #fd.close() #webbrowser.open('file://%s' % htmlfile) #--------------------------------------------------------------------- #Beispiel ISOTIME: #Datum im ISO-Format (2003-12-31 23:59:59) # import time print 'Es ist jetzt: %s' % time.strftime('%Y-%m-%d %H:%M:%S') #--------------------------------------------------------------------- # Beispiel CHARCOUNT: # Zähle wie oft die Zeichen einer Datei vorkommen datei='beispiele.py' fd=open(datei) inhalt=fd.read() # Lese die gesamte Datei countdict={} # Erstelle leeres Dictionary for char in inhalt: # char (character) == Zeichen old=countdict.get(char, 0) # Falls Zeichen noch nicht gezählt, nehme die Null old+=1 # Zähle um eins hoch countdict[char]=old # Speichere Zähler im Dictionary (char == key (Schlüssel) items=countdict.items() # Liste [(key1, value1), (key2, value2), ...] items.sort() # Sortiere die Liste nach den Zeichen for char, count in items: if char=='\n': char='\\n' # Newline als \n ausgeben. print 'Zeichen %s: %4d' % ( # %4d --> rechtsbündig (vier Zeichen) char, count) #--------------------------------------------------------------------- #Beispiel ISSTRING #Ist ein Objekt eine Zeichenkette? # myobj='abc' if isinstance(myobj, basestring): print 'Ja, das ist eine Zeichenkette: %s' % myobj #--------------------------------------------------------------------- #Beispiel UNICODE: #Zeichensatz-Konvertierung: # text=u'Der in deutschland übliche Zeichensatz: iso-8851-1 (latin1)' # wg u'... Unicode print len(text) print len(text.encode('latin1')) # von Unicode zu Bytefolge print len(text.encode('utf8')) # von Unicode zu Bytefolge # 59, 59, 60 #--------------------------------------------------------------------- #Beispiel UNICODE II: #Bytefolge vs Unicode print len('üöäß') print len(u'üöäß') #--------------------------------------------------------------------- #Beispiel UNICODE III: #Einzelnes de- und encode() vermeiden. import codecs content=codecs.open('beispiele.py', 'rt', 'utf8').read() #--------------------------------------------------------------------- #Beispiel EINMALEINS: #Das Einmaleins als HTML-Tabelle # import tempfile import webbrowser rows=[] heading=[] for i in range(1, 11): heading.append('<th bgcolor="gray">%s</th>' % i) cols=[] for j in range(1, 11): cols.append('<td align="right">%s</td>' % (i*j)) row='<tr><th bgcolor="gray">%s</th>%s</tr>' % (i, ''.join(cols)) rows.append(row) html=u''' <html> <head><title>Einmaleins</title></head> <body> <table border="1"> <tr> <th>&nbsp;</th> %s </tr> %s </table> </body> </html>''' % (''.join(heading), ''.join(rows)) temp='%s.html' % tempfile.mktemp() fd=open(temp, 'w') fd.write(html) fd.close() webbrowser.open(temp) # Bei Mozilla oder Firefox muss ggf. noch 'strg-r' (Reload) gedrückt werden. #--------------------------------------------------------------------- #Beispiel SCRIPTDIR: #Script-Verzeichnis finden: #Oft stehen im Verzeichnis des Scripts zusätzliche Dateien (z.B. Bilder) #Das Verzeichnis in dem das Script steht #erhält man wie folgt: import os import sys scriptdir=os.path.abspath(os.path.dirname(sys.argv[0])) print 'Scriptdir:', scriptdir #--------------------------------------------------------------------- #Beispiel STACKTRACE: #Stacktrace einer Exception als String #Anwendung: Fehler bei einer Web-Anwendung als Email #verschicken: def foo(): raise Exception('Das ist eine Exception') try: foo() except Exception: import traceback exc_string=''.join(traceback.format_exc()) print exc_string # raise ohne Argumente führt ein 're-raise' aus: #Die aufgefangene Exception wird wieder ausgelöst raise # Hinweis: Eine 'catch-all' Regel, die alle Exceptions auffängt # sollte vermieden werden. Normalerweise sollte man # nur bestimmte Exceptions auffangen. Beispiel: i='abc' try: i=int(i) except ValueError: print '%r ist keine Ganzzahl' % i #--------------------------------------------------------------------- #Beispiel KONFIG: #Parsen einfacher Konfig-Dateien #Variable=Wert import re fd=open('myapp.config') for line in fd: line=line.strip() # Leerzeichen am Anfang und Ende entfernen if not line: continue # Überspringe leere Zeilen if line.startswith('#'): continue # Überspringe Kommentarzeilen match=re.match(r'(.*?)\s*=\s*(.*)$', line) # Regulärer Ausdruck assert match, 'Syntax Fehler in folgender Zeile: %s' % line variable=match.group(1) wert=match.group(2) print '%s --> %s' % (variable, wert) #--------------------------------------------------------------------- #Beispiel DICTTEMPLATE: #HTML im Quelltext ist nicht schön. Noch schlimmer finde ich jedoch, #Programmierung in HTML wie bei PHP. #Dem 'magischen' Prozentzeichen kann man auch ein Dictionary übergeben. #Zum Beispiel locals() (Dictionary der lokalen Variablen) import time heute=time.strftime('%d.%m.%Y') title='Das ist der Titel' # Wird zweimal verwendet (Im Kopf, und als <h1>) html=u''' <html> <head> <title>%(title)s</title> </head> <body> <h1>%(title)s</title> ... Heute ist der %(heute)s .... </body> </html>''' % locals() print html #--------------------------------------------------------------------- #Beispiel LISTCOMPREHENSION: #Listcomprehension verwende ich selten, da man genauso mit einer #Schleife arbeiten kann: #Mit Listcomprehension staedte=['Augsburg', 'Bremen', 'Hamburg', 'Berlin'] staedte_mit_b=[s for s in staedte if s.startswith('B')] print staedte_mit_b #Mit Schleife staedte_mit_b=[] for s in staedte: if s.startswith('B'): staedte_mit_b.append(s) print staedte_mit_b #--------------------------------------------------------------------- #Beispiel OWNEXCEPTIONS: #Eigene Exceptions # #Hinweis: Das Auffangen aller Exceptions sollte vermieden werden, #da Fehler wie MemoryError, KeyboardInterrupt oder ZeroDivisionError #nicht stillschweigend übergangen werden sollten. class MyException(Exception): pass def test_func(): raise MyException('Test') try: test_func() except MyException, exc: print 'Fehler: %s' % str(exc) # --> 'Fehler: Test' #--------------------------------------------------------------------- #Beispiel DATETIME: #Rechnen mit Tagen import datetime heute=datetime.date.today() gestern=heute - datetime.timedelta(days=1) morgen=heute + datetime.timedelta(days=1) print gestern, heute, morgen #--------------------------------------------------------------------- #Beispiel MTIME ZU DATETIME: #mtime zu datetime import os import datetime mtime=os.path.getmtime('/etc/fstab') # Wert: Sekunden seit 1970 datetime.datetime.fromtimestamp(mtime) # High-Level Datumsangabe #--------------------------------------------------------------------- #Beispiel SETS: #Mengenlehre bis_fuenf = set([1, 2, 3, 4, 5]) gerade = set([2, 4, 6, 8, 10]) vereinigung = bis_fuenf | gerade # Union schnittmenge = bis_fuenf & gerade # Intersection differenz = bis_fuenf - gerade print 'Mengenlehre', vereinigung, schnittmenge, differenz #--------------------------------------------------------------------- # Beispiel WRAPPER: # Einen Funktionsaufruf mit allen Argumenten weiterleiten. # Sie wollen einen Wrapper (Hülle/Mantel) um eine Funktion programmieren, # um vor und nach dem Funktionsaufruf bestimmte Dinge zu tun. Zum Beispiel: # Mittels Locking den eine Datei sperren. Mit '*args' und '**kwargs' # (Keywordarguments) geht das ganz einfach: def myfunc(a, b, c, name='...'): print a, b, c, name def wrapper(*args, **kwargs): # Vorbereitungen ... myfunc(*args, **kwargs) # Aufräumarbeiten wrapper(1, 2, 3, name='Till') #--------------------------------------------------------------------- # Beispiel HOME: # Unter Unix hat jeder Nutzer ein Home-Verzeichnis. Meist steht der Pfadname in # der Umgebungsvariable HOME (os.environ['HOME']). Manchmal steht diese # Variable jedoch nicht zu Verfügung. So kann man das HOME-Verzeichnis bekommen: import os import pwd home=pwd.getpwuid(os.getuid())[5] #--------------------------------------------------------------------- # Beispiel os.walk(): # Das Unix-Tool 'find' durchsucht Verzeichnisse rekursiv. # In Python kann man dafür die Funktion os.walk() verwenden. # Damit die Ergebnisse reproduzierbar sind, empfiehlt es sich # die Verzeichnisse und Dateien vor dem durchforsten zu sortieren. # In diesem Beispiel werden alle Verzeichnisse übersprungen die 'temp' # oder 'tmp' heißen und Dateien die mit '.pyc' enden. import os start='.' for root, dirs, files in os.walk(start): dirs[:]=[dir for dir in sorted(dirs) if not dir in ['temp', 'tmp']] # inplace Modifikation. for file in sorted(files): if file.endswith('.pyc'): continue file=os.path.join(root, file) print file #--------------------------------------------------------------------- # Beispiel ETREE: # Die Bibliothek ElementTree bietet eine einfache API um mit XML-Daten # zu arbeiten. Einfache XPath Suchen sind möglich: from xml.etree import ElementTree etree=ElementTree.fromstring('<?xml version="1.0"?><root><test attr="value" /></root>') print etree.findall('.//test') #--------------------------------------------------------------------- # Beispiel Descriptoren # An einer unbekannten Stelle wird das Attribut 'x' einer Klasse gesetzt. Wie # kann man diese Stelle finden? Siehe auch http://docs.python.org/howto/descriptor.html # Mit einem entsprechenden Descriptor kann man zB beim Setzen der Variable # eine Exception werfen: class ExceptionRaiser(object): def __set__(self, instance, value): raise AttributeError('instance=%r value=%r' % (instance, value)) class ClassToDebug(object): # Bestehende Klasse, deren Attribut Zugriff untersucht werden soll pass r=ClassToDebug() r.__class__.x=ExceptionRaiser() # Diese Stelle soll gefunden werden: r.x=1
# -*- coding: utf-8 -*- # Unterscheidung fehlt, ob es geschafft wurde oder # ob das Spiel beendet wurde # SONDERFALL # In Python kann man Schleifen mit einem else-Fall # versehen geheimnis = 1234 versuch = 0 while versuch != geheimnis: versuch = int(input("Raten Sie: ")) if versuch > geheimnis: print("zu gross") if versuch < geheimnis: print("zu klein") if versuch == 0: print("Spiel beendet") break else: print("Geschafft")
# -*- coding: utf-8 -*- def func(a, b): print("Id der Instanz in der Funktion", id(a)) print("Id der Instanz in der Funktion", id(b)) #p = 1 #q = [1,2,3] #print("Id der Instanz", id(p)) #print("Id der Instanz", id(q)) #print(func(p, q)) # Unsichere Listen def func1(liste): liste[0] = 42 liste += [5,6,7,8,9] #zahlen = [1,2,3,4] #print(zahlen) #print(func1(zahlen)) #print(zahlen) def func2(a=[1,2,3]): a += [4,5] print(a) func2() func2() func2() func2() # IMMUTABLE None -> Save def func3(a=None): if a is None: a = [1,2,3] print(a) func3() func3() func3() func3()
# -*- coding: utf-8 -*- class A: def __init__(self): self._X = 100 def getX(self): return self._X def setX(self, wert): if wert < 0: return self._X = wert X = property(getX, setX) # Der Zugriff auf X wird mit Property # auf die getX und setX Methode gesetzt # Sie werden automatisch implizit genutzt a = A() print(a.X) a.X = 300 print(a.X) a.X = -20 print(a.X)
import os import sys fileList = [] rootdir = sys.argv[1] for root, subFolders, files in os.walk(rootdir): for file in files: fileList.append(os.path.join(root,file)) print fileList #================================================================================ # List of all the files, total count of files and folders & Total size of files. #================================================================================ import os import sys fileList = [] fileSize = 0 folderCount = 0 rootdir = sys.argv[1] for root, subFolders, files in os.walk(rootdir): folderCount += len(subFolders) for file in files: f = os.path.join(root,file) fileSize = fileSize + os.path.getsize(f) #print(f) fileList.append(f) print("Total Size is {0} bytes".format(fileSize)) print(“Total Files “, len(fileList)) print(“Total Folders “, folderCount)
# -*- coding: utf-8 -*- a = 7 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) print(a % b)
# -*- coding: utf-8 -*- """ Entspricht einem Delay """ import time, threading def wecker(gestellt): print("RIIIIIIIIIING!!!") print("Der Wecker wurde um {0} Uhr gestellt.".format(gestellt)) print("Es ist {0} Uhr".format(time.strftime("%H:%M:%S"))) timer = threading.Timer(30, wecker, [time.strftime("%H:%M:%S")]) # Timer start -> T minus 30 Sekunden # bis RIIIIIIIIIIING timer.start()
#! /usr/bin/env python #coding=utf-8 """This script generates a random circle wallpaper Range of values to get from can be adjusted below to create a more artistic wallpaper based on colour theory""" from random import randint # Document size WIDTH, HEIGHT = (1920, 1200) circles = [] blurs = [] # Make x number of circles and blur filters for id in range(20): # Get random values x_position = randint(0, 1920) y_position = randint(300, 900) radius = randint(20, 250) # The range can be limited to use more exact colours r_colour = randint(0, 255) g_colour = randint(0, 255) b_colour = randint(0, 255) colour = "#%x%x%x"%(r_colour, g_colour, b_colour) # I've used opacities between 20% and 80% to keep it more even opacity = "0.%s"%(randint(20, 80)) # I have no idea what the range for this is but inkscape suggests between 0.001 and 250 blur_amount = "%s.%s"%(randint(1, 25), randint(0, 100)) # Append circle xml to a list circles.append("""<circle cx="%s" cy="%s" r="%s" style="stroke:black; stroke-width:2; fill:%s; opacity:%s; filter:url(#blur%s);" />"""%(x_position, y_position, radius, colour, opacity, id)) # Append filter xml to another list blurs.append("""<filter id="blur%s" width="1.5" height="1.5"> <feGaussianBlur in="SourceGraphic" stdDeviation="%s"/> </filter>"""%(id, blur_amount)) # Bring it all together svg = """<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="%s" height="%s" version="1.1" xmlns="http://www.w3.org/2000/svg"> <defs> <linearGradient id="linearGradient"> <stop id="stop1" style="stop-color:#08559d;stop-opacity:1" offset="0" /> <stop id="stop2" style="stop-color:#741175;stop-opacity:1" offset="1" /> </linearGradient> <radialGradient cx="733.01025" cy="526.61871" r="625.84656" fx="733.01025" fy="526.61871" id="gradient" xlink:href="#linearGradient" gradientUnits="userSpaceOnUse" gradientTransform="matrix(3.7820774,2.7550586e-8,0,2.1400777,-1812.3015,-527.00498)" /> %s </defs> <rect width="%s" height="%s" style="fill:url(#gradient)" /> %s </svg>"""%(WIDTH, HEIGHT, "\n".join(blurs), WIDTH, HEIGHT, "\n".join(circles)) # Save the svg wallpaper_file = open('drawing.svg', 'w') print >> wallpaper_file, svg
# -*- coding: utf-8 -*- import copy as c # Echte Kopie #s = [1,2,3] #t = c.copy(s) #print(s is t) # alles ok und wie erwartet #liste = [1, [2, 3]] #liste2 = c.copy(liste) #liste2.append(4) #print(liste) #print(liste2) # Manipulieren der inneren Liste -> nicht ok #liste2[1].append(1337) #print(liste) #print(liste2) #print(liste[1] is liste2[1]) # Loesung -> deepcopy #liste = [1, [2, 3]] #liste2 = c.deepcopy(liste) #liste2.append(4) #print(liste) #print(liste2) #print(liste[1] is liste2[1]) # Geaenderte MeineKlasse class MeineKlasse: def __init__(self): self.Liste = [1,2,3] def getListe(self): return c.deepcopy(self.Liste) def zeigeListe(self): print(self.Liste) # Original wird manipuliert instanz = MeineKlasse() liste = instanz.getListe() liste.append(1337) instanz.zeigeListe()
import numpy as np import nltk from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords para = """A warm welcome to you all. I am here to deliver a speech on India. India is one of the ancient civilizations in the world and is also the 7th largest country in the world. India is one of the best countries in the world for many reasons, acceptance of people of other religions, the closely bonded family culture, the biggest democratic nation, and the fastest-growing economy. With 1.3 billion of population India is the second-largest country in the world. India is God’s favorite country to be blessed with all seasons – spring, summer, monsoon, autumn, pre-winter, and winter. People around the world also recognize India for its Bollywood stardom and Beauty pageants.""" sentences = nltk.sent_tokenize(para) Lemitizer = WordNetLemmatizer() for i in range(len(sentences)): words = nltk.word_tokenize(sentences[i]) worrds = [Lemitizer.lemmatize(word) for word in words if word not in set(stopwords.words('english'))] sentences[i] = ' '.join(words)
# 34. Find First and Last Position of Element in Sorted Array import math class Solution: def searchRange(self, nums: list, target: int) -> list: # binary search left = 0 right = len(nums) - 1 if right == -1: return [-1, -1] while left <= right: mid = left + math.floor((right - left) / 2) if target == nums[mid]: break elif target < nums[mid]: right = mid - 1 else: left = mid + 1 if target == nums[mid]: left = right = mid while left - 1 >= 0 and nums[left - 1] == target: left -= 1 while right + 1 < len(nums) and nums[right + 1] == target: right += 1 return [left, right] else: return [-1, -1] if __name__ == "__main__": import time start = time.clock() s = Solution() test_case = [1] target = 3 ans = s.searchRange(test_case, target) print(ans) end = time.clock() print('Running time: %s ms' % ((end - start) * 1000))
# 123. Best Time to Buy and Sell Stock III class Solution: def maxProfit(self, prices: list) -> int: return 1 if __name__ == "__main__": import time start = time.clock() s = Solution() test_case = 0 ans = s.function(test_case) print(ans) end = time.clock() print('Running time: %s ms' % ((end - start) * 1000))
# 155. Min Stack class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.size = 0 def push(self, x): """ :type x: int :rtype: None """ if self.size and x > self.stack[self.size - 1][1]: self.stack.append((x, self.stack[self.size - 1][1])) else: self.stack.append((x, x)) self.size += 1 def pop(self): """ :rtype: None """ self.stack.pop() self.size -= 1 def top(self): """ :rtype: int """ if self.size: return self.stack[self.size - 1][0] else: return None def getMin(self): """ :rtype: int """ if self.size: return self.stack[self.size - 1][1] else: return None if __name__ == "__main__": import time start = time.clock() minStack = MinStack() minStack.push(-2) minStack.push(0) minStack.push(-3) print(minStack.getMin()) minStack.pop() print(minStack.top()) print(minStack.getMin()) end = time.clock() print('Running time: %s ms' % ((end - start) * 1000))
# 114. Flatten Binary Tree to Linked List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ self.rebuild(root) def rebuild(self, root): if not root: return None left_head = self.rebuild(root.left) right_head = self.rebuild(root.right) left_rear = left_head if left_rear: while left_rear.right: left_rear = left_rear.right left_rear.right = right_head root.right = left_head else: root.right = right_head root.left = None return root if __name__ == "__main__": import time start = time.clock() a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) d = TreeNode(4) e = TreeNode(5) f = TreeNode(6) a.left = b b.left = c b.right = d a.right = e e.right = f s = Solution() s.flatten(a) while a: print(a.val) a = a.right end = time.clock() print('Running time: %s ms' % ((end - start) * 1000))
# 988. Smallest String Starting From Leaf from collections import deque # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): min_str = 'z' * 1000 def smallestFromLeaf(self, root): """ :type root: TreeNode :rtype: str """ self.dfs(root, '') return self.min_str def dfs(self, root, cur_str): cur_str += chr(97 + root.val) if root.left == None and root.right == None: if cur_str[::-1] < min_str: min_str = cur_str[::-1] else: if root.left: self.dfs(root.left, cur_str) if root.right: self.dfs(root.right, cur_str) # def build_tree(self, tree_arr): # node_num = len(tree_arr) # if node_num == 0: # return None # root = TreeNode(tree_arr[0]) # queue = deque([]) # queue.append(root) # index = 0 # while len(queue): # tmp_node = queue.popleft() # index += 1 # if index < node_num and tree_arr[index]: # tmp_node.left = TreeNode(tree_arr[index]) # queue.append(tmp_node.left) # index += 1 # if index < node_num and tree_arr[index]: # tmp_node.right = TreeNode(tree_arr[index]) # queue.append(tmp_node.right) # return root if __name__ == "__main__": import time start = time.clock() tree_arr = [0,1,2,3,4,3,4] s = Solution() ans = s.smallestFromLeaf(A, tree_arr) print(ans) end = time.clock() print('Running time: %s ms' % ((end - start) * 1000))
# 215. Kth Largest Element in an Array class Solution: def findKthLargest(self, nums: 'List[int]', k: 'int') -> 'int': low = 0 high = len(nums) - 1 k = len(nums) - k while low < high: pivot = self.partition(nums, low, high) if pivot > k: high = pivot - 1 elif pivot < k: low = pivot + 1 else: return nums[pivot] return nums[k] def partition(self, nums, low, high): i = low + 1 j = high p = nums[low] while True: while nums[i] < p and i < high: i += 1 while p < nums[j] and j > low: j -= 1 if i >= j: break self.swap(nums, i, j) print(nums) self.swap(nums, low, j) print(nums) return j def swap(self, nums, i, j): tmp = nums[i] nums[i] = nums[j] nums[j] = tmp if __name__ == "__main__": import time start = time.clock() s = Solution() ans = s.findKthLargest([3,2,3,1,2,4,5,5,6], 4) print(ans) end = time.clock() print('Running time: %s ms' % ((end - start) * 1000))
# 448. Find All Numbers Disappeared in an Array class Solution: def findDisappearedNumbers(self, nums: 'List[int]') -> 'List[int]': for i in range(len(nums)): while nums[i] != i + 1 and nums[nums[i] - 1] != nums[i]: tmp = nums[i] nums[i] = nums[nums[i] - 1] nums[tmp - 1] = tmp ans = [] for i, ele in enumerate(nums): if ele != i + 1: ans.append(i + 1) return ans if __name__ == "__main__": import time start = time.clock() s = Solution() ans = s.findDisappearedNumbers([4,3,2,7,8,2,3,1]) print(ans) end = time.clock() print('Running time: %s ms' % ((end - start) * 1000)) # [4,3,2,7,8,2,3,1] # [7,3,2,4,8,2,3,1] # [1,2,3,4,3,2,7,8]
# -*- coding: utf-8 -*- print "I will now count my chickens:" print "Hens", 25 + 30 /6 # %is qiuyu print "Roosters", 100 - 25 *3 % 4 print "Now i will count the eggs:" print 3 + 2 + 1- 5 + 4 % 2 - 1 / 4 + 6 print "Is it true that 3+2<5-7?" print 3 + 2 < 5 - 7 print "oh, that's why it's False." print "How about some more." print " is it greater?", 5 >= -2 print "Is it less or equal?", 5 <= -2 print 1/4 # the result is 0 #test floating point number print 20.0 print 7.0/4.0 print 7/4 print 1/3 # the result is 0 print 1.0/3.0 # the result is 0.333333
# coding: utf-8 i = 0 numbers = [] while i < 6: print "At the top i is %d" % i numbers.append(i) i = i + 1 print "Numbers now: ", numbers print "The numbers: " for num in numbers: print num #testing a = 0 variables = 10 use = 2 lists1 = [] while a < variables: print "At the top a is %d" % a lists1.append(a) a = a + use print "lists now: ", lists1 print "The lists: " for num in lists1: print num # use for-loop: list2 = [] for c in range(0, 7): print "now c is %d" % c list2.append(c) print "now list2 is:", list2
""" Answer to https://adventofcode.com/2018/day/6 """ from typing import List from collections import namedtuple class Point(object): def __init__(self, x: int, y: int, map=None): self.x = x self.y = y self.map = map def __str__(self): return '(%d, %d)' % (self.x, self.y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self == other def __hash__(self): if self.map is None: raise ValueError('Cannot compute raster position without a map') return (self.y - self.map.first_point.y) * self.map.width + (self.x - self.map.first_point.x) def distance(self, x: int, y: int): """Manhattan distance""" return abs(x - self.x) + abs(y - self.y) Zone = namedtuple('Zone', ['point', 'area']) class Map(object): def __init__(self, pois: List[Point], first_point: Point, width: int, height: int): self.pois = [] self.width = width self.height = height self.closest_raster = None self.distance_raster = None def raster_sort(p: Point): # Not using property because we cannot really do it yet return (p.y - first_point.y) * width + (p.x - first_point.x) self.pois = sorted([Point(p.x, p.y, self) for p in pois], key=raster_sort) def _populate_rasters(self): if self.closest_raster is not None and self.distance_raster is not None: return closest_raster = [] # 2D raster of List[Point] (closest) distance_raster = [] # 2D raster of int (sum of all distances) assert self.first_point.x >= 0 assert self.first_point.y >= 0 for y in range(self.height): closest_row = [] distance_row = [] for x in range(self.width): rv, total = self.closest(x + self.first_point.x, y + self.first_point.y) closest_row.append(rv) distance_row.append(total) closest_raster.append(closest_row) distance_raster.append(distance_row) self.closest_raster = closest_raster self.distance_raster = distance_raster def closest(self, x: int, y: int): # -> Tuple[List[Point], int] closest_d = self.first_point.distance(x, y) closest = [self.first_point] total_distances = closest_d for p in self.pois[1:]: # if x == p.x and y == p.y: # return [p] # It's on the point c = p.distance(x, y) total_distances += c if c < closest_d: closest = [p] closest_d = c elif c == closest_d: closest.append(p) return closest, total_distances def danger_zones(self): self._populate_rasters() # Find all zones on the corner of the raster and add them to the ignore list ignore_poi = set() for y, line in enumerate(self.closest_raster): if y == 0 or y == len(self.closest_raster): for points in line: if len(points) != 1: # Ignore ties for infinite continue ignore_poi.add(points[0]) else: if len(line[0]) == 1: ignore_poi.add(line[0][0]) if len(line[-1]) == 1: ignore_poi.add(line[-1][0]) print('Ignoring infinite areas from points %s' % ', '.join([str(p) for p in ignore_poi])) superficy = { point: None if point in ignore_poi else 0 for point in self.pois } for line in self.closest_raster: for col in line: if len(col) == 1: # Ignore the points that are equidistant to multiple POI point = col[0] if superficy[point] is not None: # Superficy count is None if they are on the edge superficy[point] += 1 return sorted([ Zone(k, v) for k, v in superficy.items() ], key=lambda v: v.area if v.area is not None else -1, reverse=True) def common_zone(self, max_dist: int): self._populate_rasters() print('Looking for common zone within a distance of %d' % max_dist) interesting_points = [] for y, line in enumerate(self.distance_raster): for x, col in enumerate(line): if col < max_dist: interesting_points.append(Point(self.first_point.x + x, self.first_point.y + y, self)) return interesting_points @property def first_point(self): # -> Point if not self.pois: raise ValueError('No points of interests') return self.pois[0] @classmethod def from_file(cls, filename: str): # -> Map coordinates = [] mins = None maxs = None with open(filename) as f: for l in f.readlines(): p = Point(*[int(p) for p in l.replace(' ', '').rstrip().split(',')]) coordinates.append(p) if mins is None: mins = Point(p.x, p.y) maxs = Point(p.x, p.y) else: mins.x = min(mins.x, p.x) mins.y = min(mins.y, p.y) maxs.x = max(maxs.x, p.x) maxs.y = max(maxs.y, p.y) print('Loading %d coordinates from %s (zone from %s to %s)' % ( len(coordinates), filename, str(mins), str(maxs), )) assert mins.x >= 0 assert mins.y >= 0 width = maxs.x - mins.x + 1 height = maxs.y - mins.y + 1 return cls( coordinates, mins, width, height ) if '__main__' == __name__: coordinates = Map.from_file('input.txt') print('Computing biggest zone within %d' % (coordinates.width * coordinates.height)) biggest = coordinates.danger_zones()[0] print('Biggest (non-infinite) zone is from point %s and covers an area of %d.' % ( str(biggest.point), biggest.area )) # 3260 dist = 10000 common_zone = coordinates.common_zone(dist) print('Safest zone with %d of all points is an area of %d.' % (dist, len(common_zone))) # 42535
import re from file_converter.column_types import DATE_TYPE, NUMERIC_TYPE, STRING_TYPE class ValueFormatter: """ Factory to return a ValueFormatter class corresponding to each type of data """ @staticmethod def validate_format(data_value): pass @staticmethod def convert(data_value): pass @staticmethod def factory(data_type): if data_type == DATE_TYPE: return DateFormatter elif data_type == NUMERIC_TYPE: return NumericFormatter elif data_type == STRING_TYPE: return StringFormatter raise Exception("Data type not supported : {}".format(data_type)) class DateFormatter(ValueFormatter): @staticmethod def validate_format(data_value): regex = re.compile(r'[0-9]{4}-[0-9]{2}-[0-9]{2}') return re.fullmatch(regex, data_value.strip()) @staticmethod def convert(data_value): return "/".join(reversed(data_value.strip().split("-"))) class NumericFormatter(ValueFormatter): @staticmethod def validate_format(data_value): regex = re.compile(r'[-+]?\d*\.\d+|\d+') return re.fullmatch(regex, data_value.strip()) @staticmethod def convert(data_value): return data_value.strip() class StringFormatter(ValueFormatter): @staticmethod def validate_format(data_value): return True @staticmethod def convert(data_value): if ',' in data_value: return '"{}"'.format(data_value.strip()) else: return data_value.strip()
#snakeEyes.py #Will Schick #5/8/2018 #Driver module that uses the Die class to repeatedly roll two dice until snake eyes are rolled. #Imports from die import Die def main(): #Declare our dice die1 = Die() die2 = Die() #init (Randomizes our face values) die1.roll() die2.roll() #While we don't have snake eyes while (die1.getValue() + die2.getValue()) != 2: #Update (Reroll our die) die1.roll() die2.roll() #Print the roll of our die, this comes after update so that it will print 1,1 at the end print(die1.getValue() , die2.getValue()) #Since our while statement doesn't stop until snake eyes, we're good print("Snake Eyes!!!!") main()
#stringProcessing.py #Will Schick #8:37 - 4/9/2018 # # ## RETURNS THE LOCATION OF THE FIRST DIGIT. -1 if no digits -------------------------------------------------- def firstDigit(string): i = 0 while i < len(string): if string[i].isdigit(): return i #Update i = i + 1 return -1 #----------------------------- ## Returns the location of the last digit. -1 if no digits -------------------------------------------------- def lastDigit(string): i = len(string) - 1 while i >= 0: if string[i].isdigit(): #If the current index is a number return i #Return the index position return -1 #If the search has gone through the entire string and found no digit this will trigger #---------------------------------- ##COUNT THE UPPERCASE LETTERS IN A STRING ------------------------------------------ def countUppercase(string): uppercaseLetters = 0 i = 0 while i < len(string): if string[i].isupper(): uppercaseLetters = uppercaseLetters + 1 #update i = i + 1 return uppercaseLetters ##EditCreditCard------------------------------------------------------------------ def editCreditCard(oldCard): #Setup i = 0 newCard = "" #Loop through the indicies while i < len(oldCard): #grab the character char = oldCard[i] if char.isdigit(): newCard = newCard + char
from temp import Temperature def main(): temp1 = Temperature() #Test Getters print("Testing getCelsius() and getFahrenheit().") print("Celsius temperuture should be 0.00 and is %.2f" % temp1.getCelsius()) print("Fahren. temperature should be 32.00 and is %.2f" % temp1.getFahrenheit()) print() #Test setCelsius, needs getCelsius and getFahrenheit to test print("Testing setCelsius.") temp1.setCelsius(15.2) print("Celsius temperuture should be 15.20 and is %.2f" % temp1.getCelsius()) print("Fahren. temperature should be 59.36 and is %.2f" % temp1.getFahrenheit()) print() #Test setFahrenheit, needs getCelsius and getFahrenheit to test print("Testing setFahrenheit.") temp1.setFahrenheit(92.5) print("Celsius temperuture should be 33.61 and is %.2f" % temp1.getCelsius()) print("Fahren. temperature should be 92.50 and is %.2f" % temp1.getFahrenheit()) print() #Test string representation, needs setCelsius and setFahrenheit to test print("Testing string representation.") temp2 = Temperature() print("Should be 0.00 C and is %7s" % temp2) temp2.setCelsius(16.73456) print("Should be 16.73 C and is %7s" % temp2) temp2.setFahrenheit(71.45) print("Should be 21.92 C and is %7s" % temp2) main()
# stringThings.py # # Created by: R. Givens # Modified by: Will Schick on 4/10/2018 @ 1:41 PM # # Module containing several functions that process strings. ##Loop through the indices and count the amount of digits def countDigits(string): i = 0 digitCount = 0 while i <= (len(string) - 1): if string[i].isdigit(): digitCount = digitCount + 1 i = i + 1 return digitCount ##Take the string and return itself printed backwards def reverseString(string): i = (len(string) -1) reversedString = "" while i >= 0: #Body reversedString = reversedString + string[i] #Update i = i - 1 return reversedString ##Returns true if the string is a palindrome def isPalindrome(word): reversedString = reverseString(word) #Call reverseString established above if word.upper() == reversedString.upper(): #Are they equivalent? return True else: return False ##Returns the middle character of an odd string, two middle characters if even def middleChar(string): if len(string) < 1: #Proofing for a blank string input return "" if len(string) % 2 == 0: #Even character = string[(len(string) - 1) //2] character2 = string[((len(string) - 1) //2) + 1] return character + character2 else: #Odd return string[(len(string) - 1) // 2] ##Repeats a phrase interspersed with a delimiter def repeatPhrase(string, num, delim): i = 0 finalString = "" while i < num: #Body finalString = finalString + string if i == (num - 1): #If we're on the last repetition, end the function early so an extra delim can't be added return finalString finalString = finalString + delim #Add the delim on if there are more repetitions to come #Update i = i + 1 return finalString ##Checks against several parameters to determine if a given password is valid def passwordCheck(password): i = 0 digits = 0 #Amount of numbers in the password symbol = False #If there is a symbol used capital = False #If the user inputs a capital letter lowerCase = False #If the user inputs a lowerCase letter while i <= (len(password) - 1): #Body if password[i] in "!@#$%&*": #Check for symbols symbol = True if password[i].isupper(): capital = True if password[i].islower(): lowerCase = True if password[i].isdigit(): digits = digits + 1 #Update i = i + 1 print(digits) if digits >= 2 and symbol == True and capital == True and lowerCase == True and i >= 8: #Upper and lowercases, 2 digits, 8 or more total characters return True else: return False
#gameOfNim.py #Will Schick #3/22/2018 from math import * from random import * #Contents-------------------------------------------------------------------------- #Constants #Welcome player #Randomly choose amount of sticks #Randomly choose who goes first #Loop ( Gameplay ) #Player who drew the last stick loses PLAYER = "You" COMPUTER = "The computer" #Welcome player--------------------------------------------------------------------- print() print("**********************************") print("*** WELCOME TO THE GAME OF NIM ***") print("**********************************") #Randomly choose amount of sticks-------------------------------------------------------- sticks = randint(25,50) print("Whoever draws the last stick loses.") print("You may draw multiple sticks at a time up to half the current number of sticks.") print() #Randomly choose who goes first---------------------------------------------------------- whoGoesFirst = randint(0,1) if whoGoesFirst == 0: turn = PLAYER else: turn = COMPUTER #Loop ( Gameplay ) --------------------------------------------------------------------- #Init withdrawError = False print(turn, "will go first") while sticks > 1: withdrawError = False #If the player's turn has been reset due to error, set the error bool back to False #Body print() print("There are", sticks, "sticks left in the pile") if turn == PLAYER: #If it's the player's turn print() print("You can withdraw up to half the current total (",sticks//2,").") withdraw = int(input("Choose an amount of sticks to withraw from the stack: ")) #Input stick withdraw if withdraw <= 0 or withdraw > sticks//2: #If the withdraw is invalid print() print("---" * 5) print("Error - input a valid number of sticks!") print("---" * 5) withdrawError = True elif withdraw == 1: #Grammar- if the player withdraws only one stick. print("You withdraw just one stick.") sticks = sticks - withdraw else: print("You withdraw", withdraw, "sticks.") sticks = sticks - withdraw else: #If it's the computer's turn #Computer takes sticks computerWithdraw = randint(1,sticks//2) sticks = sticks - computerWithdraw if (computerWithdraw == 1): #Grammar- if the computer withdraws only one stick. print("The computer withdraws just one stick.") else: print("The computer withdraws", computerWithdraw, "sticks.") #Update if turn == PLAYER and withdrawError == False: turn = COMPUTER else: turn = PLAYER #Player who drew the last stick loses --------------------------------------------------------------------- print() print("There is only one stick left in the pile...") if (turn == PLAYER): print("It is your turn...") print("You draw the last stick!") print("You lose!") else: print() print("It is the computer's turn...") print() print("They draw the last stick!") print() print("CONGRATULATIONS!!!")
class BST: '''Represents a binary search tree''' def __init__ (self, head=None): '''initialize the BST''' #None #| #head #/ \ #None None self.tree = [None,head,None,None] def left_of(self, index): '''get index left of current index''' return index * 2 def right_of(self, index): '''get index right of current index''' return (index * 2) + 1 def insert(self, value): '''insert new node into tree''' def inner_insert(self, value, index_pointer): '''traverse tree to find insertion point''' if self.tree[index_pointer] == None: #base case first return 1 elif value <= self.tree[index_pointer]: left = self.left_of(index_pointer) #base case if self.tree[left] == None: return left #recurse case else: return inner_insert(self, value, left) else: right = self.right_of(index_pointer) #base case if self.tree[right] == None: return right #recurse case else: return inner_insert(self, value, right) new_index = inner_insert(self, value, 1) #The None nodes are a good way to identify the end of the tree #due to the way python inserts new elements to a list, # list.insert(100,1) will actually insert at the smallest element # which is less than 100 #we have to do something hacky and inneficient def force_expand(self, start, end): for x in range(start-1,end+1): try: temp = self.tree[x] except IndexError: self.tree.insert(x,None) force_expand(self, len(self.tree), self.right_of(self.right_of(new_index))) self.tree.insert(new_index, value) def delete(self, value): '''delete value from tree''' def inner_delete(self, value, index): '''traverse tree to find deletion point''' if value == self.tree[index]: #base case self.delete_at(index) elif self.tree[index] == None: #null base case return None elif value < self.tree(index): #recurse left self.delete(value, left_of(index)) elif value > self.tree(index): #recurse right self.delete(value, right_of(index)) self.inner_delete(value,1) def delete_at(self, index): '''delete node from tree''' self.tree[index] = self.tree[left_of(index)] if self.tree[index] != None: #recurse self.delete_at(left_of(index)) def print_tiered(self, blanks = False): level_count = 0 level_cap = 1 out_strings = [] for x in range(1,len(self.tree)): if self.tree[x] != None: out_strings.append(self.tree[x]) elif blanks: out_strings.append('_') level_count += 1 if level_count == level_cap: if out_strings != []: print(out_strings) out_strings = [] level_cap *= 2 level_count = 0
'''平方根格式化 描述 获得用户输入的一个整数a,计算a的平方根,保留小数点后3位,并打印输出。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬ 输出结果采用宽度30个字符、右对齐输出、多余字符采用加号(+)填充。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬ 如果结果超过30个字符,则以结果宽度为准。''' a=input() print('{:+>30.3f}'.format(pow(eval(a),1/2)))
if __name__ == '__main__': n = int(input()) number = "" if 1 <= n <= 150: x = 1 while x <= n: print(x, end="") x += 1 else: print("Enter the number between 1 to 150")
""" Course: EE2703-Applied Programming Lab Name: Nihal Gajjala Roll Number: EE19B044 Assignment 1 """ from sys import argv, exit # Assigning Constant Variables CIRCUIT='.circuit' END='.end' # Validating The Number Of Arguments if len(argv)!=2: print('\nUsage: %s <inputfile>' %argv[0]) exit() # Validating The File Name try: # Opening And Reading The File with open(argv[1]) as f: lines=f.readlines() start=-1 end=-2 # Locating The Beginning And End Of The Circuit By Checking For .circuit And .end for line in lines: if CIRCUIT==line[:len(CIRCUIT)]: start=lines.index(line) elif END==line[:len(END)]: end=lines.index(line) break # Validating The Content In The Netlist i.e, Checking If .circuit And .end Are Placed Correctly if start>=end or start<0 or end<0: print('Invalid circuit definition') exit(0) # Traverse The Circuit Definition From Last Element To First Element And Print Each Line With Words In Reverse Order while end-1>start: ''' Removing Blank Spaces At The Beginning Removing Comments After '#' Splitting The String Into A List With Space As Separator ''' line1=lines[end-1].split('#')[0].split() # Reversing The Order Of The Contents In The Given List line2=reversed(line1) # Joining The Contents Of The List Using spaces line3=' '.join(line2) # Printing The Final Line print(line3) end-=1 # Closing The File f.close() # Printing Error Message For A Wrong Filename except IOError: print('Invalid file') exit()
""" Course: EE2703-Applied Programming Lab Name: Nihal Gajjala Roll Number: EE19B044 End Semester Exam """ # Importing Libraries import numpy as np import pylab # Function To Calculate Rijkl def calc(l): return np.linalg.norm(np.tile(rijk,(100,1,1,1)).reshape((100,3,3,3,1000))-np.hstack((r_vector,np.zeros((100,1)))).reshape((100,3,1,1,1)),axis=1) ''' Rijkl = | rijk - rl | .reshape - Gives A New Shape To An Array Without Changing Its Data np.hstack - Stacks Arrays In Sequence Horizontally (Column Wise) np.linalg.norm - Returns The Norm Of rijk - rl np.zeros - Returns An Array Of Given Shape And Type, Filled With Zeros ''' # Function To Calculate The Current Along x-direction And y-direction def current(x,y): return np.array([-np.sin(np.arctan(y/x)),np.cos(np.arctan(y/x))]) ''' np.array - Constructs An Array np.arctan - Tangent Inverse Function np.cos - Cosine Function ''' # Creating Meshgrid # Size Along x Direction = 3 # Size Along y Direction = 3 # Size Along z Direction = 1000 x=np.linspace(0,2,num=3) # Constructing An Array Of Evenly Spaced Numbers Over A Specified Interval y=np.linspace(0,2,num=3) # Constructing An Array Of Evenly Spaced Numbers Over A Specified Interval z=np.linspace(0,999,num=1000) # Constructing An Array Of Evenly Spaced Numbers Over A Specified Interval X,Y,Z=np.meshgrid(x,y,z) # Creating Coordinate Matrices From Coordinate Vectors # Declaring The Radius Of Wire And Number Of Sections It Is Divided Into radius=10 # Radius Of Wire sections=100 # Number Of Sections # Radius Vector -> (x - cos(phi), y - sin(phi)) r_vector=np.vstack((radius*np.cos(np.linspace(0,2*np.pi,sections)).T,radius*np.sin(np.linspace(0,2*np.pi,sections)).T)).T # dl Vector -> (x - Acos(phi), y - Asin(phi)) # A = np.pi/5 dl_vector=2*np.pi*radius/sections*np.vstack((np.cos(np.linspace(0,2*np.pi,sections)).T,np.sin(np.linspace(0,2*np.pi,sections)).T)).T # Phi phi=np.linspace(0,2*np.pi,sections) # Position Vector rijk=np.array((X,Y,Z)) ''' .T - Transposes The Array np.array - Constructs An Array np.cos - Cosine Function np.sin - Sine Function np.linspace - Constructs An Array Of Evenly Spaced Numbers Over A Specified Interval np.vstack - Stacks Arrays In Sequence Vertically (Row Wise) ''' # Plotting Current Elements In x-y Plane pylab.figure(1) pylab.plot(r_vector[:,0],r_vector[:,1],'ro',markersize=2.5) # Plotting y vs x As Lines And Markers pylab.xlabel(r'x-axis$\rightarrow$',fontsize=15) # Setting The Label For The x-axis pylab.ylabel(r'y-axis$\rightarrow$',fontsize=15) # Setting The Label For The y-axis pylab.title('Current Elements In x-y Plane',fontsize=15) # Setting Title Of The Graph pylab.grid() # Displaying The Grid pylab.show() # Displaying The Figure # Currents Along x-direction And y-direction ix,iy=current(r_vector[:,0],r_vector[:,1]) # Calculating x And y Component Of Current Using 'current' Function # Plotting Current Direction In x-y Plane pylab.figure(2) pylab.quiver(r_vector[:,0],r_vector[:,1],ix,iy,scale=50,headwidth=10,headlength=10,width=0.001) ''' Plotting A 2-D Field Of Arrows r_vector[:,0] - The x Coordinates Of The Arrow Locations r_vector[:,1] - The y Coordinates Of The Arrow Locations ix - The x-direction Components Of The Arrow Vectors iy - The y-direction Components Of The Arrow Vectors scale - The Arrow Length Unit headwidth - Head Width As Multiple Of Shaft Width headlength - Head Length As Multiple Of Shaft Width width - Shaft Width In Arrow Units ''' pylab.xlabel(r'x-axis$\rightarrow$',fontsize=15) # Setting The Label For The x-axis pylab.ylabel(r'y-axis$\rightarrow$',fontsize=15) # Setting The Label For The y-axis pylab.title('Current In Wire In x-y Plane',fontsize=15) # Setting Title Of The Graph pylab.grid() # Displaying The Grid pylab.show() # Displaying The Figure Rijkl=calc(0) # Calculating Rijkl Using 'calc' Function cosine=np.cos(phi).reshape((100,1,1,1)) # Construction Cosine Vector dl=dl_vector[:,0].reshape((100,1,1,1)) # dl Vector Component Along x-direction Ax=np.sum(cosine*dl*np.exp(1j*Rijkl/10)*dl/Rijkl,axis=0) # Potential Along x-direction dl=dl_vector[:,1].reshape((100,1,1,1)) # dl Vector Component Along y-direction Ay=np.sum(cosine*dl*np.exp(1j*Rijkl/10)*dl/Rijkl,axis=0) # Potential Along y-direction ''' j - Imaginary Unit np.cos - Cosine Function np.exp - Exponential Function np.sum - Summation Function ''' Bz=(Ay[1,0,:]-Ax[0,1,:]-Ay[-1,0,:]+Ax[0,-1,:])/(4) # Calculating Magnetic Field magneticField=(np.zeros(1000).T,np.zeros(1000).T,Bz.T) # Vectorizing Magnetic Field ''' Magnetic Field Is Zero Along x-direction Magnetic Field Is Zero Along y-direction Magnetic Field Is Bz Along z-direction ''' # Plotting Magnetic Field Along z-axis pylab.figure(3) pylab.loglog(z,np.abs(Bz)) # Making A Plot With Log Scaling On Both The Axis pylab.xlabel(r'z-axis$\rightarrow$',fontsize=15) # Setting The Label For The x-axis pylab.ylabel(r'B(Magnetic Field)$\rightarrow$',fontsize=15) # Setting The Label For The y-axis pylab.title('Magnetic Field Along z Axis',fontsize=15) # Setting Title Of The Graph pylab.grid() # Displaying The Grid pylab.show() # Displaying The Figure # Solving For B Using Least Squares A=np.hstack([np.ones(len(Bz[300:]))[:,np.newaxis],np.log(z[300:])[:,np.newaxis]]) log_c,b=np.linalg.lstsq(A,np.log(np.abs(Bz[300:])),rcond=None) [0] # Returns log(c) and b c=np.exp(log_c) # Exponential Function print("The Value Of b is:") print(b) # Printing The Value Of 'b' In The Terminal print("The Value Of c is:") print(c) # Printing The Value Of 'c' In The Terminal
#How to read a text file from Hard Disk #test.txt file is already there in current dir fileObj = open("test.txt") '''FileNotFoundError: [Errno 2] No such file or directory: 'test1.txt' ''' #read a file content data = fileObj.read() print("File Content: ", data) print('\n\n') print(open('../test.txt').read()) print('\n\n') print(open('In/test.txt').read()) #close the file fileObj.close()
'''(Replace text) Write a program that replaces text in a file. Your program should prompt the user to enter a filename, an old string, and a new string. Here is a sample run: Enter a filename: test.txt Enter the old string to be replaced: morning Enter the new string to replace the old string: afternoon ''' def start(file): f=open(file,'r') data=f.read() word=input("Enter the word\n") subs=input("Enter the word to be replaced\n") data=data.replace(word,subs) print(data) f.close() f=open(file,'w') f.write(data) f.close() if __name__=='__main__': import os getFile=input("Enter the file name along with the extension\n") if os.path.exists(getFile): start(getFile) else: print("The file does not exists")
#import csv module import csv#read the file in r mode f = open("students.txt", "r") #csv.reader() takes delimiter readercsv = csv.reader(f, delimiter='\t')#iterate the content for line in readercsv: print(line)
board = {'7': ' ' , '8': ' ' , '9': ' ' , '4': ' ' , '5': ' ' , '6': ' ' , '1': ' ' , '2': ' ' , '3': ' '} player_list = {"player 1":"X", "player 2":"O"} #track who is the current player current_player = "player 1" def change_player(curr_player): global current_player if curr_player == "player 1": current_player = "player 2" else: current_player = "player 1" def get_key(val): for key, value in player_list.items(): if val == value: return key #Check before next move if any one of the players win the game def check(): winning_combinations = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[3,5,7],[1,5,9]] for i in winning_combinations: if (board[str(i[0])] == board[str(i[1])] == board[str(i[2])] != " " ): print_board() print(str(get_key(board[str(i[0])])+ " you win!")) return True return False def print_board(): print("|",board["7"],"|", board["8"],"|",board["9"], "|") print("|",board["4"],"|", board["5"],"|",board["6"], "|") print("|",board["1"],"|", board["2"],"|",board["3"], "|") def display_board(): print("|","7","|","8","|","9", "|") print("|","4","|","5","|","6", "|") print("|","1","|","2","|","3", "|") #Prompt current player to fill in one of the squares with X or O #Detect wrong user input(space already filled, invalid number, non-numerical input) and prompt the user to try again def move(): print("Please enter a number from 1 to 9 when it is your turn to play.") print("The board now looks like this:") print_board() while True: move_position = input("It is your turn "+current_player+", Which place do you want to move to?") if move_position.isnumeric() == False: print("Non numerical input, please try again.") elif int(move_position) > 9: print("Invalid input.Please put in a number between 1 and 9.") elif board[move_position] != " ": print("Space occupied. Please choose another position.") else: board[move_position] = player_list[current_player] break #play again or quitting ipt = " " #Keep track of how many rounds are played to check if it is a tie i = 0 while ipt != "exit": while i < 9: #print("Player 1 starts first.") print("This is the corresponging position of numeber 1 to 9 onboard: ") display_board() move() if check() == True: break change_player(current_player) i = i + 1 if check() == False: print("It is a draw!\n") print_board() ipt = input("Type exit or type anything else to try again: ") board = {'7': ' ' , '8': ' ' , '9': ' ' , '4': ' ' , '5': ' ' , '6': ' ' , '1': ' ' , '2': ' ' , '3': ' '} current_player = "player 1" i = 0
import math relative = 0 for i in range(1,479001599 ): #print(i,":",end="") #print ("The gcd of 21 and ",i," is : ",end="") #print (math.gcd(21,i),end="") if(math.gcd(21,i) == 1): #print(" this is relative") relative += 1 else: pass #print() print("ϕ(n) = ",relative)
#Hackerrank Challenge #Given five positive integers, find the minimum and maximum values #that can be calculated by summing exactly four of the five integers. def miniMaxSum(arr): arr.sort() print(sum(arr[:4]), sum(arr[1:])) def miniMaxSum(arr): print(sum(arr)-max(arr),end=" ") print(sum(arr)-min(arr)) arr=list(map(int ,input().rstrip().split())) miniMaxSum(arr) #Hackerrank Challenge #given list of integers, give ratio of parities summary = { "pos" : 0, "neg" : 0, "nil" : 0 } def parity(i): if i < 0: summary["neg"] += 1 elif i > 0: summary["pos"] += 1 else: summary["nil"] += 1 def plusMinus(arr): for i in arr: parity(i) print("%0.6f" % (summary["pos"] / len(arr))) print("%0.6f" % (summary["neg"] / len(arr))) print("%0.6f" % (summary["nil"] / len(arr))) #Hackerrank Challenge #convert AM/PM to military time def timeConversion(s): s = re.sub("AM$", "", s) (s, i) = re.subn("PM$", "", s) if i > 0: hour = int(s[0:2]) + 12 if hour < 24: s = re.sub("^\d\d", str(hour), s) else: s = re.sub("^12", "00", s) return s #Hackerrank Challenge: offset k characters # The function accepts following parameters: # 1. STRING s # 2. INTEGER k # # a = 97, z = 122 # A = 65, Z = 90 def caesarCipher(s, k): offset = (k % 26) result = "" print(ord("Z")) for l in s: if l.isalpha(): i = ord(l) if i < 91: z = 90 else: z = 122 i += offset if i > z: i -= 26 result += chr(i) else: result += l return result #If k == 1, a -> b and Z -> A #JSON #compact print(json.dumps(result, separators=(',', ':'))) #Help below derived from https://www.w3schools.com/python/default.asp #Collection ordered changeable duplicates #List y y y #Dictionary y y n #Tuple y n y #Set n n n #Lists #Initialize: list1 = ["apple", "banana", "cherry"] #get list1[-1] #last #change list1[1] = "pair" list1[1:3] = ["blackcurrant", "watermelon"] #range #actions list1.append("pair") list1.insert(0, "pair") list1.extend(others) #append onto list1 list1.remove("pair") list1.pop(0) del list1[0] list1.clear() del list1 #delete #loops for x in list1: print(x) for i in range(len(list1)): print(list1[i]) i = 0 while i < len(thislist): print(thislist[i]) i = i + 1 #loop with List Comprehension [print(x) for x in thislist] #long way: for x in fruits: if "a" in x: newlist.append(x) #list comprehension: newlist = [x for x in fruits if "a" in x] #sorting list1.sort() list1.sort(reverse = True) list1.sort(key = myfunc) #case insensitive: list1.sort(key = str.lower) list1.reverse() #copy list1.copy() newlist = list(list1) #join list3 = list1 + list2 list1.update(list2) #count matches list1.count("apple") #range(i) creates list from 0 to < i #range(start, stop, step) x = range(6) for n in x: print(n) #0, 1, 2, 3, 4, 5 #Dictionaries #initialize thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } #get thisdict["brand"] thisdict.get("brand") #ordered as of 3.7 #keys thisdict.keys() #loop on keys for x in thisdict: print(x) #values thisdict.values() #loop on values for x in thisdict.values(): print(x) #key/value pairs thisdict.items() #loop for x, y in thisdict.items(): print(x, y) #test key "model" in thisdict #modify #if key new, add #if key present, change value thisdict["year"] = 2018 thisdict.update({"year": 2020}) #change key: thisdict[new_key] = thisdict.pop(old_key) #remove thisdict.pop("model") del thisdict["model"] #clear thisdict.clear() #copy mydict = thisdict.copy() mydict = dict(thisdict) #nested (multi-dimensional) myfamily = { "child1" : { "name" : "Emil", "year" : 2004 }, "child2" : { "name" : "Tobias", "year" : 2007 }, "child3" : { "name" : "Linus", "year" : 2011 } } #misc fromkeys() #Returns a dictionary with the specified keys and value popitem() #Removes the last inserted key-value pair setdefault() #Returns the value of the specified key. If the key does not exist: insert the key, with the specified value #lambda = anonymous function = macro x = lambda a, b : a * b print(x(5, 6)) # 5 * 6 #Regex import re txt = "The rain in Spain" x = re.search("^The.*Spain$", txt) findall #Returns a list containing all matches search #Returns a Match object if there is a match anywhere in the string split #Returns a list where the string has been split at each match sub #Replaces one or many matches with a string #Exceptions try: print(x) except: print("An exception occurred") #Less used data structures #Tuples #initialize: tuple1 = (1, 1, 5, 7, 9, 3) #get tuple1[0] #unpack (green, yellow, red) = fruits #work around to modify by casting into a list y = list(x) y[1] = "kiwi" x = tuple(y) #loops for x in thistuple: print(x) for i in range(len(thistuple)): print(thistuple[i]) i = 0 while i < len(thistuple): print(thistuple[i]) i = i + 1 #join tuple3 = tuple1 + tuple2 tuple1.update(tuple2) #multiply mytuple = fruits * 2 #count matches mytuple.count("apple") #find first index of value (exception if not found) mytuple.index("apple") #Sets #initialize myset = {"apple", "banana", "cherry"} #order not preserved #duplicates ignored #mixed types: set1 = {"abc", 34, True, 40, "male"} #test: "abc" in set1 #loop: for x in thisset: print(x) #add thisset.add("orange") #remove thisset.remove("orange") #error if not present thisset.discard("orange") #no error #remove last thisset.pop() #no order, so you don't know which #join thisset.update(tropical) set3 = set1.union(set2) #intersection z = x.intersection_update(y) #non-intersection z = x.symmetric_difference(y) #clear thisset.clear() #delete del thisset #misc copy() difference() difference_update() isdisjoint() issubset() issuperset() symmetric_difference_update() #__init__.py attempts to modify scope of imports: #!/usr/bin/env python import os, sys, importlib base = os.path.dirname(__file__) sys.path.append(base) for script in os.listdir(base): if script == '__init__.py' or script[-3:] != '.py': continue print("importing %s" % script[:-3]) module = importlib.import_module(script[:-3]) base = importlib.import_module(base.split("/")[-1]) #from script[:-3] import * symbols = [name for name in module.__dict__ if not name.startswith('_')] for symbol in symbols: print(" %s" % symbol) attr = getattr(module, symbol) print(attr) #setattr(base, symbol, getattr(module, symbol)) globals()[symbol] = attr #globals().update({name: module.__dict__[name] for name in symbols}) #__import__(script[:-3], locals(), globals()) #__import__(script[:-3], fromlist=symbols) del module
#method list=[1,2,3] list.append(4) list.pop() print(type(list)) print(list) myString= 'Hello' print(myString.upper()) print(type(myString))
website = "www.sadikturan.com" course= "Phyton Kursu: Baştan Sona Phyton Programlama Rehberiniz(40 saat)" #1- 'course' karakter diisinde kaç karakter bulunur? '''length= len(course) print(length)''' #2- 'website' içinden wwww karakterlerini alın. '''result=website[0:3] print(result)''' #3- 'website' içinden com karakterlerini alın. '''result= website[15:18] print(result)''' #4- 'course' içinden ilk 15 ve son 15 karakteri alın. '''result_1= course[0:14] result_2= course[-15:] print(result_1) print(result_2)''' #5- 'course' içerisindeki karakterleri tersten yazdır. '''result= course[::-1] print(result)''' #name, surname, age, job = 'Hatice Pınar','Ünal', 25, 'Mühendis' #6- yukarıda verilen ifadelerle aşağıdaki cümleyi yazdırın # 'Benim adımm Hatice Pınar Ünal, yaşım 25 ve mesleğim Mühendis.' '''print('Benim adım {} {} , yaşım {} ve mesleğim {}.'.format(name,surname, str(age), job))''' #7- 'Hello world!' ifadesindeki w karakterini W ile değiştirin. '''a= 'Hello world!' a= a[0:6]+'W'+a[-5:] a.replace('w', 'W') print(a)''' #8-'abc'ifadesini yanyana 3 defa yazdırın x= 'abc' print(str(x)*3)
'''sayilar=[1,3,5,7,9,12,19,21]''' #1-Sayılar listesindeki hangi sayılar 3'ün katıdır? '''for i in sayilar: if i%3==0: print(i)''' #2-Sayılar listesindeki sayıların toplamı kaçtır? '''sum=0 for i in sayilar: sum+=i print(sum)''' #3-Sayılar listesindeki tek sayıların karesini alın. '''for s in sayilar: sq=s**2 print(sq)''' sehirler=['kocaeli','istanbul','ankara','izmir','rize'] #4-Şehirlerden hangileri en fazla 5 karakterlidir? '''for c in sehirler: if len(c)<=5: print(c)''' urunler=[ {'name': 'Samsung S6', 'price':'3000'}, {'name': 'Samsung S7', 'price':'4000'}, {'name': 'Samsung S8', 'price':'5000'}, {'name': 'Samsung S9', 'price':'6000'}, {'name': 'Samsung S10', 'price':'7000'} ] #5-Ürünlerin fiyatları toplamı nedir? '''sum=0 for u in urunler: sum+=int(u['price']) print(sum)''' #6-Ürünlerden fiyatı en fazla 5000 olan ürünleri gösteriniz. for u in urunler: if int(u['price'])<=5000: print(u)
def not_hesapla(satir): satir= satir[:-1] #satır aalarındaki boşluğu kaldırdık liste= satir.split(':') OgrenciAdi=liste[0] notlar=liste[1].split(',') not1= int(notlar[0]) not2= int(notlar[1]) not3= int(notlar[2]) ortalama= (not1+not2+not3)/3 if ortalama>=90 and ortalama<=100: harf = 'AA' elif ortalama>=85 and ortalama<=89: harf='BA' elif ortalama>=80 and ortalama<=84: harf='BB' elif ortalama>=75 and ortalama<=79: harf='CB' elif ortalama>=70 and ortalama<=74: harf='CC' elif ortalama>=65 and ortalama<=69: harf='DC' elif ortalama>=60 and ortalama<=64: harf='DD' elif ortalama >=50 and ortalama <=59: harf ='FD' else: harf='FF' return OgrenciAdi+":"+harf+"\n" def ortalamalari_oku(): with open("sinav_notlari.txt", "r", encoding= "utf-8") as file : for satir in file: print(not_hesapla(satir)) def notlari_gir(): ad =input('Öğrencinin Adı:') soyad = input('Öğrencinin Soyadı:') not1 = input('Not 1:') not2 = input('Not 2:') not3 = input('Not 3:') with open("sinav_notlari.txt", "a", encoding="utf-8") as file: file.write(ad+' '+soyad+':'+not1+','+not2+','+not3+'\n') def notlari_kaydet(): with open("sinav_notlari.txt", "r",encoding= 'utf-8') as file: liste=[] for i in file: liste.append(not_hesapla(i)) with open("sonuclar.txt", 'w', encoding='utf-8') as file2: for i in liste: file2.write(i) while True: islem=input('1-Ortalamaları Oku\n2-Notları Gir\n3-Notları Kaydet\n4-Çıkış\n') if islem=='1': ortalamalari_oku() elif islem=='2': notlari_gir() elif islem=='3': notlari_kaydet() else: break
list=[1, 2, 3] tuple=(1, 'iki', 3) """print(type(list)) print(type(tuple)) print(list[2]) print(tuple[2]) print(len(list)) print(len(tuple))""" #listelerde karakter değişikliği yapılabilir ama tuple larda değişiklik yapılamaz list=['Damla', 'Ayşe'] tuple=('Ali', 'Veli', 'Ayşe', 'Ayşe') names=('Hatice', 'Pınar', 'Elif', 'Pelin')+ tuple list[0]= 'Ahmet' #tuple[0]= 'Ahmet' print(list) print(tuple.count('Ayşe')) print(tuple.index('Ayşe')) print(names)
#Inheritance (Kalıtım): Miras alma #Person => name, lastname, age, eat(), run(), drink() #Student(Person), Teacher(Person) #Animal=> Dog(Animal), Cat(Animal) class Person(): def __init__(self, fname, lname): self.firstName=fname self.lastName=lname print('Person Created') def who_am_i(self): print('I am a person.') def who_eat(self): print('I am eating') class Student(Person): def __init__(self, fname, lname, number): Person.__init__(self, fname, lname) self.studentNumber=number print('Student Created') #override def who_am_i(self): print('I am a stutent.') def sayHello(self): print('Hello, I am a student.') class Teacher(Person): def __init__(self,fname,lname,branch): super().__init__(fname, lname) self.branch= branch def who_am_i(self): print(f'I am a {self.branch} teacher.') p1= Person('Hatice','Ünal') s1= Student('Pınar', 'Ünal', 1233) t1=Teacher('Pınar' , 'Ünal', 'Math') print(p1.firstName +' ' + p1.lastName) print(s1.firstName +' ' + s1.lastName+ ' '+ str(s1.studentNumber)) p1.who_am_i() s1.who_am_i() p1.who_eat() s1.who_eat() s1.sayHello() t1.who_am_i()
#class class Person: # pass #yer tutar, kodun hata vermeden devamını sağlar #class attributes adress='no information' #constructur def __init__(self,name,year): #object attributes self.name= name self.year= year #methods #object,instance p1= Person('Pınar',1995) p2=Person('Zehra',1993) print(f'name: {p1.name} , year: {p1.year} , adress: {p1.adress}' ) print(f'name: {p2.name} , year: {p2.year}, adress: {p2.adress}')
from abc import abstractmethod, ABC from typing import Any, Iterable class BaseTextPreprocessor(ABC): """ Abstract class for base text explainer """ @abstractmethod def build_vocab(self, text: str): """Build the vocabulary (all words that appear at least once in text) :param text: a list of sentences (strings) :type text: list """ pass @abstractmethod def preprocess(self, data: Iterable[Any]) -> Iterable[Any]: """ Converts data into another iterable :param data text to preprocess :type data: Iterable[Any] :return: Iterable type of preprocessed text :rtype Iterable[Any] """ pass @abstractmethod def decode_single(self, id_list: Iterable[Any]) -> Iterable[Any]: """ Decodes a single list of token ids to tokens :param id_list: list of token ids :type id_list: List :return: list of tokens :rtype list """ pass @abstractmethod def generate_tokens(self, sentence: str) -> Iterable[Any]: """ Abstract mehtod to generate tokens for a given sentence :param sentence: Sentence to be tokenized :type sentence: str :return: A list of tokens :rtype Iterable[Any] """ pass def get_tokenizer(self) -> Any: """ Abstract class to get tokenzier of this preprocessor :return Tokenizer """ pass
from urllib import request from bs4 import BeautifulSoup as bs import re import nltk import heapq def text_summarizer(input, max_sentences): sentences_original = nltk.sent_tokenize(input) # if (max_sentences > len(sentences_original)): # print("Error, number of requested sentences exceeds number of sentences inputted") # input = "Today we know that machines have become smarter than us and can help us with every aspect of life, the technologies have reached to an extent where they can do all the tasks of human beings like household tasks, controlling home devices, making appointments etc. The field which makes these things happen is Machine Learning. Machine Learning train the machines with some data which makes it capable of acting when tested by the similar type of data. The machines have become capable of understanding human languages using Natural Language Processing. " \ # "Today researches are being done in the field of text analytics." allParagraphContent_cleanerData = re.sub(r'\[[0-9]*\]', ' ', input) allParagraphContent_cleanedData = re.sub(r'\s+', ' ', allParagraphContent_cleanerData) sentences_tokens = nltk.sent_tokenize(allParagraphContent_cleanedData) allParagraphContent_cleanedData = re.sub(r'[^a-zA-Z]', ' ', allParagraphContent_cleanedData) allParagraphContent_cleanedData = re.sub(r'\s+', ' ', allParagraphContent_cleanedData) # print(allParagraphContent_cleanedData) words_tokens = nltk.word_tokenize(allParagraphContent_cleanedData) # print(words_tokens) ## cal frequency stopwords = nltk.corpus.stopwords.words('english') # print(stopwords) # stopwords=nltk.corpus.stopwords.words('english') word_frequencies = {} for word in words_tokens: if word not in stopwords: if word not in word_frequencies.keys(): word_frequencies[word] = 1 else: word_frequencies[word] += 1 # print(word_frequencies) maximum_frequency_word = max(word_frequencies.values()) for word in word_frequencies.keys(): word_frequencies[word] = (word_frequencies[word] / maximum_frequency_word) # print(word_frequencies) sentences_scores = {} for sentence in sentences_tokens: for word in nltk.word_tokenize(sentence.lower()): if word in word_frequencies.keys(): if (len(sentence.split(' '))) < 30: if sentence not in sentences_scores.keys(): sentences_scores[sentence] = word_frequencies[word] else: sentences_scores[sentence] += word_frequencies[word] # print(sentences_scores) summary_MachineLearning = heapq.nlargest(max_sentences, sentences_scores, key=sentences_scores.get) # print(summary_MachineLearning) #summary = ' '.join(summary_MachineLearning) return (summary_MachineLearning)
import numpy as np def newton_multivar(fun,var,xi,tol=1.0e-12,maxiter=100000): """ Multivariate Newton root-finding using automatic differentiation. INPUTS ======= fun: an autodiff Operation or Array object whose roots are to be computed. var: an array of autodiff Var objects that are independent variables of fun. xi: an array of initial guesses for each variable in var. tol (optional, default 1e-12): the stopping tolerance for the 2-norm of residual. maxiter (optional, default 100000): the maximum number of iterations. RETURNS ======= root: the root to which the method converged. res: the 2-norm of the residual. Niter: the number of iterations performed. traj: the trajectory taken by each variable through successive iterations. Each column of traj corresponds to an independent variable in var. """ h = np.ones(len(var)) # initial step size for v,val in zip(var,xi): v.set_value(val) traj = np.array(xi) b = fun.value Niter = 0 while (np.sqrt(sum([v**2 for v in fun.value]))>tol and Niter<maxiter): J = fun.grad(var) h = -np.linalg.solve(J,b) for v,step in zip(var,h): v.set_value(v.value+step) traj = np.vstack([traj,[v.value for v in var]]) b = fun.value Niter += 1 root = [v.value for v in var] res = np.sqrt(sum([v**2 for v in fun.value])) return root,res,Niter,traj
# Set the initial state # Tile A has value 1, B has value 2, C has value 3, agent has value 4 and the rest blank tiles have value 0 initial_state = [1, 0, 0, 0, 4, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0] # Set the goal state goal = [0, 0, 0, 0, 4, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0] # Create a class for initializing a node # The state of the node, its parent, the movement which has been made, the cost of the movement and the depth of the node are included class Node: def __init__(self, state, parent, action, cost, depth): self.state = state self.parent = parent self.action = action self.cost = cost self.depth = depth # Function for movement # When direction is up, the procedure is described in details. The rest directions have the same logic def movement(state, direction): # copy the state new_state = list(state) # find the index of the agent index = new_state.index(4) # if the agent goes up if direction == "up": if index not in range(4): # find the value of the tile where the agent is going to move temp = new_state[index - 4] # move the agent to the new location new_state[index - 4] = new_state[index] # set the value, that was temporaryy stored, to the tile that the agent was located new_state[index] = temp return new_state # if the agent goes down if direction == "down": if index not in range(12, 16): temp = new_state[index + 4] new_state[index + 4] = new_state[index] new_state[index] = temp return new_state # if the agent goes left if direction == "left": if index not in range(0, 16, 4): temp = new_state[index - 1] new_state[index - 1] = new_state[index] new_state[index] = temp return new_state # if the agent goes right if direction == "right": if index not in range(3, 16, 4): temp = new_state[index + 1] new_state[index + 1] = new_state[index] new_state[index] = temp return new_state # if the agent is unable to move due to his position on the grid, return None else: return None # Visualise the grid world def display_board(state): # if none state is given, pass the function if state == None: pass else: # copy the list new_state_disp = state[:] # find the location of the tiles A, B, C and agent index_a = new_state_disp.index(1) index_b = new_state_disp.index(2) index_c = new_state_disp.index(3) index_agent = new_state_disp.index(4) # replace the values with their visual form new_state_disp[index_a] = 'A' new_state_disp[index_b] = 'B' new_state_disp[index_c] = 'C' new_state_disp[index_agent] = 'X' new_state_disp = [x if x != 0 else " " for x in new_state_disp] # print the grid print("-----------------") print("| %s | %s | %s | %s |" % (new_state_disp[0], new_state_disp[1], new_state_disp[2], new_state_disp[3])) print("-----------------") print("| %s | %s | %s | %s |" % (new_state_disp[4], new_state_disp[5], new_state_disp[6], new_state_disp[7])) print("-----------------") print("| %s | %s | %s | %s |" % (new_state_disp[8], new_state_disp[9], new_state_disp[10], new_state_disp[11])) print("-----------------") print( "| %s | %s | %s | %s |" % (new_state_disp[12], new_state_disp[13], new_state_disp[14], new_state_disp[15])) print("-----------------") # Expand node with the possible movements def expand_node(node): # initialise the list for expanded nodes expanded_nodes = [] # for each movement, create a new node and store it to the list expanded_nodes.append(Node(movement(node.state, "up"), node, "up", node.cost + 1, node.depth + 1)) expanded_nodes.append(Node(movement(node.state, "down"), node, "down", node.cost + 1, node.depth + 1)) expanded_nodes.append(Node(movement(node.state, "left"), node, "left", node.cost + 1, node.depth + 1)) expanded_nodes.append(Node(movement(node.state, "right"), node, "right", node.cost + 1, node.depth + 1)) # delete the nodes that there is no movement able to be made expanded_nodes = [node for node in expanded_nodes if node.state != None] return expanded_nodes def bfs(start, goal): # initialise the list of the nodes for exploration/expansion list_bfs = [] # Insert the initial state list_bfs.append(Node(start, None, None, 0, 0)) # initialise the list that stores which nodes were expanded explored = [] counter = 0 # set a constant which is used to break the loop if the solution is found flag = 0 while flag != -1: # if there are no nodes left for expansion if len(list_bfs) == 0: flag = -1 return None, len(explored) # use the first node of the list (FIFO) node = list_bfs.pop(0) print("node state") display_board(node.state) # check if this node is the goal if node.state == goal: # if it is, initialise a list which will contain the actions of the agent moves = [] # temporary save the node in a variable temp = node # while there movements left while True: # insert each movement at the begining of the list moves.insert(0, temp.action) # if the state is one after the initial state if temp.depth == 1: # stop the loop break # swap place of the child with its parent temp = temp.parent # terminate the while loop flag = -1 # return the moves that the agent did plus the nodes expanded return moves, len(explored) # store the expanded node to the relevant list explored.append(node.state) # create the children of the node children = expand_node(node) for child in children: if child.depth == 4: flag = -1 list_bfs.append(child) if child.depth < 3: print("BFS with depth: " + str(child.depth)) display_board(child.state) result, amount = bfs(initial_state, goal)
from sys import argv script, filename = argv txt = open(filename) print("Here's your file %r" %filename) print(txt.read()) txt.close() print("Type the filename again:") filename_again = input(">") txt_again = open(filename_again) print(txt_again.read()) txt_again.close()
def print_two(*args): arg1, arg2 = args print("arg1: %r, arg2: %r" %(arg1, arg2)) def print_two_again(arg1, arg2): print("arg1: %r, arg2: %r" %(arg1, arg2)) def print_one(arg1): print("arg1: %r" %arg1) def print_none(): print("none") print_two("a", "b") print_two_again("a", "b") print_one('aaa') print_none()
class User: def __init__(self, name, balance): self.name = name self.balance = balance def withdrawl(self,amount): self.balance -= amount print (self.name,self.balance) return self def deposit(self, amount): self.balance += amount print (f'{self.name},{self.balance}') return self user1 = User(name = "mario", balance = 500) user2 = User(name = "joe", balance = 800) user3 = User(name = "moe", balance = 400) user2.withdrawl(200) user1.withdrawl(150) user3.withdrawl(200) user1.deposit(200) user1.deposit(300) user2.deposit(300) user2.deposit(400) user2.withdrawl(500) user3.deposit(300) user3.withdrawl(400) user3.withdrawl(100)