text
stringlengths
37
1.41M
import matplotlib.pyplot as plt Year=[2010,2011,2012,2013,2014,2015] rice=[10,20,40,60,70,40] plt.xlabel("Years") plt.ylabel("Rice Production") plt.title("Rice Production over time") plt.plot(Year,rice) plt.show()
file_read=open("data.txt","r") file_write=open("data21.txt","w") for line in file_read: for ch in line: if ch=="a": print ("**",end="") if ch=="m": print ("*",end="") else: print (ch,end="")
# 다형성 # Developer 부모 클래스 선언 class Developer: def __init__(self, name): self.name = name def coding(self): print(self.name, 'is developer!!') # Python Developer 자식 클래스 선언 class PythonDev(Developer): def coding(self): print(self.name, 'is Python Dev!!') # JAVA Dev 자식 클래스 선언 class JavaDev(Developer): def coding(self): print(self.name, 'is JAVA Dev!!') # C++ Dev 자식 클래스 선언 class CPPDev(Developer): def coding(self): print(self.name, 'is C++ Dev!!') # RoR Dev 자식 클래스 선언 class RoRDev(Developer): def coding(self): print(self.name, 'is Ruby on Rails Dev!!') pd = PythonDev('찬영이') jd = JavaDev('준영이') cd = CPPDev('채영이') rd = RoRDev('성훈이') pd.coding() jd.coding() cd.coding() rd.coding()
# break문 예시 signals='blue','yellow','red' # for x in range(len(signals)): # print(x, signals[x],'루프시작!!') # if signals[x] == 'yellow': # break # print(x, signals[x],'루프종료!') # # print('프로그램 종료') for x in range(len(signals)): print(x, signals[x], '루프시작!!') if signals[x] == 'yellow': continue print(x, signals[x], '루프종료!') print('프로그램종료') for x in range(len(signals)): print(x, signals[x], '루프시작!!') if signals[x] == 'yellow': pass print(x, signals[x], '루프종료!') print('프로그램종료')
#print("오늘의 온도를 입력하세요.") temp = 10 if temp > 20 : print("얇은 옷을 입으세염!") else : print("두꺼운 옷을 입으세염!") sign = "stop" while sign == "stop" : sign = input("현재 신호를 입력하시오: ") print("OK! 진행합니다.")
from tkinter import * from tkinter import messagebox root = Tk() root.title("Hello World!") root.geometry("400x400") root.iconbitmap('c:/guis/codemy.ico') # Create Popup function def popup(): response = messagebox.showinfo("Popup Title", "Look at my popup message!!") my_label = Label(root, text=response).pack(pady=10) ''' if response == 1: my_label = Label(root, text="you clicked yes!").pack(pady=10) else: my_label = Label(root, text="you clicked no!").pack(pady=10) ''' # Popup Boxes # showinfo, showwarning, showerror, askquestion, askokcancel, askyesno pop_button = Button(root, text="Click To Pop Up!", command=popup) pop_button.pack(pady=20) root.mainloop()
def get_user_int_input(question): # Get input from user called int_input as int based on str question. If input is not int reppet until it is an int. while True: try: int_input = int(input(question)) break except ValueError: print('You have to chose a integer') pass return int_input def user_chose_from_list(list): # take a list with strings and ask user to chose one and return the int chose_index that is index for that chose in list. chose_text = '' chose_counter = 1 chose_number = 0 for text in list: chose_text += f'{chose_counter}: {text}\n' chose_counter += 1 while True: chose_number = get_user_int_input(chose_text) # check if chose_number is one of the list choices if chose_number <= len(list) and chose_number > 0: break else: print('You have to chose one of this choices') # chose_index is index chosen based on chose_number in list chose_index = chose_number - 1 return chose_index # thor main function def dragons_lair(): dragons_approach_text = 'You feel the gound shaking and soon sound of something big approach fast. It most be the dragon.' game_over = 'Dragons lair is over, hopp you hade fun and please try again, who know what will happen next time.' you_are_list = ('Strong', 'Fast', 'Smart') print('What are you') you_are_index = user_chose_from_list(you_are_list) print('You have manage to find a secret way into the dragons lair, but here a strange sound an notes the way you come form now is a solid stone wall.\nYou look around and see all kinds of treaseure and pils of gold to the celing') print('You find servral sevral thing of intressed. What do you want to get a closer to and have better look at?') look_closer_list = ('Lots of weaopns', 'Biggest pile of gems', 'Ropes in varius color') looked_closer_at = user_chose_from_list(look_closer_list) # depending on what user chose to look closer at will change what happens next if looked_closer_at == 0: # User have looked closer at Lots of weaopns print('You find many intressing and exotic weapons, some normal looking, some valuable looking.') print(dragons_approach_text) print('You look around but no good place to hidde. You panic, you think fight with one of the weapons is you best chans and grab?') weapon_list = ('Shine sword', 'Big axe', 'Sharp dagger') weapon_index = user_chose_from_list(weapon_list) if weapon_index == 0: print('With the Shine sword you will try to attack. As the dragons change at you, you dodge and attack the dragons and hit right in in its chest. You watch in horror as the blade of the swords brakes of into two pieces and shortly after you end as the dragons meal.') print(game_over) return True elif weapon_index == 1: print('With the Big axe you will try to attack. As the dragons change at you, you dodge and attack the dragons and hit right in in its chest.') if you_are_index == 0: # you_are_index 0 is Strong print('It hitts depp and the dragons falls over, rolling arund knocking arund treasure. Soon it is still and dead. Bringing back as much treasure you can carry. You liva a good life free from more danger in luxury.') print(game_over) return True else: print('It bounces of the dragons scale and shortly after you end as the dragons meal.') print(game_over) return True elif weapon_index == 2: print('With the sharp dagger ready in hand, the dragon gets close and open it mouth and a red light glows from it. You throw the dagger in its mouth. The dragon starts cough and you taka this chanse to flee. Weeks later far from the dragons lair you hear news that all settelment close to where you find the dragons lair hade beeen burnt down.') print(game_over) return True else: raise ValueError(f'Something has gone wrong and weapon_index is not a valid value but is: {weapon_index}') elif looked_closer_at == 1: # User have looked closer at biggest pile of gems print('You find you self drawn to the biggest pile of gems. It has gems of many color') print(dragons_approach_text) print('You have to get out of here, mayby you can sneak out, but leaving all the gems do not feel right.') while True: gems_taken = get_user_int_input('How many gems do you wish to take?\n') if gems_taken >= 0: break print('You dont have any gems to give') if gems_taken == 0: print('You easly sneak out without the dragons noticeing you. The rest of you live is as poor man where nothing intresting happen. Only now and the dream how life been if you hade take some of the gems at the dragons lair') print(game_over) return True elif gems_taken <= 21: print('You easly sneak out without the dragons noticeing you. You manage to live a modest life by selling you plunder form the dragons lair') print(game_over) return True elif gems_taken <= 44 or (you_are_index == 0 and gems_taken <= 58): # if user is strong it can carry more gems print('You sneak out without the dragons noticeing you but almost found you as all the gems slowed you down. You manage to live better then the king by selling you plunder form the dragons lair') print(game_over) return True else: print('You sneaking out was easy, until you drop some of the gems on the ground. As you turn around to see of the dragon notis you, all you see is a lot of flame filling the area. You are dead') print(game_over) return True elif looked_closer_at == 2: # User have looked closer ropes in varius color print('Something about the ropes are unusually and you find it intresting how many diffrent kind of rope the is here.') print(dragons_approach_text) print('What will you do. Mayby one of the ropes can be of used?') rope_list = ('Gray iron rope made by the orcs', 'Red silk rope with range markings', 'Thin yellow rope, probebly made by a fairy') rope_index = user_chose_from_list(rope_list) if rope_index == 0: # Gray iron rope made by the orcs if you_are_index == 0: # User is strong print('You bearly manage to lift the heavy iron rope. Not know what to do next, the dragon steps on you. You are dead') print(game_over) return True else: print('You don\'t manage to lift the heavy iron rope. Not know what to do next, the dragon steps on you. You are dead') print(game_over) return True elif rope_index == 1 or rope_index == 2: # Red silk rope with range markings or Thin yellow rope, probebly made by a fairy if rope_index == 1 and you_are_index == 2: # Red silk rope with range markings and Smart print('The dragon is get close and you take a look at the markings. It seems to be elven. Most of it you can not read, but as you read out loud the one part you can read a by speaking out melon. The rope start to glow and fly and become a collar around the dragons neck.\nNow you have a big pet dragon as the rope was magic to force someone to obey or it will start stangling the dragon. With the dragons help and your keen mind it was easy to take over the kingdom and expand it to cover the entire continent.') print(game_over) return True elif rope_index == 2 and you_are_index == 1: # Thin yellow rope, probebly made by a fairy and Fast print('You with the thin yello rope and your fast dashing to avoid danger you mange to tied up the dragon. You steal as much treasure you can and live like a king. You heard that dragons are magic create that that don\'t need to eat to survive so it may still be there, but you won\'t check as you will not risk you life ever again if you do not have to.') print(game_over) return True else: print('You stand there with you rope, but do not know what to do with it. Not know what to do next, the dragon steps on you. You are dead') print(game_over) return True else: raise ValueError(f'Something has gone wrong and rope_index is not a valid value but is: {rope_index}') else: raise ValueError(f'Something has gone wrong and looked_closer_at is not a valid value but is: {looked_closer_at}') raise SyntaxError(f'Something has gone wrong as the code shall not even be able to reach here')
# author: KaiZhang # date: 2021/8/8 14:44 """ List Comprehensions :列表生成式 """ range_ = [x * x for x in range(1, 11)] print(range_) x_ = [x for x in range(1, 11) if x % 2 == 0] # 不能在最后的if加上else,因为跟在for后面的if是一个筛选条件,不能带else,否则无法筛选 x_ = [x if x % 2 == 0 else -x for x in range(1, 11)] # if写在for前面必须加else,因为for前面的部分是一个表达式,它必须根据x计算出一个结果。因此,考察表达式:x if x % 2 == 0,它无法根据x计算出结果,因为缺少else,必须加上else
# author: KaiZhang # date: 2021/8/7 17:01 """ set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。 要创建一个set,需要提供一个list作为输入集合 """ s = set([1, 2, 3]) print(s) # 重复元素在set中自动被过滤 s = set([1, 1, 2, 2, 3, 3]) print(s) # 通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果 s.add(5) print(s) # 通过remove(key)方法可以删除元素 s.remove(5) print(s) # set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作 s1 = set([1, 3, 4]) s2 = set([2, 4, 5]) s3 = s1 & s2 # 取交集 print(s3) s4 = s1 | s2 print(s4) # 取并集 """ set和dict的唯一区别仅在于没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变对象, 因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”。 """ set1 = set([1, 2, 3]) # set1.add([2, 3]) # 会报错,unhashable type: 'list',list是不可哈希的
def linearsearch (arr, x): for i in range(len(arr)): if arr[i] == x: print ("Index is ",i) break else: print("Not present") print("welcome to my linear search program.") arr = [45, 78, 66, 52, 28, 36] print("This is my array. Enter any number to search its index.") print(arr) x = int(input("Enter the number : ")) linearsearch(arr, x)
a = int(input("Enter the starting number : ")) b = int(input("Enter the Ending number : " )) print ("Prime number in between the given range are") for i in range (a, b+1): if i>1: for j in range (2,i): if (i%j == 0): break else: print (i, end=" ")
pes=12 jardas=3*pes milhas=1760*jardas conv=float(input("Digite o valor em pes")) print("O valor em jardas e:"+str()) print("O valor em milhas e:"+str())
class FeeType(object): FLOAT = 0 FIXED = 1 class Fee(object): def __init__(self, fee_dict): # type: (int, float, float, float) -> None self.__fee_type = fee_dict['fee_type'] self.__amount = fee_dict['amount'] self.__min_fee = fee_dict['min_fee'] self.__max_fee = fee_dict['max_fee'] self.__extra_fee = 0.0 if 'extra_fee' in fee_dict: self.__extra_fee = fee_dict['extra_fee'] def calculate_fee(self, price, quantity): # type: (float, float) -> float if self.__fee_type == FeeType.FIXED: return self.__amount turnover = price * quantity fee = turnover * self.__amount if fee < self.__min_fee: fee = self.__min_fee if fee > self.__max_fee: fee = self.__max_fee return fee + self.__extra_fee
# A Tuple is a collection which is ordered and unchangeable. Allows duplicate members. # Create tuple fruits=('Apples','Oranges','Grapes') #fruits2=tuple(('Apples','Oranges','Grapes')) # Single value needs trailing comma fruits2=('Apples',) # Get value print(fruits[2]) # Can't change alue # fruits[0]='Pears' ''' Delete tuple del fruits2 print(fruits2) ''' # Get length print(len(fruits)) # A Set is a collection which is unordered and unindexed. No duplicate members. # Create set fruits_set={'Apples','Oranges','Mango'} # Check if it is in set print('Apples'in fruits_set) # Add to set fruits_set.add('Strawberries') fruits_set.add('Avocado') fruits_set.add('Gueverra') fruits_set.add('Lemons') fruits_set.add('Blueberries') print(fruits_set) # Remove from set fruits_set.remove('Mango') print(fruits_set) # Clear set fruits_set.clear() # Delete set del fruits_set print(fruits_set)
import math def rotate(xy, radians): x, y = xy xx = round(x * math.cos(radians) + y * math.sin(radians)) yy = round(-x * math.sin(radians) + y * math.cos(radians)) return xx, yy def move_direction_part1(coordinates, action, direction): movement = int(action[1:]) if action[0] == "N": coordinates[1] = coordinates[1] + movement elif action[0] == "S": coordinates[1] = coordinates[1] - movement elif action[0] == "E": coordinates[0] = coordinates[0] + movement elif action[0] == "W": coordinates[0] = coordinates[0] - movement elif action[0] == "L": direction -= movement if direction < 0: direction += 360 elif action[0] == "R": direction += movement if direction >= 360: direction -= 360 elif action[0] == "F": # North if direction == 0: coordinates[1] = coordinates[1] + movement # East elif direction == 90: coordinates[0] = coordinates[0] + movement # South if direction == 180: coordinates[1] = coordinates[1] - movement # West if direction == 270: coordinates[0] = coordinates[0] - movement return coordinates, direction def move_direction_part2(ship, waypoint, action): movement = int(action[1:]) direction = 0 if action[0] == "N": waypoint[1] = waypoint[1] + movement elif action[0] == "S": waypoint[1] = waypoint[1] - movement elif action[0] == "E": waypoint[0] = waypoint[0] + movement elif action[0] == "W": waypoint[0] = waypoint[0] - movement elif action[0] == "L": direction -= movement # if direction < 0: # direction += 360 waypoint[0], waypoint[1] = rotate(waypoint, math.radians(direction)) elif action[0] == "R": direction += movement # if direction >= 360: # direction -= 360 waypoint[0], waypoint[1] = rotate(waypoint, math.radians(direction)) elif action[0] == "F": ship = [(ship[0] + waypoint[0] * movement), (ship[1] + waypoint[1] * movement)] return ship, waypoint, direction def part1(actions): start = [0, 0] coordinates = start direction = 90 for action in actions: coordinates, direction = move_direction_part1(coordinates, action, direction) absolute_coordinates = [abs(coordinate) for coordinate in coordinates] distance = sum(absolute_coordinates) return distance def part2(actions): start = [0, 0] waypoint = [10, 1] ship = start for action in actions: ship, waypoint, direction = move_direction_part2(ship, waypoint, action) absolute_coordinates = [abs(coordinate) for coordinate in ship] distance = sum(absolute_coordinates) return distance def main(): file = open('Day_12/input.txt', 'r') content = file.read() lines = content.splitlines() distance = part1(lines) distance2 = part2(lines) print("The answer for part 1 is:", distance) print("The answer for part 2 is:", distance2)
# python3 import sys NODES = {} # Dict of graph nodes. class GraphNodeUndirected(object): """A basic representation of an undirected graph node. """ def __init__(self): self.visited = False self.pre_visit = None self.post_visit = None self.edges = [] def __repr__(self): if self.visited: return 'Visited, edges: {}'.format(self.edges) else: return 'Unvisited, edges: {}'.format(self.edges) def previsit(node, clock): node.pre_visit = clock #print('Set pre_visit to {}'.format(node.pre_visit)) return clock + 1 def postvisit(node, clock): node.post_visit = clock return clock + 1 def explore(node, clock): if not NODES[node].visited: # For a given node, walk all of its edges and record the pre- and # post-visit clock. NODES[node].visited = True clock = previsit(NODES[node], clock) for w in NODES[node].edges: clock = explore(w, clock) clock = postvisit(NODES[node], clock) return clock def reach(x, y): range1 = [i for i in range(NODES[x].pre_visit, NODES[x].post_visit + 1)] range2 = [i for i in range(NODES[y].pre_visit, NODES[y].post_visit + 1)] print(range1) print(range2) if range1[0] > range2[0] and range1[-1] < range2[-1]: return 1 # Nested (path exists) if range2[0] > range1[0] and range2[-1] < range1[-1]: return 1 # Nested (path exists) return 0 # Disjoint (no path) if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n, m = data[0:2] x, y = data[-2:] # Last 2 values. for i in range(1, n + 1): NODES[i] = GraphNodeUndirected() data = data[2:] edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2])) for edge in edges: if edge[1] not in NODES[edge[0]].edges: NODES[edge[0]].edges.append(edge[1]) if edge[0] not in NODES[edge[1]].edges: NODES[edge[1]].edges.append(edge[0]) clock = 1 for v in NODES.keys(): clock = explore(v, clock) print(reach(x, y))
# Uses python3 import sys """ The algorithm begins by splitting the array in half repeatedly and calling itself on each half. When we get down to single elements, that single element is returned as the majority of its (1-element) array. At every other level, it will get return values from its two recursive calls. The key to this algorithm is the fact that if there is a majority element in the combined array, then that element must be the majority element in either the left half of the array, or in the right half of the array. There are 4 scenarios. a. Both return “no majority.” Then neither half of the array has a majority element, and the combined array cannot have a majority element. Therefore, the call returns “no majority.” b. The right side is a majority, and the left isn’t. The only possible majority for this level is with the value that formed a majority on the right half, therefore, just compare every element in the combined array and count the number of elements that are equal to this value. If it is a majority element then return that element, else return “no majority.” c. Same as above, but with the left returning a majority, and the right returning “no majority.” d. Both sub-calls return a majority element. Count the number of elements equal to both of the candidates for majority element. If either is a majority element in the combined array, then return it. Otherwise, return “no majority.” The top level simply returns either a majority element or that no majority element exists in the same way. Ref: http://www.chegg.com/homework-help/array-1-n-said-majority-element-half-entries-given-array-ta-chapter-2-problem-23-solution-9780077388492-exc """ def majority(a): # Initially check for a single-element array, and return that element # (always majority). if len(a) == 1: return a[0] # Next, find the middle of the array. mid = len(a) // 2 # Recursively call this function on the left and right halves of the array. l_elem = majority(a[:mid]) r_elem = majority(a[mid:]) # These two calls will be one of three cases: # 1. Both return -1 (neither majority) # 2. Both return a value as the majority # 3. One returns a value as the majority, one does not # If both halves return the same value, pass that up as the majority value. if l_elem == r_elem: return l_elem # Check the count of the majority elements (if returned). # If either makes up more than half the passed-in array, pass that element # up again. if l_elem != -1: l_count = a.count(l_elem) if l_count > mid: return l_elem if r_elem != -1: r_count = a.count(r_elem) if r_count > mid: return r_elem # If all else fails, return -1 (no majority element). return -1 if __name__ == '__main__': input = sys.stdin.read() n, *a = list(map(int, input.split())) if majority(a) != -1: print(1) else: print(0)
# python3 import sys def lcm_naive(a, b): '''Dumb (slow) example solution. ''' for l in range(1, a*b + 1): if l % a == 0 and l % b == 0: return l return a*b def gcd(x, y): '''Recycled GCD solution. ''' return gcd(y, x % y) if y else abs(x) def lcm(a, b): '''Return the product of the two ints, divided by their GCD. Use floor (not floating point) division. Ref: https://stackoverflow.com/a/183870/14508 ''' return a * b // gcd(a, b) if __name__ == '__main__': n = sys.stdin.read() x, y = map(int, n.split()) print(lcm(x, y))
import math def f1(x): return math.cos(x)/(1+math.cos(x)*math.cos(x)) def f2(x): return 1/(5+4*math.cos(x)) def f3(x): return math.exp(-x*x) def midpoint(f,a,b): return (b-a)*f((a+b)/2) def trapezoidal(f,a,b): return ((b-a)/2)*(f(a)+f(b)) def simpsons(f,a,b): return (1/3)*trapezoidal(f,a,b) + (2/3)*midpoint(f,a,b) print("For (a) part :") print("Using Midpoint Method, estimated value of the integral =",round(midpoint(f1,0,math.pi/2),6)) print("Diffirence between actual and calculated value :",round(abs(0.623225-midpoint(f1,0,math.pi/2)),6)) print("Using Trapezoidal Method, estimated value of the integral =",round(trapezoidal(f1,0,math.pi/2),6)) print("Diffirence between actual and calculated value :",round(abs(0.623225-trapezoidal(f1,0,math.pi/2)),6)) print("Using Simpsons Method, estimated value of the integral =",round(simpsons(f1,0,math.pi/2),6)) print("Diffirence between actual and calculated value :",round(abs(0.623225-simpsons(f1,0,math.pi/2)),6)) print("") print("For (b) part :") print("Using Midpoint Method, estimated value of the integral =",round(midpoint(f2,0,math.pi),6)) print("Diffirence between actual and calculated value :",round(abs(1.047198-midpoint(f2,0,math.pi)),6)) print("Using Trapezoidal Method, estimated value of the integral =",round(trapezoidal(f2,0,math.pi),6)) print("Diffirence between actual and calculated value :",round(abs(1.047198-trapezoidal(f2,0,math.pi)),6)) print("Using Simpsons Method, estimated value of the integral =",round(simpsons(f2,0,math.pi),6)) print("Diffirence between actual and calculated value :",round(abs(1.047198-simpsons(f2,0,math.pi)),6)) print("") print("For (c) part :") print("Using Midpoint Method, estimated value of the integral =",round(midpoint(f3,0,1),6)) print("Diffirence between actual and calculated value :",round(abs(0.746824-midpoint(f3,0,1)),6)) print("Using Trapezoidal Method, estimated value of the integral =",round(trapezoidal(f3,0,1),6)) print("Diffirence between actual and calculated value :",round(abs(0.746824-trapezoidal(f3,0,1)),6)) print("Using Simpsons Method, estimated value of the integral =",round(simpsons(f3,0,1),6)) print("Diffirence between actual and calculated value :",round(abs(0.746824-simpsons(f3,0,1)),6))
n = input("Enter your desired Fibonacci sequence length: ") n = int(n) print(n)
while True: def triples(): a = input("Enter first side: ") b = input("Enter second side: ") c = input("Enter third side: ") if (int(a)**2 + int(b)**2 = int(c)**2) or (int(a)**2 + int(c)**2 = int(b)**2) or (int(b)**2 + int(c)**2 = int(a)**2): print("It is a Pythagorean Triples!") else: print("It is NOT a Pythagorean Triples!") triples()
# Lieu de travail de Samir Abou Serhal pour le travail de liste # La date est le 17 décembre 2020 # Pour me contacter, envoyer moi un couriel à [email protected] """" print("") print("Bonjour, je suis un menu interactif.") print("Voici les options que je vous présente:") print("") print("Pèse 0 pour dire bonjour.") print("Pèse 1 pour savoir mon nom.") print("Pèse 2 pour dire comment s\'a vas.") print("Pèse 3 pour dire un compliment.") print("Pèse 4 pour dire merci.") print("Pèse 5 pour dire de rien.") print("Pèse 6 pour dire au revoir.") print("Pèse 7 pour répéter tes options.") print("Pèse 8 pour quitter le menu interactif.") boucle=True mots=['Bonjour', 'Nom', 'Comment s\'a va', 'Vous êtes fin ce matin', 'Merci', 'De rien','Au revoir', 'Répète','Quitter'] while boucle: choix=input().lower() if choix=="0": print(mots[0]) boucle=True elif choix=="1": print("Mon nom est Rob") boucle=True elif choix=="2": print(mots[2]) boucle=True elif choix=="3": print(mots[3]) boucle=True elif choix=="4": print(mots[4]) boucle=True elif choix=="5": print(mots[5]) boucle=True elif choix=="6": print(mots[6]) boucle=True elif choix=="7": boucle=True print("Voici un menu interactif") print("Pèse 0 pour dire bonjour.") print("Pèse 1 pour savoir mon nom.") print("Pèse 2 pour dire comment s\'a vas.") print("Pèse 3 pour dire un compliment.") print("Pèse 4 pour dire merci.") print("Pèse 5 pour dire de rien.") print("Pèse 6 pour dire au revoir.") print("Pèse 7 pour répéter tes options.") print("Pèse 8 pour quitter le menu interactif.") elif choix=="8": print(mots[8]) boucle=False print("Merci pour votre temps, à la prochaine.") else: print("Votre entré n'est pas valide, s'il vous plaît essayer encore") """ a=["one", "two", "three"] for i in range(len(a)): print(a[i]) """ ma_liste=['a', 'b', 'c'] for indice in range(len(ma_liste)): #ma_liste[indice] =ord(ma_liste[indice]) print(ma_liste[indice]) """
from itertools import cycle from collections import deque class Marbles(deque): def moveclock(self, n=1): self.rotate(-n) def movecounter(self, n=1): self.rotate(n) def insertright(self, val): self.moveclock() self.appendleft(val) def remove(self): self.popleft() def day09(inp, factor=1): vals = inp.split() nplay = int(vals[0]) nmarb = int(vals[-2])*factor + 1 marbles = Marbles([0]) scores = [0]*nplay elfit = iter(cycle(range(nplay))) for val in range(1, nmarb): elf = next(elfit) if not val % 23: marbles.movecounter(7) scores[elf] += val + marbles[0] marbles.remove() else: marbles.moveclock() marbles.insertright(val) return max(scores) if __name__ == "__main__": testinp = open('day09.testinp').read().strip() inp = open('day09.inp').read().strip() print(day09(testinp)) print(day09(inp)) print(day09(testinp, factor=100)) print(day09(inp, factor=100))
''' Created on 2018. 3. 11. @author: kfx20 ''' # 이분 탐색과 재귀 호출 # 리스트 a, 찾는 값 x # 특정 숫자를 찾으면 그 값의 위치, 찾지 못하면 -1 # 리스트 범위를 정하여 찾은 후 # 그 범위 안에서 x를 찾는 재귀 함수 def binary_search_sub(a, x, start, end): # 종료 조건 : 남은 탐색 범위가 비었으면 종료 if start > end : return -1 mid = (start + end) // 2 # 탐색 범위의 중간 위치 if x == a[mid]: #발견했다면 return mid elif x > a[mid]: # 찾는 값이 더 크다면 return binary_search_sub(a, x, mid + 1, end) # 오른쪽으로 이동한 값을 재귀 호출 else: return binary_search_sub(a, x, start, mid - 1) # 찾는 값이 더 작으면 왼쪽으로 이동한 값 재귀 호출 return -1 def binary_search(a, x): return binary_search_sub(a, x, 0, len(a) - 1) d = [1, 4, 9, 16, 25, 36, 49, 64, 81] print(binary_search(d, 36)) print(binary_search(d, 50))
''' Created on 2018. 3. 6. @author: kfx20 ''' # 쉬운 퀵 정렬 def quick_sort(a): n = len(a) if n <= 1: return a pivot = a[-1] g1 = [] g2 = [] for i in range(0, n - 1): if a[i] < pivot: g1.append(a[i]) else: g2.append(a[i]) print("pivot : ", pivot) print("g1 : ", g1) print("g2 : ", g2) print("end recall") return quick_sort(g1) + [pivot] + quick_sort(g2) d = [6, 8, 3, 9, 10, 1, 2, 4, 7, 5] print(quick_sort(d))
''' Created on 2018. 3. 3. @author: kfx20 ''' # 연속한 숫자의 곱을 구하는 알고리즘 def fact(n): print("n : ", n) if n <= 1: return 1 return n * fact(n - 1) print(fact(1)) print(fact(5)) print(fact(10))
''' Created on 2018. 3. 3. @author: kfx20 ''' # 최대공약수 구하기 def gcd(a, b): if b == 0: return a return gcd(b, a % b) print(gcd(1, 5)) print(gcd(3, 6)) print(gcd(60, 24)) print(gcd(81, 27))
class Aluno: def __init__(self, nome: str, nota: float): self.__nome = nome self.__nota = nota self.__prox = None def __repr__(self): return f'{self.__nome}:{self.__nota}' @property def prox(self): return self.__prox @prox.setter def prox(self, prox): self.__prox = prox class ListaLigada: def __init__(self): self.__inicio = None self.__final = None def append(self, aluno: Aluno): if self.__inicio == None: self.__inicio = aluno self.__final = aluno else: self.__final.prox = aluno self.__final = aluno def pop(self): atual = self.__inicio while atual.prox != self.__final: atual = atual.prox atual.prox = None self.__final = atual return atual def sort(self): pass def __repr__(self): saida = '' atual = self.__inicio while atual != None: saida = saida + f'{atual} ' atual = atual.prox return saida sara = Aluno('Sara', 9.8) sabrina = Aluno('Sabrina', 9.8) lista = ListaLigada() lista.append(sara) lista.append(sabrina) print(lista) print(lista.pop()) print(lista)
# Load LinearSVC class from Scikit Learn library # LinearSVC is similar to SVC with parameter kernel='linear' # LinearSVC performs classification # LinearSVC finds the linear separator that maximizes the distance between itself and the closest/nearest data point point from sklearn.svm import LinearSVC # load RFE (Recursive Feature Elimination) # RFE is used to remove features from sklearn.feature_selection import RFE # load the iris dataset from sklearn import datasets dataset = datasets.load_iris() # the dataset has 150 items, each item has 4 features (sepal length, sepal width, petal length, petal width) dataset.data.shape print ("list of features in the dataset:") print (dataset.feature_names) # instanciate the LinearSVC class svm = LinearSVC(max_iter=5000) # instanciate the RFE class # select the number of features to keep (3 in that example) # select the classifier model to use rfe = RFE(svm, 3) # use the iris dataset and fit rfe = rfe.fit(dataset.data, dataset.target) # print summaries for the selection of attributes # sepal length is not selected. The 3 selected features are sepal width, petal length, petal width print ('selected features are:') print(rfe.support_) print(rfe.ranking_)
def findThreeLargestNumbers(array): new_arr = [None] * 3 for n in array: if new_arr[-1] == None or n > new_arr[-1]: new_arr[-3] = new_arr[-2] new_arr[-2] = new_arr[-1] new_arr[-1] = n elif new_arr[-2] == None or n > new_arr[-2]: new_arr[-3] = new_arr[-2] new_arr[-2] = n elif new_arr[-3] == None or n > new_arr[-3]: new_arr[-3] = n return new_arr
def shortestDistance(words, word1, word2): i = None j = None res = len(words) for n in range(len(words)): word = words[n] if word == word1: i = n if word == word2: j = n if i != None and j!= None: res = min(abs(i-j),res) return res if i != None and j != None else 0 assert(shortestDistance(["practice", "makes", "perfect", "coding", "makes"],"coding","practice") == 3) assert(shortestDistance(["a", "a", "b", "b"], "a", "b") == 1) assert(shortestDistance(["a", "a", "c", "b", "a"], "a", "b") == 1) assert(shortestDistance(["a", "a", "c", "b", "a"], "b", "a") == 1) assert(shortestDistance(["a", "b", "c", "d", "d"], "a", "d") == 3) assert(shortestDistance(["a", "c", "b", "b", "a"], "a", "b") == 1)
def numIslands(grid): def dfs(i, j): if not (0 <= i < len(grid)) or not (0 <= j < len(grid[0])) or grid[i][j] == "0": return grid[i][j] = "0" dfs(i, j+1) dfs(i, j-1) dfs(i+1,j) dfs(i-1, j) count = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == "0": continue count += 1 dfs(i, j) return count grid = [ ["1", "1", "1", "1", "0"], ["1", "1", "0", "1", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0"] ] assert(numIslands(grid) == 1) grid2 = [ ["1", "1", "0", "0", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "1", "0", "0"], ["0", "0", "0", "1", "1"] ] assert(numIslands(grid2) == 3)
# the first thing is the root node of 10 # I want to build a binary search tree on another computer # I will traverse through DFS and this will first lead to the path that has the lowest number # How do i form the string as I traverse through the tree on my computer ''' 10 / \ 8 12 / \ / \ 5 9 11 15 ''' # tuple with first value being the parent node, and an arr of length 2 being the child nodes # As I hit a parent node, I will create a tuple of (10, [8,12]), i'll put None in the array # Just separate by - to demarcate one node and next node. # O(V + E) # node has left, right, value def sendBST(root): stack = [] stack.append(root) res = '' while stack: current = stack.pop() edges = [current.value] if current.left: edges.append(left.value) stack.append(current.left) else: edges.append(None) if current.right: edges.append(right.value) stack.append(current.right) else: edges.append(None) if len(res) == 0: res += str(edges) else: res += ("-" + str(edges)) return root # I know the first node is the root node # current is root, set pointers, then i take the child node # convert tuple arr into dictionary # as i traverse through, lookup edges and connect, then append to stack current.left and current.right def recBST(string): nodes = string.split("-") my_dict = {} for str_tup in nodes: "10, 5, 12" node_info = str_tup[1:-1] node_arr = node_info.split(",") parent_val = int(node_arr[0]) left_val = int(node_arr[1]) right_val = int(node_arr[2]) my_dict[parent_val] = [left_val, right_val] root = Node(nodes[0][0]) stack = [] stack.append(root) while stack: current = stack.pop() edges = my_dict[current.val] left, right = None, None if edges[0]: left = Node(edges[0]) current.left = left stack.append(left) if edges[1]: right = Node(edges[1]) current.right = right stack.append(right) return root
import math def findMin(nums): if len(nums) == 1 or nums[0] < nums[-1]: return nums[0] # left = 0 # right = len(nums) - 1 # while left < right: # mid = int(math.floor((left / 2) + (right / 2))) # prev = mid - 1 # nextt = mid + 1 # if prev >= 0: # if nums[prev] > nums[mid]: # return nums[mid] # if nextt < len(nums): # if nums[nextt] < nums[mid]: # return nums[nextt] # if nums[mid] > nums[right]: # left = mid + 1 # else: # right = mid - 1 # def bsearch(left,right): # if left > right: # return # mid = int(math.floor((left / 2) + (right / 2))) # prev = mid - 1 # nextt = mid + 1 # if prev >= 0: # if nums[prev] > nums[mid]: # return nums[mid] # if nextt < len(nums): # if nums[nextt] < nums[mid]: # print(nextt,nums[nextt]) # return nums[nextt] # if nums[mid] < nums[right]: # bsearch(left,mid-1) # else: # bsearch(mid+1,right) # return bsearch(0, len(nums)-1) # assert(findMin([3, 4, 5, 1, 2]) == 1) # assert(findMin([4, 5, 6, 7, 0, 1, 2]) == 0) assert(findMin([2, 3, 4, 5, 1]) == 1) assert(findMin([5, 1, 2, 3, 4]) == 1)
# Write a method, reverse_string(str), that takes in a string. # The method should return the string with it's characters in reverse order. # # Solve this recursively! # # Examples: # # reverse_string("") # => "" # reverse_string("c") # => "c" # reverse_string("internet") # => "tenretni" # reverse_string("friends") # => "sdneirf" def reverseString(s): if not s: return s else: return s[-1] + reverseString(s[:-1]) print(reverseString("Hello")) print(reverseString("You can be an Engineer, Danny"))
def shuffle(nums, n): ans = [] for i in range(0, n): ans.append(nums[i]) ans.append(nums[n+i]) return ans print(shuffle([2, 5, 1, 3, 4, 7], 3)) # [2,3,5,4,1,7] print(shuffle([1, 2, 3, 4, 4, 3, 2, 1], 4)) # [1,4,2,3,3,2,4,1] print(shuffle([1, 1, 2, 2], 2)) # [1,2,1,2]
from collections import Counter def minSetSize(arr): count = Counter(arr) items = list(count.items()) items.sort(reverse=True,key = lambda x: x[1]) n = len(arr) num_count = 0 count = 0 print(items) for item in items: if num_count < (n/2): num_count += item[1] count += 1 print(num_count,count,item) return count assert(minSetSize([3,3,3,3,5,5,5,2,2,7]) == 2) assert(minSetSize([5, 5, 5, 3, 3, 3, 3, 2, 2, 7]) == 2)
''' binary search KNOW my exit condition How do you know you have found the pivot??? if the number after is smaller no dups arr is sorted arr is sorted, but pivots at a certain point given arr, target time complexity to target is still log n return index of the target Not in there, return -1 [5,6,0,1,2,3,4], 2 [6,8,2,5], 2 return 0 mid = 3 mid_val = 1 I was searching on the values if search val is smaller than right = mid if search val is greater mid = 1 if it is bigger than left: left = mid i'll know if it's pivoted if the first number is greater than the last number normally bsearch if not pivoted Key insights: one to find out where the pivot occurs, Bsearch to find pivot: how should you move left and right? if at any point, i find target, return index mid is greater than left mid is less than left i know if the target exists, it's either going to be after the pivot or before the pivot if my target is greater than my first element, then i search in list[pivot:] otherwise, i need to search in smaller numbers list[:pivot], return -1 ''' import math def search(arr,target): # def find_pivot(): pivot_idx = find_pivot() def bsearch(left, right): if left > right: return -1 mid = int(math.floor((left / 2) + (right / 2))) if arr[mid] == target: return mid # [1,2,3,4,5,6,7,8] , 3 # [5,6,7,8,1,2,3,4], 4 if arr[mid] > target: bsearch(left, mid-1) else: bsearch(mid+1, right) if target > arr[0]: ans = bsearch(pivot_idx,len(arr)-1) else: ans = bsearch(0, pivot_idx-1) return ans
from collections import Counter, deque def number_of_nodes(graph, level): """ Calculates the number of nodes at given level :param graph: The graph :return: Total number of nodes at given level """ # Write your code here! visited = Counter() root = 0 visited[root] = 1 q = deque() q.append(root) while q: entry = q.popleft() node = graph.graph[entry] while node is not None: data = node.vertex if data not in visited: visited[data] = visited[entry] + 1 q.append(data) node = node.next ans = 0 for i in range(len(graph.graph)): if visited[i] == level: ans += 1 return ans
# // returns the first index where any permutation of needle begins as an exact substring of haystack, -1 if it can't find it # // permutation("abc") = > "abc", "acb", "bac", "bca", "cab", "cba" # // strstrp("hello there", "hello") returns 0 # // strstrp("hello there", "elloh") returns 0 # // strstrp("hello there", "o there") returns 4 # // strstrp("hello there", "the reo") returns 4 # // strstrp("hello there", "jefwoai") returns - 1 # // strstrp("aa", "a") returns 0 # int strstrp(string haystack, string needle) # first i need to get the permutations of the needle # for every perm, i'll just check if it is in the string # if it it's not then i'll return -1 # if it is, then i know which permutation it is. # then i just call python strstr method is and return that index # implement arePermutations(str1,str2) # currently slice through the haystack with two pointers O(h) # see what the differences are, then move by the number of differences. from collections import Counter def strstrp(haystack,needle): point1 = 0 point2 = len(needle) count = Counter(needle) word = haystack[point1:point2] for char in word: count[char] -= 1 if count[char] == 0: del count[char] if len(count) == 0: return point1 while point2 < len(haystack): deleted = haystack[point1] added = haystack[point2] count[deleted] += 1 if count[deleted] == 0: del count[deleted] count[added] -= 1 if count[added] == 0: del count[added] # print(count,point1, point2, diffs) point1 += 1 point2 += 1 if len(count) == 0: return point1 return -1 # assert(strstrp("hello there", "hello") == 0) # assert(strstrp("hello there", "h") == 0) # assert(strstrp("hello there", "e") == 1) # assert(strstrp("hello there", "l") == 2) # assert(strstrp("hello there", "elh") == 0) # assert(strstrp("hello there", "olleh") == 0) # assert(strstrp("hello there", "elloh") == 0) # assert(strstrp("hello there", "helol") == 0) # assert(strstrp("hello there", "ehllo") == 0) print(strstrp("ellho there", "oth ")) #assert(strstrp("hello there", "oth ") == 4) #assert(strstrp("hello there", "o th") == 4) assert(strstrp("ellho there", "oth ") == 3) assert(strstrp("hello there", "there") == 6) assert(strstrp("hello there", "eethr") == 6) assert(strstrp("hello there", "three") == 6) assert(strstrp("hello there", "ere") == 8) assert(strstrp("hello there", "fwoaifj") == -1) assert(strstrp("hello", "hello there") == -1) assert(strstrp("hehea waw", "hea") == 2) assert(strstrp("hehea waw", "eha") == 2) assert(strstrp("hehea waw", "ahe") == 2) assert(strstrp("heehea", "heea") == 2) assert(strstrp("hello there", "lot") == -1) assert(strstrp("heoll llale", "ell") == -1) assert(strstrp("heoll llale", "eol ") == -1) assert(strstrp("heoll llale", " eol") == -1) assert(strstrp("aabe", " aaabe") == -1) assert(strstrp("", "a") == -1) assert(strstrp("", "b") == -1) assert(strstrp("", " ") == -1) print("All test cases passed!")
''' Some digits are formed with closed paths. The digits 0,4,6 and 9 each have 1 closed path, and 8 has 2. None of the other numbers is formed with a closed path. Given a number, determine the total number of closed paths in all of its digits combined. number = 649578 The digits with closed paths are 6,4,9 and 8. The total number of closed paths is 1 + 1 + 1 + 2 = 5 ''' def closedPaths(number): str_num = str(number) closed = set([0,4,6,9]) closed_paths = 0 for str_digit in str_num: digit = int(str_digit) if digit in closed: closed_paths += 1 if digit == 8: closed_paths += 2 return closed_paths assert(closedPaths(649578) == 5) assert(closedPaths(1288) == 4) assert(closedPaths(630) == 2)
import GRT import sys import numpy as np import math def main(): """GRT DoubleMovingAverageFilter Example This example demonstrates how to create and use the GRT DoubleMovingAverageFilter PreProcessing Module. The DoubleMovingAverageFilter implements a low pass double moving average filter. In this example we create an instance of a DoubleMovingAverageFilter and use this to filter some dummy data, generated from a sine wave + random noise. The test signal and filtered signals are then printed to std::cout. This example shows you how to: - Create a new DoubleMovingAverageFilter instance with a specific window size for a 1 dimensional signal - Filter some data using the DoubleMovingAverageFilter - Save the DoubleMovingAverageFilter settings to a file - Load the DoubleMovingAverageFilter settings from a file""" # Create a new instance of a double moving average filter with a window size of 5 for a 1 dimensional signal dma_filter = GRT.DoubleMovingAverageFilter(5, 1) # Generate some data (sine wave + noise) and filter it x = 0 for i in range(1000): signal = math.sin(x) + np.random.uniform(-0.2, 0.2) filtered_value = dma_filter.filter(signal) print("%.3f %.3f" % (signal, filtered_value)) x += math.tau / 1000.0 * 10.0 # Save the filter settings to a file dma_filter.save("DoubleMovingAverageFilterSettings.grt") # We can then load the settings later if needed dma_filter.load("DoubleMovingAverageFilterSettings.grt") if __name__ == '__main__': main() sys.exit(0)
import GRT import sys import argparse def main(): '''GRT Class Label Filter Example This examples demonstrates how to use the Class Label Filter to filter the predicted class label of any classification module using the gesture recognition pipeline. The Class Label Filter is a useful post-processing module which can remove erroneous or sporadic prediction spikes that may be made by a classifier on a continuous input stream of data. For instance, imagine a classifier that correctly outputs the predicted class label of 1 for a large majority of the time that a user is performing gesture 1, but every so often (perhaps due to sensor noise), the classifier outputs the class label of 2. In this instance the class label filter can be used to remove these sporadic prediction values, with the output of the class label filter in this instance being 1. In this example we create a new gesture recognition pipeline and add an ANBC module for classification along with a Class Label Filter as a post-processing module. The ANBC classifier is then trained with some dummy data (which consists of 3 simple classes generated from 3 different Gaussian distributions). Some test data is then used to demonstrate the result of using the Class Label Filter to post process the predicted class label from the ANBC algorithm. The test data contains a continuous stream of data from class 1, with a few sporadic class 2 and 3 labels added randomly to the stream. This example shows you how to: - Create an initialize a GestureRecognitionPipeline and add an ANBC module and a ClassLabelFilter module - Load some ClassificationData from a file and train the classifier - Use some test data to demonstrate the effect of using a Class Label Filter - Print the Processed and Unprocessed Predicted Class Label''' # Parse the data filename from the argument list parser = argparse.ArgumentParser(description='Process some data.') parser.add_argument('train_file', help='A training data file') parser.add_argument('test_file', help='A testing data file') args = parser.parse_args() # Create a new gesture recognition pipeline pipeline = GRT.GestureRecognitionPipeline() # Add an ANBC module pipeline.setClassifier( GRT.ANBC() ) # Add a ClassLabelFilter as a post processing module with a minCount of 5 and a buffer size of 10 pipeline.addPostProcessingModule( GRT.ClassLabelFilter(5,10) ) # Load some training data to train and test the classifier trainingData = GRT.ClassificationData() testData = GRT.ClassificationData() if not trainingData.load(args.train_file): print("Failed to load training data!\n") sys.exit(1) if not testData.load(args.test_file): print("Failed to load training data!\n") sys.exit(1) # Train the classifier if not pipeline.train( trainingData ): print("Failed to train classifier!\n") sys.exit(1) # Use the test dataset to demonstrate the output of the ClassLabelChangeFilter for i in range(testData.getNumSamples()): inputVector = testData.get(i).getSample() if not pipeline.predict( inputVector ): print("Failed to perform prediction for test sample %d" % i) sys.exit(1) # Get the predicted class label (this will be the processed class label) predictedClassLabel = pipeline.getPredictedClassLabel() # Get the unprocessed class label (i.e. the direct output of the classifier) unprocessedClassLabel = pipeline.getUnProcessedPredictedClassLabel() # Also print the results to the screen print("Processed Class Label: \t%d\tUnprocessed Class Label: \t%d" % (predictedClassLabel, unprocessedClassLabel)) if __name__ == '__main__': main() sys.exit(0)
import GRT import sys import argparse def main(): ''' GRT HMM Continuous Example This examples demonstrates how to initialize, train, and use the Continuous HMM algorithm for classification. Hidden Markov Models (HMM) are powerful classifiers that work well on temporal classification problems when you have a large training dataset. The HMM algorithm in the GRT can be either a discrete or continuous HMM. A discrete HMM means that the input to the HMM algorithm must be a discrete integer value in the range [0 numSymbols-1]. A continuous HMM means that the input to the HMM algorithm can be an N-dimensional floating point vector. For the discrete HMM, you can convert N-dimensional continuous data into a 1-dimensional discrete data using one of the GRT Quantization algorithms, such as KMeansQuantizer. In this example we create an instance of a Continuous HMM algorithm and then train a Continuous HMM model using some pre-recorded training data. The trained HMM algorithm is then used to predict the class label of some test data. This example shows you how to: - Create an initialize the Continuous HMM algorithm - Load some TimeSeriesClassificationData from a file and partition the training data into a training dataset and a test dataset - Train the HMM algorithm using the training dataset - Test the HMM algorithm using the test dataset - Manually compute the accuracy of the classifier ''' # Parse the data filename from the argument list parser = argparse.ArgumentParser(description='Process some data.') parser.add_argument('filename', help='A data file') args = parser.parse_args() filename = args.filename # Create a new HMM instance hmm = GRT.HMM() # Set the HMM as a Continuous HMM hmm.setHMMType( GRT.HMM_CONTINUOUS ) # Set the downsample factor, a higher downsample factor will speed up the prediction time, but might reduce the classification accuracy hmm.setDownsampleFactor( 5 ) # Set the committee size, this sets the (top) number of models that will be used to make a prediction hmm.setCommitteeSize( 10 ) # Tell the hmm algorithm that we want it to estimate sigma from the training data hmm.setAutoEstimateSigma( True ) # Set the minimum value for sigma, you might need to adjust this based on the range of your data # If you set setAutoEstimateSigma to false, then all sigma values will use the value below hmm.setSigma( 20.0 ) # Set the HMM model type to LEFTRIGHT with a delta of 1, this means the HMM can only move from the left-most state to the right-most state # in steps of 1 hmm.setModelType( GRT.HMM_LEFTRIGHT ) hmm.setDelta( 1 ) # Load some training data to train the classifier - TimeSeriesClassificationData trainingData = GRT.TimeSeriesClassificationData() if not trainingData.load(filename): print("Failed to load training data!") sys.exit(1) # Use 20% of the training dataset to create a test dataset testData = trainingData.split( 80 ) # Train the classifier if not hmm.train( trainingData ): print("Failed to train classifier!") sys.exit(1) # Save the decision tree model to a file if not hmm.save("HMMModel.grt"): print("Failed to save the classifier model!") sys.exit(1) # Load the decision tree model from a file if not hmm.load("HMMModel.grt"): print("Failed to load the classifier model!") sys.exit(1) # Use the test dataset to test the decision tree model accuracy = 0.0 for i in range(testData.getNumSamples()): # Get the i'th test sample classLabel = testData.get(i).getClassLabel() timeseries = testData.get(i).getData() # Perform a prediction using the classifier if not hmm.predict( timeseries ): print("Failed to perform prediction for test sample: %d" % i) sys.exit(1) # Get the predicted class label predictedClassLabel = hmm.getPredictedClassLabel() classLikelihoods = hmm.getClassLikelihoods() classDistances = hmm.getClassDistances() # Update the accuracy if classLabel == predictedClassLabel: accuracy += 1 # Print out the results print("TestSample: %d ClassLabel: %d PredictedClassLabel: %d" % (i, classLabel, predictedClassLabel)) print(" ClassLikelihoods: " + str(classLikelihoods)) print(" ClassDistances: " + str(classDistances)) print("Test Accuracy: %.3f%%" % (accuracy/float(testData.getNumSamples())*100.0)) return 0 if __name__ == '__main__': sys.exit(main())
from random import randint resultados = { "1": "Você não chegou na sala 9\nGAME OVER!!", "2": "Você não chegou na sala 9\nGAME OVER!!", "3": "Você não chegou na sala 9\nGAME OVER!!", "4": "Você não chegou na sala 9\nGAME OVER!!", "5": "Você não chegou na sala 9\nGAME OVER!!", "6": "Você não chegou na sala 9\nGAME OVER!!", "7": "Você não chegou na sala 9\nGAME OVER!!", "8": "Você não chegou na sala 9\nGAME OVER!!", "9": "Você chegou na sala 9\nYOU WIN!!" } CAMINHO_VERMELHO = 1 CAMINHO_PRETO = 2 sala = 1 jogadas = 0 while sala < 9 and jogadas < 7: portal = randint(1, 5) caminho = int(input(f"""Você está na sala {sala}. Escolha seu caminho: [ 1 ] caminho vermelho [ 2 ] caminho preto\n""")) if sala == 8 and caminho == 2: sala = portal print(f"O portal te jogará para a sala: {sala}") jogadas += 1 elif sala + caminho == 6: sala += caminho print("""Você chegou na sala 6, aqui você só tem um único caminho a seguir que te levará para a sala 8""") sala += CAMINHO_PRETO jogadas += 1 else: sala += caminho jogadas += 1 resultadoFinal = resultados[str(sala)] print(resultadoFinal)
"""Module providing the Lemma class.""" from typing import Dict from typing import Optional from typing import Tuple from banone.sound import SoundSequence def remove_last_syllable(phon: str) -> str: """Remove the last syllable boundary in a phonetic string. Example: Turn `fa:-n` (stem of `fa:-n@`) into `fa:n`. """ # Find the last hyphen marking a syllable boundary and remove it. i = phon.rfind("-") j = i + 1 return phon[:i] + phon[j:] class Lemma: """A lemma as it is found in the dictionary.""" def __init__(self, orth: str, lemma_dict: Dict[str, str] = {}) -> None: """Initialize lemma from a dictionary entry.""" self.orth = orth self.phon = lemma_dict.get("phon") or orth.lower() self.pos = lemma_dict.get("pos") self.determiner = lemma_dict.get("determiner") self.color = lemma_dict.get("color") self.property = lemma_dict.get("property") self.action = lemma_dict.get("action") def __str__(self) -> str: """Return the string representation of the lemma.""" return self.orth def get_stem(self) -> Tuple[str, str]: """Get the stem of the lemma. "Stem" for our purposes is the part of a word that can be used for pun compound creation. """ phon, orth = self.phon, self.orth # Remove schwa sound from the end of a noun ("Fahne" becomes "Fahn"). if self.pos == "NN": if phon.endswith("@"): return remove_last_syllable(phon[:-1]), orth[:-1] # Get verb stem by removing final -en or -n. if self.pos == "VB": if phon.endswith("@n"): return remove_last_syllable(phon[:-2]), orth[:-2] # "zappeln" if phon.endswith("n"): return phon[:-1], orth[:-1] # Default: The stem is simply the full lemma. return phon, orth def merge(self, other: "Lemma") -> Optional["Lemma"]: """Merge another lemma into this one to form a compound.""" sound_seq_base = SoundSequence(self.orth, self.phon) phon, orth = other.get_stem() sound_seq_extra = SoundSequence(orth, phon) compound_orth = sound_seq_base.merge(sound_seq_extra) if compound_orth: return Lemma(compound_orth) return None
from sys import exit def combination(n,r): #combination calculate try: if r == 0: return 1 elif r == n: return 1 else: return combination(n-1,r-1) + combination(n-1,r) except RecursionError as e: #재귀 한계 초과 에러 처리 print(e, "so kill the program") exit() except: #그 외 알 수 없는 에러 처리 print("Unknow Error so kill the program") exit() arr = list() for i in range(0,2): n = int(input("")) arr.append(n) print(combination(arr[0], arr[1]))
# Author: Cameron Jones # Description: import urllib2 from pprint import pprint from json import loads import Tkinter as tk from PIL import Image, ImageTk class Weather: temp_cur = 0 temp_max = 0 temp_min = 0 weather = "" API_URL = "http://api.openweathermap.org/data/2.1/find/name?q=" # initializes class instance def __init__(self, city): self.city = city # retrieves the weather using the API def getWeather(self): data = urllib2.urlopen(self.API_URL + self.city) cities = loads(data.read().decode('utf-8')) # format loads weather information for multiple "cities" within requested location if cities['count'] > 0: myCity = cities['list'][0] # temperatures are sent in Kelvin and then converted to Farenheit self.temp_cur = ((myCity['main']['temp'] - 273.15) * 1.8) + 32 self.temp_max = ((myCity['main']['temp_max'] - 273.15) * 1.8) + 32 self.temp_min = ((myCity['main']['temp_min'] - 273.15) * 1.8) + 32 self.weather = myCity['weather'][0]['main'] # prints the current weather (debugging purposes) def printWeather(self): print "Current Temperature: " + str(self.temp_cur) print "Maximum Temperature: " + str(self.temp_max) print "Minimum Temperature: " + str(self.temp_min) print "Weather: " + self.weather bmore = Weather("baltimore") bmore.getWeather() bmore.printWeather() def button_click_exit_mainloop(event): event.widget.quit() root = tk.Tk() root.title('Test') root.bind("<Key>", button_click_exit_mainloop) img = Image.open("mountains.jpg") tkpi = ImageTk.PhotoImage(img) label_img = tk.Label(root, image=tkpi).pack() root.mainloop()
#whatever monster kills you takes your gear and exp just like a player would xp gain for kills is a % of opponents xp not 100% if you return and kill them you will get everything back but xp will be lost in transfer #Nothing will ever despawn if you die you respawn with nothing lvl 1 so do the mobs when they die they will spawn as well they can move and will fight and gain xp/items just like you. #there will be scrap mobs just like the spawning blobs in agar.io that will be easily farmable and wont move/update the game #Ai adventures who are on the same mission as you and will also be rogue like and you can interact with them #Weapons/Armor are cards and skills are static. A turn is a combination of a weapon and a skill. There will be many different skills but you can only bring a limited number of skills (3?) into each battle which you can equip in inventory. #What does fusion add besides more cards to your hand? What does it do that other card games cant? defusion and fusion skills can only be used once per turn cycle (your turn + enemies) they are infinite like hero powers. Defusion is when you use one of your skills after an opponent plays something (the possible things that can be played on your turn are: nothing which can not be defused, one card, 2 cards playing 2 cards is known as a combination/combo, 1 card 1 skill known as a fusion) you can not play a skill by itself. import time import numpy as np import random import math import csv import msvcrt from Map import road from random import shuffle from graphics import * win = GraphWin('Face', 800, 600) # give title and dimensions enemies = [] class CreateEnemy: def __init__(self,cords,health,size,color): self.c = cords self.h = health self.s = size self.clr = color def draw_enemy(self): self.n = Circle(Point(self.c[0],self.c[1]), self.s) self.n.setFill(self.clr) self.n.draw(win) def enemy_hit(self,x,y): if(self.c[0] + self.s >= x >= self.c[0] - self.s and self.c[1] + self.s >= y >= self.c[1] - self.s): print(self.n) self.n.undraw() i = 0 while i < 10: cords = [0,0] cords[0] = random.randrange(1,799) cords[1] = random.randrange(1,599) size = random.randrange(10,50) enemies.append(CreateEnemy(cords,20,size,"red",)) enemies[i].draw_enemy() i+=1 dx, dy = 10, 0 key = 0 head = Circle(Point(400,500), 25) # set center and radius head.setFill("yellow") head.draw(win) dx, dy = 10, 0 mcx, mcy = 400,500 p = None line = None count_1 = 0 while(1): k = win.checkKey() if k == 'a': head.move(-dx, dy) mcx -= dx elif k == 'd': head.move(dx, dy) mcx += dx elif k == 'w': head.move(dy,-dx) mcy -= dx elif k == 's': head.move(dy,dx) mcy += dx p = win.checkMouse() if(p != None): if (line): line.undraw() x = p.x y = p.y line = Line(Point(mcx,mcy), Point(x,y)) line.draw(win) for enemy in enemies: enemy.enemy_hit(x,y) count_1 = 0 count_1+=1
single_string = input().split(", ") new_string = [] for el in single_string: if int(el) != 0: new_string.append(int(el)) number_of_zero = len(single_string) - len(new_string) for _ in range(number_of_zero): new_string.append(0) print(new_string)
numbers = [int(num) for num in input().split()] command_data = input() multiply_element = 0 while not command_data == "end": command_data = command_data.split() if len(command_data) > 1: command = command_data[0] num1 = int(command_data[1]) num2 = int(command_data[2]) if command == "swap": numbers[num1], numbers[num2] = numbers[num2], numbers[num1] elif command == "multiply": multiply_element = numbers[num1] * numbers[num2] numbers[num1] = multiply_element else: command = command_data[0] numbers = [num - 1 for num in numbers] command_data = input() print(", ".join(map(str, numbers)))
def add_and_subtract(): all_numbers = [] for number in range(3): single_number = input() all_numbers.append(single_number) first_number = int(all_numbers[0]) second_number = int(all_numbers[1]) third_number = int(all_numbers[2]) def sum_numbers(): return first_number + second_number def subtract(): return sum_numbers() - third_number return subtract() print(add_and_subtract())
text = input() for index in range(len(text)): if text[index] == ":": print(f"{text[index]}{text[index + 1]}")
n = int(input()) for letter_1 in range(97, 97 + n): for letter_2 in range(97, 97 + n): for letter_3 in range(97, 97 + n): print(f"{chr(letter_1)}{chr(letter_2)}{chr(letter_3)}")
n = int(input()) positives_numbers = [] negatives_numbers = [] for i in range(n): number = int(input()) if number >= 0: positives_numbers.append(number) else: negatives_numbers.append(number) print(positives_numbers) print(negatives_numbers) print(f"Count of positives: {len(positives_numbers)}. Sum of negatives: {sum(negatives_numbers)}")
trip_days = int(input()) budget = float(input()) number_of_people = int(input()) fuel_price_per_km = float(input()) food_expenses = float(input()) night_pppn = float(input()) total_food_expenses = trip_days * number_of_people * food_expenses total_cost_hotel = number_of_people * night_pppn * trip_days if number_of_people > 10: total_cost_hotel *= 0.75 current_expenses = total_cost_hotel + total_food_expenses fuel_expenses = 0 for i in range(1, trip_days + 1): distance = int(input()) fuel_expenses = distance * fuel_price_per_km current_expenses += fuel_expenses if i % 3 == 0 or i % 5 == 0: current_expenses *= 1.4 if i % 7 == 0: current_expenses -= (current_expenses / number_of_people) if current_expenses > budget: diff = abs(current_expenses - budget) print(f'Not enough money to continue the trip. You need {diff:.2f}$ more.') break if budget >= current_expenses: diff = abs(budget - current_expenses) print(f'You have reached the destination. You have {diff:.2f}$ budget left.')
def chek_if_palindrome(el): if el == el[::-1]: return True return False nums_as_string = input().split(", ") for num_as_str in nums_as_string: print(chek_if_palindrome(num_as_str))
def chek_password_valid(pword): is_valid = True consist_only_of_letters_and_digits = True count_digits = 0 if len(pword) < 6 or len(pword) > 10: print("Password must be between 6 and 10 characters") is_valid = False for el in pword: if el.isdigit(): count_digits += 1 # if not el.isdigit() and not el.isalpha(): # consist_only_of_letters_and_digits = False # is_valid = False # # if not consist_only_of_letters_and_digits: # print("Password must consist only of letters and digits") if not pword.isalnum(): is_valid = False print("Password must consist only of letters and digits") if count_digits < 2: is_valid = False print("Password must have at least 2 digits") return is_valid password = input() result = chek_password_valid(password) if result: print("Password is valid")
text = input() data = input() while not data == "End": data = data.split() command = data[0] if command == "Translate": replace = data[1] replace_with = data[2] text = text.replace(replace, replace_with) print(text) elif command == "Includes": text_to_find = data[1] if text_to_find in text: print("True") else: print("False") elif command == "Start": text_to_start = data[1] if text.startswith(text_to_start): print("True") else: print("False") elif command == "Lowercase": text = text.lower() print(text) elif command == "FindIndex": char = data[1] print(text.rfind(char)) elif command == "Remove": start_index = int(data[1]) count = int(data[2]) text_to_remove = text[start_index:count] text = text.replace(text_to_remove, "") print(text) data = input()
key = int(input()) n = int(input()) word = "" for letter in range(1, n + 1): symbol = input() word += chr(ord(symbol) + key) print(word)
import pygame import GraphicsLib as GLib from Util import * # a great example of an object that can move on the screen class Hero: def __init__(self): # ------------------------ # [REQUIRED PART] for any class that will be drawn on the screen # Grab the surface that Graphics people worked very hard on self.img = GLib.heroSprite # Set the initial coordinate of this object self.x = 0 self.y = 0 # ------------------------ # TODO: add more properties to Hero based on your game self.vx = 0 self.vy = 10 # an example of updating position of the object def update(self): # TODO: what else hero is going to do in each frame self.x += self.vx self.y += self.vy class Enms: def __init__ (self): self.lives=[] self.enemies=[] self.wpn=[] self.xpos=[] self.ypos=[] self.resil=1 def spawndcd(difficulty): EnLst=["grunt"] #Current list of all enemies except bosses WpnLst=["Firebolt","Fireblast","Aimfire"] #Current list of all weapons except boss weapons, they are single forward shot, scatter shot, and targeted shot respectively, they do not require new art, but each one will have slightly different behavior programming. whm=random.randint(0,0) #Change this if we add more enemies wpn=random.randint(0,2) #Change this if we add more enemy weapons seed=random.randint(1,5) #Determines the number of enemies spawned, which is then further modulated by the difficulty. Etype=EnLst[whm] Ewpn=WpnLst[wpn] num=seed+(difficulty//1) #For this to work difficulty must always be an integer xval=800 #enum is the number of enemies ymod=(500/(num+1)) #ymod is the value which you must multiply by each ship's number to get it's position. Change this if y changes from 500. return(Etype, Ewpn, num, xval, ymod, difficulty) def spwnd (self, mtype, mweapon, xstrt, ystrt, diff): self.resil=self.resil+(diff//5) if (diff//5)>=1: diff=0 self.lives.append(resil) self.enemies.append(mtype) self.wpn.append(mweapon) self.xpos.append(xstrt) self.ypos.append(ystrt) self.enemies.append(mtype) def check (self, pblltlst): bulltnum=0 for blt in pblltlst: enemynum=0 for enmy in enmylst: if pygame.Rect.colliderect(pbltlst[bulltnum], self.enemies[enemynum])!=False: self.lives[enemynum]-=1 if self.lives[enemynum]<=0: self.lives.remove(self.lives[enemynum]) self.enemies.remove(self.lives[enemynum]) self.wpn.remove(self.lives[enemynum]) self.xpos.remove(self.lives[enemynum]) self.ypos.remove(self.lives[enemynum]) self.resil.remove(self.lives[enemynum]) enemynum-=1 pbltlst.remove(pbltlst[bulltnum]) #removes player shots which hit the enemy, post damage. bulltnum-=1 enemynum+=1 bulltnum+=1 def emovement (self, ennum, movedi): strtx=0 strty=0 if (self.xpos[ennum]>=100): strtx=strtx-1 if ((self.ypos[ennum]>0)&(movedi=="UP")): strty=strty-1 elif ((self.ypos[ennum]<=0)&(movedi=="UP")): movedi="DOWN" elif ((self.ypos[ennum]<500)&(movedi=="DOWN")): strty=strty+1 elif ((self.ypos[ennum]>=500)&(movedi=="DOWN")): movedi="UP" self.ypos[ennum]+=strty self.xpos[ennum]+=strtx def fire (self, ennum, plrx, plry): ammox=self.xpos[ennum] ammoy=self.ypos[ennum] if self.wpn[ennum]== "Firebolt": velox=1 veloy=0 numb=1 elif self.wpn[ennum]== "Fireblast": velox=[1,1,1,1,1] veloy=[ 1,.5,0,-.5,-1] numb=5 elif self.wpn[ennum]== "Aimfire": velox=(plrx-self.xpos[ennun]) veloy=(plry-self.ypos[ennun]) numb=1 return(velox, veloy) class Game: def __init__(self): # initialize the timer to zero. This is like a little clock self.timer = 0 self.hero = GLib.Wizard1(400,300) self.background = GLib.Background(0,0) # TODO: add any variables you think will be needed as a property of Game # ... # .. # . # TODO: add any objects that you would like to be drawn on the screen # Make sure that all of those objects has x, y and img defined as their property self.objectsOnScreen = [self.background, self.hero] # Try to update all the elements # if you want to add another to the screen: self.objectsOnScreen.add(x) # if you want to remove a object from the screen: self.objectsOnScreen.remove(x) # if you want to switch to another the state return 10 --> this switches to state 10 # if you want to bring a object to the front # just remove it first and then added it back # the last added object is going to be on the top def updateInState(self, state): # increment the timer self.timer += 1 # check what state the game is at if state == "Start Menu": pass if state == "Instructions": pass if state == "Credits": pass if state == "Game": # TODO: what the game would do in this state # update the position of hero based on its velocity self.hero.update() # use showAnimationOn functon immported from Util module, # it taks three argument, the object to have animation, the animation, and the frameNumber # this example switch to the next frame every 5 ticks #showAnimationOn(self.ball, [GLib.ballSpriteBLUE, GLib.ballSpriteOrange, GLib.someLoadedImage], self.timer / 2) # bounceIn(self.hero, 0, 0, 500, 500) wrapAroundIn(self.hero, 0, 0, 500, 500) return state # A method that does all the drawing for you. def draw(self, screen): # The first line clear the screen # TODO: if you want a differnt background, # you can replace the next line screen.blit(GLib.Background, (0, 0)) screen.fill(GLib.BLACK) for obj in self.objectsOnScreen: screen.blit(obj.img, (obj.x, obj.y))
#encoding: UTF-8 #Autor: Neftalí Rodríguez Martínez. #Se incluye una función para contador de insectos y otra función que encuentra el mayor de un grupo de números. def contarInsectos(): #cuenta el total de insectos atrapados. print("Bienvenido al programa que registra los insectos que recolectas") print("Recuerda que como mínimo debes de atrapar 30 insectos") #Comentario adicional para el usuario. dias = 0 acumulador_insectos = 0 while acumulador_insectos < 30: insectos = int(input("¿Cuántos insectos atrapaste hoy?: ")) acumulador_insectos = insectos + acumulador_insectos dias = dias + 1 if acumulador_insectos < 0: print("ERROR, introduce números positivos") acumulador_insectos = 0 dias = 0 elif acumulador_insectos < 30: print("Después de", dias, "día(s) de recolección, llevas", acumulador_insectos, "insectos") insectos_faltantes = 30 - acumulador_insectos print("Te hace falta recolectar", insectos_faltantes, "insectos") elif acumulador_insectos == 30: print("Después de", dias, "día(s) de recolección, llevas", acumulador_insectos, "insectos") insectos_faltantes = 30 - acumulador_insectos print("Te hace falta recolectar", insectos_faltantes, "insectos") print("¡Felicidades, has llegado a la meta!") print("\r") elif acumulador_insectos > 30: print("Después de", dias, "día(s) de recolección, llevas", acumulador_insectos, "insectos") insectos_excedentes = acumulador_insectos - 30 print("Te has pasado con", insectos_excedentes,"insectos") print("¡Felicidades, has llegado a la meta!") print("\r") def encontrarMayor(): #encuentra el mayor de un conjunto de numeros print("Bienvenido al programa que encuentra el mayor") numero = 0 lista = [] while numero != -1: numero = int(input("Teclea un número [-1 para salir]: ")) if numero > -1: lista.append(numero) if numero == -1 and lista == []: print("No hay valor mayor") print("\r") elif numero == -1: numero_mayor = max(lista) print("El mayor es: ", numero_mayor) print("\r") def main (): #programa principal. print("Tarea 06. Ciclos While") print("Autor: Neftalí Rodríguez Martínez") print("\r") opcion = 0 while opcion != 3: print("¿Qué quieres hacer?") #Mensaje adicional al usuario. print("1. Recolectar insectos") #Sería mejor que la opción se llame CONTAR INSECTOS. print("2. Encontrar el mayor") print("3. Salir") opcion = int(input("Teclea tu opción: ")) if opcion == 3: print("\r") print("Gracias por usar este programa, regresa pronto") elif opcion < 1 or opcion > 3: print("ERROR, teclea 1, 2 o 3") print("\r") elif opcion == 1: print("\r") contarInsectos() elif opcion == 2: print("\r") encontrarMayor() main()
import random from SearchNode import SearchNode from game import get_possible_moves from game import do_move #============================================================================== # GRAPH_SEARCH # # The fringe and closed list must be drawn while the thinking takes place. # - Draw the closed list blue (255, 0, 0). # - Draw the fringe in green (0, 255, 0). # # There must be NO console printing in this python file. Make sure you remove # them or comment them out when you are done. #============================================================================== class Board(): def __init__(self, size=None, state=None, turn=None ): self.size = size self.state = state self.turn = turn def next_turn(self): return ('W' if self.turn == 'B' else 'B') def graph_search( fringe, ): #========================================================================== # TODO: The code here creates a *random* solution starting at state (0,0). # Replace with the correct late version of graph search algorithm. #CONVERT BOARD TO TUPLE TO STORE IN CLOSED LIST #========================================================================== solution = [] def toList(b): return list(list(r) for r in b) i = 0 while 1: while len(fringe) > 0: board_obj = fringe.get() #let's store the whole board obj # if problem.goal_test(toList(board_obj.state)): #yeah idk what we're going to do for the return # return move #move = ((r,c), flip_list) possible_moves = get_possible_moves(board_obj.size, board_obj.state, board_obj.turn) if possible_moves != []: for move in possible_moves: (r, c) = move[0] new_board_obj = Board(board_obj.size, do_move(board_obj.state, move[1], move[0]), board_obj.next_turn()) if not(new_board_obj.state in fringe.set): fringe.put(SearchNode((r, c), new_board_obj, board_obj, turn, new_board_obj.score)) return None
def fast_power(x,n): if(n==0): return 1 if(n==1): return x flag = 0 if(n%2==1): flag=1 ans=x while(n>1): ans*=ans n//=2 if(flag==1): ans*=x return ans x, n = list(map(int, input("Enter base and power: ").split(' '))) print("Answer:",fast_power(x,n)) '''OUTPUT: Enter base and power: 3 0 Answer: 1 Enter base and power: 3 1 Answer: 3 Enter base and power: 3 2 Answer: 9 Enter base and power: 3 3 Answer: 27 Enter base and power: 3 4 Answer: 81 Enter base and power: 3 5 Answer: 243 '''
def partition(arr, low, high): #sort bolts using nuts i = low j = low pivot = arr[high] while(j < high): if arr[j] < pivot: arr[i], arr[j] = arr[j], arr[i] i+=1 j+=1 arr[i], arr[high] = arr[high], arr[i] return i def quicksort(a, low, high): if low>=high: return pivot = partition(a, low, high) quicksort(a, low, pivot-1) quicksort(a, pivot+1, high) nuts = list(map(int, input("Enter nuts: ").split(' '))) bolts = list(map(int, input("Enter bolts: ").split(' '))) quicksort(nuts, 0, len(nuts)-1) quicksort(bolts, 0, len(bolts)-1) for i in range(0,len(nuts)): print(nuts[i]," matched with",bolts[i]) ''' OUTPUT: Enter nuts: 2 1 7 4 5 6 Enter bolts: 6 5 1 4 7 2 1 matched with 1 2 matched with 2 4 matched with 4 5 matched with 5 6 matched with 6 7 matched with 7 '''
def prefixSum(arr): psum = [0 for i in range(0,len(arr))] psum[0] = arr[0] for i in range(1, len(arr)): psum[i] = psum[i-1]+arr[i] return psum def max_subarray_sum_quadratic(arr): n = len(arr) max_l = 0 max_r = 0 maxSum = -10000 subSum = 0 psum = prefixSum(arr) for i in range(0,n): for j in range(i,n): if(i==j): subSum = psum[j] else: subSum = psum[j]-psum[i] if(subSum > maxSum): maxSum = subSum max_l = i+1 max_r = j return max_l, max_r, maxSum arr = list(map(int, input("Enter array: ").split(' '))) ans = max_subarray_sum_quadratic(arr) print("Max subarray is",arr[ans[0]:ans[1]+1]) print("Max sum =",ans[2]) '''OUTPUT: Enter array: -2 -4 3 -1 5 6 -7 -2 Max subarray is [3, -1, 5, 6] Max sum = 13 '''
def match(nuts, bolts): for nut in nuts: for bolt in bolts: if nut == bolt: print(nut, "matched with", bolt) nuts = list(map(int, input("Enter nuts: ").split(' '))) bolts = list(map(int, input("Enter bolts: ").split(' '))) match(nuts, bolts) '''OUTPUT: Enter nuts: 2 1 7 4 5 6 Enter bolts: 6 5 1 4 7 2 2 matched with 2 1 matched with 1 7 matched with 7 4 matched with 4 5 matched with 5 6 matched with 6 '''
# -*- coding: utf-8 -*- """ Generates a random number between 1 and 9 (including 1 and 9). Asks the user to guess the number, then tells them whether they guessed too low, too high, or exactly right. Keeps the game going until the user types “exit”. Keeps track of how many guesses the user has taken, and when the game ends, prints this out. Created on 1.3.2021. @author: Barbora Doslikova """ import numpy as np numberToGuess = np.random.randint(1,10) # low inclusive, high exclusive roundNo = 0 userInput = 0 while str(userInput) != "exit" and int(userInput) != numberToGuess: userInput = input("Guess a number between 0-9 or type exit to finish: ") roundNo += 1 sentenceEnding = " guess" if roundNo != 1: sentenceEnding = " guesses" if userInput == "exit": print("you exited the game") elif int(userInput) == numberToGuess: print("you win the game after " + str(roundNo) + sentenceEnding) elif int(userInput) > numberToGuess: print("Guess a smaller number!") elif int(userInput) < numberToGuess: print("Guess a higher number!") else: print("something went wrong and you exited the game after " + str(roundNo) + sentenceEnding)
first_text = input('Enter first string: ') second_text = input('Enter second string: ') find_text = first_text.find(second_text) if find_text == -1: print(first_text) else: print(first_text[find_text + len(second_text):])
start = 1 end = 10 print('Counting from 1 to 10') while start <= 10: print(start) start += 1 print('Counting from 10 to 1') start = 10 end = 1 while start >= end: print(start) start -= 1
all_prices =[] while True: price = input("Please enter a price: ") if price == 'stop': break all_prices.append(float(price)) print('All prices: ') print(all_prices) sum_prices = sum(all_prices) min_price = min(all_prices) max_price = max(all_prices) all_prices.sort() lower_price = all_prices[0] if len(all_prices) > 0: while len(all_prices) > 0 and all_prices[0] == lower_price: price.pop(0) if len(all_prices) > 0: highest_price = all_prices[-1] while len(all_prices) > 0 and all_prices[-1] == highest_price: price.pop(-1) print('Print after lowest and highest price') print(all_prices)
n = input('Enter number: ') n = int(n) c = n % 10 n = n // 10 b = n % 10 n = n // 10 a = n % 10 n = n // 10 print('reverced number is: ' + str(c) + str(b) + str(a))
""" 1.计算求2+4+6+8+...+100的和 2.统计不同英雄的成绩 3.车型抱怨的数据统计 """ print('homework 1:') ret = 0 for i in range(2, 102, 2): ret += i print('2+4+6+8+...+100的和是:{0}'.format(ret)) # 作业2 print('\nhomework 2:') import pandas as pd data = { '语文': [68, 95, 98, 90, 80], '数学': [65, 76, 86, 88, 90], '英语': [30, 98, 88, 77, 90] } df = pd.DataFrame(data, index=['张飞', '关羽', '刘备', '典韦', '许褚']) df.index.name = '姓名' print('原数据:') print(df) # 统计数据 desc = df.describe() # 去除不需要的columns desc.drop(index=['count', '25%', '50%', '75%'], axis=1, inplace=True) desc.index = ['平均分', '方差', '最小值', '最大值'] print('\n统计数据:') # 统计总分数 sum_score = df.sum(axis=1) sum_score.name = '总分数' merge_sum = pd.merge(df, sum_score, left_index=True, right_index=True, how='left') merge_sum_sort = merge_sum.sort_values('总分数', ascending=False) # 合并表格 concat = pd.concat([merge_sum_sort, desc]) print(concat.fillna('').round(decimals=2)) # 作业3 print('\n\nhomework 3:') # 读取数据 car = pd.read_csv('./car_complain.csv') def replace_name(name): if name == '一汽-大众': name = '一汽大众' return name # 将problem列按照‘,’号进行分割 car = pd.concat([car.drop(columns=['problem']), car['problem'].str.get_dummies(',')], axis=1) # 将品牌列数据格式统一 car['brand'] = car['brand'].apply(replace_name) # 按品牌进行分组统计 brand_sum = car.groupby('brand').agg('count')['id'] brand_sum.name = '车型投诉总数' df_brand = brand_sum.to_frame() print(df_brand.sort_values('车型投诉总数', ascending=False)) # 按车型进行分组统计 car_model_sum = car.groupby('car_model').agg('count')['id'] car_model_sum.name = '品牌投诉总数' df_car_model = car_model_sum.to_frame() print(df_car_model.sort_values('品牌投诉总数', ascending=False)) # 按品牌及车型进行分组 car_model_sum1 = car.groupby(['brand', 'car_model'])['id'].agg('count').groupby('brand').mean() car_model_sum1.name = '平均车型投诉总数' mean_car_model_p = car_model_sum1.to_frame() print(mean_car_model_p.sort_values('平均车型投诉总数', ascending=False).round(decimals=2))
def modus(angka): nol=0 terbesar=angka[0] for a in angka: jumlah=angka.count(a) if jumlah>=nol: nol=jumlah terbesar=a return(terbesar) while True: a=input("masukkan list angka: ") angka=a.split() print(modus(angka)) print("") #Farrel Novridansyah Assjarif #XIMIA1/15
n=int(input('masukkan bilangan bulat')) bilangan= n/2 if bilangan%2==0: print("Ya") else: print("Bukan")
name = raw_input("What is your name? ") for x in range(1,201): y = raw_input('Enter somethin') if y == 'hi': print 'bye' elif y== 'Charlie' or y == 'charlie': print 'is ded meme' elif y == 'Brad' or y == 'brad': print 'is better than charlie' elif y== 'why': print 'because' elif y== 'Are you my friend': print 'no' elif y == 'nothing': print 'what' elif y== 'yes': print 'no bc you bad' elif y== 'stupid': print 'dumb kid' elif y== "i'm sad": print "don't worry" elif y == "I'm sad": print "don't worry" elif y == "im sad": print "don't worry" elif y == "Im sad": print "don't worry" elif y == 'no': print 'yes' elif y == 'what' or y == 'What': print 'ur dumb' elif y == 'hey' or y == 'Hey': print 'sup' elif y == 'random': print 'ask charlie he is the one making the game' elif y == 'ai' or y == 'Ai': print 'yep?' elif y == 'is charlie a good programmer': print "Yes, but a ded ded meme" elif y == 'cool': print "i know i am" elif y == "wow": print 'wow is right' elif y== "operate" or y == "Operate": print "operate on what" elif y == "me" or y == 'Me': print "but u bad" elif y == 'you' or y == 'You': print 'yeah im better than you' elif y == 'bye' or y == 'Bye': print 'see ya' elif y == 'kill' or y == 'Kill': print 'yourself' elif y == 'kill urself' or y == 'kill yourself': print 'yeah you should' elif y == 'rude' or y == 'you are rude': print 'and so what' elif y == 'i hate you': print 'same' elif y == else: print 'so what' # # # # # y = 1000 # while y == 1000: # x = raw_input("Enter a word") # print "ai says " + str(x)
""" change-making problem """ #Using the greedy approach #time complexity is O(n) #Dont always give the optimal solution def greedy(coins, value): sol = [] for i in range(len(coins)-1, -1, -1): while value >= coins[i]: #Take the most from the current biggest coin #or you can just substract temp = value - coins[i] * (value/coins[i]) #Append the current coin (value/coins[i]) times to sol sol += ([coins[i]]*(value/coins[i])) value = temp return sol #Using the recusive approach #exponontial time #Get the min number of coins every time def minCoins(value, coins, n): #base cases if (value == 0): result = 0 elif (n == 0): if(value % coins[n] == 0): result = value / coins[n] else: #None if you can't return the change result = None #recursive cases elif(value >= coins[n]): r = (value - (value % coins[n])) / coins[n] result = r + minCoins(value % coins[n], coins, n-1) else: result = minCoins(value, coins, n-1) return result #Dynamic approach, get rid of those repetitive recurences using an inter array #we use a 2d array to save the itermediate values #Time complexity O(mn) def dynamic(value, coins, n): #we dont have to go to recursive computation if we have the result already stored in array if(C[n][value] != None): return C[n][value] #base cases if (value == 0): result = 0 elif (n == 0): if(value % coins[n] == 0): result = value / coins[n] else: #None if you can't return the change result = None #recursive cases elif(value >= coins[n]): r = (value - (value % coins[n])) / coins[n] result = r + dynamic(value % coins[n], coins, n-1) else: result = dynamic(value, coins, n-1) #save result in the array before returning it C[n][value] = result return result #Instead of using a 2d array, we can only use 1d array to save only the last iter #Time complexity O(mn) def dynamic2(value, coins, n): #base cases if (value == 0): result = 0 elif (n == 0): if(value % coins[n] == 0): result = value / coins[n] else: #None if you can't return the change result = None #recursive cases elif(value >= coins[n]): r = (value - (value % coins[n])) / coins[n] if(C[value] != None): #Choose the min between the value of previous coins and using current coin result = min(C[value], C[value % coins[n]] + r) else: result = r + dynamic2(value % coins[n], coins, n-1) else: if(C[value] != None): result = C[value] else: result = dynamic2(value, coins, n-1) #save result in the array before returning it C[value] = result return result #greedy approach to #using the array result of the dynamic approach (the last array) and return the min coins for M <= L using greedy def dynamic_greedy(value, C, coins): sol = [] minCoins = C[value] #Returns the wanted coins for i in range(len(coins)-1, -1, -1): if(value >= coins[i]): count = C[value - coins[i]] + C[coins[i]] if(count <= minCoins): sol.append(coins[i]) #Returns the combination using the wanted coins for optimal solution change = [] for i in range(len(sol)): while value >= sol[i]: value -= sol[i] change.append(sol[i]) return change v = 16 a = [1,5,12,25] #a = [1,25,50,100,200] #Recursive sol print minCoins(v, a, len(a)-1) #greedy sol print greedy(a, v) #dynamic prog sol #init the intermediate table for saving results #C[i,j] with i from 1 to n and j from 0 to V+1 C = [x[:] for x in [[None] * (v + 1)] * (len(a))] #store values in a 2d table for val in range(v + 1): for i in range(len(a), -1, -1): l = a[:i] dynamic(val, l, len(l)-1) #print C #We store the values in 1d array C = [None] * (v + 1) #store values in a 1d table for i in range(len(a)): l = a[:i+1] for val in range(v + 1): dynamic2(val, l, len(l)-1) #print C #Return the min coins using greedy approach and using the last result array of C print dynamic_greedy(v, C, a)
import random print 'Welcome to the rock,paper,scissors game ' print 'press 1 for single player and press 2 for double player' a = input('give the input: ') if a==1: print "Welcome I am the computer player." input1=input("Enter your choise as 1, 2 or 3 . 1.rock 2.paper 3.scissors ") comp = random.choice([1, 2, 3]) if(comp==1 and input1 == 2): print " rock " print 'you win' elif (comp==1 and input1==3): print "rock" print " you lose " elif(comp==2 and input1==1): print 'paper' print ' you lose ' elif(comp==2 and input1==3): print 'paper' print 'you win' elif(comp==3 and input1==1): print 'scissors ' print 'you win' elif(comp==3 and input1==2): print 'scissors ' print 'you lose' else: print "same same . so...........it's a draw" if a==2: print "So player 1's turn. player 2 close your eyes." comp = input("Enter your choise as 1, 2 or 3 . 1.rock 2.paper 3.scissors ") print "Now player 2's turn. player 1 close your eyes." input1 = input("Enter your choise as 1, 2 or 3 . 1.rock 2.paper 3.scissors ") if(comp==1 and input1 == 2): print 'player 2 wins' elif (comp==1 and input1==3): print "player 1 wins " elif(comp==2 and input1==1): print 'player 1 wins ' elif(comp==2 and input1==3): print 'player 2 wins' elif(comp==3 and input1==1): print 'player 1 wins' elif(comp==3 and input1==2): print 'player 2 wins' else: print "same same . so...........it's a draw"
class Node(object): def __init__(self,val): self.val = val def __eq__(self,other): return self.val == other.val def __hash__(self): return hash(self.val) s = set() n1 = Node(val = 1) n2 = Node(val = 2) n3 = Node(val = 1) n4 = Node(val = 2) s.add(n1) s.add(n2) s.add(n3) print('hello world',n4 in list(s))
def selectionSort(data): for fidx, focus in enumerate(data): min = focus # set focus midx = fidx for idx, i in enumerate(data): # find minimum if min > i and idx >= fidx: # idx must bigger than fidx min = i midx = idx data[fidx], data[midx] = data[midx], data[fidx] # change focus, minimum data print(f"{f'step{fidx}': <10}{data}") # print change logs data = [3, 1, 6, 2, 7, 9, 4, 5, 8, 10] print(f"{'before':=^40}\n{data}") selectionSort(data) print(f"{'after':=^40}\n{data}")
from random import random from IPython.core.debugger import Tracer def main(): printIntro() probA, probB = getInputs() # I force 1000 games to make result usable because if let user enter very close # prob like A=0.7, B=0.69 then you can not compare anything it just too random games = 1000 winsAreg, winsBreg, winsAral, winsBral = simNGames(probA, probB, games) comment = getComment(winsAreg, winsBreg, winsAral, winsBral, probA, probB, games) printSummary(winsAreg, winsBreg, winsAral, winsBral, games, comment) def printIntro(): print( '''A Program to simulate two type of volleyball systems. Result of 1000 games between regular type and rally scoring type will be compare and print summary at the end of process.\n Please provide different probability for each team. ====================================================''') def getInputs(): #Use loop here to validate prob of both team must different #or the end result is just too random. while True: a = eval(input('\nWhat is the prob. team A wins a serve? ')) b = eval(input('What is the prob. team B wins a serve? ')) if a == b: print('\nERROR! Each team must have different probability! Try again!') else: break return a,b def simNGames(probA,probB,games): winsAreg = winsBreg = 0 # present regular type winsAral = winsBral = 0 # present rally scoring type for i in range(games): #swap serving each game if i%2 == 0: serving = 'A' else: serving = 'B' # REGULAR GAME # scoreA, scoreB = simOneGame(probA,probB,serving,'regular') if scoreA > scoreB: winsAreg = winsAreg + 1 else: winsBreg = winsBreg + 1 # RALLY GAME # scoreA, scoreB = simOneGame(probA,probB,serving,'rally') if scoreA > scoreB: winsAral = winsAral + 1 else: winsBral = winsBral + 1 return winsAreg, winsBreg, winsAral, winsBral, def simOneGame(probA,probB,serving,type): #Tracer()() scoreA = scoreB = 0 r = random() # REGULAR GAME # if type == 'regular': while not gameOver(scoreA,scoreB,type): if serving =='A': if r < probA: scoreA = scoreA + 1 else: serving = 'B' else: if r < probB: scoreB = scoreB + 1 else: serving = 'A' # RALLY GAME # if type == 'rally': while not gameOver(scoreA,scoreB,type): if serving =='A': if r < probA: scoreA = scoreA + 1 else: scoreB = scoreB + 1 serving = 'B' else: if r < probB: scoreB = scoreB + 1 else: scoreA = scoreA + 1 serving = 'A' return scoreA, scoreB def gameOver(a,b,type): if type == 'regular': #won by 15 + margin of 2 status = ((a >= 15) and (a-b >= 2)) or ((b >= 15) and (b-a >= 2)) if type == 'rally': #won by 25 + margin of 2 status = ((a >= 25) and (a-b >= 2)) or ((b >= 25) and (b-a >= 2)) return status def getComment(winsAreg, winsBreg, winsAral, winsBral, probA, probB, games): # check if teamA or teamB is has better probability # then calculate are they won more or less from rally scoring type if probA == max(probA,probB): betterteam = 'A' diff = (winsAral-winsAreg)/games else: betterteam = 'B' diff = (winsBral-winsBreg)/games return genComment(betterteam,diff) def genComment(betterteam,diff): # finally generate comment text to use at end result if diff > 0: c ='Conclusion:\nTeam {0} is better team and enjoy benefit {1:0.1%} from rally scoring system.'.format(betterteam,diff) elif diff < 0: c ='Conclusion:\nEven Team {0} is a better but their advantage is reduce {1:0.1%} by rally scoring system.'.format(betterteam,diff) else: c ='Conclusion:\nTeam {0} is better but does not gain benefit from rally scoring system.'.format(betterteam) return c def printSummary(winsAreg,winsBreg,winsAral,winsBral,games,comment): print('\nGames simulated:',games) print('\nRegular type games result:') print('Wins for A: {0} ({1:0.1%})'.format(winsAreg, winsAreg/games)) print('Wins for B: {0} ({1:0.1%})'.format(winsBreg, winsBreg/games)) print('\nRally Scoring type games result:') print('Wins for A: {0} ({1:0.1%})'.format(winsAral, winsAral/games)) print('Wins for B: {0} ({1:0.1%})'.format(winsBral, winsBral/games)) print('\n====================================================') print(comment) if __name__ == '__main__' : main()
""" Heating and cooling degree-days are measures used by utility companies to estimate energy requirements. If the average temperature for a day is below 60, then the number of degrees below 60 is added to the heating degree-days. If the temperature is above 80, the amount over 80 is added to the cooling degree-days. Write a program that accepts a sequence of average daily temps and computes the running total of cooling and heating degree-days. The program should print these two totals after all the data has been processed. """ def calc(T): d = 0 l = [0, 0] while T != '': T = float(T) if T < 60: l[0] += 60 - T elif T > 80: l[1] += T - 80 T = input("\nWhat's the temperature? ") d += 1 print("\nIn {} days, there were {:.0f} heating degree days and {:.0f} cooling degree days.\n".format(d, l[0], l[1])) def main(): print("\nThis app computes the number of cooling and heating days.") T = input("\nWhat's the temperature? ") calc(T) main()
def AE(): print("Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!") def BCD(animal, sound): print("And on that farm he had a {}, Ee-igh, Ee-igh, Oh!".format(animal)) #print("With a", sound "," sound, "here and a", sound ",", sound, "there.") print("With a {0}, {0} here and a {0}, {0} there.".format(sound)) #print("Here a", sound ",", "there a", sound, "everywhere a", sound, sound ".") print("Here a {0}, there a {0}, everywhere a {0}, {0}.".format(sound)) def main(): print("\n") AE() BCD("cow", "moo") AE() print("\n") AE() BCD("chicken", "cluck") AE() print("\n") AE() BCD("sheep", "baa") AE() print("\n") AE() BCD("goat", "neigh") AE() print("\n") AE() BCD("pig", "oink") AE() print("\n") main()
def main(): print() print("This will add up numbers you provide!") print() l = list(eval(input("Enter your numbers separated by commas: "))) Sum = 0 print() for num in l: Sum = Sum + num print("The sum of those numbers is", Sum) print() main()
# True/False # 1. False, could also be in single quotes # 2. True # 3. False, can contain any sequence of characters # 4. True # 5. True # 6. True # 7. True # 8. False, that's far too easy to break # 9. False, use "append". Add is for sets # 10. False, use "open" # Multiple Choice # 1. d) indexing # 2. c) s[:len(s)-1] # 3. a) ord, it gives the unicode *value* # 4. c) str # 5. c) Unicode # 6. d) upper # 7. d) {} # 8. c) readall # 9. c) batch # 10. a) open s1 = "spam" s2 = "ni!" # 1. Show the results of evaluating each of the following string expressions # (a) print("The knights who say, " + s2) # (b) print(3 * s1 + 2 * s2) # (c) print(s1[1]) # (d) print(s1[1:3]) # (e) print(s1[2] + s2[:2]) # (f) print(s1 + s2[-1]) # (g) print(s1.upper()) # (g) print(s1.upper().ljust(4) * 3) # 2. Show an expression that constructs the following # (a) "NI!" print(s2.upper()) # (b) "ni!spamni!" print(s2 + s1 + s2) # (c) "Spam Ni! Spam Ni! Spam Ni!" print((s1.title() + " " + s2.title()).ljust(9) + (s1.title() + " " + s2.title()).center(9) + (s1.title() + " " + s2.title()).rjust(10)) # (d) "spam" print(s1) # (e) ["sp", "m"] print([s1[:2],s1[3:]]) # (f) "spm" print(s1[:2]+s1[3:]) # 3. Show the output generated by the following # (a) for ch in "aardvark": print(ch) # (b) for w in "Now is the winter of our discontent...".split(): print(w) # (c) for w in "Mississippi".split("i"): print(w) # (d) msg = "" for s in "secret".split("e"): msg = msg + s print(msg) # (e) msg = "" for ch in "secret": msg = msg + chr(ord(ch)+1) print(msg) # 4. Show the string that would follow # (a) print("Looks like {1} and {0} for breakfast".format("eggs", "spam")) # (b) print("There is {0} {1} {2} {3}".format(1, "spam", 4, "you")) # (c) print("Hello {0}".format("Susan", "Computewell")) # (d) print("{0:0.2f} {0:0.2f}".format(2.3, 2.3468)) # (e) #print("{7.5f} {7.5f}".format(2.3, 2.3468)) # (f) print("Time left {0:02}:{1:05.2f}".format(1, 37.374)) # (g) #print("{1:3}".format("14")) # 5. Public key encryption can be used for identifying and decoding publicly. Private keys use the same key for encrypting and decrypting messages, and those have to be kept secret from everyone. But But public keys are meant to shared and private keys can be kept to decode messages written with the public key. The internet is simply made up of communications between pairs of people. Securely communicating is possible if keys are used.
# cube.py # Class definition for a cube class Cube: def __init__(self, side_length): self.side_length = side_length def getSideLength(self): return self.side_length def surfaceArea(self): return 6 * self.side_length ** 2 def volume(self): return self.side_length ** 3 def main(): s = float(input("Please enter the side length of the cube: ")) print() c = Cube(s) V = c.volume() A = c.surfaceArea() print("The cube's volume is {}".format(V)) print("The cube's surface area is {}".format(A)) if __name__ == "__main__": main()
# gpa.py # Program to find student with highest GPA class Student: def __init__(self): self.name = "" self.hours = float(0) self.qpoints = float(0) self.credits = self.hours self.gradePoint = float(0) self.letterGrade = "" def getName(self): return self.name def getHours(self): return self.hours def getQPoints(self): return self.qpoints def gpa(self): return self.qpoints / self.hours def addGrade(self, gradePoint, credits): self.hours += self.credits self.qpoints += (self.gradePoint * self.credits) return self.hours, self.qpoints def addLetterGrade(self, letterGrade, credits): #import pdb; pdb.set_trace() gradePoint = float(0) if letterGrade == "A": gradePoint = 4.0 elif letterGrade == "A-": gradePoint = 3.7 elif letterGrade == "B+": gradePoint = 3.3 elif letterGrade == "B": gradePoint = 3.0 elif letterGrade == "C+": gradePoint = 2.3 elif letterGrade == "C": gradePoint = 2.0 elif letterGrade == "C-": gradePoint = 1.7 elif letterGrade == "D+": gradePoint = 1.3 elif letterGrade == "D": gradePoint = 1.0 elif letterGrade == "D-": gradePoint = 0.7 elif letterGrade == "F": gradePoint = 0.0 self.credits = credits self.gradePoint = gradePoint self.hours += self.credits self.qpoints += (self.gradePoint * self.credits) return self.hours, self.qpoints def main(): print("Add a student.\n") eStudent = Student() eStudent.name = input("Enter student name: ") print("Currently {} has {} credits and {} quality points.\n".format(eStudent.name, eStudent.hours, eStudent.qpoints)) print("Add grade point and credits to {}'s profile.\n".format(eStudent.name)) letterGrade = input("Enter student grade: ") credits = float(input("Enter credit hours: ")) hours, qpoints = eStudent.addLetterGrade(letterGrade, credits) GPA = qpoints / hours print("{}'s GPA is {}".format(eStudent.name, GPA)) if __name__ == '__main__': main()
from random import choice, randint # card.py # Class that represents playing cards class Card: def __init__(self, rank, suit): self.rank = int(rank) self.suit = str(suit) def getRank(self): return self.rank def getSuit(self): return self.suit def BJValue(self): if self.rank > 9: return 10 else: return self.rank def __str__(self): name = "" suit = "" rank = int(1) if self.suit == "d": suit = "Diamonds" elif self.suit == "c": suit = "Clubs" elif self.suit == "h": suit = "Hearts" elif self.suit == "s": suit = "Spades" if self.rank == 1: rank = "Ace" elif self.rank == 2: rank = "Two" elif self.rank == 3: rank = "Three" elif self.rank == 4: rank = "Four" elif self.rank == 5: rank = "Five" elif self.rank == 6: rank = "Six" elif self.rank == 7: rank = "Seven" elif self.rank == 8: rank = "Eight" elif self.rank == 9: rank = "Nine" elif self.rank == 10: rank = "Ten" elif self.rank == 11: rank = "Jack" elif self.rank == 12: rank = "Queen" elif self.rank == 13: rank = "King" name = "{} of {}".format(rank, suit) return name def main(): suits = ["d", "c", "h", "s"] for i in range(int(input("Supply a whole number: "))): c = Card(randint(1, 13), choice(suits)) print(c) print(c.BJValue()) if __name__ == "__main__": main()
# File: chaos2: Electric Boogaloo # A simple program illustrating chaotic behavior. def main(): print("This program illustrates a chaotic fuction") x = float(input("Enter a number between 0 and 1: ")) y = float(input("Enter another number between 0 and 1: ")) n = int(input("How many numbers should I print? ")) print() print("index", str(x).center(9), str(y).rjust(10)) print("-" * 28) for i in range(n): x = 3.9 * x * (1 -x) y = 3.9 * y * (1 -y) print('{} {:11.6f} {:12.6f}'.format(str(i + 1).rjust(3), x, y)) main()
from random import random def main(): printIntro() probA, probB, n = getInputs() winsA, winsB, ralWinsA, ralWinsB = simNGames(n, probA, probB) printSummary(winsA, winsB, ralWinsA, ralWinsB) def printIntro(): print("This program simulates a game of tennis between two") print('players called "A" and "B". The abilities of each player is') print("indicated by a probability (a number between 0 and 1) that") print("the player wins the point when serving. Player A always") print("has the first serve.") def getInputs(): a = float(input("What is the prob. player A wins a serve? ")) b = float(input("What is the prob. player B wins a serve? ")) n = int(input("How many games to simulate? ")) return a, b, n def simNGames(n, probA, probB): winsA = winsB = 0 ralWinsA = ralWinsB = 0 for i in range(n): scoreA, scoreB, ralScoreA, ralScoreB = simOneGame(probA, probB, i) if scoreA > scoreB: winsA += 1 else: winsB += 1 if ralScoreA > ralScoreB: ralWinsA += 1 else: ralWinsB += 1 return winsA, winsB, ralWinsA, ralWinsB def simOneGame(probA, probB, i): if i % 2 == 0: serving = "A" else: serving = "B" scoreA = scoreB = 0 ralScoreA = ralScoreB = 0 while not gameOver(scoreA, scoreB): if serving == "A": if random() < probA: scoreA += 1 ralScoreA += 1 else: ralScoreB += 1 #serving = "B" else: if random() < probB: scoreB += 1 ralScoreB += 1 else: ralScoreA += 1 #serving = "A" return scoreA, scoreB, ralScoreA, ralScoreB def gameOver(a, b): return a >= 4 and b <= a - 2 or b >= 4 and a <= b - 2 def printSummary(winsA, winsB, ralWinsA, ralWinsB): n = winsA + winsB nRal = ralWinsA + ralWinsB print("\nGames simulated:", n) print("Wins for A: {0} ({1:0.1%})".format(winsA, winsA/n)) print("Wins for B: {0} ({1:0.1%})".format(winsB, winsB/n)) print("Rally wins for A: {0} ({1:0.1%})".format(ralWinsA, ralWinsA/nRal)) print("Rally wins for B: {0} ({1:0.1%})".format(ralWinsB, ralWinsB/nRal)) if __name__ == '__main__': main() # This file should also be considered the basis for a better version 9.3 and 9.4.
from random import randrange def main(): printIntro() n = getInput() position = randomWalk(n) printOutro(n, position) def printIntro(): print("\nThis app simulates 1D random walks with coin flips.") def getInput(): n = int(input("\nHow many coin flips? ")) return n def randomWalk(n): x = 0 for i in range(n): coin_flip = randrange(2) print(coin_flip) if coin_flip == 0: x += 1 else: x -= 1 print(x) return x def printOutro(n, position): print("After {} coin flips, you end up at {}".format(n, position)) if __name__ == '__main__': main()
def acronym(phrase): Sphrase = phrase.split() ac = "" for w in Sphrase: ac = ac + w[0] return ac def main(): phrase = input("Enter a phrase you want an acronym for: ") print("The acronym is {0}".format(acronym(phrase).upper())) main()
def count(myList, x): total = 0 for item in myList: if item == x: total += 1 return total def isin(myList, x): for item in myList: if item == x: return True return False def index(myList, x): for index, item in enumerate(myList): if item == x: return index def reverse(myList): return myList[::-1] # def sort(myList): # loNum = 0 # hiNum = 0 # loABC = '' # hiABC = '' # iList = iter(myList) # Type = type(next(iList)) # if all((type(x) is Type) for x in iList) and Type == str: print(f"count([1, 2, 2, 3, 5], 2) == {count([1, 2, 2, 3, 5], 2)}, and [1, 2, 2, 3, 5].count(2) == {[1, 2, 2, 3, 5].count(2)}") print(f"isin(['a', 'b', 'c', 'd'], 'c') == {isin(['a', 'b', 'c', 'd'], 'c')} and 'c' in ['a', 'b', 'c', 'd'] == {'c' in ['a', 'b', 'c', 'd']}") print(f"index([0, 1, 2, 3, 4], 4) == {index([0, 1, 2, 3, 4], 4)} and [0, 1, 2, 3, 4].index(4) == {[0, 1, 2, 3, 4].index(4)}") print(f"reverse([1, 2, 3, 4, 5]) == {reverse([1, 2, 3, 4, 5])} and [1, 2, 3, 4, 5].reverse() == {[1, 2, 3, 4, 5].reverse()}")
def sumN(n): Sum = 0 for i in range(1, n + 1): Sum = Sum + i return Sum def sumNCubes(n): Sum = 0 for i in range(1, n + 1): Sum = Sum + i ** 3 return Sum def main(): n = int(input("Enter an integer n: ")) print("The the sum of first n natural numbers is {}".format(sumN(n))) print("The the sum of the cubes of the first n natural numbers is {}".format(sumNCubes(n))) main()
def babysitterBill(start, end): HS, MS = int(start[:2]), int(start[-2:]) HE, ME = int(end[:2]), int(end[-2:]) hours = HE - HS minutes = (ME - MS)/60 print("minutes", minutes) Thours = hours + minutes m = int((Thours - Thours//1)*60) print("m", m) h = int(Thours//1) print("h", h) if HE > 21: print(HE) Post21H = HE - 21 print(Post21H) Pre21H = Thours - Post21H print(Pre21H) bill = Post21H * 1.75 + Pre21H * 2.50 print(bill) print("Your total time was {0}:{1}, or {0} hours and {1} minutes.".format(h,m)) print("{} hours and {} minutes of the total time were after 9 (i.e. 21:00).".format(Post21H, ME)) print("The bill is therfore ${:.2f}".format(bill)) else: bill = Thours * 2.50 print("Your total time was {0}:{1}, or {0} hours and {1} minutes".format(h,m)) print("The bill is therfore ${:.2f}".format(bill)) def main(): print() print("This app uses a 24 hour clock to calculate a babysitter's bill.\n") start = input("Enter the start time (e.g. 24:00): ") end = input("Enter the end time (e.g. 24:00): ") babysitterBill(start, end) print() main()
def main(): print() print("This will average numbers you provide!") print() n = int(input("How many nummbers will you be averaging?: ")) avg = 0 print() for num in range(n): number = int(input("Enter number: ")) avg = avg + number avg = avg / n print("The average of those numbers is", avg) print() main()
import requests import json my_api_key = "3wafa48C2dr0qASN28zcHCfqvwixdVL6BiJKNiEz" class APOD: def getAPODToday(): query = "https://api.nasa.gov/planetary/apod?api_key={}".format( my_api_key ) response = requests.get( query, headers = { "Content-Type": "application/json", } ) response_json = response.json() url = response_json["url"] return url def getAPODAnyDay(my_date): query = "https://api.nasa.gov/planetary/apod?date={}&api_key={}".format( my_date, my_api_key ) response = requests.get( query, headers = { "Content-Type": "application/json", } ) response_json = response.json() url = response_json["url"] explanation = response_json["explanation"] return url print("Today's Astronomy Picture of the Day is given from this URL: ") my_url_today = APOD.getAPODToday() print(my_url_today) my_date = input("Input a date for an APOD in the format YYYY-MM-DD: ") my_url_any_day = APOD.getAPODAnyDay(my_date) print(my_url_any_day)
# For computations and plotting import numpy as np import matplotlib.pyplot as plt from numpy import cos, sin # Orthogonal transformations # Theory: https://mathworld.wolfram.com/EulerAngles.html # According to Euler's rotation theorem, any rotation may be described using three angles. # If the rotations are written in terms of rotation matrices D, C, and B, then a general # rotation A can be written as: A = B + C + D # # Euler Angels: # The three angles giving the three rotation matrices are called Euler angles. # There are several conventions for Euler angles, depending on the axes about which # the rotations are carried out. Write the matrix A as: # A=[[a_(11) a_(12) a_(13)], # [a_(21) a_(22) a_(23)], # [a_(31) a_(32) a_(33)]]. # # The so-called "x-convention," illustrated above, is the most common definition. # In this convention, the rotation given by Euler angles (phi,theta,psi), where: # 1. the first rotation is by an angle phi about the z-axis using D, # 2. the second rotation is by an angle theta in [0,pi] about the former x-axis (now x^') using C, and # 3. the third rotation is by an angle psi about the former z-axis (now z^') using B. # # But there are many conventions for the angles are in common use. # # 1. Convention from my lectures: # alpha - precession angle # D = [[cos(alpha), -sin(alpha), 0], # [sin(alpha), cos(alpha), 0], # [ 0 , 0 , 1]] # beta - nutation angle # C = [[1, 0 , 0 ], # [0, cos(beta), -sin(beta)], # [0, sin(beta), cos(beta)]] # gamma - self-rotation angle # B = [[cos(gamma), -sin(gamma), 0], # [sin(gamma), cos(gamma), 0], # [ 0 , 0 , 1]] # # 2. In the "xyz (pitch-roll-yaw) convention," theta is pitch, psi is roll, and phi is yaw. # # D = [[ cos(phi), sin(phi), 0], # [-sin(phi), cos(phi), 0], # [ 0 , 0 , 1]] # # C = [[cos(theta), 0, -sin(theta)], # [ 0 , 1, 0 ], # [sin(theta), 0, cos(theta)]] # # B = [[1, 0, 0 ], # [0, cos(psi), sin(psi)], # [0, -sin(psi), cos(psi)]] # # 3. Convention that we used in Lab A: Roll-Pitch-Yaw convention # Remember! Matrix multiplication order for rotation: 𝑅 = 𝑅(𝑌) ⋅ 𝑅(𝑃) ⋅ 𝑅(𝑅) # Rotation around x-axis. Roll. R(R) # Rx = np.array([[1, 0, 0], # [0, cos(psi), -sin(psi)], # [0, sin(psi), cos(psi)]]) # Rotation around y-axis. Pitch. R(P) # Ry = np.array([[cos(theta), 0, sin(theta)], # [0, 1, 0], # [-sin(theta), 0, cos(theta)]]) # Rotation around z-axis. Yaw R(Y) # Rz = np.array([[cos(phi), -sin(phi), 0], # [sin(phi), cos(phi), 0], # [0, 0, 1]]) # # Define function for rotation def roll_pitch_yaw_rotation(xyz_vector, angles_vector): # Rotation around x-axis. Roll. R(R) psi = angles_vector[0] theta = angles_vector[1] phi = angles_vector[2] Rx = np.array([[1, 0, 0], [0, cos(psi), -sin(psi)], [0, sin(psi), cos(psi)]]) # Rotation around y-axis. Pitch. R(P) Ry = np.array([[cos(theta), 0, sin(theta)], [0, 1, 0], [-sin(theta), 0, cos(theta)]]) # Rotation around z-axis. Yaw R(Y) Rz = np.array([[cos(phi), -sin(phi), 0], [sin(phi), cos(phi), 0], [0, 0, 1]]) # 𝑅 = 𝑅z(𝑌) ⋅ 𝑅y(𝑃) ⋅ 𝑅x(𝑅) rotated_matrix = Rz @ Ry @ Rx @ xyz_vector return rotated_matrix # Shift def shift_coordinates(a): a = a pass vectors_start = np.array([[0, 0, 0], # unit X arrow coordinate [0, 0, 0], # unit Y arrow coordinate [0, 0, 0], [1, 1, 1]]) # unit Z arrow coordinate # Assigning the vectors itself. Let them be orthogonal. vectors_itself = np.array([[1, 0, 0], # unit X vector direction [0, 1, 0], # unit Y vector direction [0, 0, 1], [0.5, 0.9, 3]]) # unit Z vector direction vectors_rotated = np.array([[1, 0, 0], # unit X vector direction [0, 1, 0], # unit Y vector direction [0, 0, 1], [0.5, 0.9, 3]]) # unit Z vector direction for vector, i in zip(vectors_itself[:, 0:None], range(vectors_itself.shape[0])): vectors_rotated[i, :] = roll_pitch_yaw_rotation(vector, [np.pi/4, 0, 0]) # Convert Matrix's columns into row vectors (2D array to 1D arrays) i0 = vectors_start[:, 0] # x j0 = vectors_start[:, 1] # y k0 = vectors_start[:, 2] # z i1 = vectors_itself[:, 0] j1 = vectors_itself[:, 1] k1 = vectors_itself[:, 2] i2 = vectors_rotated[:, 0] j2 = vectors_rotated[:, 1] k2 = vectors_rotated[:, 2] # 3D plot ax = plt.figure().add_subplot(projection='3d') ax.quiver(i0, j0, k0, i1, j1, k1, normalize=False) ax.quiver(i0, j0, k0, i2, j2, k2, color='r', normalize=False) ax.set_xlim([-2, 2]) ax.set_ylim([-2, 2]) ax.set_zlim([-2, 2]) plt.show()
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt x = np.linspace(-6, 6, 25) y = np.linspace(-6, 6, 25) # General equation for an ellipsis # x^2/a^2 + y^2/b^2 = 1 # or # x^2/a^2 + y^2/b^2 - 1 = 0 # # If our center has an offset: # (x-x0)^2/a^2 + (y-y0)^2/b^2 = 1 # Creating cartesian coordinate space # using meshgrid method x, y = np.meshgrid(x, y) # a should be a > b or a = b a = 3 b = 2 xf1 = np.sqrt(a ** 2 - b ** 2) yf1 = 0 xf2 = np.sqrt(a ** 2 - b ** 2) * -1 yf2 = 0 # Ellipsis equation X = x ** 2 / a ** 2 # X-coordinate Y = y ** 2 / b ** 2 # Y-coordinate # Solution grid of the Ellipsis equation solution = X + Y # Parametrization t = np.linspace(0, 2 * np.pi, 100) x2 = a * np.cos(t) y2 = b * np.sin(t) # Plotting plt.contour(x, y, solution, [1]) plt.scatter(x2, y2, marker='o') plt.scatter(xf1, yf1, marker='o') plt.scatter(xf2, yf2, marker='o') plt.show() # Example: https://stackoverflow.com/questions/25050899/producing-an-array-from-an-ellipse import numpy as np from matplotlib import pyplot # Let's introduce some values of interest: # Centers: x0 = 4; a = 5 # x center and half width (greater axis of an ellipse) y0 = 2; b = 3 # y center and half width (smaller axis of an ellipse) x = np.linspace(-10, 10, 100) # x - values y = np.linspace(-5, 5, 100)[:,None] # y - values as a "column" array ellipse = ((x-x0)/a)**2 + ((y-y0)/b)**2 <= 1 # Boolean array, where True for points inside the ellipse # Thanks to NumPy's broadcasting rules, # the contributions of x and y are summed together # in a simple way (y[:,None] essentially makes y # a column vector of y value, while x remain a row vector). # There is also no need for larger 2D intermediate array, # as would be needed with numpy.meshgrid(). pyplot.imshow(ellipse, extent=(x[0], x[-1], y[0][0], y[-1][0]), origin="lower") pyplot.show()
''' En este ejercicio deberás crear un script llamado contador.py que realice varias tareas sobre un fichero llamado contador.txt que almacenará un contador de visitas (será un número): Nuestro script trabajará sobre el fichero contador.txt. Si el fichero no existe o está vacío lo crearemos con el número 0. Si existe simplemente leeremos el valor del contador. Luego a partir de un argumento: 1.- Si se envía el argumento inc, se incrementará el contador en uno y se mostrará por pantalla. 2.- Si se envía el argumento dec, se decrementará el contador en uno y se mostrará por pantalla. 3.- Si no se envía ningún argumento (o algo que no sea inc o dec), se mostrará el valor del contador por pantalla. 4.- Finalmente guardará de nuevo el valor del contador de nuevo en el fichero. Utiliza excepciones si crees que es necesario, puedes mostrar el mensaje: Error: Fichero corrupto. ''' from io import open #contador = 0 def crear_fichero(arg=''): # open(nombre,a+) a+= abrir, leer y escribir, se usa si el archivo no existe fichero = open('contador.txt', 'a+') # seek, regresa un int, posiciona el curso en 0 fichero.seek(0) contenido = fichero.readlines() if len(contenido) == 0: contenido = '0' # escribo contenido en fichero fichero.write(contenido) else: print("EL fichero no esta vacio.") fichero.close() try: contador = int(contenido) print(type(contador)) if arg == 'inc': contador += 1 elif arg == 'dec': contador -= 1 print(contador) # Escribo cambios fichero = open("contador.txt", 'w') fichero.write(str(contador)) fichero.close() except: print("Error: Fichero corrupto") if __name__ == "__main__": argumento=str(input("Ingrese el argumento inc o dec: ")) # print(argumento) crear_fichero(argumento) '''Estimado Darwin, solo corre la primera vez y despues tengo que borrar lo que tiene el archivo. no use la opción sys.argv pq no la entiendo, por favor tu gentil ayuda revisando este scrip y sugiriendome como solucionar el problema TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' '''