text
stringlengths
37
1.41M
class Person: name = '' age = 110 def __init__(self,name,age): self.name = name self.age = age one = Person('zhankeqing',25) f = getattr(one,'name') print(f)
def generator(k): i = 1 while True: yield i ** k i += 1 gen_1 = generator(1) gen_3 = generator(3) print(gen_1) print(gen_3) def get_sum(n): sum_1 , sum_3 = 0,0 for i in range(n): next_1 = next(gen_1) next_3 = next(gen_3) print('next_1={},next_3={}'.format(next_1,next_3)) sum_1 += next_1 sum_3 += next_3 print(sum_1 * sum_1 ,sum_3) print(get_sum(8))
#原始字符串 s1 = "D:\codes\pythonlearn\fenpythonbook\2\2.4" print(s1) s2 = "D:\\codes\\pythonlearn\\fenpythonbook\\2\\2.4" print(s2) raws = r"D:\codes\pythonlearn\fenpythonbook\2\2.4" print(raws) raws2 = r'"Let\'s go",said Charlie' print(raws2) raws3 = r'Good Morning' '\\' print(raws3)
user = "Charli" age = 8 #格式化字符串吕有两个占位符,第三部分也应该提供两个变量 print("%s is a %s years old boy"%(user,age)) ''' num=28 #当中的 6 表示 输出宽度,也可理解 除输出外用0填充 #i/d,转换为带符号的十进制整数 print("num is: %6i" % num) print("num is: %06d" % num) #o 八进制整数 print("num is: %6o" %num) #x/X 转换为带符号的十六进制形式的整数 print("num is: %6x" %num) print("num is: %6X" %num) #使用str 转为字符串 print("num is: %6s" %num) ################################ num2 = 30 #最小宽度为6左边补0 print("num2 is: %06d" %num2) #最小宽度为6,左边补0总带上符号 print("num2 is:%+6d" % num2) #0 表示不补充空格,而是补充0 print("num2 is:%-6d" % num2) ''' my_value = 3.001415926535 #最小宽度为8,小数点后保留3位 print("my_value is: %8.3f" % my_value) #最小宽度为8,小数点后保留3位,左边补0 print("my_value is: %08.3f" % my_value) #最小宽度为8,小数点后保留3位,左边补0,始终 带符号 print("my_value is %+08.3f" % my_value) the_name = "Charlie" #只保留3个字符 print("the name is: %.3s" % the_name) #保留2个字符,最小宽度为10 print("the name is: %10.2s" % the_name)
src_list = [12,45,3.4,13,'a',4,56,'crazyit',109.5] my_sum = my_count = 0 for ele in src_list: #如果元素是整数或是浮点数 if isinstance(ele,int) or isinstance(ele,float): print(ele) #累加该元素 my_sum += ele #数值元素的个数加 1 my_count += 1 print("总和:",my_sum) print("平均数",my_sum / my_count)
s = "talk is cheap".title() print(s) ''' sq = ["1","2"] sp='+' print(sp.join(sq)) title="money python" re = title.find('fy') print(re) print('s5'.center(5,'*')) width = int(input('please enter width: ')) #35 price_width=10 item_width=width-price_width #25 header_fmt = '{{:{}}},{{:>{}}}'.format(item_width,price_width) #{:25},{:>10} fmt='{{:{}}},{{:>{}.2f}}'.format(item_width,price_width) #{:25},{:>10.2f} #print(fmt) print('='*width) print(header_fmt.format('Item',"Price")) from math import pi print("{pi!s} , {pi!r}, {pi!a},{pi}".format(pi=pi)) fullname = ["Alfred","smoketoomuch"] s = "Mr {name[0]}".format(name=fullname) print(s) f = "{foo} {} {bar} {}".format(1,2,bar=4,foo=3) print(f) from math import e print(f"contansts {e}.") print("contansts {e}.".format(e='111')) print("{name} is app {value:.2f}".format(name="PI",value=pi)) format = "hello,%s.%s enough for you " values = ("world","hot") print(format % values) print("hello,%s.%s enough for you " % ("world","hot")) from string import Template tmpl = Template("Hello ,$who! $what enough for ya ?") tmpl.substitute(who="Mars",what="Dusty") "{},{} and {}".format("first","second","third") "{0},{1} and {2}".format("first","second","third") print("{1},{2} and {0}".format("first","second","third")) '''
s_max = input("请输入您想计算的阶乘:") mx = int(s_max) result = 1 #使用for in 循环 for num in range(1,mx+1): result *= num print(result)
#关于生成器函数使用 def even_number(max): n=0 while n< max: yield n n += 2 for i in even_number(10): print(i) break
class User: def __init__(self,name="ddds"): self.name=name def walk(self,content="d"): print(self,"正在慢慢地走",content) u= User() User.walk(u) #u.walk("fkit") class Person: '这是一个学习Python定义的一个Person类' hair = "black" def __init__(self,name="Charlie"): #定义实例变量 self.name = name #定义一个say() 方法 def say(self,content): print(content) u = Person() u.say("dd")
lst = [1,2,3,4] it = iter(lst) for x in it: print(x,",")
cars = {"bmw":8.5,"bens":"44a","audi":442} #返回所有的k-v dict_items 对象 ims = cars.items() print(ims) #将dict_items转换成列表 print(list(ims)) print(tuple(ims)) #访问第二个key-v 对 print(list(ims)[1]) #获取字典中所有的key,返回一个dict_keys对象 kys = cars.keys() print(kys) #访问第二个key print(list(kys)[1]) #获取字典中所有的values,返回一个dict_values vals = cars.values() print(vals) #访问第二个value print(list(vals)[1]) print(type(vals))
''' class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) try: raise MyError('oops') except MyError as e: print('My exception occurred, value:', e.value) ''' with open("myfile.txt") as f: for line in f: print(line) #raise MyError('oops!')
#统计各元素出现的次数 src_list = [12,45,3.4,12,"fkit",45,3.4,"fkit",45,3.4] statistis = {} for ele in src_list: #如果字典中包含ele代表的key if ele in statistis: statistis[ele] += 1 else: statistis[ele] = 1 for ele,count in statistis.items(): print("%s 出现的次数为:%d" % (ele,count))
class Cat: def __init__(self,name): self.name = name #这个定义本身是为类使用的,且是为类当中有name属性才可用 def walk_func(self): print("{}慢慢地走过一片草地".format(self.name)) d1 = Cat("Garfield") d2 = Cat("Kitty") #为类赋属性 Cat.walk = walk_func Cat.params = "good job"#添加属性 #这挺神奇的,定义后的类实例,还能使用类之后 生成的动态方法与变量 d1.walk() d2.walk() print(d1.params) s = {'name':"good"} print(s['name']) def struct(): pass o = struct() #o.name = "good" #error #walk_func(o)
a_tuple=("crazyit",20,-1.2) b_tuple=(127,"crazyit","fkit",3.33) #元组相加 sum_tuple=a_tuple+b_tuple print(sum_tuple) print(a_tuple+(2,)) a_list=["crazyit",20,-1.2] b_list=[127,"crazyit","fkit",3.33] sum_list = a_list+b_list print(sum_list) #相等 print('a'==('a'))
class InConstructor: def __init__(self): # 在构造方法里定义一个foo变量(局部变量) foo = 0 # 使用self代表该构造方法正在初始化的对象 # 下面的代码将会把该构造方法正在初始化的对象的foo实例变量设为6 self.foo = 6 #所有使用InConstructor创建的对象的foo实例变量将被设为6 print(InConstructor().foo)
def check_index(key): if not isinstance(key,int):raise TypeError if key < 0: raise IndexError class ArithmeticSequence: def __init__(self,start=0,step=1): self.start = start self.step = step self.changed = {} def __getitem__(self, item): check_index(item) try:return self.changed[item] except KeyError: return self.start + self.step*item def __setitem__(self, key, value): check_index(key) self.changed[key] = value s= ArithmeticSequence(1,2) print(s[4])
import sort_4 def permutate(array: list): result = [] if len(array) == 1: return [array[:]] for i in range(len(array)): val = array.pop(0) perms = permutate(array) for j in perms: j.append(val) result.extend(perms) array.append(val) return result def insertion(e, s): for i in range(len(s)+1): yield s[:i] + [e] + s[i:] def perm(s): if not s: yield [] else: e, s1 = s[0], s[1:] for s1p in perm(s1): for p in insertion(e, s1p): yield p for pa in perm([1, 2, 3, 4]): print(pa) print("*" * 50) list1 = [3, 2, 1, 4] p_list = permutate(list1) for p in p_list: print(p) # list1.extend([[2, 3]]) # list1.extend([[3, 2]]) # print(list1)
def decorator_function(orignal_function): def wrapper_function(*args, **kwargs): print(f'wrapper fn executed before {orignal_function.__name__}') return orignal_function(*args, **kwargs) return wrapper_function @decorator_function def display(): print('display fn running..') ### for class class Decorator_class(object): def __init__(self, orignal_function): self.orignal_function = orignal_function def __call__(self, *args, **kwargs): print(f'call method executed before {self.orignal_function.__name__}') return self.orignal_function(*args, **kwargs) @decorator_function() def display(): print('display fn running..') @decorator_function def display_info(name, age): print(f'display info ran with args {name}, {age}') display_info('Mehul', 24) display()
#!/usr/bin/env python3 import re from sympy import isprime DEBUG = True def istrunc(n): for d in range(1, len(str(n))): if not isprime(int(str(n)[d:])) or not isprime(int(str(n)[:d])): return False return True n, f = 11, 1 bag = [] while len(bag) < 11: n += 3-f f = -f # if any digit is in the set {2, 4, 5, 6, 8, 0} for a prime number > 100, # then it will yield a composite number when truncated. # Credit: https://blog.dreamshire.com/project-euler-37-solution/ if not (n > 100 and re.search('[245680]', str(n))): if isprime(n) and istrunc(n): if DEBUG: print(n) bag.append(n) print(sum(bag))
def getFirstNonRepeatingChar(inputString): foundChar = "" for index in range(0, len(inputString)): currentChar = inputString[index] subStringToSearch = inputString[0: index] + inputString[index + 1: len(inputString) - 1] if (not currentChar in subStringToSearch): foundChar = currentChar; break return foundChar; if __name__ == "__main__": inputString = str(raw_input("Check for first repeating characters in the following string: ")) firstNonRepeatingChar = getFirstNonRepeatingChar(inputString) if (len(firstNonRepeatingChar)): print("This is the first non repeating char: " + firstNonRepeatingChar) else: print("No repeating char found in the string")
# simple dictionary alien = {'color': 'green', 'points': 5} # accessing a value skin = alien['color'] print(f"The alien's color is {skin}") # getting the value with get dog = {'color': 'red'} dog_color = dog.get('color') dog_points = dog.get('points', 0) print(dog_color) print(dog_points) # adding a new key-value pair alien['x_position'] = 0 print(alien) # {'color': 'green', 'points': 5, 'x_position': 0} # adding to and empty dictionary alien_0 = {} alien_0['color'] = 'green' alien_0['points'] = 5 # modifying values in a dictionary color = {'red': 1, 'blue': 2} print(color) color['red'] = 3 color['blue'] = 4 print(color) # deleting a key-value pair del color['blue'] print(color) # looping through all key-value pairs fave_numbers = {'eric': 17, 'ever': 4} for name, number in fave_numbers.items(): print(f"{name} loves {number}") # looping through all keys for name in fave_numbers.keys(): print(f"{name} loves a number") # looping through all values for number in fave_numbers.values(): print(f"{number} is a favorite") # looping through all the keys in reverse order for name in sorted(fave_numbers.keys(), reverse=True): print(f"Hi, {name}!") # finding dictionary length num_persons = len(fave_numbers) print(num_persons)
bikes = ['trek', 'redline', 'giant'] # get the first element of bikes first = bikes[0] # get the second element of bikes second = bikes[1] # get the last element of bikes last = bikes[-1] # changing an element bikes[0] = 'valerie' bikes[-2] = 'robby' # loop through a list for bike in bikes: print(bike) # or for x in bikes: print(f"Hi, this is {x}") # adding item to bikes bikes.append('specialize') print(bikes) # ['trek', 'redline', 'giant', 'specialize'] # deleting an element by its position del bikes[-1] # removing an item by its value bikes.remove('valerie') # remove any items from the list using pop users = ['val', 'bob', 'mia'] most_recent_user = users.pop() # pop the last item from the list print(most_recent_user) # 'mia' first_user = users.pop(0) # pop the first item from the list print(first_user) # 'val' # find the length of the list num_users = len(users) print(f"We have {num_users} users.") # sorting a list permanently users.sort() # sorting a list permanently in reverse alphabetical order users.sort(reverse=True) # sorting a list temporarily print(sorted(users)) print(sorted(users, reverse=True)) # reversing the order of a list users.reverse() # making numerical list squares = [] for x in range(1,11): squares.append(x ** 2) print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] cubes = [] for y in range(100): cubes.append(y ** 3) print(cubes) # list comprehensions squares = [x**2 for x in range(1,11)] title = ['one', 'two', 'three'] convert_upper = [t.upper() for t in title] # making a list of numbers from 1 to a million numbers = list(range(1, 1000001)) # using a loop to convert a list of names to upper case names = ['kai', 'abe', 'ada', 'gus', 'zoe'] upper_names = [] for name in names: upper_names.append(name.upper()) print(upper_names) # slicing a list finishers = ['sam', 'bob', 'ada', 'bea'] first_two = finishers[:2] print(first_two) # ['sam', 'bob'] middle_two = finishers[2:3] print(middle_two) # ['bob', 'ada'] last_three = finishers[-3:] print(last_three) # ['bea', 'ada', 'bob'] # copy a list of bikes copy_of_bikes = bikes[:] print(copy_of_bikes) # ['trek', 'redline', 'giant', 'specialize'] # finding the minimum value in a list ages = [6, 7, 1, 2, 3, 4, 5] youngest = min(ages) # finding the maximum ages = [6, 7, 1, 2, 3, 4, 5] oldest = max(ages) # finding the sum of all values ages = [6, 7, 1, 2, 3, 4, 5] total_years = sum(ages) # tuples - similar to list but can't be modified dimensions = (1920, 1080) # looping through a tuple for dimension in dimensions: print(dimension) # overwriting a tuple sides = (100, 200) print(sides) sides = (200, 120)
class Polynomial: "Polynomial([]) -> a polynomial" def __init__ (self,poly): self.poly = poly def __add__(self,poly_new): "return self+poly_new" if len(self.poly) >= len(poly_new.poly): big = self.poly small = poly_new.poly else: big = poly_new.poly small = self.poly d = len(big)-len(small) for i in range(0,len(small)-1): big[i+d] = big[i+d]+small[i] return big def __sub__ (self,poly_new): if len(self.poly) >= len(poly_new.poly): big = self.poly small = poly_new.poly else: big = poly_new.poly small = self.poly d = len(big)-len(small) for i in range(0,len(small)-1): big[i+d] = big[i+d]-small[i] if len(self.poly) < len(poly_new.poly): for i in range(0,len(big)): big[i] = -big[i] return big def __mul__ (self,poly_new): a = Polynomial([]) b = Polynomial([]) if len(self.poly) >= len(poly_new.poly): big = self.poly small = poly_new.poly else: big = poly_new.poly small = self.poly for i in range(len(small)-1,0): for j in range(len(big)-1,0): a.poly.insert(0,small[i]*big[j]) b.poly = Polynomial.__add__(a,b) del b.poly[0:len(big)] b.poly.insert(0,0) return a.poly def main(): a = Polynomial([1,2]) b = Polynomial([4,-9,6.5]) c = a+b print(c) if __name__=="__main__": main()
class Polynomial(): def __init__(self,coeffs,powers=[0]): self.c=coeffs[:] self.p=powers[:] if(len(self.p)!=len(self.c)): self.p.pop() for i in range(len(self.c)): self.p.insert(0,i) def __str__(self): return str(self.c) __repr__=__str__ def __len__(self): return len(self.c) def __add__(self,value): sum=Polynomial([]) sum.c=self.c sum.p=self.p for i in range(len(value)): if(value.p[i]>sum.p[0]): sum.c.insert(0,value.c[i]) sum.p.insert(0,value.p[i]) elif value.p[i]>=sum.p[len(sum.c)-1]: for j in range(len(sum.c)-1): if value.p[i]>sum.p[j+1]: sum.c.insert(j+1,value.c[i]) sum.p.insert(j+1,value.p[i]) break elif value.p[i]==sum.p[j+1]: sum.c[j+1]=sum.c[j+1]+value.c[i] break else: sum.c.append(value.c[i]) sum.p.append(value.p[i]) return sum def __sub__(self,value): sum=Polynomial([]) sum.c=self.c sum.p=self.p print(sum.c) for i in range(len(value)): if(value.p[i]>sum.p[0]): sum.c.insert(0,-value.c[i]) sum.p.insert(0,value.p[i]) print(sum.c) elif value.p[i]>=sum.p[len(sum.c)-1]: for j in range(len(sum.c)-1): if value.p[i]>sum.p[j+1]: sum.c.insert(j+1,-value.c[i]) sum.p.insert(j+1,value.p[i]) print(sum.c) break elif value.p[i]==sum.p[j+1]: sum.c[j+1]=sum.c[j+1]-value.c[i] if sum.c[j+1]==0: sum.c.pop(j+1) sum.p.pop(j+1) print(sum.c) break else: sum.c.append(-value.c[i]) sum.p.append(value.p[i]) print(sum.c) return sum def __getitem__(self,key): return self.c[len(self.c)-key-1] def __setitem__(self,key,value): if(key>self.p[0]): self.c.insert(0,value) self.p.insert(0,key) elif key>=self.p[len(self.c)-1]: for i in range(len(self.c)-1): if key>self.p[i+1]: self.c.insert(i+1,value) self.p.insert(i+1,key) break elif key==self.p[i+1]: self.c[i+1]=value break else: self.c.append(value) self.p.append(key) def __mul__(self,value): prod=Polynomial([0]) for i in range(len(self.c)): for j in range(len(value)): temp1=self.c[i]*value.c[j] temp2=self.p[i]+value.p[j] for k in range(len(prod)): if(temp2>prod.p[0]): prod.c.insert(0,temp1) prod.p.insert(0,temp2) print(prod) break elif temp2>=prod.p[len(prod.c)-1]: for q in range(len(prod.c)): if temp2>prod.p[q]: prod.c.insert(q,temp1) prod.p.insert(q,temp2) print(prod) break elif temp2==prod.p[q]: prod.c[q]=prod.c[q]+temp1 print(prod) break break else: prod.c.append(temp1) prod.p.append(temp2) print(prod) break for i in range(len(prod)): if prod.c[i]==0: prod.c.pop(i) prod.p.pop(i) return prod def __eq__(self,value): if(len(self.c)!=len(value)): return False else: k=0 sum=0 while k<len(value): if(self.c[k]!=value.c[k]): return False break elif (self.p[k]!=value.p[k]): return False break else: sum=sum+1 k=k+1 if(sum==len(value)): return True def eval(self,x): L=len(self.c) sum=0 for i in range(L): sum+=self.c[i]*(x**self.p[i]) print(sum) return sum def deriv(self): for i in range(len(self.c)): if self.p[i]==0: self.p.pop(i) self.c.pop(i) break for i in range(len(self.c)): self.c[i]=self.c[i]*self.p[i] self.p[i]=self.p[i]-1 return self.c def main(): p1=Polynomial([3,2,5],[5,2,1]) p2=Polynomial([1,2,4]) p4=p1*p2 print(p4) print(p4.p) if __name__=="__main__": main()
class Polynomial(): def __init__(self,s): self.d = { } for i in range(len(s)): if s[i] != 0: self.d[len(s)-i-1] = s[i] def __str__(self): s = "" for i in self.d: if self.d[i] != 0: s = s + "+" + str(self.d[i]) + "x^" + str(i) s = s[1:] return s def __setitem__(self, key, item): self.d[key] = item def __getitem__(self,key): if key in self.d: return self.d[value] else: return 0 def __add__(self,value): for i in value.d: if i in self.d: self.d[i] += value.d[i] else: self.d[i] = value.d[i] return self def __sub__(self,value): for i in value.d: if i in self.d: self.d[i] = self.d[i] - value.d[i] else: self.d[i] = -value.d[i] return self def __mul__(self,value): for i in value.d: if i in self.d: self.d[i] = self.d[i]*value.d[i] else: self.d[i] = 0 return self def __radd__(self,value): for i in self.d: if i in value.d: value.d[i] += self.d[i] else: value.d[i] = self.d[i] return self def __rmul__(self,value): for i in self.d: if i in value.d: value.d[i] = value.d[i]*self.d[i] else: value.d[i] = self.d[i] return self def deriv(self): s = "" for i in self.d: if self.d[i] != 0: s = s + "+" + str(self.d[i]*(i-1)) + "x^" + str(i-1) s = s[2:] return s def __eq__(self,value): for i in value.d: if i in self.d: self.d[i] == value.d[i] for i in self.d: if i in value.d: value.d[i] == self.d[i] def main(): x = Polynomial([2,3,4]) x[20] = 10 print(x) y = Polynomial([3,5,6]) print(y) print(x+y) print(x-y) print(x*y) print(x.deriv()) if __name__ == '__main__': main()
class Polynomial(): def __init__(self,List = []): self.dict = {} for key in range(len(List)): self.dict[len(List)-key-1] = List[key] def __str__(self): pass def __add__(self,poly): result = {} for key in self.dict: if key in poly.dict: result[key] = self.dict[key] + poly.dict[key] else: result[key] = self.dict[key] for key in poly.dict: if key in self.dict: pass else: result[key] = poly.dict[key] return result def __sub__(self,poly): result = {} for key in self.dict: if key in poly.dict: result[key] = self.dict[key] - poly.dict[key] else: result[key] = self.dict[key] for key in poly.dict: if key in self.dict: pass else: result[key] = -poly.dict[key] return result def __mul__(self,poly): result = {} for key in self.dict: for jey in poly.dict: if (key + jey) in result: result[ key+ jey ] = result[ key + jey ] + self.dict[key] * poly.dict[jey] else: result[ key+ jey ] = self.dict[key] * poly.dict[jey] return result def __eq__(self, poly): if isinstance(poly,Polynomial): if len(self.dict) != len(poly.dict): return False else: for key in self.dict: if key not in poly.dict: return False elif self.dict[key] != poly.dict[key]: return False else: continue return True else: if len(self.dict) != len(poly): return False else: for key in self.dict: if key not in poly: return False elif self.dict[key] != poly[key]: return False else: continue return True def __getitem__(self,val): return self.dict[val] def __setitem__(self,key,val): self.dict[key] = val def eval(self,val): result = 0 for key in self.dict: result = result + (val ** key) * self.dict[key] return result def deriv(self): result = {} for key in self.dict: result[key-1] = self.dict[key] * key if -1 in result: del result[-1] return result def main(): p = Polynomial([1,2,3]) q = Polynomial([3,2,1]) print(p+q) print(p-q) print(p*q) print(p == q) print(p[1]) p[-10]=10 print(p.eval(10)) print(p.deriv()) if __name__=="__main__": main()
class Polynomial(): pass def __init__(self,poly=[0]): self.poly = poly self.coefficient = self.poly[:] self.power = [0]*len(self.poly) for i in range(0, len(self.poly)): self.power[i] = i self.power = list(reversed(self.power)) self.coefficient = list((self.coefficient)) def __str__(self): self.poly=[] for i in range(min(self.power),max(self.power)+1): success = 0 for j in range(0, len(self.power)): if(i == self.power[j]): self.poly.append(self.coefficient[j]) success=1 if(success==0): self.poly.append(0) temp = list(reversed(self.poly[:])) return temp.__str__() def __add__(self, value): addA = self.__class__() if(max(self.power) > max(value.power)): maxP = max(self.power) else: maxP = max(value.power) if(min(self.power) < min(value.power)): minP = min(self.power) else: minP = min(value.power) result = [0]*(-minP+maxP+1) for i in range(minP, maxP+1): for j in range(0, len(self.power)): if( i==self.power[j]): result[i-minP] = result[i-minP] + self.coefficient[j] for k in range(0, len(value.power)): if( i==value.power[k]): result[i-minP] = result[i-minP] + value.coefficient[k] addA =list(reversed(result)) return addA def __radd__(self, value): addA = self.__class__() if(max(self.power) > max(value.power)): maxP = max(self.power) else: maxP = max(value.power) if(min(self.power) < min(value.power)): minP = min(self.power) else: minP = min(value.power) result = [0]*(-minP+maxP+1) for i in range(minP, maxP+1): for j in range(0, len(self.power)): if( i==self.power[j]): result[i-minP] = result[i-minP] + self.coefficient[j] for k in range(0, len(value.power)): if( i==value.power[k]): result[i-minP] = result[i-minP] + value.coefficient[k] addA =list(reversed(result)) return addA def __sub__(self, value): subA = self.__class__() if(max(self.power) > max(value.power)): maxP = max(self.power) else: maxP = max(value.power) if(min(self.power) < min(value.power)): minP = min(self.power) else: minP = min(value.power) result = [0]*(-minP+maxP+1) for i in range(minP, maxP+1): for j in range(0, len(self.power)): if( i==self.power[j]): result[i-minP] = result[i-minP] + self.coefficient[j] for k in range(0, len(value.power)): if( i==value.power[k]): result[i-minP] = result[i-minP] - value.coefficient[k] subA =list(reversed(result)) return subA def __rsub__(self, value): subA = self.__class__() if(max(self.power) > max(value.power)): maxP = max(self.power) else: maxP = max(value.power) if(min(self.power) < min(value.power)): minP = min(self.power) else: minP = min(value.power) result = [0]*(-minP+maxP+1) for i in range(minP, maxP+1): for j in range(0, len(self.power)): if( i==self.power[j]): result[i-minP] = result[i-minP] + self.coefficient[j] for k in range(0, len(value.power)): if( i==value.power[k]): result[i-minP] = result[i-minP] - value.coefficient[k] subA =list(reversed(result)) return subA def __mul__(self, value): mulA = self.__class__() result = [0]*(max(self.power)+max(value.power)-min(self.power)-min(value.power)+1) for i in range(0, len(self.power)): for j in range(0, len(value.power)): result[self.power[i]+value.power[j]] = result[self.power[i]+value.power[j]] + self.coefficient[i] * value.coefficient[j] mulA= list(reversed(result)) return mulA def __rmul__(self, value): mulA = self.__class__() result = [0]*(max(self.power)+max(value.power)-min(self.power)-min(value.power)+1) for i in range(0, len(self.power)): for j in range(0, len(value.power)): result[self.power[i]+value.power[j]] = result[self.power[i]+value.power[j]] + self.coefficient[i] * value.coefficient[j] mulA= list(reversed(result)) return mulA def __eq__(self, value): for i in range(min(self.power), max(self.power)+1): success = 0 for j in range(min(value.power), max(value.power)+1): if(i==j): for k in range(0, len(self.power)): if(self.power[k] == i): iSelf = k for l in range(0, len(value.power)): if(value.power[l] == i): iValue = l temp = self.coefficient[k] - value.coefficient[l] if temp != 0: return("False") else: success = 1 if(success == 0): return("False") return("True") def eval(self, value): evalA = 0 for i in range(0, len(self.power)): evalA = evalA + self.coefficient[i]*value**self.power[i] return(evalA) def deriv(self): derivA = self.__class__() derivA = [0]*(max(self.power)-min(self.power)+1) for i in range(0, len(self.power)): if(self.power[i] != 0): derivA[self.power[i]-1-(min(self.power)-1)] = self.coefficient[i]*self.power[i] if(min(self.power)>=0): derivA.pop(0) return(list(reversed(derivA))) def __getitem__(self, index): for i in range(0,len(self.power)): if(self.power[i] == index): return(self.coefficient[i]) def __setitem__(self, index, value): for j in range(0,len(self.power)): if(self.power[j] == index): self.coefficient[j] = value break self.coefficient.append(value) self.power.append(index) def main(): pass if __name__=="__main__": main()
\ \ \ \ class Polynomial(): def __new__(self): self={0:0} def __init__(self): self={0:0} def __getitem__(self,x): self={0:0} i=0 while(i<len(x)): self[i]=x[len(x)-1-i] i+=1 def __add__(self,value): result={0:0} a=list(self.keys()) b=list(value.keys()) i=0 j=0 while(i<len(a)): result[a[i]]=self.get(a[i],0)+value.get(a[i],0) i+=1 while(j<len(b)): result[b[j]]=self.get(b[j],0)+value.get(b[j],0) j+=1 return result def __sub__(self,value): result={0:0} a=list(self.keys()) b=list(value.keys()) i=0 j=0 while(i<len(a)): result[a[i]]=self.get(a[i],0)-value.get(a[i],0) i+=1 while(j<len(b)): result[b[j]]=self.get(b[j],0)-value.get(b[j],0) j+=1 return result def __mul__(self,value): result={0:0} a=list(self.keys()) b=list(value.keys()) i=0 while(i<len(a)): j=0 while(j<len(b)): result[a[i]+b[j]]=result.get(a[i]+b[j],0)+self[a[i]]*value[b[j]] j+=1 i+=1 return result def __eq__(self,value): i=cmp(self,value) if(i==0): return True else: return False def eval(self,value): result = 0 a=list(self.keys()) i=0 while(i<len(a)): result+=self[a[i]]*value**a[i] i+=1 return result def derive(self): result={0:0} a=list(self.keys()) i=0 while(i<len(a)): result[a[i]-1]=self[a[i]]*a[i] i+=1 return result
class Polynomial(): def __init__(self,poly=[0]): self.dict = {} for i in range (0, len(poly)): self.dict[(len(poly)-1-i)] = poly[i] def __getitem__(self, index): if index in (self.dict): return(self.dict[index]) else: return(0) def __setitem__(self, index, value): self.dict[index] = value def __add__(self, value): temp = Polynomial([]) for i in (self.dict): temp.dict[i] = self.dict[i] for i in (value.dict): try: temp[i] += value.dict[i] except: temp[i] = value.dict[i] return(temp) def __radd__(self, value): temp = Polynomial([]) for i in (self.dict): temp.dict[i] = self.dict[i] for i in (value.dict): try: temp[i] += value.dict[i] except: temp[i] = value.dict[i] return(temp) def __sub__(self, value): temp = Polynomial([]) for i in (self.dict): temp.dict[i] = self.dict[i] for i in (value.dict): try: temp[i] -= value.dict[i] except: temp[i] = -1*value.dict[i] return(temp) def __rsub__(self, value): temp = Polynomial([]) for i in (self.dict): temp.dict[i] = self.dict[i] for i in (value.dict): try: temp[i] -= value.dict[i] except: temp[i] = -1*value.dict[i] return(temp) def __mul__(self, value): temp = Polynomial([]) for i in (self.dict): for j in (value.dict): try: temp[i+j] += self.dict[i] * value.dict[j] except: temp[i+j] = self.dict[i] * value.dict[j] return(temp) def __rmul__(self, value): temp = Polynomial([]) for i in (self.dict): for j in (value.dict): try: temp[i+j] += self.dict[i] * value.dict[j] except: temp[i+j] = self.dict[i] * value.dict[j] return(temp) def eval(self, value): temp = 0 for i in (self.dict): temp += self.dict[i]*value**i return(temp) def deriv(self): temp = Polynomial([]) for i in (self.dict): temp[i-1] = self.dict[i]*i return(temp) def __eq__(self, value): if (len(self.dict) > len(value.dict)): for i in (self.dict): if (self.dict[i] != 0): if (i in (value.dict)): if (value.dict[i] != self.dict[i]): return 0 else: return 0 else: for i in (value.dict): if (value.dict[i] != 0): if (i in (self.dict)): if (self.dict[i] != value.dict[i]): return 0 else: return 0 return 1 def main(): pass if __name__=="__main__": main()
import random for x in range(10): print(random.randint(10,100)) for x in range(10): print(random.randint(100,1000)) for x in range(5): print(random.randint(1000,10000)) for x in range(5): print(random.randint(10**90, 10**100))
class Tree(object): def __init__(self): self.left = None self.right = None self.dim = None self.val = None self.parent = None def build_kd_tree(vecs, dim, d): if(len(vecs) == 0): return None if(len(vecs) == 1): ret = Tree() ret.val = vecs[0] return ret vals = sorted(vecs, key=lambda v: v[dim]) mid = int(len(vals)/2) tree = Tree() tree.val = vals[mid] tree.dim = dim tree.left = build_kd_tree(vals[:mid], (dim+1)%d, d) if(tree.left != None): tree.left.parent = tree tree.right = build_kd_tree(vals[mid+1:], (dim+1)%d, d) if(tree.right != None): tree.right.parent = tree return tree def dist_squared_3(A, B): return (A[0] - B[0])**2 + (A[1] - B[1])**2 + (A[2] - B[2])**2 (N, K) = list(map(int, input().split(' '))) ns = [(0,0,0)] * N for x in range(N): ns[x] = tuple(map(int, input().split(','))) tree = build_kd_tree(ns, 0, 3) ks = [(0,0,0)] * K for x in range(K): ks[x] = tuple(map(int, input().split(','))) def find_nearest_neighbor(root, color, top): # We go down the tree to find the nearest leaf node while(root.left != None or root.right != None): if(color[root.dim] < root.val[root.dim] and root.left != None): root = root.left continue elif(color[root.dim] >= root.val[root.dim] and root.right != None): root = root.right continue # We MUST traverse to leaf node, even if it doesn't fit with binary search if(root.left != None): root = root.left continue elif(root.right != None): root = root.right continue break # We set our best guess to this leaf node best_guess = root.val guess_dist = dist_squared_3(root.val, color) while(root != top): prev = root; root = root.parent dist = dist_squared_3(root.val, color) if(dist <= guess_dist): guess_dist = dist best_guess = root.val # If the sphere intersects with the cube of the other half of # the tree we must recurse down it. if(guess_dist > (root.val[root.dim] - color[root.dim])**2): other = root if(root.left == prev): other = root.right elif(root.right == prev): other = root.left if(other != None): recurse_guess = find_nearest_neighbor(other, color, other) recurse_guess_dist = dist_squared_3(recurse_guess, color) if(recurse_guess_dist <= guess_dist): guess_dist = recurse_guess_dist best_guess = recurse_guess dist_top = dist_squared_3(top.val, color) if(dist_top <= guess_dist): best_guess = top.val guess_dist = dist_top return best_guess for x in range(K): color = ks[x] nn = find_nearest_neighbor(tree, color, tree) print(nn)
#!/usr/bin/python3 """Create the module""" import json def save_to_json_file(my_obj, filename): """Function that writes an Object to a text file""" with open(filename, 'w', encoding="utf-8") as myfile: return json.dump(my_obj, myfile)
def stolen_lunch(note): result = "" code_dict = { "a": "0", "b": "1", "c": "2", "d": "3", "e": "4", "f": "5", "g": "6", "h": "7", "i": "8", "j": "9", "0": "a", "1": "b", "2": "c", "3": "d", "4": "e", "5": "f", "6": "g", "7": "h", "8": "i", "9": "j", } chars = list(note) for i in range(len(chars)): to_add = code_dict[chars[i]] if chars[i] in code_dict else chars[i] result += to_add return result # Test print(stolen_lunch("you'll n4v4r 6u4ss 8t: cdja")) # you'll never guess it: 2390
def almost_increasing_sequence(array): count = 0 for i in range(len(array) - 1): if (array[i] <= array[i - 1]): count += 1 if ((array[i] <= array[i - 2]) and (array[i + 1] <= array[i - 1])): return False return count <= 1 # Test print(almost_increasing_sequence([1, 3, 2, 1])) # False print(almost_increasing_sequence([1, 3, 2])) # True
import re def digits_prefix(string): numbers = re.findall(r'\d+', string) return max(numbers) # Test print(digits_prefix("123aa1")) # 123
def check_palindrome(inp_str): inp_str = inp_str.lower() rvsd_str = inp_str[::-1] return inp_str == rvsd_str # Test print(check_palindrome("aabaa")) # True print(check_palindrome("abac")) # False print(check_palindrome("a")) # True
def cip(input_string): input_string = input_string.lower() reversed_str = input_string[::-1] return input_string == reversed_str # Test print(cip("AaBaa")) # True print(cip("abac")) # False
def first_not_repeating_char(s): for i in range(len(s)): repeat = False for j in range(len(s)): if (s[i] == s[j]) and i != j: repeat = True if not repeat: return s[i] return "_" # Test print(first_not_repeating_char("abacabad")) # c print(first_not_repeating_char("abacabaabacaba")) # _
def launch_sequence(system_names, steps): sequence = {} for i in range(len(system_names)): sequence[system_names[i]] = [] for j in range(len(steps)): sequence[system_names[j]].append(steps[j]) for _, value in sequence.items(): for i in range(len(value) - 1): if value[i] >= value[i + 1]: return False return True # Test print(launch_sequence(["stage_1", "stage_2", "dragon", "stage_1", "stage_2", "dragon"], [1, 10, 11, 2, 12, 111])) # True print(launch_sequence(["stage_1", "stage_1", "stage_2", "dragon"], [2, 1, 12, 111])) # False
""" Checking out the Wikipedia API You're doing so well and having so much fun that we're going to throw one more API at you: the Wikipedia API (documented here). You'll figure out how to find and extract information from the Wikipedia page for Pizza. What gets a bit wild here is that your query will return nested JSONs, that is, JSONs with JSONs, but Python can handle that because it will translate them into dictionaries within dictionaries. The URL that requests the relevant query from the Wikipedia API is https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=pizza """ # Import package import requests # Assign URL to variable: url url = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=pizza' # Package the request, send the request and catch the response: r r = requests.get(url) # Decode the JSON data into a dictionary: json_data json_data = r.json() # Print the Wikipedia page extract pizza_extract = json_data['query']['pages']['24768']['extract'] print(pizza_extract)
class Number(): def __init__(self, number=0): self.value = float(number) def __str__(self): return "Your number = {}".format(self.value) def add(self, number=0): self.value += float(number) def sub(self, number=0): self.value -= float(number) def mult(self, number=1): self.value *= float(number) def div(self, number=1): self.value /= float(number)
import bisect class TestBisect: def test_bisect_left(self): A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] # -10 is at index 1 assert bisect.bisect_left(A, -10) == 1 # First occurrence of 285 is at index 6 assert bisect.bisect_left(A, 285) == 6 def test_bisect_right(self): A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] # Index position to right of -10 is 2. assert bisect.bisect_right(A, -10) == 2 # Index position after last occurrence of 285 is 9. assert bisect.bisect_right(A, 285) == 9 def test_bisect(self): A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] # Index position to right of -10 is 2. assert bisect.bisect(A, -10) == 2 # Index position after last occurrence of 285 is 9. assert bisect.bisect(A, 285) == 9 def test_insort_left(self): """ functions same as `bisect_left` except it insert at the index positions """ A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] # operation bisect.insort_left(A, 108) assert A == [-14, -10, 2, 108, 108, 108, 243, 285, 285, 285, 401] # operation bisect.insort_right(A, 108) assert A == [-14, -10, 2, 108, 108, 108, 108, 243, 285, 285, 285, 401]
""" Given two sorted arrays, A and B, determine their intersection. What elements are common to A and B? SIMPLE SOLUTION: res = set(A).intersection(B) Though the above solution works just fine even with unsorted arrays, but the solution given below is efficient. Assumption: - The arrays passed as argument to the function are sorted. """ def intersect_soted_arrays(array1, array2): i = j = 0 intersections = [] while i < len(array1) and j < len(array2): if array1[i] == array2[j]: if i == 0 or array1[i] != array1[i - 1]: # handling duplicates intersections.append(array1[i]) i += 1 j += 1 elif array1[i] < array2[j]: i += 1 else: j += 1 return intersections
""" PROBLEM: Given a string, find the first occurrence of an uppercase letter and return the index of that letter. If no uppercase letters return None. Algorithm: 1. Iterate through the string and check if the current character is uppercase. If so, return the tuple with given format -> (alphabet, index) 2. Recursive approach """ def find_uppercase_iterative(input_str): for i in range(0, len(input_str)): if input_str[i].isupper(): return input_str[i], i return None, None def find_uppercase_recusive(input_str, idx=0): if input_str[idx].isupper(): return input_str[idx], idx if idx == len(input_str) - 1: return None, None return find_uppercase_recusive(input_str, idx+1)
def create_db_and_tables(cnx, cursor, tables_sql, db_name): ''' Use database or create it if not exist; create tables :param cnx: pymysql connection object :param cursor: pymysql cursor object :param tables_sql: dict of SQL to create tables :return: None ''' try: cursor.execute(f"USE {db_name}") cnx.database = db_name except: print(f"Database {db_name} does not exist, creating now.") try: cursor.execute(f"CREATE DATABASE {db_name}") cursor.execute(f"USE {db_name}") except: print("Failed creating database") cnx.database = db_name # Create tables for k, v in tables_sql.items(): cursor.execute(v)
#!/usr/bin/env python # USAGE: day_11_01.py # Michael Chambers, 2015 file = "day_11_input.txt" movements = open(file,'r').read().rstrip() movements = movements.split(',') def calcDist(x,y): return(abs(x) + abs(y)) posx = 0 posy = 0 maxdist = 0 for m in movements: # print(m) if m == "n": posy += 1 elif m == "s": posy -= 1 elif m == "ne": posx += 0.5 posy += 0.5 elif m == "se": posx += 0.5 posy -= 0.5 elif m == "nw": posx -= 0.5 posy += 0.5 elif m == "sw": posx -= 0.5 posy -= 0.5 else: print("ERROR") cdist = calcDist(posx,posy) if cdist > maxdist: maxdist = cdist print("Final coord: {},{}".format(posx, posy)) print("Distance to origin: {}".format(calcDist(posx, posy))) print("Maximum distance from origin: {}".format(maxdist))
#!/usr/bin/env python # USAGE: day_02_01.py # Michael Chambers, 2015 class RecKeyPress(object): def __init__(self, startpos): self.keys = [[1,4,7],[2,5,8],[3,6,9]] self.pos = startpos def move(self, mdir): if mdir == "U": newpos = (self.pos[0], self.pos[1] - 1) elif mdir == "D": newpos = (self.pos[0], self.pos[1] + 1) elif mdir == "L": newpos = (self.pos[0] - 1, self.pos[1]) elif mdir == "R": newpos = (self.pos[0] + 1, self.pos[1]) if newpos[0] < 0 or newpos[0] > 2 or newpos[1] < 0 or newpos[1] > 2: return else: self.pos = newpos def getLocation(self): return self.keys[self.pos[0]][self.pos[1]] class DiagKeyPress(object): def __init__(self, startpos): self.keys = [[0,0,5,0,0],[0,"A",6,2,0],["D","B",7,3,1],[0,"C",8,4],[0,0,9,0,0]] self.pos = startpos def move(self, mdir): if mdir == "U": newpos = (self.pos[0], self.pos[1] + 1) elif mdir == "D": newpos = (self.pos[0], self.pos[1] - 1) elif mdir == "L": newpos = (self.pos[0] - 1, self.pos[1]) elif mdir == "R": newpos = (self.pos[0] + 1, self.pos[1]) if newpos[0] < -2 or newpos[0] > 2 or newpos[1] < -2 or newpos[1] > 2: return elif abs(newpos[0]) + abs(newpos[1]) >= 3: return else: self.pos = newpos def getLocation(self): keymap = (self.pos[0] + 2, self.pos[1] + 2) # print("{} {}".format(self.pos, keymap)) return self.keys[keymap[0]][keymap[1]] def main(): file = "day_02_input.txt" # file = "day_02_test.txt" fo = open(file, 'r') code = "" key = RecKeyPress((1,1)) for line in fo: line = line.strip() for movement in line: key.move(movement) # print("{} {} {}".format(movement, key.pos, key.getLocation())) code += format(key.getLocation()) print(code) fo.close() ## Part 2 fo = open(file, 'r') key = DiagKeyPress((-2, 0)) code = "" for line in fo: line = line.strip() for movement in line: key.move(movement) print("{} {} {}".format(movement, key.pos, key.getLocation())) code += format(key.getLocation()) print("---") print(code) fo.close() if __name__ == '__main__': main()
def fibonacci (int1): x = 0 alist = [0,1,2] for i in range(int1+1): if int1<3 : break if i<3: continue else: alist.append(alist[i-1]+alist[i-2]) continue else: print "range is" , len(alist) return alist[int1] inputX = True while inputX: inputX = int(raw_input("input")) print str(fibonacci(inputX)) if inputX == 999: break
#!/usr/bin/python3 import math def distance(point1, point2): return math.sqrt((point2[0]-point1[0])**2 + (point2[1]-point1[1])**2 + (point2[2]-point1[2])**2) def sphere_coords(center, radius, point): if distance(center, point) > radius: return [] else: res = [] xDist = math.sqrt(radius**2 - (point[1]-center[1])**2 - (point[2] - center[2])**2) zDist = math.sqrt(radius**2 - (point[0]-center[0])**2 - (point[1] - center[1])**2) res.append((math.ceil(center[0] - xDist), point[1], point[2])) res.append((math.floor(center[0] + xDist), point[1], point[2])) res.append((point[0], point[1], math.ceil(center[2] - zDist))) res.append((point[0], point[1], math.floor(center[2] + zDist))) return res def sphere_shell_coords(center, rad1, rad2, point): if distance(center, point) > rad2 or distance(center, point) < rad1: return [] else: res = [] x2Dist = math.sqrt(rad2**2 - (point[1]-center[1])**2 - (point[2] - center[2])**2) z2Dist = math.sqrt(rad2**2 - (point[0]-center[0])**2 - (point[1] - center[1])**2) x1DistSq = rad1**2 - (point[1] - center[1])**2 - (point[2] - center[2])**2 z1DistSq = rad1**2 - (point[0] - center[0])**2 - (point[1] - center[1])**2 if x1DistSq < 0: res.append((math.ceil(center[0] - x2Dist), point[1], point[2])) res.append((math.floor(center[0] + x2Dist), point[1], point[2])) else: res.append((math.ceil(center[0] - x2Dist), point[1], point[2])) res.append((math.floor(center[0] - math.sqrt(x1DistSq)), point[1], point[2])) res.append((math.ceil(center[0] + math.sqrt(x1DistSq)), point[1], point[2])) res.append((math.floor(center[0] + x2Dist), point[1], point[2])) if z1DistSq < 0: res.append((point[0], point[1], math.ceil(center[2] - z2Dist))) res.append((point[0], point[1], math.floor(center[2] + z2Dist))) else: res.append((point[0], point[1], math.ceil(center[2] - z2Dist))) res.append((point[0], point[1], math.floor(center[2] - math.sqrt(z1DistSq)))) res.append((point[0], point[1], math.ceil(center[2] + math.sqrt(z1DistSq)))) res.append((point[0], point[1], math.floor(center[2] + z2Dist))) return res def pretty_print_test(center, rad1, rad2, point): print("center:", center) print("From", rad1, "to", rad2) print("At", point) print(sphere_shell_coords(center, rad1, rad2, point)) pretty_print_test((24, 37, 164), 24, 32, (1, 46, 160)) pretty_print_test((24, 37, 164), 24, 32, (1, 46, 180))
# Task 7 # Write a password generator in Python. Be creative with how you generate passwords - # strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. # The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main method. # Extra: # Ask the user how strong they want their password to be. # For weak passwords, pick a word or two from a list. import string import random def pwd_gen(strenth): strength = {'weak': 8, 'strong': 12} letters = string.ascii_letters numbers = string.digits puncs = string.punctuation if pwd_strength == 'weak': chars = letters + numbers return ''.join(random.choice(chars) for _ in range(strength[pwd_strength])) elif pwd_strength == 'strong': chars = letters + numbers + puncs return ''.join(random.choice(chars) for _ in range(strength[pwd_strength])) if __name__ == "__main__": while True: pwd_strength = str(input('Do you want strong or weak password? ').lower()) if pwd_strength == 'weak' or pwd_strength == 'strong': password = pwd_gen(pwd_strength) print('The generated password is: ', password) while True: new_gen = input('Do you want to generate new one? Yes or No ').lower() if new_gen == 'no': print('Selected password: ',password) break else: password = pwd_gen(pwd_strength) print('The generated password is: ', password) break else: print('Please choose either weak or strong strength') continue '''if pwd_strength == 'weak' or pwd_strength == 'strong': password = pwd_gen(pwd_strength) print('The generated password is: ' + password) else: print('Please choose either weak or strong strength')'''
import random first_names = ['Róisín', 'Ciara', 'Amy', 'Aoife'] last_names = ['Murphy', 'Finan', 'Monahan', 'Whelan'] chosen_name = random.choice(first_names) + ' ' + random.choice(last_names) print(chosen_name)
import turtle turtle.speed(1) turtle.color('aqua', 'yellow') def triangle(side_length): angle=120 for side in range(3): turtle.forward(side_length) turtle.right(angle) triangle(50) turtle.forward(50) triangle(75)
#Prompt: # Write an efficient function that checks whether any permutation ↴ of an input string is a palindrome. ↴ # You can assume the input string only contains lowercase letters. # Examples: # "civic" should return True # "ivicc" should return True # "civil" should return False # "livci" should return False # Possible Questions for Interviewer: # Does case matter? (Already answered) # Will there be any punctuation? (Techinically answered) # Will it be a continuous string of letters or will there be spaces? (Technically answered) # Will there be any letters occurring more than twice? (Implied answer based on solution) def has_palindrome_permutation(the_string): # Check if any permutation of the input is a palindrome letter_count_1 = {} letter_count_2 = {} for letter in the_string: if letter in letter_count_1: if letter in letter_count_2: if letter_count_1[letter] > letter_count_2[letter]: letter_count_2[letter] += 1 else: letter_count_1[letter] += 1 else: letter_count_2[letter] = 1 else: letter_count_1[letter] = 1 return abs(len(letter_count_1) - len(letter_count_2)) < 2 # Although this code passed the tests for the prompt, it will not pass if there is an even number of letters, with only one occurance of one unique letter and a 3rd occurance of another unique letter. # This could be resolved by checking if string is len even or odd and then having extra tests for even-lengthed strings, but that would involve also comparing all of the keys in the dictionaries, # which is highly inefficient at longer inputs with many unique letters. # This solution is O(n) time. # InterviewCake Solution: def has_palindrome_permutation(the_string): # Track characters we've seen an odd number of times unpaired_characters = set() for char in the_string: if char in unpaired_characters: unpaired_characters.remove(char) else: unpaired_characters.add(char) # The string has a palindrome permutation if it # has one or zero characters without a pair return len(unpaired_characters) <= 1 # I had another idea so close to this!!! Noooooo!!! :)
def one_away(word1, word2): count = 0 difference = 0 length1 = len(word1) length2 = len(word2) if (abs(length1 - length2) <= 1): while (count < length1) & (count < length2) & (difference < 2): if word1[count] != word2[count]: count += 1 difference += 1 else: count += 1 if (difference == 1) & (abs(length1 - length2) == 0): return True elif difference == 0: return True return False #Test Cases print(one_away('make', 'fake')) #True print(one_away('task', 'take')) #False print(one_away('ask', 'asks')) #True print(one_away('asks', 'ask')) #True print(one_away('form', 'format')) #False print(one_away('ask', 'asta')) #False print(one_away('task', 'ask')) #True # This last one won't work with this code. Fix it.
""" Написать функцию, которая будет проверять счастливый билетик или нет. Билет счастливый, если сумма одной половины цифр равняется сумме второй. """ def is_lucky(ticket_num): pass assert is_lucky(1230) is True assert is_lucky(239017) is False assert is_lucky(134008) is True assert is_lucky(15) is False assert is_lucky(2020) is True assert is_lucky(199999) is False assert is_lucky(77) is True assert is_lucky(479974) is True print("All tests passed successfully!")
import numpy as np #NumPy incorporated for typical sin or cosines def f(x): #Define the Function return (np.cos(x)) def gc(a, b, n): #Define the Rule quadrature = 0 #Set the loop for sub-intervals for i in range (1, n+1): integration = f(np.cos((2*i-1)*np.pi /(2*n))) quadrature = integration + quadrature print (i, integration) quadrature = quadrature * np.pi / (n) print(quadrature) gc(-1, 1, 6) #Call the function with parameters a, b and steps
import re def statistics_upper_words(text): upper_count = 0 for token in text.split(): if re.search(r'[A-Z]', token): upper_count += 1 return upper_count def statistics_unique_words(text): words_set = set() for token in text.split(): words_set.add(token) return len(words_set) def statistics_characters_nums(text): chars_set = set() for char in text: chars_set.add(char) return len(chars_set) def statistics_swear_words(text, swear_words): swear_count = 0 for swear_word in swear_words: if swear_word in text: swear_count += 1 return swear_count
# # @lc app=leetcode.cn id=206 lang=python3 # # [206] 反转链表 # # https://leetcode-cn.com/problems/reverse-linked-list/description/ # # algorithms # Easy (57.57%) # Total Accepted: 35.2K # Total Submissions: 60.6K # Testcase Example: '[1,2,3,4,5]' # # 反转一个单链表。 # # 示例: # # 输入: 1->2->3->4->5->NULL # 输出: 5->4->3->2->1->NULL # # 进阶: # 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? # # # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: node = head temp = None while head: head = head.next node.next = temp temp = node if not head: return node node = head return None
# # @lc app=leetcode.cn id=114 lang=python3 # # [114] 二叉树展开为链表 # # https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/description/ # # algorithms # Medium (60.73%) # Likes: 108 # Dislikes: 0 # Total Accepted: 6.8K # Total Submissions: 11.2K # Testcase Example: '[1,2,5,3,4,null,6]' # # 给定一个二叉树,原地将它展开为链表。 # # 例如,给定二叉树 # # ⁠ 1 # ⁠ / \ # ⁠ 2 5 # ⁠/ \ \ # 3 4 6 # # 将其展开为: # # 1 # ⁠\ # ⁠ 2 # ⁠ \ # ⁠ 3 # ⁠ \ # ⁠ 4 # ⁠ \ # ⁠ 5 # ⁠ \ # ⁠ 6 # # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if not root: return if not root.left and not root.right: return if root.left: self.flatten(root.left) if root.right: self.flatten(root.right) if not root.left: return r = root.right l = root.left node = l while node and node.right: node = node.right node.right = r root.right = l root.left = None
# # @lc app=leetcode.cn id=187 lang=python3 # # [187] 重复的DNA序列 # # https://leetcode-cn.com/problems/repeated-dna-sequences/description/ # # algorithms # Medium (42.75%) # Likes: 30 # Dislikes: 0 # Total Accepted: 3.7K # Total Submissions: 8.7K # Testcase Example: '"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"' # # 所有 DNA 由一系列缩写为 A,C,G 和 T 的核苷酸组成,例如:“ACGAATTCCG”。在研究 DNA 时,识别 DNA # 中的重复序列有时会对研究非常有帮助。 # # 编写一个函数来查找 DNA 分子中所有出现超多一次的10个字母长的序列(子串)。 # # 示例: # # 输入: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" # # 输出: ["AAAAACCCCC", "CCCCCAAAAA"] # # class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: m = {} res = set() for i in range(len(s) - 9): str = s[i:i+10] if str in m: res.add(str) else: m[str] = 1 return list(res)
# # @lc app=leetcode.cn id=33 lang=python3 # # [33] 搜索旋转排序数组 # # https://leetcode-cn.com/problems/search-in-rotated-sorted-array/description/ # # algorithms # Medium (36.04%) # Total Accepted: 18.3K # Total Submissions: 50.8K # Testcase Example: '[4,5,6,7,0,1,2]\n0' # # 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 # # ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 # # 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 # # 你可以假设数组中不存在重复的元素。 # # 你的算法时间复杂度必须是 O(log n) 级别。 # # 示例 1: # # 输入: nums = [4,5,6,7,0,1,2], target = 0 # 输出: 4 # # # 示例 2: # # 输入: nums = [4,5,6,7,0,1,2], target = 3 # 输出: -1 # # class Solution: def search(self, nums: List[int], target: int) -> int: return self.__search__(nums, target, 0, len(nums) - 1) def __search__(self, nums, target, low, high): if low > high: return -1 mid = (low + high) // 2 if nums[mid] == target: return mid if nums[mid] < nums[high]: if nums[mid] < target and target <= nums[high]: return self.__search__(nums, target, mid + 1, high) else: return self.__search__(nums, target, low, mid - 1) else: if nums[low] <= target and target < nums[mid]: return self.__search__(nums, target, low, mid - 1) else: return self.__search__(nums, target, mid + 1, high)
# # @lc app=leetcode.cn id=475 lang=python3 # # [475] 供暖器 # # https://leetcode-cn.com/problems/heaters/description/ # # algorithms # Easy (26.72%) # Total Accepted: 1.9K # Total Submissions: 7.1K # Testcase Example: '[1,2,3]\n[2]' # # 冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。 # # 现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半径。 # # 所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。 # # 说明: # # # 给出的房屋和供暖器的数目是非负数且不会超过 25000。 # 给出的房屋和供暖器的位置均是非负数且不会超过10^9。 # 只要房屋位于供暖器的半径内(包括在边缘上),它就可以得到供暖。 # 所有供暖器都遵循你的半径标准,加热的半径也一样。 # # # 示例 1: # # # 输入: [1,2,3],[2] # 输出: 1 # 解释: 仅在位置2上有一个供暖器。如果我们将加热半径设为1,那么所有房屋就都能得到供暖。 # # # 示例 2: # # # 输入: [1,2,3,4],[1,4] # 输出: 1 # 解释: 在位置1, 4上有两个供暖器。我们需要将加热半径设为1,这样所有房屋就都能得到供暖。 # # # class Solution: def findRadius(self, houses: List[int], heaters: List[int]) -> int: houses = sorted(houses) heaters = sorted(heaters) l1, l2 = len(heaters), len(houses) if l1 == 1: return max(abs(houses[0] - heaters[0]), abs(houses[-1] - heaters[0])) res = 0 j = 0 m = l2 - 1 while m >= 0 and houses[m] >= heaters[-1]: m -= 1 if m != l2 - 1: res = houses[-1] - heaters[-1] n = 0 while n < l2 and houses[n] <= heaters[0]: n += 1 if n != 0: res = max(res, heaters[0] - houses[0]) for i in range(n, m + 1): while houses[i] > heaters[j]: j += 1 if houses[i] == heaters[j]: continue res = max( res, min(houses[i] - heaters[j - 1], heaters[j] - houses[i])) return res
# # @lc app=leetcode.cn id=105 lang=python3 # # [105] 从前序与中序遍历序列构造二叉树 # # https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/ # # algorithms # Medium (57.84%) # Likes: 158 # Dislikes: 0 # Total Accepted: 12.8K # Total Submissions: 22.1K # Testcase Example: '[3,9,20,15,7]\n[9,3,15,20,7]' # # 根据一棵树的前序遍历与中序遍历构造二叉树。 # # 注意: # 你可以假设树中没有重复的元素。 # # 例如,给出 # # 前序遍历 preorder = [3,9,20,15,7] # 中序遍历 inorder = [9,3,15,20,7] # # 返回如下的二叉树: # # ⁠ 3 # ⁠ / \ # ⁠ 9 20 # ⁠ / \ # ⁠ 15 7 # # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def build(il, ir, pl, pr): if pl > pr or il > ir: return None node = TreeNode(preorder[pl]) index = 0 for i in range(il, ir + 1): if inorder[i] == preorder[pl]: index = i break leftCount = index - il node.left = build(il, index - 1, pl + 1, pl + leftCount) node.right = build(index + 1, ir, pl + leftCount + 1, pr) return node return build(0, len(inorder) - 1, 0, len(preorder) - 1)
# # @lc app=leetcode.cn id=147 lang=python3 # # [147] 对链表进行插入排序 # # https://leetcode-cn.com/problems/insertion-sort-list/description/ # # algorithms # Medium (58.06%) # Likes: 63 # Dislikes: 0 # Total Accepted: 7.5K # Total Submissions: 12.8K # Testcase Example: '[4,2,1,3]' # # 对链表进行插入排序。 # # # 插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。 # 每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。 # # # # 插入排序算法: # # # 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。 # 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。 # 重复直到所有输入数据插入完为止。 # # # # # 示例 1: # # 输入: 4->2->1->3 # 输出: 1->2->3->4 # # # 示例 2: # # 输入: -1->5->3->4->0 # 输出: -1->0->3->4->5 # # # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def insertionSortList(self, head: ListNode) -> ListNode: dummy = ListNode(0) while head: cur = dummy next = head.next while cur.next and cur.next.val < head.val: cur = cur.next head.next = cur.next cur.next = head head = next return dummy.next
# # @lc app=leetcode.cn id=129 lang=python3 # # [129] 求根到叶子节点数字之和 # # https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/description/ # # algorithms # Medium (56.98%) # Likes: 60 # Dislikes: 0 # Total Accepted: 5.9K # Total Submissions: 10.4K # Testcase Example: '[1,2,3]' # # 给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。 # # 例如,从根到叶子节点路径 1->2->3 代表数字 123。 # # 计算从根到叶子节点生成的所有数字之和。 # # 说明: 叶子节点是指没有子节点的节点。 # # 示例 1: # # 输入: [1,2,3] # ⁠ 1 # ⁠ / \ # ⁠ 2 3 # 输出: 25 # 解释: # 从根到叶子节点路径 1->2 代表数字 12. # 从根到叶子节点路径 1->3 代表数字 13. # 因此,数字总和 = 12 + 13 = 25. # # 示例 2: # # 输入: [4,9,0,5,1] # ⁠ 4 # ⁠ / \ # ⁠ 9 0 # / \ # 5 1 # 输出: 1026 # 解释: # 从根到叶子节点路径 4->9->5 代表数字 495. # 从根到叶子节点路径 4->9->1 代表数字 491. # 从根到叶子节点路径 4->0 代表数字 40. # 因此,数字总和 = 495 + 491 + 40 = 1026. # # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: res = 0 def sumNumbers(self, root: TreeNode) -> int: if not root: return 0 self.dfs(root, root.val) return self.res def dfs(self, root, num): if not root.left and not root.right: self.res += num if root.left: self.dfs(root.left, num * 10 + root.left.val) if root.right: self.dfs(root.right, num * 10 + root.right.val)
# # @lc app=leetcode.cn id=92 lang=python3 # # [92] 反转链表 II # # https://leetcode-cn.com/problems/reverse-linked-list-ii/description/ # # algorithms # Medium (42.49%) # Likes: 137 # Dislikes: 0 # Total Accepted: 10.4K # Total Submissions: 23.8K # Testcase Example: '[1,2,3,4,5]\n2\n4' # # 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 # # 说明: # 1 ≤ m ≤ n ≤ 链表长度。 # # 示例: # # 输入: 1->2->3->4->5->NULL, m = 2, n = 4 # 输出: 1->4->3->2->5->NULL # # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: dummy = ListNode(-10000) dummy.next = head i = 1 node = dummy while i < m: node = node.next i += 1 p, q = None, None while i <= n: temp = node.next if q == None: q = temp node.next = node.next.next temp.next = p p = temp i += 1 q.next = node.next node.next = p return dummy.next
# # @lc app=leetcode.cn id=387 lang=python3 # # [387] 字符串中的第一个唯一字符 # # https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/ # # algorithms # Easy (35.49%) # Total Accepted: 21.3K # Total Submissions: 59.4K # Testcase Example: '"leetcode"' # # 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 # # 案例: # # # s = "leetcode" # 返回 0. # # s = "loveleetcode", # 返回 2. # # # # # 注意事项:您可以假定该字符串只包含小写字母。 # # class Solution: def firstUniqChar(self, s: str) -> int: arr = [0] * 26 for n in s: arr[ord(n) - ord('a')] += 1 for i in range(len(s)): if arr[ord(s[i]) - ord('a')] == 1: return i return -1
# # @lc app=leetcode.cn id=204 lang=python3 # # [204] 计数质数 # # https://leetcode-cn.com/problems/count-primes/description/ # # algorithms # Easy (25.80%) # Total Accepted: 12.4K # Total Submissions: 47.4K # Testcase Example: '10' # # 统计所有小于非负整数 n 的质数的数量。 # # 示例: # # 输入: 10 # 输出: 4 # 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 # # # class Solution: def countPrimes(self, n: int) -> int: if n < 3: return 0 primes = [True] * n primes[0] = primes[1] = False for i in range(2, int(n ** 0.5) + 1): if primes[i]: primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) return sum(primes)
class Node: def __init__(self, name): self.name = name self.children = [] def add_child(self, node): self.children.append(node) def build_orbit(node, object_dictionary): if node.name not in object_dictionary.keys(): return node for child in object_dictionary[node.name]: node.add_child(build_orbit(Node(child), object_dictionary)) return node def print_orbit(node, depth): print('-' * depth + node.name) for child_node in node.children: print_orbit(child_node, depth + 1) def orbit_count(node, depth=0): if not node.children: return depth total = 0 for child in node.children: total += orbit_count(child, depth + 1) return depth + total def build_input(): dictionary = {} with open("input.txt") as inputFile: for line in inputFile: orbit = line.split(')') a = orbit[0].rstrip() b = orbit[1].rstrip() if a in dictionary.keys(): dictionary[a].append(b) else: dictionary[a] = [b] return dictionary def main(): orbits = build_orbit(Node('COM'), build_input()) # print_orbit(orbits, 0) print(orbit_count(orbits)) if __name__ == '__main__': main()
#!/usr/bin/python #-*-coding:utf-8-*- '''@Date:18-10-13''' '''@Time:下午10:01''' '''@author: Duncan''' money_dic = {'美元':7,'日元':0.06,'香港元':0.88,'欧元':8,'瑞士法郎':7,'加元':5.31,'新加坡元':5.02,'丹麦克朗':1.07,"人民币元":1} # 数据预处理,将币种统一 def convert(x): if x in money_dic.keys(): return money_dic[x] else: return x # 转换币种 def Convert_money(df): df["rate"] = df["注册资本(金)币种名称"].apply(convert) df["注册资金(元)"] = df["注册资金"] * df["rate"] df.drop(columns={"注册资金","rate"},inplace=True) return df
# FileName : Chapter8_5.py ''' 类中封装实例的私有数据: python中没有访问控制,所以可以通过一定的属性、方法命名规则来达到这个目的: '_name'、'__name'和'__name__'的区别 ''' if __name__ == '__main__': class A: def __init__(self): self.value = 'value' self._value = '_value' self.__value = '__value' self.__value__ = '__value__' def method(self): print('Method') def _method(self): print('_Method') def __method(self): print('__Method') def __methon__(self): print('__Method__') a = A() print(a.value) print(a._value) print(a._A__value) print(a.__value__) a.method() a._method() a._A__method() a.__methon__() class B: def __init__(self): self.__private = 0 def __private_method(self): print('B : private_method') def public_method(self): print('B : public_method') self.__private_method() class C(B): def __init__(self): super().__init__() self.__private = 1 def __private_method(self): print('C : private_method') def public_method(self): print('C: public_method') self.__private_method() super().public_method() b = B() c = C() print(b.__dict__) print(c.__dict__) b.public_method() c.public_method()
# FileName : Chapter3_8.py ''' 分数操作: 通过fractions模块定义分数 ''' if __name__ == '__main__': from fractions import Fraction a = Fraction(5, 4) b = Fraction(7, 16) c = a * b print(a + b) print(a * b) print(c.numerator) print(c.denominator) print(float(c)) print(c.limit_denominator(8)) x = 3.75 print(Fraction(*x.as_integer_ratio()))
# FileName : Chapter2_5.py ''' 字符串搜索、替换(大小写敏感): 简单替换:str.replace(ori, new) 负责替换:re.sub(ori, new), re.subn(ori, new),可以指定替换模式或者通过回调函数指定替换方式 ''' import re if __name__ == '__main__': text = 'yeah, but no, but yeah, but no, but yeah' print(text.replace('yeah', 'yep')) text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\2-\1', text)) pat = re.compile(r'(\d+)/(\d+)/(\d+)') print(pat.sub(r'\3-\2-\1', text)) def change_data(m): from calendar import month_abbr mon_name = month_abbr[int(m.group(1))] return '{} {} {}'.format(m.group(2), mon_name, m.group(3)) print(pat.sub(change_data, text))
""" Written by Nicolette Lewis at University of Washington for CESG 505: Engineering Computing Date: October 15, 2019 Homework 2 Problem 1 - baseconverter.py Program Description: basecheck(base,inval,pr=0): Checks to see if the input string is a valid expression of an integer in the provided base if not, changes the base of the number to the minimum possible base to_base(newbase,inval,pr=0): Takes the input base as an integer and the input value as a string, returns a new string containing the integer and its base and an equation showing the input decimal(inbase,inval,pr=0): Takes an input base integer and a string of the integer to be converted from the specified base to decimal Returns both the input integer with its base and the converted integer with its base (decimal) add(base, inval1,inval2,pr=0): Takes an input base integer and a string of the integers to be added converts from the specified base to decimal adds the integers in decimal Converts back to the specified base and returns the sum of the two numbers in their original bases """ import re import operator # functions ## def basecheck(base,inval,pr=0): if (type(inval) is str) !=True: print("Please input a string!") inval=str(inval) charlist = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] charlist1=charlist+['-'] for x in inval: # this is a check on the input base of the number. if (str(x.lower()) not in charlist1) and (str(x.upper()) not in charlist1): print('The program cannot return a value for {} in base {}, sorry :('.format(inval,base)) exit return inval def to_base(newbase,inval,pr=0): # takes an input base integer and a string of the integer to be converted to the specified base # returns both the input integer with its base and the converted integer with its base inval=basecheck(newbase,str(inval),1) s = decimal(newbase,str(inval)) inval=str(inval) if newbase not in range(2, 17, 1): print("Please enter a base between 2 (binary) and 16 (hex)") exit() charlist = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] out=[] SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉") if inval[0] == '-': hold = '-' s=-s else: hold = '' while s > 0: rem = s % newbase s //= newbase out.insert(0, charlist[rem]) out=''.join(out) out=out.upper() empty = '' if out == empty: out = '0' if pr==1: report = "{}{} = {}{}" print(report.format(inval, str(base).translate(SUB), out, str(newbase).translate(SUB))) return hold + out ## def decimal(base,inval,pr=0): # takes an input base integer and a string of the integer to be converted from the specified base to decimal # returns both the input integer with its base and the converted integer with its base (decimal) charlist = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] inval=basecheck(base,inval) inval=str(inval) SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉") # this allows the output to be put into subscript form dec = 0 # initializing output decimal hold = '' # initializing the sign of the output if inval[0] == '-': # creating a conditional for the sign of the output integer hold = '-' start=1 else: start=0 for i in range(start,len(inval)): if (inval[i] not in charlist) and (str(inval[i]).lower() not in charlist): print('The requested input is not representable in bases 2 through 16') inval='0'*len(inval) if len(inval) != 1: for i in range(start, len(inval)): dec += charlist.index(str(inval[i]).lower()) * (base ** ((len(inval) - 1) - i)) else: inval=str(inval).lower() dec += charlist.index(inval.lower()) * base ** ((len(inval) - 1)) out = hold+str(dec).upper() if pr==1: report = "{}{} = {}{}" print(report.format(inval, str(base).translate(SUB), out, str(10).translate(SUB))) return int(out) ##
""" Calculates and storyes x,y coordinates for an item that bounces up and down based on sinusiodal curve. It does not hold the graphical item to be animated. """ """ Begun 5 April by Jason Cisarano. Included complete setBounce, getCoord, and isBouncing functions. """ from math import sin, pi import pygame class Bouncer(object): """ Calculates and storyes x,y coordinates for an item that bounces up and down based on sine curve. Amount and time of bounce is predetermined. It does not hold the graphical item to be animated. """ def __init__(self, x,y): """ Set initial state -- expects starting x, y values """ #tweakable settings self.__period = 300 ####time in milliseconds for cycle self.__displacement = 50 ###how far to move up and down #state variables self.__isBouncing = False self.__y_original = y self.__y = y self.__x = x self.__startTime = 0 self.__frequency = pi /(self.__period) def setBounce(self): """ Used to set this Bouncer to bounce status so that it will automatically begin moving with subsequent calls to getCoords. """ if not self.__isBouncing: self.__startTime = pygame.time.get_ticks() self.__isBouncing = True def isBouncing(self): """ Returns the bouncing state of this Bouncer. """ return self.__isBouncing def getCoords(self): """ Returns x,y coordinates of this Bouncer as a tuple (x,y). If this Bouncer is currently bouncing, the y value will reflect this automatically. """ if self.__isBouncing: self.__updateY() return (self.__x, self.__y) def __updateY(self): """ Sets y value of bouncing item as function of time since bounce began. On end of bounce, updateY returns y value to original baseline and sets bounce status to False. """ if self.__isBouncing: elapsedTime = pygame.time.get_ticks() - self.__startTime # print "Frequency = " + self.__frequency.__str__() # print "Current time = " + pygame.time.get_ticks().__str__() # print "Start time = " + self.__startTime.__str__() # print "Elapsed time = " + elapsedTime.__str__() # print "elapsedTime * frequency =" + (elapsedTime * self.__frequency).__str__() if elapsedTime < self.__period: f = sin(-(abs(elapsedTime * self.__frequency))) # print "f = " + f.__str__() self.__y = int(f * self.__displacement + self.__y_original) else: self.__y = self.__y_original self.__isBouncing = False
""" SongChooserMenu displays a list of songs appropriate for the player's current status in the game and allows her to choose a song to play. It takes a GameInfo item as input and returns a song file. this class is usable with both freeplay and challenge mode levels. """ """ 6 April -- Begun by Jason Cisarano -- Completed "freeplay" song chooser with text-only, no-audio interface "career" mode interface displays songs and available levels, but doesn't allow user to choose song yet. 26 April -- added filenames and titles for new songs """ """ Navigation scheme is the same regardless of input method (keyboard, number pad, dance mat): ====================== | XX | XX | XX | ====================== | XX | UP | XX | ====================== | BACK | XX | ENTER | ====================== | XX | DOWN | XX | ====================== """ import pygame from pygame.locals import * from GoodStep import GoodStep from Controller import Controller from GameInfo import GameInfo from FileLocations import FileLocations from GameOverScreen import GameOverScreen from SoundEffectController import SoundEffectController import SinglePlayerMode import CareerMode class ScreenInfo(): """ Holds standard info about display including font and font size. """ pygame.init() game = GameInfo() SCREEN_SIZE = game.getSettings().getScreenSize() font = pygame.font.SysFont("arial", 16); font_height = font.get_linesize() class SongChooserMenu (object): """ SongChooserMenu displays a list of songs appropriate for the player's current status in the game and allows her to choose a song to play. It takes a GameInfo item as input and returns a song file. SongChooserMenu adjusts its output for freeplay and challenge mode levels. """ def __init__(self, screen, gameInfo): """ Set default values for font, menu items Parameters: screen is current screen in use gameInfo is up-to-date GameInfo object """ self.__game = gameInfo self.__cntrl = Controller() self.__selectedSong = "" self.__screen = screen self.__screen_size = screen.get_size() self.__screenInfo = ScreenInfo() self.__soundEffects = SoundEffectController() self.__font_size = self.__chooseFontSize() self.__font = pygame.font.SysFont("arial", self.__font_size) self.__font_color = (244, 123, 25) self.__font_height = self.__font.get_linesize() print self.__font_height self.__selected = 0 #initialize menus and set starting menu to main self.__initMenus() self.__loadAudio() self.__loadImages() def __initMenus(self): """ Initialize all menus needed for IntroMenu navigation. These menus are used indirectly by main program's currentMenuItems and currentMenuColors attributes. """ self.__menuItems=["Login", "Play", "Single Player", "Multiplayer", "Setup", "Quit"] self.__songTitles={"1":(("TeQuieroMas", "\TeQuieroMas"), ("Ditto Ditto", "\ditto_ditto")), "2":(("Identity of Self", "\identity"), ("Whole Wide Whole", "\WholeWideWhole")), "3":(("Code Monkey", "\CodeMonkey"), ("Nadeya", "\\nadeya")), "4":(("DNA Funkdafied Mix", "\dna"), ("Best Friend Remix", "\\best_friend")), "5":(("Sleeping Alone", "\sleeping_alone"), ("The Sweetest Sin", "\sweetest_sin"))} self.__songTitle_filenames = { "TeQuieroMas":"\menu_10_00.ogg", "Ditto Ditto": "\menu_10_02.ogg", "Identity of Self" : "\menu_10_01.ogg", "Whole Wide Whole" : "\menu_10_03.ogg", "Code Monkey" : "\menu_10_04.ogg", "Nadeya" : "\menu_10_05.ogg", "DNA Funkdafied Mix" : "\menu_10_06.ogg", "Best Friend Remix" : "\menu_10_07.ogg", "Sleeping Alone" : "\menu_10_08.ogg", "The Sweetest Sin" : "\menu_10_09.ogg"} self.__levelSongs = {} if self.__game.getGameMode() == "career": #make dictionary of levels player has unlocked self.__availableLevels = {} for level in self.__songTitles.iterkeys(): if int(level) <= self.__game.getPlayer(0).getProfile().getLevelReached(): self.__availableLevels[level] = self.__songTitles[level] self.__selectMode = "chooseLevel" #init with level 1 songs -- assumes only 2 songs per level song1, song2 = self.__songTitles["1"] self.__levelSongs[2] = song1 self.__levelSongs[1] = song2 self.__levelSongs[0] = ("Back", "") else: self.__selectMode = "chooseSong" index = 0 for level in self.__songTitles.iterkeys(): song1, song2 = self.__songTitles[level] self.__levelSongs[index +1] = song2 self.__levelSongs[index] = song1 index = index + 2 def __checkNavEvent(self, step): """ Looks at GoodStep item, updates self.selected as appropriate. """ if self.__selectMode == "chooseLevel": length = self.__availableLevels.__len__() else: length = len(self.__levelSongs) "Scroll down logic -- down arrow" if(step.getLocation()==(1, 0)): #update selected self.__selected += 1 if length-1 < self.__selected: self.__selected = 0 self.__playMenuItemSound() "Scroll up logic -- up arrow" if(step.getLocation()==(1, 2)): #update selected self.__selected -= 1 if self.__selected < 0: self.__selected = length-1 self.__playMenuItemSound() "Choose an option logic -- right arrow" if(step.getLocation()==(2, 1)): if (self.__selectMode == "chooseLevel"): #convert all elements to "choose song" self.__game.setCurrentLevel(self.__selected + 1) #sets current level song1, song2 = self.__songTitles[(self.__selected + 1).__str__()] self.__levelSongs[2] = song1 self.__levelSongs[1] = song2 self.__selected = 0 self.__selectMode = "chooseSong" self.__playSound(self.__pickSong) self.__noteStart_y = self.__offset_y + self.__songList_y #self.__noteStart_y = self.__songList_y + self.__font_height return True else: if self.__levelSongs[self.__selected][0] == "Back": self.__selectMode = "chooseLevel" self.__noteStart_y = self.__offset_y + 2*self.__font_height #self.__noteStart_y = self.__offset_y + 2*self.__font_height self.__playSound(self.__pickLevel) self.__selected = 0 return True else: self.__selectedSong = self.__levelSongs[self.__selected] self.__game.setCurrentSong(self.__selectedSong) if self.__game.getGameMode() == "freeplay": lastGameInfo=SinglePlayerMode.startGame(self.__screen, self.__screenInfo, self.__game) elif self.__game.getGameMode() == "career": lastGameInfo=CareerMode.startGame(self.__screen, self.__screenInfo, self.__game) self.__game = lastGameInfo self.backFromSong = True gameOverScreen = GameOverScreen(self.__screen,self.__game) gameOverScreen.drawScreen(self.__screenInfo, self.__game, self.__soundEffects) gameOverScreen = None self.__playSound(self.__returnMessage) return True "Escape -- left arrow" if(step.getLocation()==(0, 1)): return False return True def __loadImages(self): """ Loads images for menus, resizes them for current screen dimensions. """ fileLocs=FileLocations() menuImage_file = fileLocs.images_menus+r"\songChooserMenu.png" note_file = fileLocs.images_menus+r"\note.png" menu_bkgrd_file = fileLocs.images_menus+r"\menu_right.png" self.__menuImage = pygame.image.load(menuImage_file).convert_alpha() self.__noteImage = pygame.image.load(note_file).convert_alpha() self.__bkgrd_rightImage = pygame.image.load(menu_bkgrd_file).convert_alpha() #scale note to match font height note_x, note_y = self.__noteImage.get_size() self.__noteImage = pygame.transform.scale(self.__noteImage, (note_x, self.__font_height)) #settings for placement on screen -- default items self.__offset_x = 80 self.__offset_y = 50 self.__menuItem_height = self.__font_height self.__menu_Y_bump = 10 #centers the note on menu item screen_x, screen_y = self.__screen_size #scale image dimensions according to screen size if needed if(screen_x != 1280): transform = 0 if(screen_x == 800): transform = 0.625 elif(screen_x == 1024): transform = 0.8 self.__offset_x = self.__offset_x * transform # menu_x, menu_y = self.__menuImage.get_size() # menu_x = int(menu_x * transform) # menu_y = int(menu_y * transform) note_x, note_y = self.__noteImage.get_size() note_x = int(note_x * transform) note_y = int(note_y * transform) # self.__menuImage = pygame.transform.scale( self.__menuImage, (menu_x, menu_y)) self.__noteImage = pygame.transform.scale(self.__noteImage, (note_x, note_y)) #level list only displays in career mode if self.__game.getGameMode() == "career": self.__songList_y = self.__offset_y + (self.__font_height * 7) self.__noteStart_y = 2* self.__offset_y + self.__font_height else: self.__songList_y = self.__offset_y + self.__font_height self.__noteStart_y = self.__offset_y + self.__songList_y #+ 2*self.__font_height self.__bkgrd_x = screen_x - self.__bkgrd_rightImage.get_width() self.__bkgrd_y = screen_y - self.__bkgrd_rightImage.get_height() def __loadAudio(self): """ Loads voice and sound effects files for this menu. """ fileLocs=FileLocations() self.__menuSoundsFilename=["\menu_01_01.ogg", "\menu_01_02.ogg", "\menu_01_03.ogg", "\menu_01_04.ogg", "\menu_01_05.ogg", "\menu_01_06.ogg"] self.__menuSound=[] for filename in self.__menuSoundsFilename: self.__menuSound.append(pygame.mixer.Sound(fileLocs.menuSounds+filename)) self.__songTitleAudio = {} for title, filename in self.__songTitle_filenames.iteritems(): self.__songTitleAudio[title] = pygame.mixer.Sound(fileLocs.menuSounds+filename) self.__levelNumber = [] self.__levelNumberFilename = ["\menu_09_04.ogg", "\menu_09_05.ogg", "\menu_09_06.ogg", "\menu_09_07.ogg", "\menu_09_08.ogg"] for filename in self.__levelNumberFilename: self.__levelNumber.append(pygame.mixer.Sound(fileLocs.menuSounds+filename)) #one-off sounds self.__diffLevel = pygame.mixer.Sound(fileLocs.menuSounds+r"\menu_09_09.ogg") self.__pickSong = pygame.mixer.Sound(fileLocs.menuSounds+r"\menu_09_01.ogg") self.__pickLevel = pygame.mixer.Sound(fileLocs.menuSounds+r"\menu_09_02.ogg") self.__returnMessage = pygame.mixer.Sound(fileLocs.menuSounds+r"\menu_09_03.ogg") self.__buzzer = pygame.mixer.Sound(fileLocs.soundEffects+"\\fx_00_00.ogg") self.__narrationChannel = pygame.mixer.Channel(0) def __playSound(self, soundFile): """ Plays soundFile on __narrationChannel. Only one sound can be played at a time and subsequent sounds will override one another. """ soundValue = self.__game.getSettings().getVoiceVolume() / 100.0 soundFile.set_volume(soundValue) self.__narrationChannel.play(soundFile) def __playMenuItemSound(self): """ Chooses a song title or level number to play based on current mode. """ if self.__selectMode == "chooseSong": if self.__levelSongs[self.__selected][0] != "Back": self.__playSound(self.__songTitleAudio[self.__levelSongs[self.__selected][0]]) else: self.__playSound(self.__diffLevel) elif self.__selectMode == "chooseLevel": self.__playSound(self.__levelNumber[(self.__selected)]) def __chooseFontSize(self): if (self.__screen_size == (1280, 960)): return 48 elif (self.__screen_size == (1024, 768)): return 38 elif (self.__screen_size == (800, 600)): return 30 def drawSongChooserMenu(self, screen): """ Draws menu to screen. Takes control of game while menus are displayed. Menu can change based on menu level (some items have sub-levels) and what item is selected. Currently selected item is highlighted. Param is screen currently in use. """ notDone=True firstTime=True self.backFromSong=False if self.__game.getGameMode() == "career": self.__playSound(self.__pickLevel) else: self.__playSound(self.__pickSong) while notDone: if self.backFromSong == True: self.__initMenus() self.__noteStart_y = self.__offset_y + 2*self.__font_height self.__selected = 0 self.backFromSong = False self.__screen.fill((74, 83, 71)) event = pygame.event.wait() if not(self.__cntrl.checkEvent(event) == None): self.__statusPlaying = False notDone = self.__checkNavEvent((self.__cntrl.checkEvent(event, 42))) #42 is fake--time doesn't matter in navigation yChange = 0 # screen.blit(self.__menuImage, (self.__offset_x, self.__offset_y)) screen.blit(self.__bkgrd_rightImage, (self.__bkgrd_x, self.__bkgrd_y)) #menu note screen.blit(self.__noteImage, (self.__offset_x, self.__noteStart_y + (self.__selected * self.__menuItem_height))) screen.blit(self.__font.render("Current mode: "+str(self.__game.getGameMode()), True, self.__font_color), (self.__offset_x, self.__offset_y)) if self.__game.getGameMode() == "career": screen.blit(self.__font.render("Choose a Level: ", True, self.__font_color), (self.__offset_x, self.__offset_y + self.__font_height)) for level in self.__availableLevels: screen.blit(self.__font.render("Level "+level, True, self.__font_color), (self.__offset_x * 2, self.__offset_y + (self.__font_height * 2 + (self.__font_height * (int(level)-1))))) screen.blit(self.__font.render("Choose a song: ", True, self.__font_color), (self.__offset_x, self.__songList_y)) for index in self.__levelSongs: screen.blit(self.__font.render(str(self.__levelSongs[index][0]), True, self.__font_color), (self.__offset_x * 2, self.__offset_y + self.__songList_y + (self.__font_height* int(index)))) screen.blit(self.__font.render(str(self.__game.getPlayer(0).getName()), True, self.__font_color), (0, self.__screen_size[1] - self.__font_height -5)) pygame.display.flip() pygame.time.wait(5) self.__screen.fill((74, 83, 71)) print self.__selectedSong return self.getSelectedSong() def getSelectedSong(self): """ Returns game info as determined by user input. """ return self.__selectedSong
# https://github.com/EricCharnesky/CIS2001-Winter2021/blob/f7f628db35c8af29024460713d8e06c3dd5b0be9/Lab3/main.py class Queue: DEFAULT_CAPACITY = 10 def __init__(self, initial_size = DEFAULT_CAPACITY): self._data = [None] * initial_size self._front = 0 self._back = 0 self._number_of_items = 0 def enqueue(self, item): self._check_capacity() self._data[self._back] = item self._back += 1 if self._back == len(self._data): self._back = 0 self._number_of_items += 1 def dequeue(self): if self._number_of_items == 0: raise IndexError item = self._data[self._front] self._data[self._front] = None self._front += 1 if self._front == len(self._data): self._front = 0 self._number_of_items -= 1 return item def front(self): if self._number_of_items == 0: raise IndexError return self._data[self._front] def __len__(self): return self._number_of_items def _check_capacity(self): if self._number_of_items >= len(self._data): new_data = [None] * len(self._data) * 2 new_data_index = 0 for index in range(self._front, len(self._data)): new_data[new_data_index] = self._data[index] new_data_index += 1 for index in range(0, self._back): new_data[new_data_index] = self._data[index] new_data_index += 1 self._data = new_data self._front = 0 self._back = self._number_of_items
class DoublyLinkedList: class Position: def __init__(self, container, node): self._container = container self._node = node def data(self): return self._node.data def __eq__(self, other): return type(other) is type(self) and other._node is self._node def __ne__(self, other): return not ( self == other ) def __init__(self): self._head = self.Node(None) # Sentinel head/tail self._head.next = self._head # always the first node or itself if it's empty self._head.previous = self._head # always the last node or itself if it's empty self._number_of_items = 0 def __len__(self): return self._number_of_items # O(1) def first(self): return self._make_position(self._head.next) # O(1) def last(self): return self._make_position(self._head.previous) # O(1) def after(self, position): node = self._validate(position) return self._make_position(node.next) # O(1) def before(self, position): node = self._validate(position) return self._make_position(node.previous) # O(1) def add_after(self, position, data): node = self._validate(position) return self._make_position(self._insert_between(data, previous=node, next=node.next)) # O(1) def add_before(self, position, data): node = self._validate(position) return self._make_position(self._insert_between(data, previous=node.previous, next=node)) # O(1) def delete(self, position): node = self._validate(position) return self._remove_node(node) # O(1) def replace(self, position, data): node = self._validate(position) original = node.data node.data = data return original def is_empty(self): return self._number_of_items == 0 # O(1) def add_to_front(self, item): self._insert_between(item, next=self._head.next, previous=self._head) # O(1) def add_to_back(self, item): self._insert_between(item, next=self._head, previous=self._head.previous) # O(1) def remove_back(self): if self.is_empty(): raise ValueError("List is empty") return self._remove_node(self._head.previous) # O(1) def remove_front(self): if self.is_empty(): raise ValueError("List is empty") return self._remove_node(self._head.next) # O ( k ) def pop(self, index): if not (0 <= index < self._number_of_items): raise IndexError("invalid index") current_item = self._head.next for number in range(index): current_item = current_item.next return self._remove_node(current_item) # O ( k ) def insert(self, index, item): if not (0 <= index < self._number_of_items): raise IndexError("invalid index") current_item = self._head.next for number in range(index): current_item = current_item.next self._insert_between(item, previous=current_item.previous, next=current_item) def __iter__(self): current = self.first() while current is not None: yield current.data() current = self.after(current) def _insert_between(self, item, previous, next): new_node = self.Node(item, next=next, previous=previous) new_node.previous.next = new_node new_node.next.previous = new_node self._number_of_items += 1 return new_node def _remove_node(self, current_item): data = current_item.data current_item.data = None current_item.previous.next = current_item.next current_item.next.previous = current_item.previous self._number_of_items -= 1 return data def _validate(self, position): if not isinstance(position, self.Position): raise TypeError() if position._container is not self: raise ValueError() if position._node.next is None: raise ValueError return position._node def _make_position(self, node): if node is self._head: return None return self.Position(self, node) class Node: def __init__(self, data, next=None, previous=None): self.data = data self.next = next self.previous = previous class SinglyLinkedList: def __init__(self): self._head = None # front self._tail = None # back self._number_of_items = 0 def __len__(self): return self._number_of_items def add_to_front(self, data): new_node = self.Node(data, self._head) self._head = new_node if self._head.next is None: self._tail = new_node self._number_of_items += 1 def add_to_back(self, data): new_node = self.Node(data, None) if self._tail is None: self._tail = new_node self._head = new_node else: self._tail.next = new_node self._number_of_items += 1 def front(self): if self._number_of_items == 0: raise ValueError("List is empty") return self._head.data def remove_front(self): if self._number_of_items == 0: raise ValueError("List is empty") data = self._head.data self._head.data = None # cleanup for garbage collection self._head = self._head.next if self._head is None: self._tail = None self._number_of_items -= 1 return data # O ( k ) def get(self, index): if not (0 <= index < self._number_of_items): raise IndexError("invalid index") current_item = self._head for number in range(index): current_item = current_item.next return current_item.data # O ( k ) def pop(self, index): if not (0 <= index < self._number_of_items): raise IndexError("invalid index") if index == 0: return self.remove_front() else: current_item = self._head for number in range(index-1): current_item = current_item.next data = current_item.next.data current_item.next.data = None current_item.next = current_item.next.next self._number_of_items -= 1 # check for new tail if current_item.next is None: self._tail = current_item return data # O ( index ) - no shifting of items after the index def add_to_index(self, index, item): if not (0 <= index <= self._number_of_items): raise IndexError("invalid index") if index == 0: self.add_to_front(item) elif index == self._number_of_items: self.add_to_back(item) else: current_item = self._head for number in range(index-1): current_item = current_item.next new_item = self.Node(item, current_item.next) current_item.next = new_item self._number_of_items += 1 # O ( k ) - no shifting of items after the removed item to 'fill' an empty spot def remove(self, item): if self._number_of_items == 0: raise ValueError("List is empty") if self._head.data == item: self.remove_front() else: current = self._head while current.next is not None: if current.next.data == item: # clears the reference for garbage collection current.next.data = None # jump it in the list current.next = current.next.next self._number_of_items -= 1 # check for new tail if current.next is None: self._tail = current current = current.next else: raise ValueError("Item not found!") class Node: def __init__(self, data, next=None): self.data = data self.next = next class LLStack: def __init__(self): self._data = SinglyLinkedList() def __len__(self): return len(self._data) def push(self, item): self._data.add_to_front(item) def peek(self): return self._data.front() def pop(self): return self._data.remove_front() class LLQueue: def __init__(self): self._data = SinglyLinkedList() def __len__(self): return len(self._data) def front(self): return self._data.front() def enqueue(self, data): self._data.add_to_back(data) def dequeue(self): return self._data.remove_front() doublyLinkedList = DoublyLinkedList() for n in range(10): doublyLinkedList.add_to_back(n) # using the iterator for item in doublyLinkedList: print(item) # our iteration using position current_position = doublyLinkedList.first() while current_position is not None: print(current_position.data()) current_position = doublyLinkedList.after(current_position)
# Write the Python code that takes two integer values and returns the first value raised to the power of the second value. number = int(input()) power = int(input()) squared = lambda number, power: number**power print(squared(number, power))
# days = int(input("How many days:")) # years = days // 365 # weeks = (days % 365) // 7 # days = days - ((years * 365) + (weeks * 7)) # print("Years:", years) # print("Weeks:", weeks) # print("Days:", days) user_input = input() number = int(user_input) binary = bin(number) print(binary)
# JSON = JavaScript Object Notation # json.dumps() method is used for JSON encoding, ex: converting dictionaries to JSON objects import json sample = { 'name': 'Bert Bertie', 'age': 24 } sample_json = json.dumps(sample) print(sample_json) print(type(sample_json)) # the output type is a str object # If you want to decode the JSON object, you can use json.loads() to do so. We are going to add some code in our original code to illustrate this: original_sample = json.loads(sample_json) print(original_sample) print(type(original_sample)) # this reconverts the JSON data we converted from a dict to JSON object back to a dict object
import random def random_number_generator(l): output = [] for i in range(l): output.append(random.randint(1, 5)) return output print(random_number_generator(1))
import csv output = [] # creating csv file with names and hours worked columns with open('input.csv', 'r') as f: mock_data_reader = csv.reader(f) output_data = [] line_count = 1 for row in mock_data_reader: if line_count != 1: # iterates through the file and multiplies the int(hours worked) by 15 row[1] = int(row[1]) * 15 output_data.append(row) line_count +=1 with open('output.csv', 'w') as f: fields = ['name', 'wages'] output_writer = csv.DictWriter(f, fieldnames = fields) # creates the header row output_writer.writeheader() # input of the dictionary for line in output_data: output_writer.writerow( { 'name': line[0], # first index/column 'wages': line[1] # second index/column } ) # code won't run beacause there is no input.csv file to read from
# creating a file f = open('myfile.txt', 'w') # writing something to the new file we just created print(f.write('Hello, World\n')) print(f.write('Hello, world again')) # closing the file f.close() # if we want to add need to re-open (this is an append version) f = open('myfile.txt', 'a') f.write('More content') f.close # reading a file f = open('myfile.txt', 'r') print(f.read()) f.close # combining reading and writing (when writing it appends to last string in doc) f = open('myfile.txt', 'r+') print(f.read()) f.write('Some Content') # Context manager, helps with cleaner code and easier syntax: with open('myfile.txt', 'r+') as f: content = f.read() print(content)
height = float(input("What is your height in meters?: ")) weight = int(input("What is your weight in Kg?: ")) bmi = weight / (height * height) if bmi < 30: if bmi >= 25: print("Overweight") if bmi >= 18.5: print("Normal") if bmi < 18.5: print("Underweight") else: print("Obesity")
numbers = [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10] # 'i' is the singular item in the 'numbers' list for num in numbers: square = num * num print(num, "squared is ", square)
## union() a = {1,2,3,4,5,6} b = {1,2,3,7,8,9,10} print(a.union(b)) ## another syntax for union is: print(a | b) ## intersection of sets is what they have in common a = {1,2,3,4,5,6} b = {1,2,3,7,8,9,10} print(a.intersection(b)) ## other syntax example: print(a & b) ## difference, self explanatory a = {1,2,3,4,5,6} b = {1,2,3,7,8,9,10} print(a.difference(b)) print(b.difference(a)) ## symmetric difference gives everything rather than the difference print(a.symmetric_difference(b)) ## you can update sets with values from results of set operations a = {1,2,3} b = {3,4,5} a.difference_update(b) print(a) ## print() the updated set, not the set operation_update a = {1,2,3} b = {3,4,5} a.intersection_update(b) print(a) ## Knowledge check first = {1,2,3,4,5,6} second = {1,2,3,7,8,9,10} print(first | second) print(first.intersection(second)) print(first.difference(second)) ## frozenset() method, support all set operations but are immutable(not changeable) a = frozenset([1,2,3]) ## Activity 27: Creating Unions of Elements in a Collection def find_union(x,y): union = [] for items in x + y: if items not in union: union.append(items) return union print(find_union([1, 2, 3, 4], [3, 4, 5, 6]))
import os import csv import time import units def rule_god(cell: bool, neighbors: int) -> bool: """ godmode """ return True """ cell: cell state; True or False neighbors: number of alive neighbor cells, 0<=int<=9 """ def rule_underpopulation(cell: bool, neighbors: int) -> bool: """ Any live cell with fewer than two live neighbors dies, as if by under population. """ assert bool(cell) is True return not (cell and neighbors < 2) def rule_survive(cell: bool, neighbors: int) -> bool: """ Any live cell with two or three live neighbors lives on to the next generation. """ assert bool(cell) is True return cell and neighbors in (2, 3) def rule_overpopulation(cell: bool, neighbors: int) -> bool: """ Any live cell with more than three live neighbors dies, as if by overpopulation. """ assert bool(cell) is True return not (cell and neighbors > 3) def rule_reproduction(cell: bool, neighbors: int) -> bool: """ Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. """ assert bool(cell) is False return not cell and neighbors == 3 def apply_rules(state: bool, neighbors: int, rules_for_alive: tuple, rules_for_dead: tuple, debug: bool = False) -> bool: '''Apply rules on the cell''' next_state = state if state: next_state = all(rule(state, neighbors) for rule in rules_for_alive) else: next_state = all(rule(state, neighbors) for rule in rules_for_dead) if debug: print((state, neighbors), '->', next_state) return next_state def find_neighbors(world: tuple, cell_pos: tuple) -> int: '''Return the number of alive neighbors''' neighbors = [] row, cell = cell_pos top = world[row-1][cell] neighbors.append(top) bottom = world[(row + 1) % len(world)][cell] neighbors.append(bottom) left = world[row][cell-1] neighbors.append(left) right = world[row][(cell + 1) % len(world[row])] neighbors.append(right) top_left = world[row-1][cell-1] neighbors.append(top_left) top_right = world[row-1][(cell + 1) % len(world[row])] neighbors.append(top_right) bottom_left = world[(row + 1) % len(world)][cell-1] neighbors.append(bottom_left) bottom_right = world[(row + 1) % len(world)][(cell + 1) % len(world[row])] neighbors.append(bottom_right) # print(cell_pos, neighbors) return sum(neighbors) def change_world(world_state: tuple) -> tuple: '''Return the next state of the world''' new_world = [] for i, row in enumerate(world_state): new_row = [] for j, cell_state in enumerate(row): cell_pos = i, j neighbors = find_neighbors(world_state, cell_pos) cell_state_new = apply_rules(cell_state, neighbors, (rule_underpopulation, rule_survive, rule_overpopulation), (rule_reproduction,)) # print(f'at {cell_pos}', # cell_state, neighbors, '->', int(cell_state_new)) new_row.append(int(cell_state_new)) new_world.append(tuple(new_row)) return tuple(new_world) def repr_cell(cell: bool) -> str: '''Return a representation of a cell''' return '@' if cell else '_' def repr_world(world: tuple) -> str: '''Return a representation of a world''' world_repr = '' for row in world: world_repr += ''.join([repr_cell(cell) for cell in row]) world_repr += '\n' return world_repr def life(state: tuple, generations: int=50, pause_time: float=0.5) -> tuple: '''Update screen with the state of the world in each generation''' for gen_number in range(generations+1): os.system('clear') print(f'Gen: {gen_number}') print(repr_world(state)) state = change_world(state) time.sleep(pause_time) return state def load_map(map_file) -> tuple: map = [] for row in csv.reader(map_file): map.append(tuple([int(cell) for cell in row])) return tuple(map) if __name__ == "__main__": with open('tiled/gosper-gun-wide.csv') as map_file: map = load_map(map_file) life(map, 500, 0.1) print('OK.')
## 기본 출력을 위한 print 함수 import sys print(1) print('hello', 'world') # sep 파라미터 x = 0.2 s = "hello" print(x) print(s) # 기본적으로 ',' 로 구분이 되면 separator가 ' '로 동작한다 print(x, s, sep=' ') print(x, s) # 기본적인 print() 함수 호출 print('abc', 'des', sep=' ', end='\n') # file 파라미터를 지정 print('Hello World', file=sys.stdout) print('Error: Hello World', file=sys.stderr) # file 출력 # hello.txt를 write모드로 연 후 file=f에 Hello World를 작성한다. f = open('hello.txt', 'w') print(type(f)) print('Hello World', file=f) f.close() # 참고 sys.stdout.write('Hello World!!!!!!!!!!!!!')
class lesson: def inputgrades(self, m, f, p): self.grades["midterm"]=m self.grades["final"]=f self.grades["project"]=p def lettergrade(self): a = ((self.grades["midterm"] * self.percent["midterm"]) + (self.grades["final"] * self.percent["final"]) + (self.grades["project"] * self.percent["project"])) if a > 90: return "AA" elif 70 < a and a < 90: return "BB" elif 50 < a and a < 70: return "CC" elif 30 < a and a < 50: return "DD" else: return "FF" def __init__(self, name): self.name=name self.grades = {"midterm":0, "final":0, "project":0} self.percent = {"midterm":0.3, "final":0.5, "project":0.2} class student: name = "" surname = "" takenlesson = [] def __init__(self, name, surname,course): self.name=name self.surname=surname self.takenlesson=course def enter(st): for k in st.takenlesson: print("Enter grades for: " + k.name) k.inputgrades(int(input("midterm: ")),int(input("final: ")),int(input("project: "))) def printgrades(st1): for m in st1.takenlesson: print("Grades for: " + m.name) print("lettergrade: " +str(m.lettergrade())) def main(): ogr = [student("Bora","KIŞ",[lesson("Biology"),lesson("Mathematics"),lesson("Physics"),lesson("Art"),lesson("Chemistry")]),student("Muhammed Galip","ULUDAĞ",[lesson("Biology"),lesson("Mathematics"),lesson("Physics"),lesson("Art"),lesson("Chemistry")])] for i in range(3): inputname = input("Please enter your name: ") inputsurname = input("Please enter your surname: ") for j in ogr: if j.name == inputname and j.surname == inputsurname: print("Welcome!") enter(j) printgrades(j) print("Please try again.") if __name__ == "__main__": main()
# Python program to print the file extension in a given file name #Ex: Hello.java should output java file_name = input('Please enter a file name: ') print(str(file_name.split('.')[-1]))
""" stringjumble.py Author: Jackson Lake Credit: https://www.youtube.com/watch?v=u1jdar3WADY https://www.youtube.com/watch?v=OFSELeMx2nE Assignment: The purpose of this challenge is to gain proficiency with manipulating lists. Write and submit a Python program that accepts a string from the user and prints it back in three different ways: * With all letters in reverse. * With words in reverse order, but letters within each word in the correct order. * With all words in correct order, but letters reversed within the words. Output of your program should look like this: Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy You entered "There are a few techniques or tricks that you may find handy". Now jumble it: ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT handy find may you that tricks or techniques few a are There erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah """ string = input("Please enter a string of text (the bigger the better): ") print('You entered "{0}". Now jumble it:'.format(string)) print(string[::-1]) sep = string.split() print(' '.join((sep[::-1]))) one = (string[::-1]) three = one.split() print(' '.join(three[::-1]))
a=eval(input('a=')) b=eval(input('b=')) eps=eval(input('eps=')) x=a y=b while abs(x-y)>=eps: z=(x+y)/2 x=y y=z print('Limita este:',z)
x=0 prog=[] while True: x=int(input('x=')) if x>-1: prog.append(x) else: break r=prog[1]-prog[0] este_prog=True for i in range(len(prog)-1, 1, -1): if prog[i]-prog[i-1]!=r: este_prog=False print('Sirul nu este o progresie aritmetica') break if este_prog==True: print('Sirul este o progresie aritmetica')
from math import sqrt def radical(a, eps): x = a y = 0.5*(x+a/x) while abs(x-y) >= eps: x = y y = 0.5*(x+a/x) return y while True: a=eval(input()) if a>0: break eps=eval(input('eps=')) print('Radicalul aproximativ=', radical(a,eps)) print('Rezultatul cu functia sqrt este:', sqrt(a))
p=int(input("p=")) q=int(input("q=")) d=p i=q r=1 while r!=0: r=d%i d=i i=r print(p,"/",q," ",p//d,"/",q/d)
"""Description Write a computer program to implement SVM method. (i)preprocessthe data instances:if data instances have categorical features, then call the subroutine convert(X). (ii) given the training data instances, your program should be able to compute the w, b, alpha, margin. (iii) when a new data instance is presented, the program uses pre-trained SVM model to predict the class label for the new data instance. """ from sklearn import svm import matplotlib.pyplot as plt import numpy as np def plot_decision_function(classifier, axis, title): # plot the decision function xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500)) Z = classifier.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # plot the line, the points, and the nearest vectors to the plane axis.contourf(xx, yy, Z, alpha=0.75, cmap=plt.cm.bone) axis.scatter(X[:, 0], X[:, 1], c=y, s=100, alpha=0.9, cmap=plt.cm.bone, edgecolors='black') # axis.axis('off') axis.set_title(title) if __name__ == "__main__": X = np.array([[0, 0], [1, 1]]) y = np.array([0, 1]) clf = svm.SVC(kernel='linear') clf.fit(X, y) # pred = clf.predict([[2., 2.]]) print(clf.dual_coef_) w = clf.coef_[0] alpha = -w[0]/w[1] b = clf.intercept_ margin = 1 / np.sqrt(np.sum(clf.coef_ ** 2)) print('w of SVM is:', w) print('b of SVM is:', b) print('alpha of SVM is:', alpha) print('margin of SVM is:', margin) fig, axes = plt.subplots(1, 2, figsize=(14, 6)) plot_decision_function(clf, axes[0], "Constant weights") plt.show()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 8 09:46:56 2018 @author: denisvrdoljak """ import random class Card: possiblesuits = ('Spade', 'Heart', 'Diamond', 'Club') suitsymbols = {text: symbol for text, symbol in zip(('Spade', 'Heart', 'Diamond', 'Club'), ['\u2660', '\u2665', '\u2666', '\u2663'])} possiblecardvalues = [str(n) for n in range(2, 11)] + ['J', 'Q', 'K','A'] def __init__(self,suit,cardvalue): if suit.title() not in self.possiblesuits: raise ValueError("'{}' is not a valid suit. Valid suits are -- {} -- passed in as a string".format(suit,self.possiblesuits)) if cardvalue.upper() not in self.possiblecardvalues: raise ValueError("'{}' is not a valid card value. Valid suits are -- {} -- passed in as a string".format(cardvalue, self.possiblecardvalues)) self.value = cardvalue.upper() self.suit = suit.title() self.suitsymbol = self.suitsymbols[self.suit] def __repr__(self): return '{}{}'.format(self.value, self.suitsymbol) class Deck: def __init__(self): self.loadnewdeck() self.shuffledeck() def loadnewdeck(self): self.deck = list() for value in Card.possiblecardvalues: for suit in Card.possiblesuits: self.deck.append(Card(suit,value)) def shuffledeck(self): random.shuffle(self.deck) def cardsleftindeck(self): return len(self.deck) def dealcard(self): return self.deck.pop() if __name__ == "__main__": print("=== === testing deal card function=== ===") print("\nTesting the duck") myduck = Duck() myduck.nametheduck("Bob") myduck.quack() print("\nTesting the soccer ball") mysoccerball = SoccerBall() mysoccerball.kick() #random.seed(5) # remove seed when done testing print("\nTesting the card deck:") testdeck = Deck() testdeck.loadnewdeck() #testdeck.shuffledeck() print("(Dealing the whole deck)") while testdeck.cardsleftindeck() > 0: card = testdeck.dealcard() print(card,end=" ")
import numpy as np import math as m import pytest class Point: """A point. Inputs: Point = list of points ex: Point((0,0,0)) Methods: add = sum of point and vector radd = sum of vector and point sub = subtraction of point from point eq = check for if two points are equal""" def __init__(self, point): self._point = np.array(point, dtype=float) def __repr__(self): return f"Point({self._point.tolist()})" def __add__(self, other): if isinstance(other, Vector): return Point(self._point + other._vector) return NotImplemented def __radd__(self, other): if isinstance(other, Vector): return Point(other._vector + self._point) return NotImplemented def __sub__(self, other): if isinstance(other, Point): return Vector(self._point - other._point) return NotImplemented def __eq__(self, other): if isinstance(other, Point): return np.array_equal(other._point, self._point) return False class Vector: """A vector. Inputs: Vector = list of vector points ex: Vector((0,0,0)) Methods: repr = return the output format for vector class add = sum of vector and vector sub = subtraction of vector from point cross = cross product of two vectors magnitude = return the magnitude of the vector unit_vector = return normalized vector mul = dot product of two vectors eq = check for if two vectors are equal """ def __init__(self, vector): self._vector = np.array(vector, dtype=float) def __repr__(self): return f"Vector({self._vector.tolist()})" def __add__(self, other): if isinstance(other, Vector): return Vector(self._vector + other._vector) return NotImplemented def __sub__(self, other): if isinstance(other, Vector): return Vector(self._vector - other._vector) return NotImplemented def cross(self,other): if isinstance(other,Vector): cross=np.cross(self._vector,other._vector) return Vector(cross) if isinstance(other,Point): cross=np.cross(self._vector,other._point) return Vector(cross) return NotImplemented def magnitude(self): c=np.linalg.norm(self._vector) return c def unit_vector(self): return Vector((1/self.magnitude())*self._vector) def __mul__(self,other): if isinstance(other,Vector): return np.dot(self._vector,other._vector) if isinstance(other,Point): return np.dot(self._vector,other._point) if isinstance(other,float) or isinstance(other,int) : return Vector(self._vector*other) return NotImplemented def __eq__(self, other): if isinstance(other, Vector): return np.array_equal(other._vector, self._vector) return False class Ray(Point,Vector): """A ray. INPUT: origin = input can be an array or point Ex-(0,0,0) or Point((0,1,0)) direction = input can be an array or point Ex- (0,1,0) or Point((0,1,0)) Methods: repr = return the output format for Ray class unit_vector = returns normalized vector of a ray magnitude = return the magnitude of the vector mul = dot product of two vectors eq = check for if two Rays are equal""" def __init__(self,origin,direction): if not isinstance(origin,Point) : if Point(origin)==Point(direction): self._origin=() self._direction=() raise Exception("The end point and direction should not be same") else: self._origin=Point(origin) self._direction=Point(direction) self._t=self._direction-self._origin else: if origin==direction: self._origin=() self._direction=() raise Exception("The end point and direction should not be same") else: self._origin=origin self._direction=direction self._t=self._direction-self._origin def magnitude(self): c=Vector.magnitude((self._t)) return c def unit_vector(self): u=Vector.unit_vector((self._t)) return u def __repr__(self): return f"Ray{self._origin,self._direction}" def __eq__(self,other): if isinstance(other,Ray): return np.array_equal(other._origin,self._origin) & np.array_equal(other._direction,self._direction) return False class Sphere(Point): """A sphere. INPUT: center = input can be an array or point Ex-(0,0,0) or Point((0,1,0)) Radius = input can be an array or point Ex- (0,1,0) or Point((0,1,0)) Methods: repr = return the output format for Sphere class area = returns the area of the sphere circumfernece = return the circumference of the sphere eq = check for if two Spheres are equal """ def __init__(self,center,radius:float): if radius<=0: return Exception("Radius cannot be negative or zero") else: if not isinstance(center,Point): self._center=Point(center) self._radius=radius elif isinstance(center,Point): self._center=center self._radius=radius def __repr__(self): return f"Sphere{self._center,self._radius}" def area(self): area=(4/3)*(m.pi)*(self._radius)**3 return area def circumfernece(self): return (4*m.pi*self._radius**2) def __eq__(self,other): if isinstance(other,Sphere): return np.array_equal(other._center,self._center)& (other._radius==self._radius) return class Triangle(Point,Vector): """A triangle. INPUT: vertice1 = input can be an array or point Ex- (0,0,0) or Point((0,1,0)) vertice2 = input can be an array or point Ex- (0,1,0) or Point((0,1,0)) vertice3 = input can be an array or point Ex- (0,1,0) or Point((0,1,0)) Methods: repr = return the output format for Triangle class sidelength = returns the magnitude of the side of the triangle perimeter = return the perimeter of the triangle area = return the area of the triangle eq = check for if two triangles are equal """ def __init__(self,vertice1,vertice2,vertice3): if isinstance(vertice1,Point): self._v1=vertice1 self._v2=vertice2 self._v3=vertice3 else : self._v1=Point(vertice1) self._v2=Point(vertice2) self._v3=Point(vertice3) self._AB=self._v2-self._v1 self._BC=self._v3-self._v2 self._AC=self._v3-self._v1 a,b,c=self.sidelengths() if ((a + b) > c) & ((a + c) > b ) & ((b + c) > a) : pass else: raise Exception("The vertices are collinear") def __repr__(self): return f"Triangle{self._v1,self._v2,self._v3}" def sidelengths(self): a=Vector.magnitude(self._AB) b=Vector.magnitude(self._BC) c=Vector.magnitude(self._AC) return a,b,c def perimeter(self): a,b,c=self.sidelengths() p=(a+b+c) return p def area(self): a,b,c=self.sidelengths() s=a+b+c/3 Area=np.sqrt((s*(s-a)*(s-b)*(s-c))) return Area def __eq__(self,other): a,b,c=self.sidelengths() a1,b1,c1=other.sidelengths() if isinstance(other,Triangle): if (a/b==a1/b1) and (a/c==a1/c1) and (b/c==b1/c1): return True else: return False return NotImplemented