text
stringlengths
37
1.41M
# This class creates and displays graphs to illustrate solutions import matplotlib.pyplot as plt # Used to show the positions of the locations on the grid def ShowPositions(locations): locationsx = [] locationsy = [] for x in range(len(locations)): locationsx.append(locations[x][0]) locationsy.append(locations[x][1]) plt.scatter(locationsx,locationsy) plt.title('Travelling salesman problem') print("\nYou must close the graph before carrying on\n") plt.show() # Shows the route taken between all of the points on the grid def DisplayRoute(locations): locationsx = [] locationsy = [] for x in range(len(locations)): locationsx.append(locations[x][0]) locationsy.append(locations[x][1]) plt.title('Travelling salesman problem') plt.scatter(locationsx,locationsy) plt.plot(locationsx,locationsy) print("\nYou must close the graph before carrying on\n") plt.show()
""" What was the max amount of snow per date? """ from mrjob.job import MRJob import mrjob class Snow_days(MRJob): INPUT_PROTOCOL = mrjob.protocol.RawProtocol def mapper(self, key, line): all_data = line.split(",") yield "key",key if all_data[4] and float(all_data[4]) > 0: yield all_data[3], float(all_data[4]) def reducer(self, date, snow): if str(date) != "key": tl,ts=0,0 alldata=[] for i in snow: tl+=1 ts+=i alldata.append(i) yield "avg snow on "+date, ts/tl yield "avg snow on "+date, sum(alldata)/len(alldata) yield "max snow on "+date, max(alldata) # yield "max", "by date" # yield date, max(snow) else: yield "key",list(snow) if __name__ == "__main__": Snow_days.run()
word = input() length = 0 for i in range(len(word)): for i2 in range(len(word)): if i2 >= i: newword = word[i:i2+1] if newword == newword[::-1]: if i2+1-i > length: length = i2+1-i print(length)
quarters = int(input()) machine = 1 m1 = int(input()) m2 = int(input()) m3 = int(input()) counts = 0 while quarters > 0: quarters -= 1 if machine == 1: m1 += 1 if m1%35 == 0: quarters += 30 machine = 2 elif machine == 2: m2 += 1 if m2%100 == 0: quarters += 60 machine = 3 else: m3 += 1 if m3%10 == 0: quarters += 9 machine = 1 counts += 1 print("Martha plays", counts, "times before going broke.")
#Generalize the above implementation of csv parser to support any delimiter and comments. import csv def parse_csv(): with open('sample.csv', newline='') as f: reader = csv.reader(f, delimiter=' ', quotechar='|') for row in reader: print(','.join(row)) parse_csv()
import numpy as np np.random.seed(25) def sigmoid(x,deriv=False): if deriv==True: return x*(1-x) return 1/(1+np.exp(-x)) X = np.array([[0,1,1],[1,0,1],[0,0,1],[1,1,0]]) Y = np.array([[1,1,0,0]]).T weight1 = 2*np.random.random((3,4))-1 weight2 = 2*np.random.random((4,1))-1 for j in range(50000): layer1 = X layer2 = sigmoid(np.dot(layer1,weight1)) layer3 = sigmoid(np.dot(layer2,weight2)) l3_error = Y - layer3 if j%10000==0: print("Error is "+str(np.mean(np.abs(l3_error)))) l3_del = l3_error * sigmoid(layer3,deriv=True) l2_error = l3_del.dot(weight2.T) l2_del = l2_error * sigmoid(layer2,deriv=True) weight2 += (layer2.T).dot(l3_del) weight1 += (layer1.T).dot(l2_del) print(" Output after training is : \n" +str(layer3))
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # !@Time :2019/7/19 10:17 # !@Author :will import threading class MyThread(threading.Thread): def __init__(self, func, args): threading.Thread.__init__(self) self.func = func self.args = args self.result = None def run(self): self.result = self.func(*self.args) def get_result(self): threading.Thread.join(self) # 等待线程执行完毕 return self.result def add(a, b): return a + b if __name__ == '__main__': task = MyThread(add, args=(2, 3)) task1 = MyThread(add, args=(4, 3, 1)) task.start() task1.start() a, b = task.get_result(), task1.get_result() print(a, b)
def brute(g,p,y) : i=2 sol = pow(g,i,p) if sol == y : return 2; if(y==g) : return 1 if(y==1) : return p-1 for i in range(3,p-1) : sol = pow(g,i,p) if sol == y : return i if __name__ == "__main__" : g,p,y = map(int,raw_input().split(' ')) print(brute(g,p,y))
#write a program to delete double space in a string st = "This is a string with double spaces" doubleSpaces = st.find(" ") print(doubleSpaces)
list_1 = ["apple", "banana", "orange", "peru"] print(list_1) #['apple', 'banana', 'orange', 'peru'] print(list_1[0]) #apple
i_want_drink = False i_want_food = False # if i_want_drink : # print ("Lets go to restaurant!") # else :print ("I'm good") # if i_want_drink : # print ("Lets go to restaurant!") # elif i_want_food :print ("I'm good") # else :print ("nope") if not i_want_drink :print ("Lets go to restaurant!")
# Evan Wiederspan # Advanced Python Lab 7: Producer and Consumer threads # 2-24-2017 from random import randrange from time import sleep from queue import Queue, Empty from myThread import MyThread NITEMS = 5 NREADERS = 3 WRITEDELAY = 2 finishedWriting = False def writeQ(queue, item): print('producing object {} for Q...'.format(item)) queue.put(item, True) print("size now {}".format(queue.qsize())) def readQ(queue, name): # needs to be marked as global so that it knows were not trying to make a local variable global finishedWriting while True: try: val = queue.get(False) print('{} consumed object {} from Q... size now {}'.format(name, val, queue.qsize())) return val # thrown when queue is empty except Empty: if not finishedWriting: print("{} is polling an empty queue".format(name)) sleep(WRITEDELAY) else: return None def writer(queue, loops): # needs to be marked as global so that it knows were not trying to make a local variable global finishedWriting for i in range(loops): sleep(randrange(1, 3)) writeQ(queue, i) finishedWriting = True def reader(queue, loops, name): # read will handle sleeping if the queue is empty # and will return None if the writer is finished # it intentionally does nothing with the data it returns, except # for making sure that it is not None while readQ(queue, name) != None: pass def main(): q = Queue(NITEMS) # create one write and NREADERS reader threads threads = [MyThread(writer, (q, NITEMS), 'writer')] + [MyThread(reader, (q, NITEMS, 'reader-' + str(i)), 'reader-' + str(i), True) for i in range(1,NREADERS+1)] for t in threads: t.start() for t in threads: t.join() print('all done') if __name__ == '__main__': main()
import re message = 'Call me on 415-555-1234 tommorow or on 415-555-9999 today' phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phone_num_regex.findall(message) print(mo) """" def is_phone_number(text): if len(text) != 12: return False for i in range(0, 3): if not text[i].isdecimal(): return False if text[3] != '-': return False for i in range(4, 7): if not text[i].isdecimal(): return False if text[7] != '-': return False for i in range(8, 12): if not text[i].isdecimal(): return False return True message = 'Call me on 415-555-1234 tommorow or on 415-555-9999 today' found_number = False for i in range(len(message)): chunk = message[i:i + 12] if is_phone_number(chunk): print(f'Phone number found: {chunk}') found_number = True if not found_number: print("Could not find any phone numbers") """
from math import * from sys import stdin,stdout def cross(v1, v2): #return the cross product of two vectors return (v1[0] * v2[1]) - (v1[1] * v2[0]) def angle_cmp(pivot): ''' receive a coord as the pivot and return a function for comparing angles formed by another two coords around the pivot ''' def _angle_cmp(c1, c2): v1 = c1[0] - pivot[0], c1[1] - pivot[1] v2 = c2[0] - pivot[0], c2[1] - pivot[1] cp = cross(v1, v2) if cp < 0: return 1 elif cp == 0: return 0 else: return -1 return _angle_cmp def turnning(c1, c2, c3): #detemine which way does c1 -> c2 -> c3 go v1 = c2[0] - c1[0], c2[1] - c1[1] v2 = c3[0] - c2[0], c3[1] - c2[1] cp = cross(v1, v2) if cp < 0: return 'RIGHT' elif cp == 0: return 'STRAIGHT' else: return 'LEFT' def graham_scan(coords): num = len(coords) if num < 3: raise Exception('too few coords') coords.sort() # select the leftmost coord as the pivot pivot = coords[0] coords = coords[1:] # for remaining coords, sort them by polar angle # in counterclockwise order around pivot coords.sort(angle_cmp(pivot)) # push the first three coords in a stack stack = [] stack.append(pivot) stack.append(coords[0]) stack.append(coords[1]) # for the rest of the coords, while the angle formed by # the coord of the next-to-top of the stack, coord of # top of stack and the next coord makes a nonleft turn, # pop the stack # also, push the next coord into the stack at each loop for i in range(2, num - 1): while len(stack) >= 2 and \ turnning(stack[-2], stack[-1], coords[i]) != 'LEFT': stack = stack[:-1] stack.append(coords[i]) return stack t = int(stdin.readline()) for _ in xrange(t): n = int(stdin.readline()) a = map(int,stdin.readline().split()) point = [] for i in xrange(len(a)-1): for j in xrange(i+1,len(a)): point.append((a[i],a[j])) ch = graham_scan(point) area = 0 for i in xrange(len(ch)): area += ch[i][0]*ch[(i+1)%len(ch)][1]-ch[i][1]*ch[(i+1)%len(ch)][0] stdout.write(str(abs(area))+"\n")
def mod_pow(x,y,p): res = 1 x = x % p while(y > 0): if((y & 1) == 1): res = (res * x) % p y = y >> 1 x = (x*x)%p return res n = int(input("Enter n : ")) c = int(input("Enter cipher text to decrypt : ")) m = int(input("Enter message to encrypt : ")) d = 1 while(mod_pow(c,d,n) != m): d = d+1 print(d)
# Second version of the exercise 'firstRepInList', which works for numbers # repeated more than two times. def firstRep(numList): # Define counters c1 = 0 c2 = 0 # Variables used to compare the index for each of the two iterations done. indRep = 0 guardRep = None for i in numList: c2 = c1 c1 = c1 + 1 for j in numList[c2+1:]: c2 = c2 + 1 if j == i: indRep = c2 if guardRep == None or guardRep > indRep: guardRep = indRep # Exit the second iterator as soon as the first repetition is # found. break # Return the first repeated number's index. return guardRep list = [1,2,5,6,1,6,1,2,3,6,7] repNumInd = firstRep(list) if repNumInd == 'None': print('There are no repeated numbers in the list',list) else: print('First repeated number:',list[repNumInd])
import urllib.request,urllib.parse,urllib.error # Request for the given url using urllib fhand = urllib.request.urlopen('http://data.pr4e.org') # Prepare to count the overall number of characters char = 0 for line in fhand: if len(line) < 1: print('No more info to show\n') break # Even more precise words = line.split() for word in words: # Finish condition if char >= 3000 or char + len(word) > 3000: break # Decodes incoming bytes and delets endlines print(word.decode()) # Counts number of displayed characters char = char + len(word) print('\n\nTotal displayed characters:',char)
import numpy as np def normalization(data): # data is a numpy multidim array minval=np.amin(data,axis=0) # axis=0 returns an array containing the smallest element for each column maxval=np.amax(data,axis=0) # Iterate over each column (feature) and compute the normalized value of each value in feature column for i in range(0,len(minval)): data[:,i]=(data[:,i]-minval[i])/(maxval[i]-minval[i]) return data def standardization(data): # data is a numpy multidim array meanval=np.mean(data,axis=0) # axis=0 returns an array containing the smallest element for each column std_dev=np.std(data,axis=0) # Iterate over each column (feature) and compute the normalized value of each value in feature column for i in range(0,len(meanval)): data[:,i]=(data[:,i]-meanval[i])/(std_dev[i]) return data def train_test_split(data): np.random.shuffle(data) # Shuffle datapoints randomly # Split training and testing data in 70:30 ratio training_set=data[0:936,:] testing_set=data[936:,:] return (training_set,testing_set)
import string ENCODING = 'UTF-8' def remove_punctuation(in_str): for p in string.punctuation: in_str.replace(p, '') return in_str def get_words(in_str): return remove_punctuation(in_str).split() def find_count_words(file_name, word): sum_w = 0 with open(file_name, 'r', encoding=ENCODING) as file: for line in file: list_words = get_words(line) sum_w = sum_w + list_words.count(word) return sum_w def run(file_name, word): count = find_count_words(file_name, word) print("В файле '" + file_name + "' частота вхождения слова '" + word + "' " + str(count)) run("Test.txt", "Иван")
# for num in range(0,100): # if num % 15 == 0: # print("FizzBuzz") # elif num % 3 == 0: # print("Fizz") # elif num % 5 == 0: # print("Buzz") # else: # print(num) str = "create a list of first letter of every word" lst = list() lst = ([word[0] for word in str.split()]) print(lst) for wrd in str.split(): if wrd[0].lower() == 'l': print(wrd)
#Lists #1:simple difference friends = ['joe','moe','poe'] for i in range(len(friends)): friend = friends[i] print('Happy New Year: ',friend) for friend in friends: print('Happy New Year: ',friend) #2: cal average numlist = list() while True: inp = input("enter a number:") if inp == "done" : break value = float(inp) numlist.append(value) average = sum(numlist) / len(numlist) print('Average of numbers: ', average) #3: strings in list text = 'my name is prateek masali ,' txt = text.split() print(txt) #4: arrange list friends = [ 'Joseph', 'Glenn', 'Sally' ] friends.sort() print(friends[0]) #5: find a pattern (working with dataset) xfile = open('/Users/prateekmasali/Desktop/Git/Python/mbox-short.txt') words = list() for line in xfile: line = line.rstrip() if not line.startswith('From ') : continue # print(line) words.append(line.split()) #Getting Distinct days for email was sent days = list() for i in words: if i[2] in days: continue days.append(i[2]) print(days) #6: # /Users/prateekmasali/Desktop/Git/Python/romeo.txt xfile = input("Enter the file:") fh = open(xfile) lst = list() buffer = list() for line in fh: buffer = line.split() for x in buffer: if x not in lst : lst.append(x) lst.sort() print(lst) #7: # /Users/prateekmasali/Desktop/Git/Python/mbox-short.txt xfile = input("Enter the file:") fh = open(xfile) count = 0 words = list() for line in fh: line = line.rstrip() if not line.startswith('From:'): continue words = line.split() print(words[1]) count += 1 print("There were", count, "lines in the file with From as the first word")
a = {"a": 1, "b": 2} print(a) a.update([("c", 3)]) print(a) a.update(dict(zip(['one', 'two'], [11, 22]))) print(a)
# -*- coding: utf-8 -*- # Copyright @ 2018 HuiXin Zhao from math import hypot class Vector: """ 一个简单的二维向量类 different between __repr__ and __str__: __repr__ goal is to be unambiguous __str__ goal is to be readable Container’s __str__ uses contained objects’ __repr__ __bool__: 我们自己定义的类的实例总被认为是真的,除非这个类对__bool__ 或者 __len__ 函数有 自己的实现。bool(x) 的背后是调用x.__bool__() 的结果;如果不存在 __bool__ 方法,那么 bool(x) 会尝试调用 x.__len__()。若返回 0,则 bool 会返回 False;否则返回True。 """ def __init__(self, x=0, y=0): self.x = x self.y = y '''__repr__会响应控制台''' def __repr__(self): return 'Vector(%r, %r)' % (self.x, self.y) '''__str__只会响应print和str(),如果没有__str__则找__repr__实现print和str()''' # def __str__(self): # return 'Vector(%r, %r)' % (self.x, self.y) def __abs__(self): return hypot(self.x, self.y) # def __bool__(self): # return bool(abs(self)) '''Improve:''' def __bool__(self): return bool(self.x or self.y) def __add__(self, other): x = self.x + other.x y = self.y + other.y return Vector(x, y) def __mul__(self, scalar): return Vector(self.x * scalar, self.y * scalar) '''使得 n * Vector(x, y)可用,即可以使用乘法交换律''' def __rmul__(self, scalar): return self * scalar
""" 所有的映射类型在处理找不到的键的时候,都会牵扯到 __missing__方法。这也是这个方法称作 “missing”的原因。虽然基类 dict 并没有定义这个方法,但是 dict 是知道有这么个东西存在的。也 就是说,如果有一个类继承了 dict,然后这个继承类提供了 __missing__ 方法,那么在 __getitem__ 碰到找不到的键的时候,Python 就会自动调用它,而不是抛出一个 KeyError 异常。 __missing__ 方法只会被 __getitem__ 调用(比如在表达式 d[k] 中)。提供 __missing__ 方法对 get 或者__contains__(in 运算符会用到这个方法)这些方法的使用没有影响。 Tests for item retrieval using `d[key]` notation:: >>> d = StrKeyDict0([('2', 'two'), ('4', 'four')]) >>> d['2'] 'two' >>> d[4] 'four' >>> d[1] Traceback (most recent call last): ... KeyError: '1' Tests for item retrieval using `d.get(key)` notation:: >>> d.get('2') 'two' >>> d.get(4) 'four' >>> d.get(1, 'N/A') 'N/A' Tests for the `in` operator:: >>> 2 in d True >>> 1 in d False 如果要自定义一个映射类型,更合适的策略其实是继承collections.UserDict 类。这里我们从 dict 继承,只是为了演示 __missing__ 是如何被dict.__getitem__ 调用的。 """ class StrKeyDict0(dict): def __missing__(self, key): if isinstance(key, str): # 如果找不到的键本身就是字符串,那就抛出 KeyError 异常。 raise KeyError(key) # 如果找不到的键不是字符串,那么把它转换成字符串再进行查找。 # return self[str(key)] def get(self, key, default=None): try: # get 方法把查找工作用 self[key] 的形式委托给 __getitem__,这样在宣布查找 # 失败之前,还能通过 __missing__ 再给某个键一个机会。 return self[key] except KeyError: # 如果抛出 KeyError,那么说明 __missing__ 也失败了,于是返回 default。 return default # def __setitem__(self, key, value): # self[str(key)] = value # 会递归调用__setitem__,进入无限循环 def __contains__(self, key): # 先按照传入键的原本的值来查找(我们的映射类型中可能含有非字符串的键),如果没找到, # 再用 str() 方法把键转换成字符串再查找一次。 # return key in self or str(key) in self # in dict操作会调用self.__contains__陷入无限循环,所以这里必须使用keys() return key in self.keys() or str(key) in self.keys() """ 下面来看看为什么 isinstance(key, str) 测试在上面的__missing__ 中是必需的。如果没有 这个测试,只要 str(k) 返回的是一个存在的键,那么__missing__ 方法是没问题的,不管是字符串键还 是非字符串键,它都能正常运行。但是如果 str(k) 不是一个存在的键,代码就会陷入无限递归。这是因 为 __missing__ 的最后一行中的 self[str(key)] 会调用 __getitem__,而这个 str(key) 又不 存在,于是 __missing__又会被调用。为了保持一致性,__contains__ 方法在这里也是必需的。这是 因为 k in d 这个操作会调用它,但是我们从 dict 继承到的 __contains__方法不会在找不到键的时 候调用 __missing__ 方法。__contains__里还有个细节,就是我们这里没有用更具 Python 风格的 方式——k inmy_dict——来检查键是否存在,因为那也会导致 __contains__ 被递归调用。为了避免这一 情况,这里采取了更显式的方法,直接在这个self.keys() 里查询。 像 k in my_dict.keys() 这种操作在 Python 3 中是很快的,而且即便映射类型对象很庞大也 没关系。这是因为dict.keys() 的返回值是一个“视图”。视图就像一个集合,而且跟字典类似的是,在视 图里查找一个元素的速度很快。 Python 2 的 dict.keys() 返回的是个列表,因此虽然上面的方法仍然是正确的,它在处理体积大 的对象的时候效率不会太高,因为 k in my_list 操作需要扫描整个列表。 """ a = StrKeyDict0() a[1] = 100 print(a[1]) print(1 in a)
# -*- coding=utf-8 -*- # # Copyright @ 2018 HuiXin Zhao import bisect # eg1: def grade(score, breakpoints=(60, 70, 80, 90), grades='FDCBA'): i = bisect.bisect(breakpoints, score) return grades[i] if __name__ == '__main__': res1 = [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]] print(res1) # eg2: data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)] data.sort(key=lambda x: x[1]) keys = [d[1] for d in data] for i in range(9): print(data[bisect.bisect_left(keys, i)])
# -*- coding: utf-8 -*- # Copyright @ 2018 HuiXin Zhao # 黑桃:S-Spade # 红桃:H-Heart # 方块:D-Diamond # 梅花:C-Club import collections Card = collections.namedtuple('Card', ['rank', 'suit']) class FrenchDeck: """ 通过实现 __len__和 __getitem__ 这两个特殊方法,FrenchDeck 就跟一个 Python 自 有的序列数据类型一样.同时这个类还可以用于标准库中诸如random.choice、reversed 和 sorted 这些函数。另外,对合成的运用使得 __len__ 和 __getitem__ 的具体实现可以代理给 self._cards这个 Python 列表(即 list 对象)。 shuffle 函数要调换集合中元素的位置,而 FrenchDeck 只实现了不可变的序列协议。可变 的序列还必须提供 __setitem__ 方法。 """ ranks = [str(n) for n in range(2, 11)] + list('JQKA') suits = 'spades clubs hearts diamonds'.split() def __init__(self): self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks] def __len__(self): return len(self._cards) def __getitem__(self, position): return self._cards[position] # 可变序列必须提供__setitem__方法 def __setitem__(self, key, value): """ random.shuffle 函数不关心参数的类型,只要那个对象实现了部分可变序列协议即可。 即便对象一开始没有所需的方法也没关系,后来再提供也行。 """ self._cards[key] = value # 对纸牌排序,按花色:黑红片花,序号2最小A最大 suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0) # 将纸牌升序排序的函数 def spades_high(card): rank_value = FrenchDeck.ranks.index(card.rank) return rank_value * len(suit_values) + suit_values[card.suit] if __name__ == '__main__': from random import choice deck = FrenchDeck() print("deck响应len:", len(deck)) for i in range(3): print("随机取3张:", choice(deck)) print("只取最上面3张:", deck[:3]) print("取所有的A:", deck[12::13]) for card in deck: print("正向迭代deck:", card) for card in reversed(deck): print("反向迭代deck:", card) print("对纸牌排序:") for card in sorted(deck, key=spades_high): print(card)
# Write a function that generates ten scores between 60 and 100. Each time a score is generated, # your function should display what the grade is for a particular score. import random def student_grade(): print "enter the score" score= random.randint(1, 100) print score if (score<100 and score>90): grade = "A" return "score: " + str(score) + " "+ " your grade is " + str(grade) elif(score<90 and score>80): grade = "B" return "score: " + str(score) + " "+ " your grade is " + str(grade) elif(score<80 and score>70): grade = "C" return "score: " + str(score) + " "+ " your grade is " + str(grade) else: grade = "D" return "score: " + str(score) + " "+ " your grade is " + str(grade) print student_grade()
#Write a program that prints a 'checkerboard' pattern to the console def my_checkerboard(): list_one = ["*"," ","*"," ","*"," "] list_two = [" ","*"," ","*"," ","*"] for i in range(6): print " ".join(list_one) print " ".join(list_two) print my_checkerboard()
class Animal(object): def __init__(self,name,health): self.name = name self.health = health def walking(self): self.health -= 1 return self def running(self): self.health -= 5 return self def display_health(self): print self.name , "did some activities " print self.health , "is the new health after it" # animal1 = Animal("sam",30) # animal1.walking().display_health() # animal2 = Animal("tito",30) # animal2.running().display_health() # animal3 = Animal("ruff",70) # animal3.walking().walking().walking().running().running().display_health() class Dog(Animal): def __init__(self,name): super(Dog, self).__init__(name,150) def pet(self): self.health -= 5 return self # dog1 = Dog("rex") # dog1.walking().walking().walking().running().running().pet().display_health() class Dragon(Animal): def __init__(self,name): super(Dragon, self).__init__(name,170) def fly(self): self.health -= 10 print "this is the new health after flying " return self def display_health(self): print "This is a dragon" super(Dragon, self).display_health() return self dragon1 = Dragon("pigeon") dragon1.display_health()
class MathDojo(object): def __init__(self): self.result = 0 def add(self,*args): for i in args: if type(i) == list or type(i) == tuple: for k in i: self.result += k else: self.result += i print self.result return self def subtract(self,*args): self.result -=arg2 print self.result return self def final_result(self): return self.result md = MathDojo() md.add(1,[1,1]).final_result()
import numpy as np ''' Input Population, Distance, and Flow Arrays, compute fitness scores from distance array and flow array. The flow is given by the indices at the corresponding coordinates from the chromosomes. The scores from all chromosomes are added, later to be normalized. ''' def get_fitness_scores(population, distance_array, flow_array): array_size = distance_array.shape[0] fitness_scores = [] for chromosome in population: # Make sure there are no duplicates in chromosome assert len(chromosome) == len(set(chromosome)) # Initialize sum chromosome_fitness_sum = 0 # At each (x, y) the distance is given by the distance array # and the flow for each item given by the chromosome are # multiplied to get the fitness. # This is done for all chromosomes in the population. for x in range(array_size): for y in range(array_size): chromosome_fitness_sum += distance_array[x, y] * flow_array[chromosome[x] - 1, chromosome[y] - 1] # Add calculated sum to the scores array fitness_scores.append(chromosome_fitness_sum) return fitness_scores # NORMALISE FITNESS SCORES (SOME PART OF CODE TAKEN FROM INTERNET NUMPY DOCUMENTATION) def normalise_fitness_scores(fitness_scores): # Generate list of inverses from fitness_scores map_to_minimization_problem = list(map(lambda value: 1.0 / value, fitness_scores)) # Normalizes each score by dividing it by the total normalized_scores = np.array(map_to_minimization_problem) / np.sum(map_to_minimization_problem) return normalized_scores
# Create your first MLP in Keras # importing libs from keras.models import Sequential from keras.layers import Dense import numpy as np import pandas as pd # In[3]: # fix random seed for reproducibility seed = 7 np.random.seed(seed) # In[3]: # load pima indians dataset dataset = np.loadtxt("data/pima-indians-diabetes.csv", delimiter=",") # In[3]: # split into input (X) and output (Y) variables X = dataset[:,0:8] Y = dataset[:,8] # In[3]: # create model model = Sequential() model.add(Dense(12, input_dim=8, init='uniform', activation='relu')) model.add(Dense(8, init='uniform', activation='relu')) model.add(Dense(1, init='uniform', activation='sigmoid')) #model.summary() # In[3]: # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # In[3]: # Fit the model model.fit(X,Y, nb_epoch=150, batch_size=10) # In[3]: # evaluate the model scores = model.evaluate(X, Y) print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
def same (list1, list2): list_same = [i for i in list1 + list2 if i in list1 and i in list2] list_same = list(dict.fromkeys(list_same)) return list_same a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] print ("List first: " + str(a)) print ("List second: " + str(b)) z = same (a, b) print ("Found in both lists: " + str(z))
from typing import List class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: data = [] for list in lists: while list: data.append(list.val) list = list.next data = sorted(data) root = temp = ListNode() for i in data: temp.next = ListNode(i) temp = temp.next return root.next def mergeKLists2(self,lists:List[ListNode])->ListNode: import heapq heap = [] root = result = ListNode() #각 연결리스트의 루트를 힙에 저장 for i in range(len(lists)): if lists[i]: heapq.heappush(heap,(lists[i].val,i,lists[i])) # 힙 추출 이후 다음 노드는 다시 저장 while heap: node = heapq.heappop(heap) idx = node[1] result.next = node[2] result = result.next if result.next: # 다음노드가 None이 아닌경우 heapq.heappush(heap,(result.next.val,idx,result.next)) return root.next
# Definition for singly-linked list. import collections from typing import Deque class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def isPalindrome(self, head): res = [] while head: res.append(head.val) head = head.next center = int(len(res)/2) if(len(res)%2==0): return res[:center] == res[:center-1:-1] else: return res[:center] == res[:center:-1] def isPalindrome2(self,head:ListNode)->bool: q : Deque = collections.deque() if not head: return True node = head while node is not None: q.append(node.val) node = node.next while len(q)>1: if q.popleft() != q.pop(): return False return True def isPalindrome3(self,head:ListNode)-> bool: rev = None slow = fast = head #런너를 이용해 역순 연결리스트 구성 while fast and fast.next: #노드가 짝수 개인 경우를 대비해서 fast.next추가 fast = fast.next.next rev , rev.next , slow = slow , rev ,slow.next if fast: #노드가 짝수인경우 slow = slow.next while rev and rev.val == slow.val: slow , rev = slow.next , rev.next return not rev app = Solution()
class Solution(object): def reverseString(self, s): for i in range(int(len(s)/2)): temp = s[i] s[i] = s[-(i+1)] s[-(i+1)] = temp lst = ["h","e","l","l","o"] app = Solution() print(lst) app.reverseString(lst) print(lst)
def solution(msg): answer =[] dic = [] for i in range(26): dic.append(chr(ord("A")+i)) start = 0 i = 1 while i<=len(msg): if msg[start:i] in dic : i+=1 continue else: dic.append(msg[start:i]) answer.append(dic.index(msg[start:i-1])+1) start = i-1 answer.append(dic.index(msg[start:])+1) return answer print(solution("TOBEORNOTTOBEORTOBEORNOT")) s = "ABABABABABABABAB" print(s[0:1])
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: def reverse_List(head: ListNode) -> ListNode: curr = head prev = next = None while curr: next = curr.next curr.next = prev prev = curr curr = next return prev if n == m: return head target_head = target = ListNode() temp = head cnt = 1 prev = None while cnt < m: prev = temp temp = temp.next cnt += 1 target_head = target = temp while cnt < n and temp.next: target.next = temp.next temp = temp.next target = target.next cnt += 1 end = target.next target.next = None reversed_List = reverse_List(target_head) t = reversed_List while t.next: t = t.next t.next = end if not prev: return reversed_List else: prev.next = reversed_List return head
from Restaurant import Restaurant class Combo(Restaurant): def __init__(self, name, price, comboProducts): super().__init__(name, price) self.comboProducts = comboProducts #REVIEW def showInformation(self): print(f"\nNombre del combo: {self.name} \nPrecio: {self.price}") products_combo = ', '.join(self.comboProducts) print(f"Productos del combo: {products_combo}") def setCombo(self): while True: try: change_combo = int(input("\n¿Qué desea cambiar de la información del combo? \n1.Nombre \n2.Clase de alimento \n3.Precio \n>>> ")) if change_combo not in range(1,4): raise ValueError break except ValueError: print("Error: El dato ingresado no forma parte de las opciones") if change_combo == 1: self.name = input("Ingrese el nuevo nombre: ") while not (self.name).isalpha(): self.name = input("Ingrese un nombre válido sin espacios: ") elif change_combo == 2: while True: try: products_amount = int(input("\nIngrese la cantidad de productos que tendrá el combo (min: 2 y max: 10): ")) if products_amount not in range(2,10): raise ValueError break except ValueError as identifier: print("Error: Dato ingresado no es válido") print("\nIngrese un solo producto a medida que le vaya preguntando el sistema") for i in range(products_amount): combo_product = input("Ingrese el nombre del producto: ") self.comboProducts.append(combo_product) elif change_combo == 3: while True: try: self.price = float(input("Ingrese el nuevo precio: ")) if self.price<0: raise ValueError break except ValueError: print("\nError: Dato inválido\n") self.price = self.price*1.16
from simulation import BaseObject class Warehouse(BaseObject): def __init__(self, initial_goods=None, *args, **kwargs): super().__init__() if initial_goods is not None: self.contains = initial_goods else: self.contains = {} def add_good(self, good, count): if good.name in self.contains: self.contains[good.name] += count else: self.contains[good.name] = count def remove_good(self, good, count): if good.name in self.contains: if count > self.contains[good.name]: raise ValueError("You don't have that many %s" % good.name) else: self.contains[good.name] -= count else: raise ValueError("You don't have any %s" % good.name) def trade(self, warehouse, good, count): self.remove_good(good, count) warehouse.add_good(good, count) def count(self, good): if good.name in self.contains: return self.contains[good.name] return 0
age = 18 if age>18: print('大于18岁') elif age<18: print('小于18岁') else: print('等于18岁')
# i = 0; # while i < 5: # str = '*' * (i+1) # print(str) # i+=1 row = 1 while row<=5: i = 1 while i<=row: print('*',end="") i+=1 print('') # 换行 row+=1
# try: # num = int(input('输入一个整数')) # except Exception as e: # print(e) def demo1(): return int(input('输入一个整数')) def demo2(): return demo1() try: print(demo2()) except Exception as e: print(e)
import tkinter from tkinter import ttk # 创建主窗口 win = tkinter.Tk() # 设置标题 win.title('title-hjl') # 设置大小和位置 win.geometry("600x400+200+50") # 表格 tree = ttk.Treeview(win) tree.pack() # 定义列 tree['columns'] = ('姓名','年龄','身高','体重') # 设置列,不显示 tree.column('姓名',width=100) tree.column('年龄',width=100) tree.column('身高',width=100) tree.column('体重',width=100) # 设置表头 tree.heading('姓名',text='姓名-name') tree.heading('年龄',text='年龄-age') tree.heading('身高',text='身高-height') tree.heading('体重',text='体重-weight') # 添加数据 tree.insert('',0,text='line1',values=('何胶龙','23','170','55')) tree.insert('',1,text='line2',values=('杨幂','30','168','55')) # 进入消息循环 win.mainloop()
row=1 while row<=9: col=1 while col<=row: ji = col * row print("%d * %d = %d\t"%(col,row,ji),end='') col+=1 print() row+=1
import tkinter # 创建主窗口 win = tkinter.Tk() # 设置标题 win.title('title-hjl') # 设置大小和位置 win.geometry("400x400+200+50") lbv = tkinter.StringVar() # 与BORWSE相似,但是不支持鼠标选中位置 lb = tkinter.Listbox(win,selectmode=tkinter.SINGLE, listvariable=lbv) lb.pack() for item in ['good','nice','handsome','word','haha']: # 按顺序添加 lb.insert(tkinter.END,item) # 当前列表中的选项 print(lbv.get()) # 改变列表选项 # lbv.set(('1','2','3','4')) def myPrint(event): print(lb.get(lb.curselection())) # 给控件绑定事件 lb.bind("<Double-Button-1>",myPrint) # 进入消息循环 win.mainloop()
class Person: def __init__(self,name,weight): self.name = name self.weight = weight def __str__(self): return "我的名字shi%s体重是%.2f公斤"%(self.name,self.weight) def eat(self): print('吃饭') self.weight +=1 def run(self): print('跑步') self.weight -=0.5 wo = Person('小明',55) wo.eat() wo.run() print(wo)
import threading import time def run(num): print("子线程%s启动"%(threading.current_thread().name)) print("打印%d"%num) time.sleep(2) print("子线程%s结束"%(threading.current_thread().name)) if __name__ == "__main__": # 任何进程默认会启动一个线程,称为主线程,主线程可以启动新的子线程 # current_thread() 返回当前线程的实力 print("主线程启动--%s" %(threading.current_thread().name)) # 创建子线程 t = threading.Thread(target=run,name="runThread",args=(1,)) t.start() # 主进程等待子线程结束 t.join() print("主线程结束--%s" %(threading.current_thread().name))
import tkinter # 创建主窗口 win = tkinter.Tk() # 设置标题 win.title('title-hjl') # 设置大小和位置 win.geometry("400x400+200+50") # <Enter> 鼠标光标进入控件时候触发 # <Leave> 鼠标光标离开控件时候触发 label = tkinter.Label(win,text='he jiao long is a good man',bg='yellow') label.pack() def func(event): print(event.x) label.bind('<Leave>',func) # 进入消息循环 win.mainloop()
#These are the items in our shoping list shopping_list = ["pants", "skateboards"] #dictionary called "stock" stock = { "hoodie": 5, "pants": 5, "skateboards": 30, "Wheels": 10 } #dictionary called "prices" prices = { "hoodie": 1, "pants": 15, "skateboards": 35, "Wheels": 5 } #fucntion is made that computes the bill after shopping def compute_bill(food): total = 0 for item in food: if stock[item] > 0: total += prices[item] stock[item] -= 1 else: return "The item out of stock!" return "%s dollars" % total print("Your total bill: ") print (compute_bill(shopping_list))
# imports import time # calculation function def calculate(): for i in range(0,10000): pass # function that calculates how long the calculation function takes def timeFunc(): startTime = time.time() calculate() endTime = time.time() print(endTime-startTime) timeFunc()
"""Common algorithm interviewed on that I wanted to try""" def main(): # creating an empty list array = [] # number of elemetns as input n = int(input("Enter number of elements : ")) # iterating till the range for i in range(0, n): ele = int(input("Enter element: ")) array.append(ele) # adding the element number = int(input("How many left rotates? ")) result = rotate(array, number) return result def rotate(array, n): for i in range(0,n): send = array.pop(0) array.append(send) return array # driver code print(main())
from tkinter import * from tkinter import messagebox ''' def keyEvent(event): messagebox.showinfo("키보드 이벤트","눌린 키 : "+chr(event.keycode)) print(event.keycode) ''' def keyEvent(event): if event.keycode==37: messagebox.showinfo("키보드 이벤트","눌린 키 : shift + 아래쪽 화살표") elif event.keycode==38: messagebox.showinfo("키보드 이벤트","눌린 키 : shift + 위쪽 화살표") elif event.keycode==39: messagebox.showinfo("키보드 이벤트","눌린 키 : shift + 오른쪽 화살표") elif event.keycode==40: messagebox.showinfo("키보드 이벤트","눌린 키 : shift + 왼쪽 화살표") window=Tk() window.bind("<Shift-Up>",keyEvent) window.bind("<Shift-Down>",keyEvent) window.bind("<Shift-Left>",keyEvent) window.bind("<Shift-Right>",keyEvent) window.mainloop()
import turtle turtle.speed(4) turtle.pensize(5) turtle.color('black', 'pink') turtle.begin_fill() for i in range(4): #사각형 turtle.forward(200) turtle.left(90) turtle.end_fill() turtle.penup() turtle.goto(0, -100) turtle.write("speed는 4, pensize 5, color는 black&pink") turtle.forward(200) turtle.reset() #다시 시작, 전부 reset turtle.color('red','blue') turtle.begin_fill() turtle.circle(100) turtle.end_fill() turtle.goto(0, -100) turtle.write("circle()")
""" board.py author: Colin Clement and Samuel Kachuck date: 2016-01-15 Representation of a Bananagrams board, an unbounded square lattice """ from collections import defaultdict class Board(object): """ Representation of a Bananagram board """ def __init__(self): self.reset() def reset(self): """ Empty board """ self.ys = [] # integers of occupied sites y-coords self.xs = [] # integers of occupied sites x-coords self.ss = [] # list of str at corresponding y, x self.bb = {} def show(self, **kwargs): """ Pretty print the board! Coords are abs """ bb = kwargs.get('board', self.bb) if not bb: return super(Board, self).__repr__() ymin, ymax, xmin, xmax = self.limits(**kwargs) xc_range = range(xmin, xmax+1) boardstr = ' ' + ''.join(map(lambda x: str(abs(x)), xc_range)) boardstr += '\n' for y in range(ymin, ymax+1): boardstr += str(abs(y)) + "\033[0;30;47m" for x in range(xmin, xmax+1): s = self.check(y, x, transpose=False, **kwargs) if s: boardstr += s.upper() else: boardstr += ' ' boardstr += '\033[0m' + '\n' return boardstr def __repr__(self): return self.show() def place(self, y, x, s): """ Place tile at y, x with letter s """ assert isinstance(y, int), "y must be int" assert isinstance(x, int), "x must be int" assert isinstance(s, str), "s must be str" self.ys.append(y) self.xs.append(x) self.ss.append(s) self.bb[(y,x)] = s def replace(self, board): """ Reset then placeall """ self.reset() self.placeall(board) def pop(self, ind=-1): """ Removes the last-placed tile and returns y, x, s """ y, x, s = self.ys.pop(ind), self.xs.pop(ind), self.ss.pop(ind) bb.pop((y,x)) return y, x, s def placeall(self, board): """ place a list of tiles """ if type(board) is dict: for s in board: self.place(s[0],s[1],board[s]) if type(board) is list: for (y, x, s) in board: self.place(y, x, s) def limits(self, **kwargs): """ Returns board limits ymin, ymax, xmin, xmax """ bb = kwargs.get('board', self.bb) ymin = min(bb, key=lambda x: x[0])[0] ymax = max(bb, key=lambda x: x[0])[0] xmin = min(bb, key=lambda x: x[1])[1] xmax = max(bb, key=lambda x: x[1])[1] return ymin, ymax, xmin, xmax def check(self, line, coord, transpose=False, **kwargs): """ Find value of tile in line, along coord. (line, coord) = (y, x) if transpose=False (line, coord) = (x, y) if transpose=True kwargs: board: tuple (ys (list), xs (list), ss (list)) for specifying a custom board """ bb = kwargs.get('board', self.bb) if transpose: return bb.get((coord, line), '') else: return bb.get((line, coord), '') def walk(self, line, coord, transpose=False, sgn=1, **kwargs): """ Starting at site (y,x) = (line, coord) if transpose=False (x,y) = (line, coord) if transpose=True in direction sgn (+/-1) along line (across if transpose=False) input: line: int, line along which to walk (y=line if transpose=False, x=line if tranpose=True) coord: int, coordinate along line to start walking (x=coord if transpose=False, y=coord if transpose=True) transpose: False/True, swap (y,x) sgn: +/-1, direction along line of walk. kwargs: board: tuple (ys (list), xs (list), ss (list)) for specifying a custom board returns: path: str of tiles visited, including start point """ path = '' tocheck = [coord] while tocheck: nxt = tocheck.pop(0) n = self.check(line, nxt, transpose, **kwargs) if n: tocheck.append(nxt + sgn) if sgn > 0: path += n else: # add backwards path = n + path return path def occupied(self, line, transpose=False, **kwargs): """ Find occupied indices from row y=line (transpose=False) or column x=line (transpose=True) kwargs: board: tuple (ys (list), xs (list), ss (list)) for specifying a custom board """ bb = kwargs.get('board', self.bb) if transpose: return {yx[0] for yx in bb if yx[1]==line} else: return {yx[1] for yx in bb if yx[0]==line} def find_anchors(self, line, transpose=False, **kwargs): """ Find anchor points, left(up)-most unnocupied sites adjacent to occupied tiles. input: line: int, row (transpose=False) or col (transpose=True) transpose: True/False. swap y, x kwargs: board: tuple (ys (list), xs (list), ss (list)) for specifying a custom board returns: set of anchor coords in row or col ind """ occupied = self.occupied(line, transpose, **kwargs) left = {o - 1 for o in occupied} left.difference_update(occupied) return left def cross_checks(self, line, transpose=False, **kwargs): """ Find points which need to be cross-check for board consistency. input: line: int, y = row (transpose=False) or x=col (transpose=True) transpose: True/False, swap y,x kwargs: board: tuple (ys (list), xs (list), ss (list)) for specifying a custom board returns: set of cross-check coords in row or col ind """ occupied = self.occupied(line, transpose, **kwargs) up = self.occupied(line - 1, transpose, **kwargs) down = self.occupied(line + 1, transpose, **kwargs) return (up.union(down)).difference(occupied) if __name__ == "__main__": B = Board() ys = [-1, 0, 0, 1, 1, 1, 2, 2] xs = [2, 0, 2, 0, 1, 2, 0, 2] ss = [s for s in 'claeatts'] B.placeall(ys, xs, ss)
#This is Python. The file extension is .py #It is used mainly as it is a general language, and can be used for lots of things import time #This is a framework, used for adding functionality to the program numVariable = 5 # This is a variable decleration, setting numVariable as 5 stringVariable = "Hello" # This is a string variable decleration, setting stringVariable as "Hello" if numVariable >= 5: #This if statement says if numVariable is greater than or equal to 5, then execute. #In an if loop, it is important that The code inside is indented properly and the statement ends with a ':' numVariable += 1 #This adds one to numVariable, making it = 6 numVariable -= 1 #This subtracts one from numVariable, making it = 5 #This is out of the if loop, as it is not indented. #This will run after the if loop
timein = int(input("Введите время в секундах: ")) hour = timein // 3600 minut = timein % 3600 // 60 second = timein % 3600 % 60 if hour < 10: hour = str(0) + str(hour) if minut < 10: minut = str(0) + str(minut) if second < 10: second = str(0) + str(second) print(f"{hour}:{minut}:{second}")
# Let's generalize a mutex so that multiple threads can run in the critical section at the same time. # But we set an upper limit on the number of concurrent rheads. import threading multiplex = threading.Semaphore(3) # 3 threads, we do 3 for the semaphore! count = 0 def fun1(): global count multiplex.acquire() count += 1 print(count) multiplex.release() threading.Thread(target=fun1).start() threading.Thread(target=fun1).start() threading.Thread(target=fun1).start() # well, due to the way it's set up in Python it works anyways without the multiplex # but if we did have threads coming in and the scheduler picking whatever to run, # that multiplex would help! # Now that we set the number in the semaphore to the number of threads, # this means that it'll only allow 3 concurrent ones inside the critical point, since # more than 3 would get locked.
import unittest from myproj.array import Array class TestArray(unittest.TestCase): """ Create class instance """ def setUp(self): self.array = Array('1 2 3 4 10 11') """ Test that the result sum of all numbers """ def test_sum(self): result = self.array.sum(6) self.assertEqual(result, 31) """ Tests that an exception occurs when the number of arguments is different """ def test_sum_raise_exception(self): self.assertRaises(Exception, lambda: self.array.sum(5)) """ Print array elements """ def tearDown(self): print('elements = {}'.format(self.array)) if __name__ == '__main__': unittest.main()
import numpy as np import matplotlib.pyplot as plt #data x = np.arange(0,6,0.1) y1 = np.sin(x) y2 = np.cos(x) #draw graph plt.plot(x,y1,label="sin") plt.plot(x,y2,linestyle="--",label="cos") plt.xlabel("x") #x축 이름 plt.ylabel("y") #y축 이름 plt.title('sin & cos') #title plt.legend() plt.show()
# -*- coding: utf-8 -*- import numpy as np def AND(x1,x2): x = np.array([x1,x2]) w = np.array([0.5,0.5]) b = -0.7 # 편향 : 뉴런이 얼마나 쉽게 활성화 하느냐를 조정하는 매개변수 (theta의 이항 값) tmp = np.sum(w*x) + b if tmp <=0 : return 0 else: return 1 print AND(0,0) print AND(1,0) print AND(0,1) print AND(1,1) # NAND 와 OR 는 AND와 가중치(w,b)만 다르다 def NAND(x1,x2): x = np.array([x1,x2]) w = np.array([-0.5,-0.5]) b = 0.7 tmp = np.sum(w*x) + b if tmp <=0 : return 0 else: return 1 print NAND(0,0) print NAND(1,0) print NAND(0,1) print NAND(1,1) def OR(x1,x2): x = np.array([x1,x2]) w = np.array([0.5,0.5]) b = -0.2 tmp = np.sum(w*x) + b if tmp <=0 : return 0 else: return 1 print NAND(0,0) print NAND(1,0) print NAND(0,1) print NAND(1,1) # 퍼셉트론은 비선형 XOR를 표현하지 못하므로 NAND ,AND, OR를 사용해서 구현 (다층 퍼셉트론) def XOR (x1,x2): s1 = NAND(x1,x2) s2 = OR(x1,x2) y = AND(s1,s2) return y print XOR(0,0) print XOR(1,0) print XOR(0,1) print XOR(1,1)
name = input("Please enter your name:") bday = input("Please enter your numerical birthday (month/day):") bdayParts = bday.split("/") month = int(bdayParts[0]) day = int(bdayParts[1]) if (( month == 3 and day >= 21 ) or (month == 4 and day <=20)): zodiac = "Aries" elif((month == 4 and day >= 21) or (month == 5 and day <= 21)): zodiac = "Taurus" elif((month == 5 and day >= 22) or (month == 6 and day <= 21)): zodiac = "Gemini" elif((month == 6 and day >= 22) or (month == 7 and day <= 23)): zodiac = "Cancer" elif((month == 7 and day >= 24) or (month == 8 and day <= 23)): zodiac = "Leo" elif((month == 8 and day >= 24) or (month == 9 and day <= 23)): zodiac = "Virgo" elif((month == 9 and day >= 24) or (month == 10 and day <= 23)): zodiac = "Libra" elif((month == 10 and day >= 24) or (month == 11 and day <= 22)): zodiac = "Scorpio" elif((month == 11 and day >= 23) or (month == 12 and day <=22)): zodiac = "Sagittarius" elif((month == 12 and day >= 23) or (month == 1 and day <=20)): zodiac = "Capricorn" elif((month == 1 and day >= 21) or (month == 2 and day <=19)): zodiac = "Aquarius" else: zodiac = "Pisces" print("\n\n" + name + ", your zodiac sign is: " + zodiac + "\n")
"""2D random walk simulation in pygame.""" import pygame import random rows = 100 w = 1200 sizeBtwn = w // rows start_pos = (480,480) curr_pos = start_pos mov_opts = ((0,sizeBtwn),(0,-sizeBtwn),(sizeBtwn,0),(-sizeBtwn,0)) line_to_draw = [start_pos] # Intializing widnow pygame.init() win = pygame.display.set_mode((1200,800)) pygame.display.set_caption("Random walk") def drawGrid(w, rows, surface): x = 0 y = 0 for l in range(rows): x = x + sizeBtwn y = y + sizeBtwn pygame.draw.line(win, (0,0,0), (x,0),(x,w) , 2) pygame.draw.line(win, (0,0,0), (0,y),(w,y) , 2) def movChoice (start_pos=start_pos,line_to_draw =line_to_draw): choice = random.choice(mov_opts) curr_pos = (start_pos[0] + choice[0], start_pos[1] + choice[1]) line_to_draw.append(curr_pos) return line_to_draw, curr_pos def drawMov(line_to_draw=line_to_draw): for item in range (1,len(line_to_draw)): x1 = line_to_draw[item-1][0] y1 = line_to_draw[item-1][1] x2 = line_to_draw[item][0] y2 = line_to_draw[item][1] pygame.draw.line(win, (242, 231, 80), (x1,y1),(x2,y2), 3 ) #"head" is a current position represented on the grid by circle def drawHead(curr_pos=curr_pos): head_x = int(curr_pos[0]) head_y = int(curr_pos[1]) pygame.draw.circle(win, (217, 160, 54),(head_x,head_y) , 5) #drawing starting position of the walk represented by a black circle def drawStart (start_pos=start_pos): start_x = int(start_pos[0]) start_y = int(start_pos[1]) pygame.draw.circle(win, (13, 13, 13),(start_x,start_y) , 5) run = True # Main loop while run: pygame.time.delay(500) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False win.fill((140, 103, 35)) drawGrid(w,rows,win) line_to_draw, curr_pos = movChoice(curr_pos) drawMov(line_to_draw) drawHead(curr_pos) drawStart() print("STEPS:",len(line_to_draw)-1) pygame.display.update() pygame.quit()
a = int(input('输入年份')) if(a%4 == 0 and a%100 != 0) or (a%400 == 0): print("闰年") else: print("平年")
list = [] for i in range(3): d = {} name = input("请输入名字") d["name"] = name age = int(input("请输入年龄")) d["age"] = age sex = input("请输入性别") d["sex"] = sex list.append(d) print(list) for i in list: for k,v in items(): print(k,v)
list = [] def print_menu(): print("欢迎进入点菜系统".center(30," ")) while True: print("1:上菜") print("2:查菜") print("3:换菜") print("4:撤菜") print("5:打印菜单") print("6:退出") input_info() def input_info(): # 选择 num = input("请选择功能") if isNum(num): num = int(num) else: print("输入有误") if num == 1: add() elif num == 2: find() elif num == 3: change() elif num == 4: delete() elif num == 5: print_list() elif num == 6: exit() else: showError() def showError(): print("输入有误,重新输入") def isNum(num): if num.isdigit(): return True else: return False def add(): # 添加 dcb = {} while True: num = input("请输入桌号") if isNum(num): num = int(num) else: print("输入有误") continue if num > 0 and num < 101: dcb["num"] = num break else: showError("桌号必须大于0小于101") while True: name = input("输入菜名") if len(name) >= 2 and len(name) <= 8: dcb["name"] = name break else: showError("菜名必须大于等于2小于8") while True: count = input("输入数量") if isNum(count): count = int(count) else: print("输入有误") continue if count > 0 and count < 11: dcb["count"] = count break else: showError("数量必须大于0小于11") list.append(eat) print("完成") def find(): # 查看 a = input("输入要查找桌号") for eat in list: if eat["a"] == a: print("桌号:%d\n菜名:%s\n数量%d"%(eat["a"],eat["name"],eat["count"])) break def change(): # 修改 while True: a = input("输入桌号") flag = False #假定不存在 for eat in list: if eat["name"] == name: print("1:修改菜名") print("2:修改数量") num1 = input("请选择功能") if isNum(num1): num1 = input(num1) else: print("输入有误") continue if num1 == 1: name = input("输入新菜名") eat["name"] = name elif num1 == 2: count = input("输入新数量") eat["count"] = count print("修改成功") break break if not flag: print("无") def delete(): # 删除 a = input("输入桌号") name = input("选择要删除的菜") for eat in list: if eat["name"] == name: list.remove(eat) print("删除成功") break def print_list(): # 打印 print("桌号 菜名 数量 ") for eat in list: print("%d %s %d"%(eat["a"],eat["name"],eat["count"])) print_menu()
for i in range(1,5): for a in range(1,5): for c in range(1,5): if i != a and a != c and c != i: print(i,a,c)
i = 1 a = 0 while i < 11: a = 1 while a <= 2: a+=1 a+=i print("共花%.00%f")
list = [1,2,4,65,7,8,6,64,86] for i in range(0,len(list)-1): for j in range(i+1,len(list)): if list[i] > list[j]: list[i],list[j] = list[j],list[i] print(list)
FOR LOOP In [60]: for i in range(len(nba_teams)): ...: each_team = nba_teams[i] ...: print(nba_teams[i]) Lakers Nuggets Celtics Clippers In [59]: for i in range(len(nba_teams)): ...: each_team = nba_teams[i] ...: print(i) ...: 0 1 2 3 --------------------------------------------------- In [56]: for i in range(0,15): ...: print(i) ...: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ------------------------------------------------- WHILE LOOP In [54]: while number < 10: ...: number+= 1 ...: print (number) ...: 1 2 3 4 5 6 7 8 9 10 FUNCTION In [46]: vip = True In [47]: food_place = "busy" In [48]: def the_spot(vip, food_place, location="Bay Area"): ...: if (food_place == "full" and not vip): ...: print("Sorry, we have no room tonight at this {} loaction".form ...: at(location)) ...: elif( ...: food_place == "busy" and not vip): ...: print("Please wait 30 mins for a table at this {} location".for ...: mat(location)) ...: else: ...: print("Welcome! Come sit down right away") ...: -------------------------------------------------- In [49]: the_spot(vip, food_place) Welcome! Come sit down right away In [50]: the_spot(False, food_place) Please wait 30 mins for a table at this Bay Area location In [51]: the_spot(False, food_place, "Los Angeles") Please wait 30 mins for a table at this Los Angeles location In [44]: def legal_age(age): ...: if(age < 21): ...: return "Sorry your too young." ...: elif (age == 21): ...: return"You made it. Welcome to adulthood" ...: else: ...: return "Your free to pass. Enjoy" ...: In [45]: legal_age(32) Out[45]: 'Your free to pass. Enjoy' --------------------------- In [36]: def add_numbers(num1, num2): ...: result = num1 + num2 ...: return result ...: In [37]: add_numbers Out[37]: <function __main__.add_numbers(num1, num2)> In [38]: add_numbers(5,5) Out[38]: 10 ---------------------------- In [18]: dog = { ...: "name": "Rocco", ...: "age": "7", ...: "location": "Los Angeles" ...: } In [30]: my_message = f"{dog['name']} lives in {dog['location']}." In [31]: my_message Out[31]: 'Rocco lives in Los Angeles.' -------------------------------- In [14]: arr_of_numbers = [1] * 3 In [15]: arr_of_numbers Out[15]: [1, 1, 1]
import time timer = int(input("타이머를 입력해주세요(초 단위) : ")) for i in range(timer): print(timer) timer -= 1 time.sleep(1) print("끝") #한글
# Input: s = "III" # Output: 3 # Input: s = "LVIII" # Output: 58 # Explanation: L = 50, V= 5, III = 3 # Input: s = "MCMXCIV" # Output: 1994 # Explanation: M = 1000, CM = 900, XC = 90 and IV = 4 # Roman numerals are usually written largest to smallest from left to right. # However, the numeral for four is not IIII. Instead, the number four is written as IV. # Because the one is before the five we subtract it making four. # The same principle applies to the number nine, which is written as IX. # There are six instances where subtraction is used: # I can be placed before V (5) and X (10) to make 4 and 9. # X can be placed before L (50) and C (100) to make 40 and 90. # C can be placed before D (500) and M (1000) to make 400 and 900. class Solution: def __init__(self): self.nums = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def romanToInt(self, s: str): # tally of the exceptions tally = 0 if 'IV' in s: tally += 4 s = s.replace("IV", '') if 'IX' in s: tally += 9 s = s.replace("IX", '') if 'XL' in s: tally += 40 s = s.replace("XL", '') if 'XC' in s: tally += 90 s = s.replace("XC", '') if 'CD' in s: tally += 400 s = s.replace("CD", '') if 'CM' in s: tally += 900 s = s.replace("CM", '') # sum of roman numerals once exceptions removed roman = 0 for i in s: if i in self.nums.keys(): roman += (self.nums[i]) z = (roman+tally) return z test = Solution() test = test.romanToInt("IX") print(test)
''' Test board for Game Evaluation ''' from typing import List # constants ROWS = 5 COLS = 8 BOARD_H = ROWS + 2 BOARD_W = COLS + 2 # 1d array board representation board =[9,9,9,9,9,9,9,9,9,9, 9,1,0,0,0,0,0,0,0,9, 9,0,0,0,2,2,2,0,0,9, 9,1,0,0,0,0,0,0,0,9, 9,0,0,0,0,0,0,0,0,9, 9,0,0,0,0,0,0,0,0,9, 9,9,9,9,9,9,9,9,9,9,] # CHECK 3 in a ROW - todo add code for 2 in a row def check_rows(game_board:List)->int: ''' see if there is a row of 2 or 3 present ''' for i in range(1,BOARD_H) : for j in range(1,BOARD_W-1) : if 0 < game_board[j+(BOARD_W*i)] <9: if (game_board[j+(BOARD_W)*i]==board[j+(BOARD_W*i)+1] and board[j+(BOARD_W*i)+1] == board[j+(BOARD_W*i)+2]): return 30 return 0 # CHECK 3 in a COL - todo add code for 2 in a col def check_cols(game_board:List)->int: ''' see if there is a column of 2 or 3 present ''' for i in range(1,BOARD_H) : for j in range(1,BOARD_W-1) : if 0 < game_board[(i*BOARD_W)+j] <9: if (board[(i*BOARD_W)+j]==board[(i+1)*BOARD_W+j] and board[(i+1)*(BOARD_W)+j] == board[(i+2)*(BOARD_W)+j]): return 30 return 0 if __name__ == '__main__': RES_R = check_rows(board) RES_C = check_cols(board) print(RES_R) print(RES_C)
# 1. Make a Class that processes Employee Details (3 employees will do) # 2. Make a function that creates instances of that class from a Dictionary # 3. Use the function to display the new Details # 4* Make a new dictionary with the new values? employees = {"Dr Pi":49000, "Bob Marshall" : 22000, "Tommy Vance" :33000} class Worker(object): def __init__(self, name, pay): self.name = name self.pay = pay def give_raise(self, percent): self.pay *= (1 + percent) def firstname(self): return self.name.split()[0] def display(): employeesV2 = {} for keys, values in employees.items() : en = keys.split()[0] print("Instance Name = ", en) en = Worker(keys, values) en.give_raise(0.12) print("Employee Name = ", en.name) print("Original Salary =", values) print("Employee New Salary = ", int(en.pay)) print("-" * 30) #employeesV2.update({keys, values}) print(employeesV2) display()
class Solution: def countOdds(self, low: int, high: int) -> int: if high%2==0 and low%2==0: return ((high-low)//2) if high%2!=0 and low%2!=0: return ((high-low)//2)+1 if high%2!=0 and low%2==0: return (((high+1)-low)//2) if high%2==0 and low%2!=0: return (((high+1)-low)//2) x = Solution() print(x.countOdds(7,10)) # Example 1: # Input: low = 3, high = 7 # Output: 3 # Explanation: The odd numbers between 3 and 7 are [3,5,7]. # Example 2: # Input: low = 8, high = 10 # Output: 1 # Explanation: The odd numbers between 8 and 10 are [9].
num = int(input("maraton de peliculas")) pelicula =[] for i in range(num): print(i+1,"duraccion de pelicula") lista =input().split() nombre = lista[0] hora =int (lista[1]) minuto= int(lista[2]) pelicula.append([nombre,hora,minuto]) pass print() for x in range(num): print(pelicula[x]) for i in range(num): temp=pelicula[i] for j in range(num-i-1): temp2 = pelicula[j] if temp2[1] > temp[1] : pelicula[j],pelicula[j+1] = pelicula[j+1],pelicula[j] elif temp2[1] == temp[1]: if temp2[2] > temp[2]: pelicula[j],pelicula[j+1] = pelicula[j+1],pelicula[j] elif temp2[2] == temp[2]: if temp2[0] > temp[0]: pelicula[j],pelicula[j+1] = pelicula[j+1],pelicula[j] elif temp2[0] == temp[0]: if temp2[0] > temp[0]: pelicula[j],pelicula[j+1] = pelicula[j+1],pelicula[j] pass pass pass pass pass print ("") for x in range(num): print(pelicula[x]) pass
print 'hello, global..!' x = 2 y = 0 if x != y : print 'in if' else : print 'in else' names = {'mahi', 'manu', 'siva', 'sri', 'sharu', 'kd'} for char in names : print char
""" # Simple Thresholding - Thresholding is a technique in OpenCV, which is the assignment of pixel values in relation to the threshold value provided. In thresholding, each pixel value is compared with the threshold value. If the pixel value is smaller than the threshold, it is set to 0, otherwise, it is set to a maximum value (generally 255). Thresholding is a very popular segmentation technique, used for separating an object considered as a foreground from its background. A threshold is a value which has two regions on its either side i.e. below the threshold or above the threshold. In Computer Vision, this technique of thresholding is done on grayscale images. So initially, the image has to be converted in grayscale color space. """ # Python programe to illustrate # simple thresholding type on an image # organizing imports import cv2 import numpy as np # path to input image is specified and # image is loaded with imread command image1 = cv2.imread('./inputImages/input.png') # cv2.cvtColor is applied over the image input with applied parameters # to convert the image in grayscale img = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) # applying different thresholding # techniques on the input image # all pixels value above 120 will # be set to 255 ret, thresh1 = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY) ret, thresh2 = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY_INV) ret, thresh3 = cv2.threshold(img, 120, 255, cv2.THRESH_TRUNC) ret, thresh4 = cv2.threshold(img, 120, 255, cv2.THRESH_TOZERO) ret, thresh5 = cv2.threshold(img, 120, 255, cv2.THRESH_TOZERO_INV) # the window showing output images # with the corresponding thresholding # techniques applied to the input images cv2.imshow('Binary Threshold', thresh1) cv2.imshow('Binary Threshold Inverted', thresh2) cv2.imshow('Truncated Threshold', thresh3) cv2.imshow('Set to 0', thresh4) cv2.imshow('Set to 0 Inverted', thresh5) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Savin Ilya Python Homework N9 # 6 Problem # The sum of the squares of the first ten natural numbers is, # The square of the sum of the first ten natural numbers is, # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. print((sum([sq_of_sum for sq_of_sum in range(1, 101)])**2) - (sum([sum_of_sq**2 for sum_of_sq in range(1, 101)]))) # --------------------------------
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Savin Ilya Python Homework N5 # ------- # Встроенная функция input позволяет ожидать и возвращать данные из стандартного # ввода ввиде строки (весь введенный пользователем текст до нажатия им enter). # Используя данную функцию, напишите программу, которая: # 1. После запуска предлагает пользователю ввести неотрицательные целые числа, # разделенные через пробел и ожидает ввода от пользователя. # 2. Находит наименьшее положительное число, не входящее в данный пользователем # список чисел и печатает его. # -------- input_string = input("Enter string of numbers: ") numbers_list = [] split_string = input_string.split() for i in split_string: numbers_list.append(int(i)) numbers_list = list(set(numbers_list)) numbers_list.sort() counter = 0 flag = 0 for i in numbers_list: counter += 1 if i > counter: print(counter) flag = 1 break if flag == 0: print(counter+1)
from tkinter import * from functools import partial # To prevent unwanted windows import random class Quiz: def __init__(self): # Formatting variables... self.quiz_results_list = [4, 6] # In actual program this is blank and is populated with user calculation self.round_results_list = ['5 ÷ 5 = | correct | you entered:1 | score:1\n' '2 × 12 = | correct | you entered:24 | score:2\n' '2 × 7 = | incorrect | you entered:15 | the correct answer:14 | score:2\n' '9 × 7 = | correct | you entered:63 | score:3\n' '7 × 2 = | correct | you entered:14 | score:4\n' '4 × 7 = | incorrect | you entered:12 | the correct answer:28 | score:4'] self.quiz_frame = Frame() self.quiz_frame.grid() # Heading Row self.heading_label = Label(self.quiz_frame, text="Play...", font="Arial 24 bold", padx=10, pady=10) self.heading_label.grid(row=0) # History Button (row 1) self.results_button = Button(self.quiz_frame, text="Quiz Results", font="Arial 14", padx=10, pady=10, command=lambda: self.to_results(self.round_results_list, self.quiz_results_list)) self.results_button.grid(row=1) if len(self.round_results_list) == 0: self.results_button.config(state=NORMAL) def to_results(self, quiz_history, quiz_results): QuizResults(self, quiz_history, quiz_results) class QuizResults: def __init__(self, partner, quiz_history, quiz_results): print(quiz_history) # disable help button partner.results_button.config(state=DISABLED) heading = "Arial 12 bold" content = "Arial 12" # Sets up child window (i.e: history box) self.results_box = Toplevel() # if users press cross at top, closes help and 'releases' help button self.results_box.protocol('WM_DELETE_WINDOW', partial(self.close_results, partner)) # Set up GUI Frame self.results_frame = Frame(self.results_box) self.results_frame.grid() # Set up help heading (row 0) self.results_heading = Label(self.results_frame,text="Quiz Results", font="arial 19 bold") self.results_heading.grid(row=0) # To Export <instruction> (row 1) self.export_instructions = Label(self.results_frame, text="Here are your quiz results " "Please use the " "Export button to access the results " "of each round that you played ", wrap=250, font="arial 10 italic", justify=LEFT, width=40, fg="green", padx=10, pady=10) self.export_instructions.grid(row=1) # Selected Questions (row 2) self.details_frame = Frame(self.results_frame) self.details_frame.grid(row=2) # Score (row 2.0) self.score_label = Label(self.details_frame, font=heading, text="Score:", anchor="e") self.score_label.grid(row=0, column=0, padx=0) self.score_label = Label(self.details_frame, font=content, text="{}/{}" .format(quiz_results[0], quiz_results[1]), anchor="w") self.score_label.grid(row=0, column=1, padx=0) # Correct answers (row 2.1) self.correct_ans_label = Label(self.details_frame, font=heading, text="Correct Answers:", anchor="e") self.correct_ans_label.grid(row=1, column=0, padx=0) self.correct_ans_label = Label(self.details_frame, font=content, text="{}" .format(quiz_results[0]), anchor="w") self.correct_ans_label.grid(row=1, column=1, padx=0) # Wrong Answers (row 2.2) self.wrong_ans_label = Label(self.details_frame, font=heading, text="Wrong Answers: ", anchor="e") self.wrong_ans_label.grid(row=3, column=0, padx=0) self.wrong_ans_label = Label(self.details_frame, font=content, text="{}" .format(quiz_results[1] - quiz_results[0]), anchor="w") self.wrong_ans_label.grid(row=3, column=1, padx=0) # Percentage (row 2.3) self.percentage_label = Label(self.details_frame, font=heading, text="Percentage: ", anchor="e") self.percentage_label.grid(row=4, column=0, padx=0) self.percentage_label = Label(self.details_frame, font=content, text=" {:.1f}%" .format(quiz_results[0] / quiz_results[1]*100), anchor="w") self.percentage_label.grid(row=4, column=1, padx=0) # Dismiss button (row 3) self.dismiss_button = Button(self.details_frame, text="Dismiss", font="Arial 12 bold", width=10, bg="#660000", fg="white", command=partial(self.close_results, partner)) self.dismiss_button.grid(row=5, column=1, pady=10) all_quiz_results = ["Score: {}/{}\n" "Correct answers:{}\n" "Wrong answers:{}\n" "Percentage:{:.1f}%".format(quiz_results[0], quiz_results[1], quiz_results[0], (quiz_results[1]-quiz_results[0]), (quiz_results[0] / quiz_results[1]*100))] # Export Button self.export_button = Button(self.details_frame, text="Export...", font="Arial 12 bold", fg="white", bg="#003366", width="10" , command=lambda: self.export(partner, quiz_history, all_quiz_results)) self.export_button.grid(row=5, column=0, pady=10) def close_results(self, partner): # Put stats back to normal... partner.results_button.config(state=NORMAL) self.results_box.destroy() def export(self, partner, quiz_history, all_quiz_results): Export(self, quiz_history, all_quiz_results) class Export: def __init__(self, partner, quiz_history, all_quiz_results): print(all_quiz_results) # disable export button partner.export_button.config(state=DISABLED) # Sets up child window (i.e: export box) self.export_box = Toplevel() # if users press cross at top, closes export and 'releases' export button self.export_box.protocol('WM_DELETE_WINDOW', partial(self.close_export, partner)) # Set up GUI Frame self.export_frame = Frame(self.export_box, width=300) self.export_frame.grid() # Set up export heading (row) self.how_heading = Label(self.export_frame, text="Export / Instruction", font="arial 14 bold") self.how_heading.grid(row=0) # Export Instruction (label, row 1) self.export_text = Label(self.export_frame, text="Enter a filename " "in the box below " "and press the Save " "button to save your " "calculation history " "to a text file ", justify=LEFT, width=40, wrap=250) self.export_text.grid(row=1) # warning text(label, row 2) self.export_text = Label(self.export_frame, text="If the filename " "you enter below " "already exists, " " its contents will " "be replaced with " "your calculation " "history", justify=LEFT, bg="#ffafaf", fg="maroon", font="Arial 10 italic", wrap=225, padx=10, pady=10) self.export_text.grid(row=2, pady=10) # Filename Entry box (row 3) self.filename_entry = Entry(self.export_frame, width=20, font="Arial 14 bold", justify=CENTER) self.filename_entry.grid(row=3, pady=10) # Error Message Labels (initially blank, row 4) self.save_error_label = Label(self.export_frame, text="", fg="maroon") self.save_error_label.grid(row=4) # Save / cancel Frame (row 5) self.save_cancel_frame = Frame(self.export_frame) self.save_cancel_frame.grid(row=5, pady=10) # Save and cancel Buttons (row 0 of save_cancel_frame) self.save_button = Button(self.save_cancel_frame, text="Save", font="Arial 15 bold", bg="#003366", fg="white", command=partial(lambda: self.save_history(partner, quiz_history, all_quiz_results))) self.save_button.grid(row=0, column=0) self.cancel_button = Button(self.save_cancel_frame, text="Cancel", font="Arial 15 bold", bg="#660000", fg="white", command=partial(self.close_export, partner)) self.cancel_button.grid(row=0, column=1) def save_history(self, partner, quiz_history, quiz_results): # Regular expression to check filename is valid valid_char = "[A-Za-z0-9_]" has_error = "no" filename = self.filename_entry.get() for letter in filename: if re.match(valid_char, letter): continue elif letter == " ": problem = "(no space allowed)" else: problem = ("(no {}'s allowed)".format(letter)) has_error = "yes" break if filename == "": problem = "can't be blank" has_error = "yes" if has_error == "yes": # Display error message self.save_error_label.config(text="Invalid filename - {}".format(problem)) # Change entry box background to pink self.filename_entry.config(bg="#ffafaf") else: # If there are no errors, generate text file and then close dialogue # add .txt suffix! filename = filename + ".txt" # create file to hold data f = open(filename, "w+") # Heading for stats f.write("Quiz Results\n\n") # Game Stats for rounds in quiz_results: f.write(rounds + "\n") # Heading for Rounds f.write("\nRound Details\n\n") # add new line at end of each item for item in quiz_history: f.write(item + "\n") # close file f.close() # close dialogue self.close_export(partner) def close_export(self, partner): # Put export back to normal... partner.export_button.config(state=NORMAL) self.export_box.destroy() # main routine: if __name__ == "__main__": root = Tk() root.title("Maths Quiz") something = Quiz() root.mainloop()
#!/usr/bin/env python #-*- coding:utf-8 -*- # author:FCQ # datetime:2018/4/9 13:48 # software: PyCharm #本模块包换购物车主体函数、购物记录查询函数 def shoppingcart(username,salary): ' 购物车主体函数 ' # salary = input("请输入工资:") product_list = [ ('Iphone',5800), ('mac',9800), ('bike',800), ('watch',5800), ('coffee',31), ('alex',100) ] shopping_list = [] if salary.isdigit() : salary = int(salary) while True: for item in product_list: print(product_list.index(item),item) user_choice = input("选择要买吗,输入q退出>>>:") if user_choice.isdigit(): user_choice = int(user_choice) if user_choice < len(product_list) and user_choice >= 0: p_item = product_list[user_choice] if p_item[1] <= salary: shopping_list.append(p_item) # print(shopping_list, "\033[36;1放入购物车成功!\033[0m") salary -=p_item[1] print("\033[36;1m added %s into shopping cart ,your current balance is %s \033[0m" %(p_item,salary)) else: print("\033[41;1m 你的余额只剩[%s] \033[0m" %salary) else: print("product code [%s] is not exist!" %user_choice) elif user_choice == 'q': print('------shoping list------') for p in shopping_list: with open('./' + username + "/recording.txt", "a+", encoding="utf-8") as f: p = str(p) f.write(p+'\n') print(p) with open('./' + username + "/salary.txt", "w+", encoding="utf-8") as f: salary = str(salary) f.write(salary) print("your current balance:", salary) exit() else: print("invalid option") def Query_the_records(choose,username): '购物车记录查询' if choose == 'y': with open('./' + username + "/recording.txt", "r", encoding="utf-8") as f: recording = f.read() # 显示文本内容 print(recording) else: pass
#Palindrome def is_palindrome(): str1 = input("enter a input:") if str1 == str1[::-1]: print("yes palindrome") else: print("No palindrome") is_palindrome()
#if statement to determine whether a variable holding a year is a leap year. def is_prime(year): if year % 4 == 0 and year % 100 != 0: print("leap2 year") elif year % 100 == 0: print("Not leap year") elif year % 400 == 0: print("leap year") else: print("Not leap year") year = int(input("Enter a year:")) is_prime(year)
#filters out strings an returns the array filled with numbers #First attempt import unittest def filter_list(l): new_l = [] for value in l: if isinstance(value, int): new_l.append(int(value)) return new_l print(filter_list([10,2,50,77,'abd','ccd',89,100])) print(filter_list([1,2,'a','b'])) class Test(unittest.TestCase): def test(self): self.assertEqual(filter_list([1,2,'a','b']),[1,2]) self.assertEqual(filter_list([1,'a','b',0,15]),[1,0,15]) self.assertEqual(filter_list([1,2,'aasf','1','223',123]),[1,2,123]) if __name__ == '__main__': unittest.main()
"""Short Rules 1 Arrange your ships on Grid according to FLEET table 2 Take turns firsing a salvo at your enemy, calling out squares as "A3,B3", etc Salvo = number of your ships you have left (use count)/1 shot(easy) 3 Mark salvos fired on "Enemy Ships" grid "/" marks water, "X" marks hit 4 Sink 'em all! (Victory Condition) """ import arcade # Screen title and size SCREEN_WIDTH = 1024 SCREEN_HEIGHT = 768 SCREEN_TITLE = "Map Screen Test" GAME_TILE_WIDTH = (SCREEN_WIDTH - (SCREEN_WIDTH*.1))/11 GAME_TILE_HEIGHT = (SCREEN_HEIGHT - (SCREEN_HEIGHT*.1))/11 VERTICAL_SPACING_PERCENT = 0.010 HORIZONTAL_SPACING_PERCENT = 0.010 VERTICAL_BORDER_PERCENT = .1 HORIZONTAL_BORDER_PERCENT = .0909 class EgohBattleShipGame(arcade.Window): # """ Main application class. """ def __init__(self): super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) arcade.set_background_color(arcade.color.GRAY_BLUE) self.players = [] self.tileList = [] self.newTileList = None def setup(self): """ Set up the game here. Call this function to restart the game. """ self.newTileList = arcade.SpriteList() def on_draw(self): """ Render the screen. """ # Clear the screen arcade.start_render() # test = arcade.draw_rectangle_filled( # (HORIZONTAL_BORDER_PERCENT*SCREEN_WIDTH)/2 , # 100, GAME_TILE_WIDTH, GAME_TILE_HEIGHT, # arcade.csscolor.AZURE) # arcade.draw_rectangle_filled( # (HORIZONTAL_BORDER_PERCENT*SCREEN_WIDTH)/2 + GAME_TILE_WIDTH + SCREEN_WIDTH*HORIZONTAL_MARGIN_PERCENT , # 100, GAME_TILE_WIDTH, GAME_TILE_HEIGHT, # arcade.csscolor.AZURE) # distance = (HORIZONTAL_BORDER_PERCENT * SCREEN_WIDTH)/2 - (HORIZONTAL_SPACING_PERCENT*SCREEN_WIDTH)/2 self.newTileList.draw() # newTile = self.createGameTile("A", "3") # print(newTile.shape.position) # newTile.shape.draw() # newTile02 = self.createGameTile("J", "1") # newTile02.shape.draw() # newTile03 = self.createGameTile("D", "8") # newTile03.shape.draw() # columns = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] # rows = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] # tilesCreated = set() # for column in columns: # for row in rows: # if (column, row) not in tilesCreated: # gameTile = self.createGameTile(column, row) # self.placeGameTile(gameTile) # tilesCreated.add((column, row)) # gameTile.shape.draw() def on_mouse_press(self, x, y, button, key_modifiers): """ Called when the user presses a mouse button. """ pass def on_mouse_release(self, x: float, y: float, button: int, modifiers: int): """ Called when the user presses a mouse button. """ pass def on_mouse_motion(self, x: float, y: float, dx: float, dy: float): """ User moves mouse """ pass def addPlayer(self, name: str): if len(self.players) < 2: self.players.append(name) def createShip(self, type): newShip = Ship(type) return newShip def createGameTile(self, type, column, row): # distance = (HORIZONTAL_BORDER_PERCENT * SCREEN_WIDTH)/2 - (HORIZONTAL_SPACING_PERCENT*SCREEN_WIDTH)/2 gameTile = GameTile(type, column, row) return gameTile def placeGameTile(self, gametile): tempTileList = self.tileList.copy() tempTileList.append(gametile) self.newTileList.append(gametile.shape) self.tileList = tempTileList class Ship: def __init__(self, type): shipDict = { "AircraftCarrier": 5, "Battleship" : 4, "Cruiser" : 3, "Destroyer" : 2, "Submarine" : 1 } self.type = type self.size = shipDict[type] self.damage = 0 class GameTile: def __init__(self, tileType, column: chr, row: int): xPositionDict = {"A": .05+1*.09, "B": .05+2*.09, "C": .05+3*.09, "D": .05+4*.09, "E": .05+5*.09, "F": .05+6*.09, "G": .05+7*.09, "H": .05+8*.09, "I": .05+9*.09, "J": .05+10*.09, } yPositionDict = {"1": .05+1*.09, "2": .05+2*.09, "3" : .05+3*.09, "4": .05+4*.09, "5": .05+5*.09, "6": .05+6*.09, "7": .05+7*.09, "8": .05+8*.09, "9": .05+9*.09, "10": .05+10*.09, } typeDict = { "water": arcade.csscolor.AZURE, "ship" : arcade.csscolor.DIM_GREY, "hit" : arcade.csscolor.DARK_RED, "miss" : arcade.csscolor.BLACK, "damaged" : arcade.csscolor.DARK_ORANGE } self.type = tileType self.column = column self.row = row self.x_pos = xPositionDict[column]*SCREEN_WIDTH self.y_pos = yPositionDict[row]*SCREEN_HEIGHT self.shape = arcade.SpriteSolidColor( int(GAME_TILE_WIDTH), int(GAME_TILE_HEIGHT), typeDict[tileType]) self.shape.position = self.x_pos, self.y_pos # top/bottom/right/left margin = 5% # tile spacing = ?? # tile size = ?? def main(): """ Main method """ window = EgohBattleShipGame() window.setup() # newTile = window.createGameTile("A", "3") # window.newTileList.append(newTile.shape) columns = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] rows = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] tilesCreated = set() for column in columns: for row in rows: if (column, row) not in tilesCreated: gameTile = window.createGameTile("hit", column, row) window.placeGameTile(gameTile) tilesCreated.add((column, row)) arcade.run() if __name__ == "__main__": main()
# Importing the libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # The table loaded is the births data births = pd.read_csv('https://raw.githubusercontent.com/jakevdp/data-CDCbirths/master/births.csv') # Code Below is trying to acheive something # Please explain what is being done here # If there is any potential error, please bring that up as well quartiles = np.percentile(births['births'], [25, 50, 75]) mu, sig = quartiles[1], 0.74 * (quartiles[2] - quartiles[0]) births = births.query('(births > @mu - 5 * @sig) & (births < @mu + 5 * @sig)') # Q1 Find the sum of Male and Female Birth # High difficulty : Feel free to ask for direction from interviewer # Q2. a) Combine the columns Year, Month and Day to a single column into a single column # Q2. b) For the new column, convert it to table index births.index = pd.to_datetime(10000 * births.year + 100 * births.month + births.day, format='%Y%m%d') # Q3. Show the distinct columns in the dataframe # Q4. Remove the Year, Month & Day column # Q5. What is your understanding of inplace command in pandas # Why would you use inplace command ? Cite an example # Solutions # Potential Error # 50th Percentile/ .5 Quartile is Median # There is difference between Mean & Median # mu should be mean not Median (Statistically) # Sol 1 births.groupby(['gender'])['births'].sum() # Sol 2 births.index = pd.to_datetime(10000 * births.year + 100 * births.month + births.day, format='%Y%m%d') # Sol 3 births.column # Sol 4 births.drop(['year','month','day'],axis=1) # Sol 5 # Inplace is used to do the operation on the original dataframe births_1 = births.drop(['year','month','day'],axis=1) # Can be replaced by births.drop(['year','month','day'],axis=1,inplace=True)
cases = int(input()) def SolveCase(case): lst = [int(x) for x in input()] string = '' nestLevel = 0 for el in lst: if nestLevel == el: pass elif nestLevel > el: while nestLevel > el: string += ')' nestLevel -= 1 elif nestLevel < el: while nestLevel < el: string += '(' nestLevel += 1 string += str(el) while nestLevel>0: string += ')' nestLevel -=1 print('Case #' + str(case+1) + ':', string) for i in range(cases): SolveCase(i)
m = float(input("Enter the month")) d = float(input("Enter the day")) y = float(input("Enter the year")) y0 = y - (14 - m) // 12 x = y0 + y0//4 - y0//100+ y0//400 m0 = m + 12 * ((14 - m) // 12) - 2 d0= (d + x + (31*m0)//12) % 7 print ("The day of the week is:", d0)
def merge_sort(start, end, nums): if start > end: return if start == end: return nums[start] mid = (start + end) / 2 merge_sort(start, mid, nums) merge_sort(mid+1, end, nums) merge(start, end, mid, nums) def merge(start, end, mid, nums): temp = [0] * (end-start+1) index1 = start index2 = mid+1 list1_size = mid index = 0 while index1 <= list1_size and index2 <= end: if nums[index1] <= nums[index2]: temp[index] = nums[index1] index1 += 1 else: temp[index] = nums[index2] index2 += 1 index += 1 while index1 <= list1_size: temp[index] = nums[index1] index1 += 1 index += 1 while index2 <= end: temp[index] = nums[index2] index2 += 1 index += 1 for i in range(start, end+1): nums[i] = temp[i-start] def sort(nums): return merge_sort(0, len(nums)-1, nums) foo = [1,3,2,5,4,9,7,12] sort(foo) print foo
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def find_mid(self, head): if not head: return None slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next return slow def merge(self, list1, list2): curr = ListNode(0) head = curr while list1 and list2: if list1.val <= list2.val: curr.next = list1 list1 = list1.next else: curr.next = list2 list2 = list2.next curr = curr.next if list1: curr.next = list1 if list2: curr.next = list2 return head.next def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head mid = self.find_mid(head) next = mid.next mid.next = None left = self.sortList(head) right = self.sortList(next) return self.merge(left, right)
class Solution(object): def change(self, amount, coins, level): """ :type amount: int :type coins: List[int] :rtype: int """ level += "-" ways = 0 if amount == 0: return 1 if amount < 0: return 0 for c in coins: way = self.change(amount-c, coins, level) print level + str(way) ways += way return ways s = Solution() print s.change(5, [1,2,5], "")
class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return head slow, fast = head, head.next while fast and fast.next: if slow == fast: break slow = slow.next fast = fast.next.next else: return None slow = head while slow: if slow == fast: return slow fast = fast.next slow = slow.next return None class ListNode(object): def __init__(self, x): self.val = x self.next = None def print_all(self): rst = str(self.val)+"->" curr = self.next while curr: rst += str(curr.val) rst += "->" curr = curr.next rst += "null" return rst def convert_arr_to_list(nums): head = ListNode(0) curr = head for i in range(0, len(nums)): curr.next = ListNode(nums[i]) curr = curr.next return head.next s = Solution() one = ListNode(1) two = ListNode(2) one.next = two two.next = one s.detectCycle(one)
def permutation(numstr): rst = [] level = [] dfs(rst, level, numstr) return rst def dfs(rst, level, numstr): if len(level) == len(numstr): rst.append(level[:]) for s in numstr: if s.lower() in level or s.upper() in level: continue level.append(s.lower()) dfs(rst, level, numstr) level.pop() level.append(s.upper()) dfs(rst, level, numstr) level.pop() print permutation("abc")
#I am creating an array signifyig the board. class board(): def __init__(self): self.board=[[0 for l in range(32)] for j in range(30)] #returns 1 if the block can occupy else 0. def checkpiecepos(self,x,y,array): for i in range(x,x+4): for j in range(y,y+4): if(array[i-x][j-y]): if(i<0 or i>31 or j>=30): return 0 if( (i>=0 and i<=31 and j<=29) and (array[i-x][j-y]==1) ): if (self.board[j][i]==1): return 0 return 1 def fillpiecepos(self,x,y,array): for i in range(x,x+4): for j in range(y,y+4): if(array[i-x][j-y]==1): self.board[j][i] = 1 #This is used for making the old co-ordinates of the block #empty when it is ready to move i.e only if checkpiecepos #returns 1. #The co-ordinates used are the old ones used for previous fill and should be called before move or rotate is called. def resetblockplace(self,x,y,array): for i in range(x,x+4): for j in range(y,y+4): if(i>=0 and i<32 and j<30 and array[i-x][j-y]==1): self.board[j][i] = 0
#Sawyer Paeth #Due Dec. 7th #CS 325 Portfolio Project - Sudoku Solver def checkRow(board, row): seenArr = [] #Creates empty array to track non empty squares for i in range(0, 9): if board[row][i] in seenArr: #return false if repeat is found return False if board[row][i] != 0: #Add new number to array seenArr.append(board[row][i]) return True def checkCol(board, col): seenArray = [] #Creates empty array to track non empty squares for i in range(0, 9): if board[i][col] in seenArray: #return false if repeat is found return False if board[i][col] != 0: seenArray.append(board[i][col]) #Add new number to array return True def checkBox(board, sRow, sCol): seenArray = [] #Creates empty array to track non empty squares for row in range(0, 3): for col in range(0, 3): current = board[row+sRow][col + sCol] #set current if current in seenArray: #repeat found in 3x3 return False return False if current != 0: seenArray.append(current) return True def verify(board, row, col): #Check for repeats in row, column and 3x3 square return (checkRow(board, row) and checkCol(board, col) and checkBox(board, row - row%3, col - col%3)) def verifySetUp(board): for i in range(0, 9): for j in range(0, 9): if not verify(board, i, j): #return False is checkRow, CheckCol or checkBox returns False return False return True def checker(row,col,n): for i in range(0,9): #check if newly placed number is a repeat in row if board[row][i] == n: return False for j in range(0,9): #check if newly placed number is already in column if board[j][col] == n: return False col2 = (col//3) * 3 row2 = (row//3) * 3 for k in range(0,3): for l in range(0,3): if board[row2 + k][col2 + l] == n: #check if newly placed number already in 3x3 square return False return True def find(row, col): #find squares that are empty num_find = 0 for a in range(0,9): for b in range(0,9): if board[a][b] == 0: #check if empty square row = a col = b num_find = 1 x = [row, col, num_find] return x #return x with location of empty square x = [-1, -1, num_find] return x def solveSudoku(): row = 0 column = 0 x = find(row,column) #call num remove on 0,0 if x[2] == 0: return True row = x[0] column = x[1] for n in range(1,10): #check through integers 1-9 if checker(row, column, n) == True: #check if current n can be placed board[row][column] = n if solveSudoku(): #return True if solver works return True board[row][column] = 0 return False board = [[0, 0, 0, 0, 0, 9, 0, 7, 8], [0, 0, 0, 7, 0, 0, 9, 0, 0], [5, 0, 0, 0, 2, 0, 0, 0, 4], [0, 0, 3, 0, 7, 0, 0, 8, 0], [0, 2, 5, 0, 8, 0, 7, 6, 0], [0, 9, 0, 0, 5, 0, 4, 0, 0], [1, 0, 0, 0, 9, 0, 0, 0, 5], [0, 0, 4, 0, 0, 3, 0, 0, 0], [9, 3, 0, 4, 0, 0, 0, 0, 0]] if verifySetUp(board): if solveSudoku() == True: print('Solution:') for x in range(0,9): print(board[x]) else: print("No solution possible") else: print("Input board is not valid.")
#!/usr/bin/env python import matplotlib.pyplot as plt x = [0,1,2,3,4,5,6,7] x1 = [8,9,10,11] y = [0,1,2,3,5,6,7,8] y1 = [9,10,11,12] x2 = [2,23,45,68] def main(): plt.plot(x, y, 'go-', label = 'Test1', antialiased = False) lines = plt.plot(x1,y1, 'b*-', label = 'Test2') plt.setp(lines) plt.xlabel('Testx') plt.ylabel('Testy') plt.axis([0,15,0,15]) plt.legend() plt.show() plt.close() if __name__ == '__main__': main()
#!/usr/bin/env python3 import random board = [] board_ends = [] player_pos = [] monster_type = '' x = 0 y = 0 #print menu at beginning def menu(): print('> Welcome to the game!') choose_board() choose_monster() def choose_board(): choose_dim = input('> Default board dimensions is 3x3. Press Y for default or N to customize: ').lower() if choose_dim == 'n': dim = tuple(map(int,input('> Please input number of cells, seperated by a comma (e.g. 3,4): ').split(','))) get_dimensions(dim) elif choose_dim == 'y': get_dimensions((3,3)) else: print('Input invalid. Please enter "Y" or "N"') return choose_board() def choose_monster(): choose_monster = input('> Monster is static by default. If you would like a dynamic monster, press Y, else press N: ').lower() if choose_monster.isalpha(): global monster_type monster_type = choose_monster elif not choose_monster.isalpha(): print('> Input invalic. Please select "Y" or "N".') return choose_monster() #function to make list of ends of board def ends(): n_board = board num = (y - 1) for index, tup in enumerate(n_board): if index == num: board_ends.append(index) num += y #function to get number of cells in game def get_dimensions(cells): length,width = cells #length, width global x x = length global y y = width length_index = 0 width_index = 0 for length_index in range(length): for width_index in range((width)): board.append((length_index, width_index)) #function to print map def draw_map(player, monster): for line in range(y-1): print(' _', end = '') print(' _ ') tile = '|{}' for index, cell in enumerate(board): if index not in board_ends: if cell == player: print(tile.format('X'), end = '') elif cell == monster: print(tile.format('M'), end = '') else: print(tile.format('_'), end = '') else: if cell == player: print(tile.format('X|')) elif cell == monster: print(tile.format('M|')) else: print(tile.format('_|')) #function to keep track of players moves #def track_player(player): #function to move player def move_player(player, move): x_player,y_player = player if move == 'LEFT': y_player -= 1 elif move == 'RIGHT': y_player += 1 elif move == 'UP': x_player -= 1 elif move == 'DOWN': x_player += 1 return x_player,y_player #function to move monster def move_monster(monster, value, moves): if value == 1: x_monster,y_monster = monster move = random.choice(moves) if move == 'LEFT': y_monster -= 1 elif move == 'RIGHT': y_monster += 1 elif move == 'UP': x_monster -= 1 elif move == 'DOWN': x_monster += 1 return x_monster,y_monster else: pass #function to keep track of available moves def get_moves(player): moves = ['LEFT', 'RIGHT', 'UP', 'DOWN'] if player[1] == 0: moves.remove('LEFT') if player[1] == (y-1): moves.remove('RIGHT') if player[0] == 0: moves.remove('UP') if player[0] == (x-1): moves.remove('DOWN') return moves def get_moves_monster(monster, value): if value == 1: moves = ['LEFT', 'RIGHT', 'UP', 'DOWN'] if monster[1] == 0: moves.remove('LEFT') if monster[1] == (y-1): moves.remove('RIGHT') if monster[0] == 0: moves.remove('UP') if monster[0] == (x-1): moves.remove('DOWN') return moves else: pass #function to get starting positions of player, monster, and door def get_positions(): player = random.choice(board) monster = random.choice(board) door = random.choice(board) if door == player or door == monster or monster == player: return get_positions() return player, monster, door def main(): menu() ends() player, monster, door = get_positions() value = 0 if monster_type == 'y': value = 1 while True: print() print('You are currently in position {}'.format(player)) #fill in with player position moves = get_moves(player) moves_monster = get_moves_monster(monster, value) draw_map(player, monster) print('You can move {}'.format(moves)) #fill in with available moves print('Enter QUIT to quit.') move = input('> ') move = move.upper() if move == 'QUIT': break if move in moves: #track_player(player) player = move_player(player, move) monster = move_monster(monster, value, moves_monster) elif move not in moves: print('Move not acceptable.') continue if player == door: print('You escaped. You Win!') break elif player == monster: print('You were eaten by the monster.You Lose.') break else: continue if __name__ == '__main__': main()
#!/usr/bin/env python3 from queue import Queue class BinaryTree: def __init__(self, value): self.value = value self.left_node = None self.right_node = None def insert_left(self, value): if self.left_node == None: self.left_node = BinaryTree(value) else: new_node = BinaryTree(value) new_node.left_node = self.left_node self.left_node = new_node def insert_right(self, value): if self.right_node == None: self.right_node = BinaryTree(value) else: new_node = BinaryTree(value) new_node.right_node = self.right_node self.right_node = new_node def bfs(self): queue = Queue() queue.put(self) while not queue.empty(): current_node = queue.get() print(current_node.value) if current_node.left_node: queue.put(current_node.left_node) if current_node.right_node: queue.put(current_node.right_node) def BinarySearchTree(self): def __init__(self, value): self.value = value self.left_node = None self.right_node = None def insert_node(self, value): if(value <= self.value and self.left_node): self.left_node.insert_node(value) elif(value <= self.value): self.left_node = BinarySearchTree(value) elif(value > self.value and self.right_node): self.right_node.insert_node(value) else: self.right_node = BinarySearchTree(value) def find_node(self, value): if(value < self.value and self.left_node): self.left_node.find_node(value) elif(value > self.value and self.right_node): self.right_node.find_node(value) return value == self.value def remove_node(self, value, parent): if (value < self.value and self.left_node): return self.left_node.remove_node(value, self) elif (value < self.value): return False elif (value > self.value and self.right_node): return self.right_node.remove_node(value, self) elif (value > self.value): return False else: if (self.left_node is None and self.right_node is None and self == parent.left_node): parent.left_node = None self.clear_node() elif (self.left_node is None and self.right_node is None and self == parent.right_node): parent.right_node = None self.clear_node() elif (self.left_node and self.right_node is None and self == parent.left_node): parent.left_node = self.left_node self.clear_node() elif (self.left_node and self.right_node is None and self == parent.right_node): parent.right_node = self.left_node self.clear_node() elif (self.right_node and self.left_node is None and self == parent.left_node): parent.left_node = self.right_node self.clear_node() elif (self.right_node and self.left_node is None and self == parent.right_node): parent.right_node = self.right_node self.clear_node() else: self.value = self.right_node.find_minimum_node() self.right_node.remove_node(self.value, self) return True def clear_node(self): self.value = None self.left_node = None self.right_node = None def find_minimum_node(self): if self.left_node: return self.left_node.find_minimum_node() else: return self.value def printBinaryTree(): a_tree = BinaryTree('a') print(a_tree.value) print(a_tree.left_node) print(a_tree.right_node) a_tree.insert_left('b') b_tree = a_tree.left_node b_tree.insert_right('d') a_tree.insert_right('c') c_tree = a_tree.right_node c_tree.insert_right('f') c_tree.insert_left('e') print("A: Left: " + a_tree.left_node.value) print("A: Right: " + a_tree.right_node.value) print("B: Right: " + b_tree.right_node.value) print("C: Left: " + c_tree.left_node.value) print("C: Right: " + c_tree.right_node.value) a_tree.bfs() def printBinarySearchTree(): bst = BinarySearchTree(15) bst.insert_node(10) bst.insert_node(8) bst.insert_node(12) bst.insert_node(20) bst.insert_node(17) bst.insert_node(25) bst.insert_node(19) print(bst.find_node(15)) print(bst.find_node(10)) print(bst.find_node(8)) print(bst.find_node(12)) print(bst.find_node(20)) print(bst.find_node(17)) print(bst.find_node(25)) print(bst.find_node(19)) print(bst.remove_node(8, None)) # True print(bst.remove_node(17, None)) # True print(bst.remove_node(15, None)) # True def main(): printBinarySearchTree() if __name__ == '__main__': main()
def dp_make_weight(egg_weights, target_weight, memo = {}): new_eggs = egg_weights if target_weight in memo: return memo[target_weight] elif len(new_eggs) == 1: result = target_weight elif new_eggs[-1] > target_weight: result = dp_make_weight(new_eggs[:-1], target_weight, memo) else: nextItem = new_eggs[-1] Withvalue = dp_make_weight(new_eggs, target_weight - nextItem, memo) Withvalue += 1 WithoutValue = dp_make_weight(new_eggs[:-1], target_weight, memo) if Withvalue > WithoutValue: result = WithoutValue else: result = Withvalue memo[target_weight] = result return result # bottom up approach def dp_make_weight2(egg_weights, target_weight, memo = {}): assert 1 in egg_weights assert all(x<y for x, y in zip(egg_weights, egg_weights[1:])) # creates a list of zeros dp = [0 for i in range(target_weight+1)] for i in range(1, target_weight+1): dp[i] = 1 + min([dp[i-weight] for weight in egg_weights if weight<=i]) print(dp) return dp[target_weight] # EXAMPLE TESTING CODE, feel free to add more if you'd like if __name__ == '__main__': egg_weights = (1, 5, 10, 25) n = 99 print("Egg weights = (1, 5, 10, 25)") print("n = 99") print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)") print("Actual output:", dp_make_weight2(egg_weights, n)) print()