text
stringlengths
37
1.41M
a,b,c = map(int, input("세 정수를 입력하시오: ").split()) if a>b: if a>c: if b>c: print(a,b,c) else: print(a,c,b) else: print(c,a,b) else: if b>c: if a>c: print(b,a,c) else: print(b,c,a) else: print(c,b,a)
x1 = int(input("x1: ")) y1 = int(input("y1: ")) x2 = int(input("x2: ")) y2 = int(input("y2: ")) def abs(x,y): if x - y > 0: return x-y else: return y - x def distance(x1, y1, x2, y2): r = ((abs(x1,x2))**2 + (abs(y1,y2))**2)**0.5 return r print("두 점 사이의 거리는", distance(x1, y1, x2, y2))
import math def circle(r): area = math.pi * r * r circum = 2 * math.pi * r return area, circum radius = int(input("반지름을 입력하세요: ")) (x, y) = circle(radius) print("원의 넓이는 {}이고 원의 둘레는 {}이다.".format(x, y))
s = input("알파벳을 입력하시오: ") if s in ["a","e","i","o","u"]: print(s,"은(는) 모음입니다.") else: print(s,"은(는) 자음입니다.")
import turtle t = turtle.Turtle() t.shape("turtle") i = 0 while i < 5: t.forward(50) t.left(144) i = i + 1
nlist = input("문자열을 입력하세요: ") for i in range(len(nlist)): print(nlist[:i]) for i in range(len(nlist)): print(nlist[:len(nlist)-i])
money = int(input("투입한 돈: ")) price = int(input("물건값: ")) change = money - price print("거스름돈: ", change) cash = change // 1000 coin500 = change % 1000 // 500 coin100 = change % 500 // 100 coin50 = change % 100 // 50 coin10 = change % 100 % 50 // 10 print("1000원: {0}개".format(cash)) print("500원: {0}개".format(coin500)) print("100원: {0}개".format(coin100)) print("50원: {0}개".format(coin50)) print("10원: {0}개".format(coin10))
import numpy as np x = np.array([['a','b','c','d'],['c','c','g','h']]) print(x[x == 'c']) mat_a = np.array([[10,20,30],[10,20,30]]) mat_b = np.array([[2,2,2],[1,2,3]]) print(mat_a-mat_b)
import re while True: password = input("패스워드를 입력하세요: ") if (len(password)< 8) \ or not (re.search('[A-Z]', password)) \ or not(re.search('[a-z]', password)) \ or not (re.search('[0-9]', password)) \ or not(re.search('[\_\@\$\!]', password)): print("유효하지 않은 패스워드") else: print("유효한 패스워드") break
import turtle t = turtle.Turtle() t.shape("turtle") t.color("blue") t.fillcolor("red") t.pensize(3) t.speed(0) t.right(90) mylist = [120,56,309,156,23,98] for i in range(len(mylist)): t.begin_fill() t.left(180) t.forward(mylist[i]) t.right(90) t.write(mylist[i]) t.forward(15) t.right(90) t.forward(mylist[i]) t.end_fill()
list1 = [3,5,7] list2 = [2,3,4,5,6] for i in range(len(list1)): for j in range(len(list2)): print(list1[i],"x",list2[j], "=", list1[i]*list2[j])
import random n1 = random.randint(0,9) n2 = random.randint(0,9) n3 = random.randint(0,9) n = [n1,n2,n3] x,y,z = map(int,input("세 복권번호를 입력하시오: ").split()) print("복권번호:",n1,n2,n3) if (x in n) and (y in n) and (z in n): print("상금 1억원") elif (x in n and y in n) or (x in n and z in n) or (y in n and z in n): print("상금 1천만원") elif (x in n) or (y in n) or (z in n): print("상금 1만원") else: print("다음 기회에..")
# -*- coding: utf-8 -*- """ Created on Fri Nov 23 11:56:50 2018 @author: gy15js """ '''NEED TO COMMENT OUT THIS SECTION OF CODE''' #changing the values given what the levels of food are #use an if command so if store is lower than '' eat #https://dadaromeo.github.io/posts/mesa-a-library-for-agent-based-modeling-in-python/ import random as r class Agent(): def __init__ (self, environment, agents, r_seed, y, x): #self._y = r.randint(0,100) #self._x = r.randint(0,100) self._y = y self._x = x if (x == None): self._x = r.randint(0,100) else: self._x = x if (y == None): self._y = r.randint(0,100) else: self._y = y #def __init__(environment): added the two together to ensure use of #init self.environment = environment self.store = 0 self.agents = agents self.store = 0 self.r_seed = 1 self.store = 0 def move(self): if r.random() < 0.5: self._y = (self._y + 1) % 100 else: self._y = (self._y - 1) % 100 if r.random() < 0.5: self._x = (self._x + 1) % 100 else: self._x = (self._x - 1) % 100 def eat(self): #can you make it eat what is left? if self.environment[self._y][self._x] > 10: self.environment[self._y][self._x] -= 10 self.store += 10 #this method tells the agents to share with their nearby neighbours #that are closest def share_with_neighbours (self, neighbourhood): for agent in self.agents: dist = self.distance_between(agent) #for agents, find the distance between them if dist <= neighbourhood: #if the distance is lower than or equals to the neighbourhood sum = self.store + agent.store ave = sum/2 self.store = ave #averaging self.store and agent.store out agent.store = ave #print("sharing" + str(dist) + "" + str(ave)) '''this is just to make sure it works, now that it does can comment out''' def distance_between (self,agent): return (((self._x - agent._x)**2) + ((self._y - agent._y)**2))**0.5
# - hash function + array = hash table # -array full of linked lists # index Chain # 0 None # 1 None # 2 None # 3 None # 4 None # 5 None # put('foo', 12) # hash to 1 # put('baz', 13) # hash to 3 # put('bar', 23) # hash to 1 # get('bar') # How do we do a get when handling collision with linked list # Store the key unhashed, and compare as we iterate/traverse down the linked list # put # Check if key is in linked list if so overwrite if not add new Node # delete # delete('bar') # find the matching pair of values # -point the previous node of that one to the next node of the found node # - # Linked lists # - Single linked node.next # - Double linked, node.next and node.prev class SLL: def __init__(self): self.head = None def get(self, value): # start at the head node = self.head while node is not None: # check for the target value if node.value == target_value: return node # move to next node else: node = node.next
#%% n = int(input("principle quantum number? ")) if n>=0: E = (n+1/2) E = str(E) print(E+"h") else: print("input a posivite value u dumbell")
import numpy as np arr1 = np.arange(10) print(arr1.shape) # 수직축 추가 arr2 = arr1[:, np.newaxis] print(arr2.shape) # 수평축 추가 arr3 = arr1[np.newaxis, :] print(arr3.shape) print(arr3)
command = input("Enter a command > ") while command: print(f"You entered command: {command}") command = input("Enter a command > ")
0;136;0c""" File: proj1.py Author: Rooklyn Kline Date: 10/25/19 Section: 15 E-mail: rkline2@umbc.edu Description: This program is a baking sim where each player has to bake baguettes, macarons, and croissants. They must go to the grocery store to purchase ingredients. If they don't have enough ingredients or they go over budget, they automatically loose the game. """ ASK_QUANTITY_QUESTION = ["How many ", " of ", " would you like to purchase? "] BAGUETTES_QUANTITY = 100 BAGUETTES = 2 BAGUETTES_ING_QUANTITY_LIST = [112.5, 0, 0, 50, 0] BAKE_INTRODUCTION = "We have everything we need! Ready! Set! Bake!" BAGUETTES_NOT_FIRST = "We should really start the baguette dough first!" BAKE_QUESTION = "What action would you like to cross off your list next? " BAGUETTE_DOUGH_STATEMENT = "Ok, let's knead some baguette dough!" BUTTER = 'butter' CROISSANTS = 0 CROISSANTS_QUANTITY = 300 COLON = ":" CROISSANTS_STATEMENT = "Let's make some flaky crescent goodness!" CROISSANTS_ING_QUANTITY_LIST = [48, 12, 144, 39, 18] DISHES_LIST = ["croissants", "macarons", "baguettes"] DISHES_QUANTITY = [300, 600, 100] DIDNT_BUY_ENOUGH = "You didn't buy enough" DASH = ' - ' EXCLAMATION_POINT = '!' FAILURE = "You did not buy enough ingredients to even begin baking. You are a failure of all sorts. Good day." FLOAT = "." FOUR = 4 GREETING = "Welcome to the supermarket!" INGREDIENTS = ['flour', 'eggs', 'butter', 'yeast', 'milk'] INGREDIENTS_DESCRIPTION_LIST = ["cups of flour", "eggs", "tbsp of butter", "tsp of yeast", "cups of milk"] INDENT = "" INTRO = "Baker! You must buy the following with $ " ING_INTRO = "For" INGREDIENT_DESCRIPTION = ["bags", "crates", "packs", "bags", "jugs"] INVALID_ENTRY = "That is not a valid entry." MACARONS = 1 MACARONS_QUANTITY = 600 MACARONS_ING_QUANTITY_LIST = [0, 60, 0, 0, 0] MEASUREMENT = ['more cups', 'more eggs', 'more tbsp', 'more tsp', 'more cups'] MACARONS_STATEMENT = "Adorable sandwich cookies coming right up!" NOTHING = 'NOTHING' NUMBER_LIST = [1, 2, 3, 4] OVERSPENT = "You ran out of money!" ONE = 1 PURCHASE_QUESTION = 'What would you like to purchase (ENTER "NOTHING" to leave store) ' QUANTITY_QUESTION_PART_ONE = 0 QUANTITY_QUESTION_PART_TWO = 1 QUANTITY_QUESTION_PART_THREE = 2 QUESTION_LIST = ["Begin the baguette dough", "Make the macarons", "make the croissants", "bake the baguettes"] REMAINING_TASKS_TITLE = "Here are your remaining tasks of the day " TWO = 2 THREE = 3 WE_NEEDED = 'We needed:' WINNER = "All done! Let's hope we've PRUEven ourselves worthy." WRONG_BAKING_RESPONSE = "Whoa, we should probably do everything else first!" ZERO = 0 STARTING_FUNDS = 80.0 BUTTER_COST_PER_PACK = 1.25 BUTTER_REQUIRED = 144.0 TBSP_BUTTER_PER_PACK = 64.0 FLOUR_COST_PER_BAG = 2.5 CUPS_FLOUR_PER_BAG = 25.0 FLOUR_REQUIRED = 48.0 + 112.5 EGGS_COST_PER_CRATE = 1.9 EGGS_PER_CRATE = 24.0 EGGS_REQUIRED = 12.0 + 60.0 YEAST_COST_PER_BAG = 3.25 CUP_YEAST_PER_BAG = 6.0 YEAST_REQUIRED = 39 + 50 MILK_COST_PER_JUG = 2.75 GALLONS_MILK_PER_JUG = 1.0 MILK_REQUIRED = 18.0 CUPS_IN_GALLON = 16 TSP_IN_CUP = 48 def print_shopping_list(): """ Prints the ingredients that are required for the user to purchase as well as its budget. :return: none """ starting_funds = str(STARTING_FUNDS) print(INTRO + starting_funds + COLON) print() # for-loop that will print out each ingredient as well as the quantity for list_value in range(len(DISHES_LIST)): print(ING_INTRO, DISHES_QUANTITY[list_value], DISHES_LIST[list_value] + COLON) if list_value == CROISSANTS: for ingredients_list_value in range(len(CROISSANTS_ING_QUANTITY_LIST)): if CROISSANTS_ING_QUANTITY_LIST[ingredients_list_value] != 0: print(INDENT, CROISSANTS_ING_QUANTITY_LIST[ingredients_list_value], INGREDIENTS_DESCRIPTION_LIST[ingredients_list_value]) print() if list_value == MACARONS: for ingredients_list_value in range(len(MACARONS_ING_QUANTITY_LIST)): if MACARONS_ING_QUANTITY_LIST[ingredients_list_value] != 0: print(INDENT, MACARONS_ING_QUANTITY_LIST[ingredients_list_value], INGREDIENTS_DESCRIPTION_LIST[ingredients_list_value]) print() if list_value == BAGUETTES: for ingredients_list_value in range(len(BAGUETTES_ING_QUANTITY_LIST)): if BAGUETTES_ING_QUANTITY_LIST[ingredients_list_value] != 0: print(INDENT, BAGUETTES_ING_QUANTITY_LIST[ingredients_list_value], INGREDIENTS_DESCRIPTION_LIST[ingredients_list_value]) print() def nowhitespace(input_response): """ This function removes all of the white spaces of any statement :param input_response: This parameter represents the word you would like to remove all of the white spaces from :return: the parameter as a single word """ input_response = input_response.strip() input_response = input_response.split() input_response = INDENT.join(input_response) return input_response def go_shopping(): """ This function will ask the user what they would like to purchase. It will also ask for the quantity of the specific item and record it. It will print out a over budget statement if the user went over budget. :return: one list that contains all the ingredients amount. The items are classified by using a sub-list. """ flour_shopping_list = [] egg_shopping_list = [] butter_shopping_list = [] yeast_shopping_list = [] milk_shopping_list = [] shopping_list = [flour_shopping_list] + [egg_shopping_list] + \ [butter_shopping_list] + [yeast_shopping_list] + \ [milk_shopping_list] starting_funds = 80.0 ask_ingredients = BUTTER print(GREETING) # while-loop that will continue looping until the input is "NOTHING" or # its funds are less than zero while (ask_ingredients.upper() != NOTHING) and (starting_funds >= 0): ask_ingredients = nowhitespace(input(PURCHASE_QUESTION)) ask_ingredients = ask_ingredients.lower() if ask_ingredients.upper() == NOTHING: print() elif (ask_ingredients not in INGREDIENTS) or (ask_ingredients == INDENT): print(INVALID_ENTRY) # for loop that validates the user's input and finds the correct follow-up question for list_value in range(len(INGREDIENTS)): if INGREDIENTS[list_value] == ask_ingredients: ask_quantity = INDENT while (ask_quantity == INDENT) or (float(ask_quantity) < 0.0): ask_quantity = nowhitespace(input(ASK_QUANTITY_QUESTION[QUANTITY_QUESTION_PART_ONE] + INGREDIENT_DESCRIPTION[list_value] + ASK_QUANTITY_QUESTION[QUANTITY_QUESTION_PART_TWO] + INGREDIENTS[list_value] + ASK_QUANTITY_QUESTION[QUANTITY_QUESTION_PART_THREE])) if ask_quantity == INDENT or float(ask_quantity) < 0: print(INVALID_ENTRY) elif float(ask_quantity) > 0.0: # finds the correct ingredient and calculates its cost and # appends the quantity to its specific list for ingredient_value in range(1): if ask_ingredients == INGREDIENTS[ingredient_value]: starting_funds = starting_funds - (float(ask_quantity) * FLOUR_COST_PER_BAG) flour_shopping_list.append(ask_quantity) elif ask_ingredients == INGREDIENTS[ingredient_value + ONE]: starting_funds = starting_funds - (float(ask_quantity) * EGGS_COST_PER_CRATE) egg_shopping_list.append(ask_quantity) elif ask_ingredients == INGREDIENTS[ingredient_value + TWO]: starting_funds = starting_funds - (float(ask_quantity) * BUTTER_COST_PER_PACK) butter_shopping_list.append(ask_quantity) elif ask_ingredients == INGREDIENTS[ingredient_value + THREE]: starting_funds = starting_funds - (float(ask_quantity) * YEAST_COST_PER_BAG) yeast_shopping_list.append(ask_quantity) elif ask_ingredients == INGREDIENTS[ingredient_value + FOUR]: starting_funds = starting_funds - (float(ask_quantity) * MILK_COST_PER_JUG) milk_shopping_list.append(ask_quantity) if starting_funds < 0.0: print(OVERSPENT) print() return shopping_list def check_items_enough(shopping_cart): """ A function that will determine if the user has enough ingredients. If they do not, then it will print out how much they still need :param shopping_cart: A list of all of the imputed values :return: returns false if they don't have enough in ingredients. Returns true if the user does have enough ingredients """ difference_list = [] # for-loop that finds the total quantity amount of each ingredient (sublist) for first_list_value in range(len(shopping_cart)): total = 0.0 for second_list_value in range(len(shopping_cart[first_list_value])): list_value = float(shopping_cart[first_list_value][second_list_value]) total = total + list_value # for-loop that finds ingredient that corresponds to the value # and convert the value (if necessary) to cups or tsp and # will calculate its difference if its less than the required amount for num in range(1): if first_list_value == num: total_flour_cups = total * CUPS_FLOUR_PER_BAG if total_flour_cups < FLOUR_REQUIRED: ingredient_difference = FLOUR_REQUIRED - total_flour_cups difference_list.append(ingredient_difference) print(DIDNT_BUY_ENOUGH, INGREDIENTS[first_list_value] + EXCLAMATION_POINT, WE_NEEDED, ingredient_difference, MEASUREMENT[first_list_value]) elif first_list_value == num + ONE: total_eggs = total * EGGS_PER_CRATE if total_eggs < EGGS_REQUIRED: ingredient_difference = EGGS_REQUIRED - total_eggs difference_list.append(ingredient_difference) print(DIDNT_BUY_ENOUGH, INGREDIENTS[first_list_value] + EXCLAMATION_POINT, WE_NEEDED, ingredient_difference, MEASUREMENT[first_list_value]) elif first_list_value == num + TWO: total_butter = total * TBSP_BUTTER_PER_PACK if total_butter < BUTTER_REQUIRED: ingredient_difference = BUTTER_REQUIRED - total_butter difference_list.append(ingredient_difference) print(DIDNT_BUY_ENOUGH, INGREDIENTS[first_list_value] + EXCLAMATION_POINT, WE_NEEDED, ingredient_difference, MEASUREMENT[first_list_value]) elif first_list_value == num + THREE: total_yeast = total * CUP_YEAST_PER_BAG total_yeast *= float(TSP_IN_CUP) if total_yeast < YEAST_REQUIRED: ingredient_difference = float(YEAST_REQUIRED) - total_yeast difference_list.append(ingredient_difference) print(DIDNT_BUY_ENOUGH, INGREDIENTS[first_list_value] + EXCLAMATION_POINT, WE_NEEDED, ingredient_difference, MEASUREMENT[first_list_value]) elif first_list_value == num + FOUR: total_milk = total * GALLONS_MILK_PER_JUG total_milk *= float(CUPS_IN_GALLON) if total_milk < MILK_REQUIRED: ingredient_difference = MILK_REQUIRED - total_milk difference_list.append(ingredient_difference) print(DIDNT_BUY_ENOUGH, INGREDIENTS[first_list_value] + EXCLAMATION_POINT, WE_NEEDED, ingredient_difference, MEASUREMENT[first_list_value]) if len(difference_list) > 0: print(FAILURE) return False else: return True def is_valid_input(index, tasks): """ determines whether the user input is valid in the bake() function given the list of supplied tasks. :param index: represents the length of the list :param tasks: represents the list of the task values :return: true if the index is valid and false if index is not valid """ if FLOAT in index: print(INVALID_ENTRY) return False index = int(index) word_value = index - 1 if (index > len(tasks)) or (index < ZERO): print(INVALID_ENTRY) return False if (len(tasks) <= THREE) and (len(tasks) > ONE): if tasks[word_value] == QUESTION_LIST[THREE]: print(WRONG_BAKING_RESPONSE) return False else: if tasks[word_value] == QUESTION_LIST[ONE]: print(MACARONS_STATEMENT) return True else: print(CROISSANTS_STATEMENT) return True elif QUESTION_LIST[ZERO] in tasks and len(tasks) > THREE: if tasks[word_value] == QUESTION_LIST[ZERO]: print(BAGUETTE_DOUGH_STATEMENT) return True else: print(BAGUETTES_NOT_FIRST) return False else: return True def print_task_list(tasks_remaining): """ prints the tasks that are remaining for the user to do in the bake() function :param tasks_remaining: a list of the menu options :return: none """ for list_value in range(len(tasks_remaining)): print(str(list_value + 1) + DASH + tasks_remaining[list_value]) def bake(): """ presents the user with a list of tasks and asks to perform them in the correct order :return: none """ question_list_copy = ["Begin the baguette dough", "Make the macarons", "make the croissants", "bake the baguettes"] print(BAKE_INTRODUCTION) # this while loop will remain true until there isn't any more tasks # to perform while len(question_list_copy) > 0: print(REMAINING_TASKS_TITLE) print_task_list(question_list_copy) bake_action = nowhitespace(input(BAKE_QUESTION)) if is_valid_input(bake_action, question_list_copy): question_list_copy.remove(question_list_copy[int(bake_action) - 1]) print(WINNER) if __name__ == "__main__": print_shopping_list() shopping_list_valid = check_items_enough(go_shopping()) if shopping_list_valid: bake()
a = 1 while a == 1: num = int(input("\nDigite um numero: ")) if num < 0: print("NEGATIVO") else: print("POSITIVO")
#Faça um programa que calcule o volume de um cilindro area = raio * raio * 3.14 volume = area * altura raio = float(input("Digite o raio: ")) altura = float(input("Digite a altura: ")) area = raio * raio * 3.14 volume = area * altura print("O volume do seu cilindro é de: {}m³".format(volume))
# -*- coding: utf-8 -*- """68""" import pymongo def main(): client = pymongo.MongoClient() db = client.monDB col = db.artist_data artists = col.find({u'tags.value':"dance"}).sort('rating.count',pymongo.DESCENDING).limit(10) for i,artist in enumerate(artists, start=1): print '{}\t{}\t{}'.format(i, artist.get('rating').get('count'), artist.get('name')) # 順位,投票数,アーティスト名 をタブ区切りで表示 if __name__ == '__main__': main() """ $ python 68.py 1 26 Madonna 2 23 Björk 3 23 The Prodigy 4 15 Rihanna 5 13 Britney Spears 6 11 Maroon 5 7 7 Adam Lambert 8 7 Fatboy Slim 9 6 Basement Jaxx 10 5 Cornershop """
# 05 # -*- coding: utf-8 -*- #terminal入力 #s = raw_input('Please input string > ') #n = input('Please input n > ') s = 'I am an NLPer' n = 2 def w_n_gram(s,n): w_list = s.split( ) w_gram = [] for i in range(len(w_list)): w_gram.append(w_list[i:i+n]) return w_gram def c_n_gram(s,n): c_gram = [] for i in range(len(s)): c_gram.append(s[i:i+n]) return c_gram print 'word_' + str(n) +'-gram:' print w_n_gram(s,n) print 'character_' + str(n) +'-gram:' print c_n_gram(s,n)
str1="yogeeeshijaa" print(str1.count("e")) print(str1.count("a")) print(str1.count("i")) print(str1.count("o")) print(str1.count("u"))
base,height=input("Enter base,height : ").split(",") base,height=int(base),int(height) print(0.5*base*height)
""" import re compile : understand the pattern search : finding something into a slelected string findall : find all matching values """ import re ob= re.compile(r'\d\d-\d"{10}') result=ob.search(" hello 91-9166371779") #print(result.group()) link="adhdf,fflgcgjlgjcfg;fkgmc,www.google.com,fjdslgdrgjrdlogdjgoierg,www.yahoo.com" r1=re.findall(r'[\w\.]+[\w\.]+com',link) for i in r1: print(i)
num=int(input("Enter the number :")) fact =1 while num: fact*=num num=num-1 print(fact)
from math import atan, inf, degrees, sqrt, acos, pi class Point: def __init__(self, x, y): self.x = x self.y = y class Vector2D: def __init__(self, x, y): self.x = x self.y = y def mag(self): return sqrt(dot(self, self)) def dir(self): return Vector2D(self.x / self.mag(), self.y / self.mag()) def toAngle(self): if self.x != 0: return atan(self.y / self.x) else: return atan(inf * self.y) class Triangle: def __init__(self, points): self.p1 = Point(points[0], points[1]) self.p2 = Point(points[2], points[3]) self.p3 = Point(points[4], points[5]) self.s1 = Vector2D(self.p2.x - self.p1.x, self.p2.y - self.p1.y) self.s2 = Vector2D(self.p3.x - self.p2.x, self.p3.y - self.p2.y) self.s3 = Vector2D(self.p1.x - self.p3.x, self.p1.y - self.p3.y) def to_origin(p): return Vector2D(p.x, p.y) def dot(v1, v2): return v1.x * v2.x + v1.y * v2.y def angle(v1, v2): if v1.x != 0 and v1.y != 0 and v2.x != 0 and v2.y != 0: return acos(dot(v1, v2) / (v1.mag() * v2.mag())) else: return 0 def contains_origin(t): ang1 = angle(t.s1, to_origin(t.p1)) ang2 = angle(to_origin(t.p2), t.s2) ang3 = angle(t.s2, t.s3) ang4 = angle(t.s3, t.s1) # ang1 = min(ang1, pi - ang1) # ang2 = min(ang2, pi - ang2) # ang3 = min(ang3, pi - ang3) # ang4 = min(ang4, pi - ang4) print(degrees(ang1), degrees(ang2), degrees(ang3), degrees(ang4), degrees(ang1 + ang2 + ang3 + ang4)) return ang1 + ang2 + ang3 + ang4 == 2 * pi triangles = [] f = open('p102_trianglessample.txt', 'r') for line in f.readlines(): line = line if line[-1] != '\n' else line[:-1] triangles.append(Triangle(list(map(int, line.split(','))))) f.close() for t in triangles: print(t.s1.dir().x, t.s1.dir().y) print(degrees(t.s1.dir().toAngle())) print() print(t.s2.dir().x, t.s2.dir().y) print(degrees(t.s2.dir().toAngle())) print() print(t.s3.dir().x, t.s3.dir().y) print(degrees(t.s3.dir().toAngle())) print() # print(degrees(angle(t.s1, t.s2))) # print(degrees(angle(t.s2, t.s3))) # print(degrees(angle(t.s3, t.s1))) print(contains_origin(t))
''' Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' def sum_of_div_by_3_and_5(limit=1000): return sum(x for x in range(limit) if div_by_3_and_5(x)) def div_by_3_and_5(num): return num % 3 == 0 or num % 5 == 0 print(sum_of_div_by_3_and_5(1000))
#author: vysakh # for using creation of complex objects # Have 4 parts #1. Director #2. Abstract Class #3. Concrete Class #4. Product class Director(): """Director Class""" def __init__(self, builder): self._builder = builder def create_car(self): self._builder.create_new_car() self._builder.add_model() self._builder.add_tire() self._builder.add_engine() def get_car(self): return self._builder.car class Builder(): """Abstract Class""" def __init__(self): self.car = None def create_new_car(self): self.car = Car() class FordBuilder(Builder): """Concrete Class""" def add_model(self): self.car.model = "Ford" def add_tire(self): self.car.tire = "F tires" def add_engine(self): self.car.engine = 'F engine' class Car(): """Product Class""" def __init__(self): self.model = None self.tire = None self.engine = None def __str__(self): return "{}|{}|{}".format(self.model,self.tire,self.engine) ford = FordBuilder() director = Director(ford) director.create_car() car = director.get_car() print(car)
''' author: SryMkr date: 2021.10.12 The library consists of some basic functions to support Snake Game ''' # import packages import pygame import random import numpy as np from Snake_food_library import MySprite_food # 26 alphabet ALPHABET_LIST = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # the width of one frame FRAME_WIDTH = 30 # add correct alphabet,正确单词图片主要是要添加在蛇尾部 class Snakebody_alphabet(MySprite_food): def __init__(self, frame_nuber): MySprite_food.__init__(self) self.load_multi_frames("Game_Pictures/NEW_AL1.png", FRAME_WIDTH, FRAME_WIDTH, 13) self.draw_current_frame(frame_nuber) # add wrong alphabet,错误单词图片在这修改主要是添加在蛇尾部 class wrong_alphabet(MySprite_food): def __init__(self, frame_nuber): MySprite_food.__init__(self) self.load_multi_frames("Game_Pictures/NEW_AL1.png", FRAME_WIDTH, FRAME_WIDTH, 13) self.draw_current_frame(frame_nuber) # show general texts on the screen 主要是在屏幕上显示 def print_text(font_size, x_coordinate, y_coordinate, text, color=(0, 0, 0)): # return a surface text_img = font_size.render(text, True, color) # get window/screen/display surface return surface screen = pygame.display.get_surface() # built surface onto screen screen.blit(text_img, (x_coordinate, y_coordinate)) # show game results of screen,最多只能训练20个单词,主要是游戏结束以后显示玩家已经记住的单词 这里其实可以显示正确的,玩家自己拼写的,以及汉语翻译 def print_result(font_size, x_start, y_start, list, color=(0,0,0)): # get window/screen/display surface return surface screen = pygame.display.get_surface() # show the completed English words for text in list: # return a surface text_img = font_size.render(text, True, color) # draw result one by one screen.blit(text_img, (x_start, y_start)) # change the x coordinate x_start += 240 # change the y coordinate if x_start > 30 * 16: x_start = 0 y_start += 120 # get index of words task 现在是直接把所有的单词保留进去,单词编号,第几个字母编号,以及单词在字母表中的编号 '1-1': 14 # get the counterpart index of alphabet def built_spelling_dic(task_list, alphabet_list): # create empty dictionary spelling_dic = {} # spelling index spelling_index = 1 # task index task_index = 1 # reture an alphabet dictionary for show correct alphabet for word in task_list: word = word.lower() word = word.strip() for correct_spelling in word: # find out every alphabet index alphabet_index = alphabet_list.index(correct_spelling) # built dictionary spelling_dic["{}-{}".format(task_index, spelling_index)] = alphabet_index # alphabet number plus 1 只是为了保证字典键值唯一,其他作用有待开发 spelling_index += 1 # word number plus 1 # word_index is to track current word task task_index += 1 # return dictionary return spelling_dic # set audio of game 游戏声音 def game_audio(filename,volumn=0.1,times = 0): #initialize the mixer pygame.mixer.init() # get the sound file sound = pygame.mixer.Sound(filename) # force to find a channel channel = pygame.mixer.find_channel(True) # set music volume channel.set_volume(volumn) # directly play once call channel.play(sound,times) # 获得菜单里输入的各种参数 def game_play_setting(variables): return variables.get_value() # 最多有三个干扰选项,加一个提示的位置,加一个正确选项,一共就是6个位置 # for three different position of three different food # in case they overlap # the food cannot have the same axe coordinate with snake head def food_random_position(snake_head_x_coordinate,snake_head_y_coordinate,wrong_letters_num): # create x coordinate list x_coordinate_list = list(np.arange(0, 27)*FRAME_WIDTH) # avoid occasional snake head contact x_coordinate_list.remove(snake_head_x_coordinate) # create y coordinate list y_coordinate_list = list(np.arange(6, 24)*FRAME_WIDTH) # avoid occasional snake head contact y_coordinate_list.remove(snake_head_y_coordinate) # randomly choose three x coordinate x_coordinate = random.sample(x_coordinate_list, wrong_letters_num) # randomly choose three y coordinate y_coordinate = random.sample(y_coordinate_list, wrong_letters_num) # return the x, y coordinate return x_coordinate, y_coordinate # define two variate with two method respectively 设定两个变量,控制蛇的方向 class two_Variate(object): # define two private variates def __init__(self, variate_one, variate_two): self.__x = variate_one self.__y = variate_two # get first variate def get_variate_one(self): return self.__x # set first variate def set_variate_one(self, x): self.__x = x # the function of property is to allow variate_one have the two method # automatically trigger when calling # (property has claimed the class property # therefore, there is not self before first_variate) first_variate = property(get_variate_one, set_variate_one) # get second variate def get_variate_two(self): return self.__y # set second variate def set_variate_two(self, y): self.__y = y # the function of property is to allow variate_one have the two method # automatically trigger when calling second_variate = property(get_variate_two, set_variate_two)
# -*- coding: utf-8 -*- import unittest import main class MyTest(unittest.TestCase):#继承unittest.TestCase def setUp(self): print("正在建立初始化连接......") print("") def tearDown(self): print("") print(u"该条用例执行完毕,启动退出程序") #球员升级 def test_PlayerUpgrade(self): try: self.assertEqual(main.result[16].playerRespVo.instance.level,40) print("球员升级无误") except Exception as e: print("用例执行失败原因:",main.result[16]) raise e #球员升星1:星级 def test_PlayerUpstar1(self): try: self.assertEqual(main.result[17].playerRespVo.instance.star, 1) print("球员升星 星级无误") except Exception as e: print("用例执行失败原因:", main.result[17]) raise e # 球员升星2:道具消耗 def test_PlayerUpstar2(self): try: self.assertEqual(main.result[17].property.num, 315) print("球员升星 道具消耗无误") except Exception as e: print("用例执行失败原因:", main.result[17]) raise e # 球员升星3:欧元消耗 def test_PlayerUpstar3(self): try: self.assertEqual(main.result[17].coin+9000, main.result[13].teamInfoAndPropListRespVo.gameTeamInfo.coin) print("球员升星 欧元消耗无误") except Exception as e: print("用例执行失败原因:", main.result[17]) raise e #装备升级1:装备等级 def test_EquipUpLevel1(self): try: self.assertEqual(main.result[18].equipmentRespVo.equipRespVo.level, 2) print("装备升级 等级无误") except Exception as e: print("用例执行失败原因:", main.result[18]) raise e # 装备升级2:装备扣除欧元 def test_EquipUpLevel2(self): try: self.assertEqual(main.result[18].equipmentRespVo.gameTeamInfoRespVo.coin+75,main.result[17].coin ) print("装备升级 扣除欧元无误") except Exception as e: print("用例执行失败原因:", main.result[18]) raise e #球员特训1:扣除道具 def test_PlayerTrain1(self): try: self.assertEqual(main.result[19].gameProperty.num, 9994) print("球员特训 扣除道具无误") except Exception as e: print("用例执行失败原因:", main.result[19]) raise e # 球员特训2:特训数值 def test_PlayerTrain2(self): try: self.assertEqual(main.result[19].instance.attr.shemen-2, main.result[17].playerRespVo.attr.shemen) print("球员特训 特训数值无误") except Exception as e: print("用例执行失败原因:", main.result[19]) raise e #默契升级1:默契等级 def test_UPT1(self): try: self.assertEqual(main.result[20].totalTacitLevel,2) print("球员默契升级无误") except Exception as e: print("用例执行失败原因:", main.result[20]) raise e #默契升级2:道具消耗 def test_UPT2(self): try: self.assertEqual(main.result[20].propRespVo[0].propNum, 9997) print("球员默契升级道具消耗无误") except Exception as e: print("用例执行失败原因:",main.result[20]) raise e
## String Pattern Matching ## # Time: O(mn) worst case; O(m+n) avg case # Space: O(1) def match(text, pattern): for i in range(0, len(text)-len(pattern)): j = 0 while j < len(pattern) and text[i+j]==pattern[j]: j += 1 if j == len(pattern): return i return -1 print(match('somebirdsarenotmeanttobecaged', 'bird')) print(match('somebirdsarenotmeanttobecaged', 'meag'))
class Solution: def shortestDistance(self, words: List[str], word1: str, word2: str) -> int: word1_instances = [] word2_instances = [] for i in range(0, len(words)): if words[i] == word1: word1_instances.append(i) if words[i] == word2: word2_instances.append(i) min_dif = 99999 for i in word1_instances: for j in word2_instances: if abs(i - j) < min_dif: min_dif = abs(i - j) return min_dif
import time import datetime def agent(LinkedList): ''' Agent function that traverses a linked list and sets the status of all nodes with TTL <= 0 to inactive ''' while True: time.sleep(2) if LinkedList.startNode is None: return else: n = LinkedList.startNode while n is not None: TTL = (n.TTL - datetime.datetime.now()).total_seconds() if TTL <= 0: n.status = 'inactive' n = n.next
""" 1. Initialize the cells in the grid. 2. At each time step in the simulation, for each cell (i, j) in the grid, do the following: a. Update the value of cell (i, j) based on its neighbors, taking into account the boundary conditions. b. Update the display of grid values. extras-toroidal boundary conditions? -GUI buttons to reset/start/pause -preset patterns you can use without having to draw them out """ #attempt to make a grid import pygame #Constants for the grid design def gridinitialise(): # 10x10 matrix filled with zeros grid=[] for row in range(51): grid.append([]) for column in range(101): grid[row].append(0) pygame.init() return grid def gridCalculate(grid): sumarray=[] for row in range(50): sumarray.append([]) for column in range(100): sum=((grid[row+1][column+1])+(grid[row][column+1])+(grid[row+1][column])+(grid[row-1][column-1])+(grid[row][column-1])+(grid[row-1][column])+(grid[row+1][column-1])+(grid[row-1][column+1])) sumarray[row].append(sum) #print(sumarray) #this bit is changing the grid array so that values which should be changed according to conways rules change from 1 to 0 or vice-versa #currently sum is accurately calculating the number of adjacent lit squares for each square, but isnt changing the grid array for row in range(50): for column in range(100): if grid[row][column]==1: if sumarray[row][column]<=1: grid[row][column]=0 elif sumarray[row][column]>=4: grid[row][column]=0 else: if sumarray[row][column]==3: grid[row][column]=1 return grid #game logic here # #screen clear code here def graphicprint(WHITE,BLACK,RED,margin,width,height,screen,clock,grid): screen.fill(BLACK) for row in range(50): for column in range(100): colour=WHITE if grid[row][column]==1: colour = RED pygame.draw.rect(screen,colour,(((margin+width)*column +margin),((margin+height)*row +margin),width,height)) clock.tick(10)#tick speed pygame.display.flip() def clickgraphicprint(WHITE,BLACK,RED,margin,width,height,screen,grid): done=False while not done: for event in pygame.event.get(): # User did something if event.type == pygame.KEYDOWN: if event.key==pygame.K_RETURN:# If user clicked close done = True # Flag that we are done so we exit this loop elif event.type == pygame.MOUSEBUTTONDOWN: # User clicks the mouse. Get the position pos = pygame.mouse.get_pos() # Change the x/y screen coordinates to grid coordinates column = pos[0] // (width + margin) row = pos[1] // (height + margin) # Set that location to one if grid[row][column] == 1: grid[row][column]=0 else: grid[row][column]=1 screen.fill(BLACK) for row in range(50): for column in range(100): colour=WHITE if grid[row][column]==1: colour = RED pygame.draw.rect(screen,colour,(((margin+width)*column +margin),((margin+height)*row +margin),width,height)) pygame.display.flip() return grid def main(): #print("checkpoint 1") BLACK = (0,0,0) WHITE=(255,255,255) RED=(255,0,0) windowheight=650 windowwidth=900 size =(windowwidth,windowheight) screen = pygame.display.set_mode(size) pygame.display.set_caption("my game") done = False clock = pygame.time.Clock() width =10 height=10 margin=2 grid = gridinitialise() grid=clickgraphicprint(WHITE,BLACK,RED,margin,width,height,screen,grid) """ for event in pygame.event.get(): if event.type==pygame.KEYDOWN: if event.key==pygame.K_RETURN: """ while not done: graphicprint(WHITE,BLACK,RED,margin,width,height,screen,clock,grid) gridCalculate(grid) for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop #print(grid) pygame.quit() if __name__ == "__main__": main()
''' Grouping the data based on the Columns and performing Aggregate Functions over it. Aggregate Functions like sum,avg,min,max,count,mean etc ''' from pyspark.sql import SparkSession from pyspark.sql.functions import sum, avg, max, min, mean, count, col if __name__ == "__main__": spark = SparkSession.builder \ .appName("grouping and Aggregation") \ .master("local[3]") \ .getOrCreate() simpleData = [("James", "Sales", "NY", 90000, 34, 10000), ("Michael", "Sales", "NY", 86000, 56, 20000), ("Robert", "Sales", "CA", 81000, 30, 23000), ("Maria", "Finance", "CA", 90000, 24, 23000), ("Raman", "Finance", "CA", 99000, 40, 24000), ("Scott", "Finance", "NY", 83000, 36, 19000), ("Jen", "Finance", "NY", 79000, 53, 15000), ("Jeff", "Marketing", "CA", 80000, 25, 18000), ("Kumar", "Marketing", "NY", 91000, 50, 21000) ] schema = ["employee_name", "department", "state", "salary", "age", "bonus"] df = spark.createDataFrame(data=simpleData, schema=schema) df.printSchema() ''' root |-- employee_name: string (nullable = true) |-- department: string (nullable = true) |-- state: string (nullable = true) |-- salary: long (nullable = true) |-- age: long (nullable = true) |-- bonus: long (nullable = true) ''' df.show(truncate=False) ''' +-------------+----------+-----+------+---+-----+ |employee_name|department|state|salary|age|bonus| +-------------+----------+-----+------+---+-----+ |James |Sales |NY |90000 |34 |10000| |Michael |Sales |NY |86000 |56 |20000| |Robert |Sales |CA |81000 |30 |23000| |Maria |Finance |CA |90000 |24 |23000| |Raman |Finance |CA |99000 |40 |24000| |Scott |Finance |NY |83000 |36 |19000| |Jen |Finance |NY |79000 |53 |15000| |Jeff |Marketing |CA |80000 |25 |18000| |Kumar |Marketing |NY |91000 |50 |21000| +-------------+----------+-----+------+---+-----+ ''' ''' Get the Sum of Salary of Each Department or Department wise Total Salary. For this we will have to first Group the Data based on the Department and then use sum to get the Salary ''' df.groupBy("department").sum("salary").show() ''' +----------+-----------+ |department|sum(salary)| +----------+-----------+ | Sales| 257000| | Finance| 351000| | Marketing| 171000| +----------+-----------+ ''' ''' Get the Average Salary of each Department or Department wise average Salary. ''' df.groupBy("department").avg("salary").show() ''' +----------+-----------------+ |department| avg(salary)| +----------+-----------------+ | Sales|85666.66666666667| | Finance| 87750.0| | Marketing| 85500.0| +----------+-----------------+ ''' ''' #Get the Number of Employee in Each Department or Department wise Number of Employees #Apply GroupBy on the Department and then use count to get the Number of Employee ''' df.groupBy("department").count().show() ''' +----------+-----+ |department|count| +----------+-----+ | Sales| 3| | Finance| 4| | Marketing| 2| +----------+-----+ ''' ''' Get the Department wise min/max salary ''' df.groupBy("department").min("salary").show() ''' +----------+-----------+ |department|min(salary)| +----------+-----------+ | Sales| 81000| | Finance| 79000| | Marketing| 80000| +----------+-----------+ ''' df.groupBy("department").max('salary').show() ''' +----------+-----------+ |department|max(salary)| +----------+-----------+ | Sales| 90000| | Finance| 99000| | Marketing| 91000| +----------+-----------+ ''' df.groupBy("department").agg( min("salary"), max("salary") ).show() ''' +----------+-----------+-----------+ |department|min(salary)|max(salary)| +----------+-----------+-----------+ | Sales| 81000| 90000| | Finance| 79000| 99000| | Marketing| 80000| 91000| +----------+-----------+-----------+ ''' ''' GroupBy and Aggregate Function on multiple columns Get the Department wise Total salary and Total Bonus in each State ''' df.groupBy("department", "state") \ .sum("salary", "bonus") \ .show() ''' +----------+-----+-----------+----------+ |department|state|sum(salary)|sum(bonus)| +----------+-----+-----------+----------+ | Finance| NY| 162000| 34000| | Marketing| NY| 91000| 21000| | Sales| CA| 81000| 23000| | Marketing| CA| 80000| 18000| | Finance| CA| 189000| 47000| | Sales| NY| 176000| 30000| +----------+-----+-----------+----------+ ''' ''' Performing Multiple Aggregation at a Time To perform multiple aggregation all at a time, We can use agg() function. Example: Department wise min,max,avg and total(sum) salary ''' df.groupBy("department") \ .agg(sum("salary").alias("sum_salary"), avg("salary").alias("avg_salary"), sum("bonus").alias("sum_bonus"), max("bonus").alias("max_bonus"), min("salary").alias("minSalary"), mean("salary").alias("MeanValue"))\ .show(truncate=False) ''' +----------+----------+-----------------+---------+---------+---------+-----------------+ |department|sum_salary|avg_salary |sum_bonus|max_bonus|minSalary|MeanValue | +----------+----------+-----------------+---------+---------+---------+-----------------+ |Sales |257000 |85666.66666666667|53000 |23000 |81000 |85666.66666666667| |Finance |351000 |87750.0 |81000 |24000 |79000 |87750.0 | |Marketing |171000 |85500.0 |39000 |21000 |80000 |85500.0 | +----------+----------+-----------------+---------+---------+---------+-----------------+ ''' ''' Using Filter on Aggregate Data Find the Department wise total salary,average salary,total Bonus, maximum bonus Minimum Salary where total bonus is Greater than 50000. ''' df.groupBy("department") \ .agg(sum("salary").alias("sum_salary"), avg("salary").alias("avg_salary"), sum("bonus").alias("sum_bonus"), max("bonus").alias("max_bonus"), min("salary").alias("minSalary"), mean("salary").alias("MeanValue")) \ .where(col("sum_bonus") > 50000) \ .show(truncate=False) ''' +----------+----------+-----------------+---------+---------+---------+-----------------+ |department|sum_salary|avg_salary |sum_bonus|max_bonus|minSalary|MeanValue | +----------+----------+-----------------+---------+---------+---------+-----------------+ |Sales |257000 |85666.66666666667|53000 |23000 |81000 |85666.66666666667| |Finance |351000 |87750.0 |81000 |24000 |79000 |87750.0 | +----------+----------+-----------------+---------+---------+---------+-----------------+ '''
def new_alph(ch): ch = ch.lower() alph = 'abcdefghijklmnopqrstuvwxyz' new_alph = alph[alph.index(ch):] + alph[:alph.index(ch)] return new_alph def encrypt(text, big_key): res = '' alph = 'abcdefghijklmnopqrstuvwxyz' i = 1 for char in big_key: new = new_alph(char) for t in text: if alph.count(t) == 1 : res += new[alph.index(t)] text = text[i:] break elif alph.count(t.lower()) == 1: res += new[alph.index(t.lower())].upper() text = text[i:] break else: res += t text = text[i:] break i += 1 return res text1 = 'SHRADDHA' text_dec = 'MNOPQRRT' key = 'KEY' if len(key) <= len(text1): big_key = key * (len(text1) // len(key)) + key[:len(text1) % len(key)] text_encrypt = encrypt(text1, big_key) print('PLAIN-TEXT: "' + text1 + '"') print('KEYWORD : "' + key + '"') print('CIPHERTEXT : ' + text_encrypt)
def areAscendingNumbers(txt, numdigits): first = int(txt[0:numdigits]) for i in range(1, len(txt)//numdigits): if int(txt[i*numdigits:(i+1)*numdigits]) != (first + i): return False return True def ascending(txt): if len(txt) <= 1: return False for numdigits in range(1, len(txt)//2 + 1): if len(txt) % numdigits == 0: if areAscendingNumbers(txt, numdigits): return True return False
def drawboard(ashish): ashish = int(ashish) i = 0 ho = "--- " ve = "| " ho = ho * ashish ve = ve * (ashish+1) while i < ashish+1: print(ho) if not (i == ashish): print(ve) i += 1
def jumping_frog(n, stones): jumps = {0: 1} queue = [0] while len(queue) > 0: cur = queue.pop(0) jump = stones[cur] if cur + jump >= n: return jumps[cur] + 1 if cur + jump == n - 1: return jumps[cur] + 2 if cur + jump not in jumps: jumps[cur + jump] = jumps[cur] + 1 queue.append(cur + jump) if cur - jump > 0 and cur - jump not in jumps: jumps[cur - jump] = jumps[cur] + 1 queue.append(cur - jump) return "no chance :-("
def digits(number): if number == 1: return 0 a = 0 myans = 0 while number > 1: if number <= 9*10**a: myans += (a+1)*(number-1) number -= number*10**a else: myans += (a+1)*9*10**a number -= 9*10**a a += 1 return myans
# Uses python3 import sys def get_change(money): coin_number = 0 while money > 0: if money >= 10: money = money - 10 print('in 10', coin_number) elif money >= 5: money = money - 5 print('in 5', coin_number) else: money = money - 1 print('in 1', coin_number) coin_number = coin_number + 1 return coin_number if __name__ == '__main__': m = int(sys.stdin.readline()) print(get_change(m)) array = [8, 1, 0, 1] print(array.index())
words = [] result = [] import itertools from itertools import chain with open("e8.txt") as file: for line in file: #lines.append(line.split()) #words = list(itertools.chain.from_iterable(lines)) words = line.strip().split() for element in words: if element not in result: result.append(element) result.sort() print(result)
xh = float(input ("Enter Hours: ")) xr = float(input ("Enter Rate: ")) if xh > 40: bonus_hr = xh - 40.0 bonus = bonus_hr * xr * 0.5 xp = xh * xr + bonus else : xp = xh * xr print("Pay : " , xp)
""" Irj programot, mely beker egy egesz szamot: n. Feltetelezhetjuk, hogy ez pozitiv. Ezt kovetoen kerjen be egesz szamokat addig, amig n db nemnegativ szamot nem kapott. A program a futasa vegen irja ki egy listaban ezeket a szamokat. Pelda bemenet: 3 1 2 3 Pelda kimenet: [1, 2, 3] Pelda bemenet: 3 -1 0 -44 35 -19 -35 1 Pelda kimenet: [0, 35, 1] """ n = int(input()) lista = [] poz = 0 neg = 0 valtozo = 0 while valtozo != n: n2 = int(input()) if n2 < 0: neg = n2 valtozo -=1 if n2 >= 0: poz = n2 lista.append(poz) valtozo+=1 print(lista)
""" Problem 1 Floating Point Operations Per Second """ from time import time from numpy.random import random def flops(seconds): """calculates the number of operations performed in some length of time: returns a tuple ( time_counting_operations, number_of_operations, operations_per_second, ) """ time_computing_operations = 0 number_of_operations = 0 while time_computing_operations < seconds: number_of_operations += 1 float1 = random() float2 = random() t1 = time() float1 * float2 t2 = time() elapsed = t2 - t1 time_computing_operations += elapsed return ( time_computing_operations, number_of_operations, number_of_operations/time_computing_operations, ) _, _, val = flops(1) print(f'floating point operations per second is: {val}')
""" Newman 9.7 The Relaxation Method for Ordinary Differential Equations """ import numpy as np import matplotlib.pyplot as plt # Constant Declaration m = 1 # kg g = 9.81 # m/s^2 tstart = 0 # seconds tstop = 10 # seconds N = 100 # number of points eps = 1.e-6 # desired accuracy timestep = (tstop - tstart)/N # Initialization ts = np.linspace(tstart, tstop, N+1) xs = np.zeros(N+1, float) # Function Definition def iterate(xlist): diff = 1 xs = xlist new_xs = np.empty(N+1, float) # Loop until desired accuracy while diff > eps: new_xs[0] = 0 new_xs[1:N] = (g*timestep*timestep + xs[2:N+1] + xs[0:N-1])/2 # calc new diff & switch values diff = np.max(np.abs(new_xs - xs)) new_xs, xs = xs, new_xs return new_xs # Plotting stuff plt.plot(ts, iterate(xs), label = "Trajectory of Ball") plt.xlabel("Time") plt.ylabel("Height") plt.show()
import numpy as np import matplotlib.pyplot as plt def mandelbrot(divs, number): # initialize array of complex numbers complex_numbers = np.empty((divs, divs), dtype = np.complex128) temp = np.linspace(-number, number, divs).astype(np.complex128) # adding real numbers to array for i in range(divs): complex_numbers[i] = temp # adding imaginary parts complex_numbers = complex_numbers.transpose() for i in range(divs): complex_numbers[i] += temp * 1j # Flip orientation again complex_numbers = complex_numbers.transpose() # Mandelbrot set initiation z = np.zeros((divs, divs), dtype = np.complex128) _mandelbrot = np.empty((divs, divs), dtype = np.uint64) # Begin loop for Mandbrot set for i in range(50): # Equation with numpy arrays z = np.square(z) + complex_numbers # replace values in _mandelbrot with index count where > 2 _mandelbrot[abs(z) > 2] = i """ The following block was inserted to avoid overflows in z, but it runs faster if I comment it out, so... """ # replace values > 2 with 0 to avoid overflows z[abs(z) > 2] = 0 return _mandelbrot plt.imshow( mandelbrot(1000, 2), cmap = 'hot', ) plt.show()
""" Problem #4 Orthog Modification #3 """ import numpy as np from numpy.linalg import norm def orthog(): """finds a vector that is: - Orthogonal to a - Same magnitude as b - In plane made by a & b """ global cross global a global b global dot_product # user input for vectors a = np.array(eval(input("Enter the first vector: "))) b = np.array(eval(input("Enter the second vector: "))) a, b = a.flatten(), b.flatten() # checking that both are 3-D if len(a) == 3 and len(b) == 3: cross = np.cross(a, b) else: print("Make sure you enter 3-D vectors for BOTH") orthog() # checking to see if the two vectors are orthogonal dot_product = np.dot(a, b) if dot_product == 0: return None else: pass # checking that a & b are NOT in same direction if norm(cross) != 0: pass else: print("Make sure both vectors are different directions!") orthog() # finding vector orthogonal to plane of a & b unit = cross/norm(cross) # finding vector orthogonal to unit cross = np.cross(a, unit) result = cross/norm(cross) # making sure vector is same magnitude as b result = unit * norm(b) return list(result) result = orthog() if result == None: print("The two vectors are orthogonal!") else: print(f"Vector orthogonal to a with magnitude of b: {result}")
# Uses python3 from math import sqrt def fib_naive(n): if (n <= 1): return n return fib_naive(n - 1) + fib_naive(n - 2) def fib_fast(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current def fib_instant(n): return int((((1 + sqrt(5)) / 2) ** n - ((1 - sqrt(5)) / 2) ** n) / sqrt(5)) if __name__ == "__main__": n = int(input()) print(fib_fast(n))
from random import randint from timeit import timeit from week1_programming_challenges.max_pairwise_product \ import max_pairwise_product as fast_implementation def slow_implementation(num_array): product = num_array[0] * num_array[1] for i in range(len(num_array)): for j in range(i + 1, len(num_array)): product = max(product, num_array[i] * num_array[j]) return product def test_correctness(max_len_of_array=50, max_num=1000, num_of_tests=1000): for i in range(num_of_tests): len_of_test_array = randint(2, max_len_of_array) test_array = [randint(-max_num, max_num) for _ in range(len_of_test_array)] correct_result = slow_implementation(test_array) tested_result = fast_implementation(test_array) if correct_result == tested_result: print(f"{i} test passed") else: print("Test failed: ", test_array, correct_result, tested_result) return def test_timing(): print(timeit(test_correctness, number=1) / 1000) if __name__ == "__main__": test_timing()
def f(): yield 1 return "hello" print(next(f())) f = f() try: print(next(f)) print(next(f)) print(next(f)) print(next(f)) except StopIteration as e: print(e)
""" 生成器 """ # 生成一个列表 L = [x for x in range(10)] # 打印一下列表的内容和数据 print(L, type(L)) # 生成生成器 G = (x for x in range(10)) # 打印生成器内容 print(G, type(G)) # 需要用next方法获取 print(G.__next__()) print(next(G)) # for 循环获取 for x in G: print(x) # 使用yield得到函数生成器,内部储存斐波拉契数列 def red(num): a = 0 b = 1 # 计数参数默认值为0 index = 0 yield a yield b while index < num: a, b = b, a+b # 返回b yield b # 计数加一 index +=1 for x in red(10): print(x) # 有return yield的函数如何返回值为return中的内容 def test(): yield 1 return "hello" result = test() try: print(next(result)) print(next(result)) except StopIteration as e: print(e) finally: print("end")
# coding=utf-8 # 进阶Python # 高阶函数 import math def add(x, y, f): return f(x) + f(y) print(add(25, 9, math.sqrt)) # map()函数应用,capitalize()首字母大写的函数 def format_name(s): return s.capitalize() print(list(map(format_name, ['adam', 'LISA', 'barT']))) # 用reduce()函数求积 from functools import reduce def prod(x, y): return x * y print(reduce(prod, [2, 4, 5, 7, 12])) # filter()函数过滤出1-100中平方根是整数的数 import math def is_sqr(x): return math.sqrt(x) % 1 == 0 print(list(filter(is_sqr, list(range(1, 101))))) # sorted()自定义排序函数 print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)) # 写一个函数calc_prod(lst),它接收一个list,返回一个函数,返回函数可以计算参数的乘积。 def calc_prod(lst): def plus(x, y): return x * y return reduce(plus, lst) f = calc_prod([1, 2, 3, 4]) print(f) # 匿名函数简化代码 l = lambda x: x and len(x.strip()) > 0 s = filter(l, ['test', None, '', 'str', ' ', 'END']) print(list(s)) print(list(filter(lambda x: x and len(x.strip()) > 0, ['test', None, '', 'str', ' ', 'END']))) # 函数装饰器的应用 # hello.py def now(): print('2015-3-27') # 函数也是对象,将函数now赋值给变量f f = now # f指向函数now,f() = now() print(f.__name__) f() # 将函数值now()赋值给变量f f = now() print(now.__name__) # 装饰器函数的使用解析,编写一个log,f = factorial def log(f): # 创建一个装饰器函数fn,如果调用,fn返回的函数赋给了原函数factorial = fn(factorial),新factorial==f,旧的factorial就被隐藏了。 def fn(x): # 打印日志 print('call ' + f.__name__ + '()...') # 调用原函数也就是factorial() return f(x) return fn @log def factorial(n): return reduce(lambda x, y: x * y, range(1, n + 1)) print(factorial(10)) # 写一个@perfomance的函数,可以打印出函数调用的时间 import time def performance(origin): def showtimes(*args, **kw): print('call ' + origin.__name__ + '() in ' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) return origin(*args, **kw) return showtimes @performance def factorial(n): return reduce(lambda x, y: x * y, range(1, n + 1)) print(factorial(10)) # 编写带参数的decorator,将上述函数增加一个参数,允许传入s或者ms import time def performance(unit): def perf_decorator(f): def wrapper(*args, **kw): t1 = time.time() r = f(*args, **kw) t2 = time.time() t = (t2 - t1) * 1000 if unit == 'ms' else (t2 - t1) print('call %s() in %f %s' % (f.__name__, t, unit)) return r return wrapper return perf_decorator @performance('ms') def factorial(n): return reduce(lambda x, y: x * y, range(1, n + 1)) print(factorial(10)) # python中完善decorator,python中完善decorator import time, functools def perfomance(unit): def perf_decorator(f): @functools.wraps(f) def wrapper(*args, **kw): t1 = time.time() print('call %s() in %s%s' % (f.__name__, t1, unit)) return f(*args, **kw) return wrapper return perf_decorator @performance('ms') def factorial(n): return reduce(lambda x, y: range(n, n + 1)) print(factorial.__name__) # 偏函数的用法,functools.partial import functools sorted_ignore_case = functools.partial(sorted, key=str.lower) print(sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit']))
# 返回函数值mul() def count(): L = [] for i in range(1, 4): def mul(): return i * i L.append(mul()) return L a, b, c = count() print(count()) print(a, b, c) # 返回函数mul,调用的函数并没有进行计算 def count(): L = [] for i in range(1, 4): def mul(): return i * i L.append(mul) return L a, b, c = count() print(count()) print(a(), b(), c()) # 返回函数mul,调用的函数并没有进行计算 def count(): L = [] def mul(n): def j(): return n * n return j for i in range(1, 4): L.append(mul(i)) return L a, b, c = count() print(a()) print(b()) print(c()) # time函数的用法 import time # 输出时间戳 t = time.time() # 输出时间元祖 mytime = time.localtime(t) print('本地时间为:', mytime) # 输出格式化的时间 formattime = time.asctime(mytime) print(formattime) # 输出格式化日期 # 格式化为YY-mm-dd H:M:S形式 print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) # 格式化时间为Week mm dd H:M:S Y格式 print(time.strftime('%a %b %d %H:%M:%S %Y', time.localtime())) # 将格式化字符串转换为时间戳 a = 'Thu May 17 15:41:56 2018' b = time.strptime(a, '%a %b %d %H:%M:%S %Y') print(time.mktime(b)) import functools def logger(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print('%s %s():' % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator @logger('DEBUG') def today(): print('2015-3-25') # 装饰器理解例子 import time def deco(func): def wrapper(a, b): startTime = time.time() func(a, b) endTime = time.time() msecs = (endTime - startTime) * 1000 print('elapsed time: %f ms' % msecs) return wrapper # @deco # def myfunc(): # print('start myfunc') # time.sleep(0.6) # print('end myfunc') @deco def addFunc(a, b): print('start addFun') time.sleep(0.6) print('result is %d' % (a + b)) print('end addFun') addFunc(3, 8) # # 带参数的装饰器 # # import time # # # def performance(unit): # def perf_decorator(f): # def wrapper(*args, **kw): # t1 = time.time() # r = f(*args, **kw) # t2 = time.time() # t = (t2 - t1) * 1000 if unit == 'ms' else (t2 - t1) # print('call %s() in %f %s' % (f.__name__, t, unit)) # return r # # return wrapper # # return perf_decorator # # # @performance('ms') # def factorial(n): # return reduce(lambda x, y: x * y, range(1, n + 1)) # # # print(factorial(10)) # 带参数的装饰器 # import time # # def performance(unit): # def perf_decorator(f): # def wrapper(*args, **kw): # t1 = time.time() # r = f(*args, **kw) # t2 = time.time() # t = (t2 - t1)*1000 if unit =='ms' else (t2 - t1) # print ('call %s() in %f %s'%(f.__name__, t, unit)) # return r # return wrapper # return perf_decorator # # @performance('ms') # def factorial(n): # return reduce(lambda x,y: x*y, range(1, n+1)) # # print (factorial(10)) # 类和实例,实例属性等 class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print('%s: %s' % (self.name, self.score)) def get_grade(self): if self.score >= 90: return 'A' elif self.score >= 60: return 'B' else: return 'C' bart = Student('Bart Simpson', 59) lisa = Student('Lisa Simpson', 87) print('bart.name =', bart.name) print('bart.score =', bart.score) bart.print_score() print('grade of Bart:', bart.get_grade()) print('grade of Lisa:', lisa.get_grade()) # 获取对象属性getattr(),setattr() class MyObject(object): def __init__(self): self.x = 9 def power(self): return self.x * self.x obj = MyObject() print('hasattr(obj, \'x\') =', hasattr(obj, 'x')) # 有属性'x'吗? print('hasattr(obj, \'y\') =', hasattr(obj, 'y')) # 有属性'y'吗? setattr(obj, 'y', 19) # 设置一个属性'y' print('hasattr(obj, \'y\') =', hasattr(obj, 'y')) # 有属性'y'吗? print('getattr(obj, \'y\') =', getattr(obj, 'y')) # 获取属性'y' print('obj.y =', obj.y) # 获取属性'y' print('getattr(obj, \'z\') =', getattr(obj, 'z', 404)) # 获取属性'z',如果不存在,返回默认值404 f = getattr(obj, 'power') # 获取属性'power' print(f) print(f())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import zipfile, os def backupTozip(folder): # 保存整个“folder”的目录到ZIP文件 folder = os.path.abspath(folder) number = 1 while True: zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip' if not os.path.exists(zipFilename): break number = number + 1 # 创建zip文件 print('Creating %s...' % (zipFilename)) backupZip = zipfile.ZipFile(zipFilename, 'w') # 遍历整个文件夹压缩文件 for foldername, subfolders, filenames in os.walk(folder): print('Adding files in %s...' % (foldername)) # 把当前文件夹加入到ZIP文件 backupZip.write(foldername) for filname in filenames: newBase / os.path.basename(folder) + '_' if filename.startswith(newBase) and filename.endswith('.zip') continue backupZip.write(os.path.join(foldername, filname)) backupZip.close() print('done') backupTozip('c:\\am_date')
import math, random import numpy as np P = 1 def activation(value): #Map the output to a curve between 0 and 1 #output = 1/(1+e^(-a/p)) try: return 1/(1+math.exp(-value/P)) except OverflowError: return 1/(1+math.exp(700/P)) class Neuron(object): def reset(self): return def adjustWeights(self, targetOutput, EW,\ learningRate = None, useMomentum = None ): return class OutputNeuron(Neuron): def __init__(self, outputCount, bias = None, learningRate = 0.3, useMomentum = False ): self.outputCount = outputCount self.inputs = list() self.weights = list() self.learningRate = learningRate self.useMomentum = useMomentum if bias is None: self.bias = random.random() * 1.0 else: self.bias = bias self.processed = False self.rightReceived = 0 self.errorRate = 0 self.outputValue = 0 self.changeMomentums = list() def getOutput(self): #If we've already processed it this time around then just skip the work and return #the answer if self.processed: return self.outputValue #Do some work, get the values from the inputs times by their respective weights #added all up totalSum = 0 for i in range(len(self.inputs)): totalSum += self.inputs[i].getOutput() * self.weights[i] #Subtract the bias totalSum -= self.bias #Save the outputValue after putting it between 0 and 1 self.outputValue = activation(totalSum) self.processed = True return self.outputValue def adjustWeights(self, targetOutput, EW,\ learningRate = None, useMomentum = None ): #If this is an output layer neuron targetOutput will be a value and EW will be 0 # if this is a hidden layer neuron targetOutput will be 0 and EW will be # one of the downstream connected neuron's weight times error rate #Only if we've processed it if learningRate is not None: self.learningRate = learningRate if useMomentum is not None: self.useMomentum = useMomentum if self.processed: runAdjustment = False #If this is an output layer neuron if self.outputCount == 0: runAdjustment = True self.errorRate = (targetOutput - self.outputValue) * \ self.outputValue * ( 1 - self.outputValue ) else: # if this is a hidden layer neuron # add the weighted error rate self.errorRate += EW # count on up self.rightReceived += 1 # if that's all the downstream connected neurons that we're waiting for if self.rightReceived == self.outputCount: runAdjustment = True #calculate our actual error rate self.errorRate *= self.outputValue * ( 1 - self.outputValue ) if runAdjustment: for i in range(len(self.inputs)): # Adjust the weight for each input based on its weight and output if self.useMomentum: self.changeMomentums[i] += self.inputs[i].getOutput() *\ self.learningRate * self.errorRate self.changeMomentums[i] /= 2.0 self.weights[i] += self.changeMomentums[i] else: self.weights[i] += self.inputs[i].getOutput() *\ self.learningRate * self.errorRate # Then adjust the weight on up self.inputs[i].adjustWeights( 0, self.weights[i] * self.errorRate,\ learningRate = learningRate, useMomentum = useMomentum ) return def reset(self): if self.processed: self.processed = False self.rightReceived = 0 self.errorRate = 0 self.outputValue = 0 for i in self.inputs: i.reset() class InputNeuron(Neuron): def __init__(self ): self.inputValue = 0 def getOutput(self): #return activation( self.inputValue ) return self.inputValue class Network(object): def __init__(self, inputs, outputs, hiddenLayerMakeup, structure = None, learningRate = 0.3, useMomentum = False ): self.inputs = inputs self.outputs = outputs self.inputNeurons = list() #self.outputNeurons = list() self.allNeurons = list() self.tempLayer = list() self.lastLayer = list() self.hiddenLayerMakeup = hiddenLayerMakeup #Create input layer for i in range(inputs): newNeuron = InputNeuron( ) self.inputNeurons.append( newNeuron ) self.allNeurons.append( newNeuron ) self.lastLayer.append( newNeuron ) #Create each hidden layer id = 0 for i in range(len(hiddenLayerMakeup)): outputCount = outputs if i < len(hiddenLayerMakeup)-1: outputCount = hiddenLayerMakeup[i+1] for j in range(hiddenLayerMakeup[i]): s = None if structure is not None: s = structure[id] self.createNeuron( outputCount, structure = s,\ learningRate = learningRate, useMomentum = useMomentum ) id += 1 self.lastLayer = self.tempLayer self.tempLayer = list() #Create the output layer for i in range(outputs): s = None if structure is not None: s = structure[id] self.createNeuron( 0, structure = s ) id += 1 self.outputNeurons = self.tempLayer def createNeuron(self, outputCount, structure = None, learningRate = 0.3, useMomentum = False ): b = None if structure is not None: b = structure[0] # float newNeuron = OutputNeuron( outputCount, bias = b,\ learningRate = learningRate, useMomentum = useMomentum ) if structure is not None: newNeuron.weights = structure[1] # list for n in self.lastLayer: newNeuron.inputs.append( n ) if structure is None: newNeuron.weights.append( random.random() * 1.0 + 0.0000000000001 ) newNeuron.changeMomentums.append( 0.0 ) self.tempLayer.append( newNeuron ) self.allNeurons.append( newNeuron ) def getOutput(self, inputs): if len(inputs) != len(self.inputNeurons): raise NameError('Inputs not the same, expected ' + str(len(self.inputNeurons))\ + ' but got ' +str(len(inputs)) ) #Give the input neurons their inputs for i in range(len(inputs)): self.inputNeurons[i].inputValue = inputs[i] # self.inputNeurons[i].inputValue = activation( inputs[i] ) #Reset the neurons for outputNeuron in self.outputNeurons: outputNeuron.reset() #Fill the output list and return it outputList = list() for outputNeuron in self.outputNeurons: outputList.append( outputNeuron.getOutput() ) return outputList def adjustWeights( self, targetOutputs,\ learningRate = None, useMomentum = None ): if len(targetOutputs) != len(self.outputNeurons): raise NameError('Outputs not the same, expected ' + str(len(self.outputNeurons))\ + ' but got ' +str(len(targetOutputs)) ) # make sure our targetOutputs are all between 0 and 1 if np.less(targetOutputs,0.0).any(): raise NameError('Outputs cannot be below 0.0 ') if np.greater(targetOutputs,1.0).any(): raise NameError('Outputs cannot be above 1.0 ') ## for i in range( len( targetOutputs) ): ## if targetOutputs[i] > 1: ## targetOutputs[i] = 1 ## elif targetOutputs[i] < 0: ## targetOutputs[i] = 0 for i in range( len( self.outputNeurons ) ): self.outputNeurons[i].adjustWeights( targetOutputs[i], 0,\ learningRate = learningRate, useMomentum = useMomentum ) def printStructure(self): print( 'Inputs:', self.inputs ) print( 'Hidden Layer Makeup:', self.hiddenLayerMakeup ) print( 'Outputs:', self.outputs ) print( 'Structure:' ) print ('[' ) for neuron in self.allNeurons: if neuron in self.inputNeurons: continue print ('[', neuron.bias, ',', neuron.weights,' ],' ) print (']' ) print() if __name__ is '__main__': import time starttime = time.time() network = Network(2,1,[ 2 ] ) results = list() count = 0 while True: count += 1 a = random.randint(0,1) b = random.randint(0,1) outputs = network.getOutput( [ a, b] ) if len(results)>=500: del results[0] if (a or b) and not (a and b): network.adjustWeights( [1] ) if outputs[0]>0.5: results.append( True ) else: results.append( False ) else: network.adjustWeights( [0] ) if outputs[0]<0.5: results.append( True ) else: results.append( False ) ratio = 0.0 for result in results: if result: ratio += 1.0 ratio /= len(results) print( 'Accuracy: %s' % ratio ) if len(results)>90 and ratio==1.0: break; print( count ) secs = time.time() - starttime print( 'Per iteration time: ', secs/count ) # network.printStructure() # # # network = Network(2,1,[ 3, 2 ], structure = [ # [ 0.6633567588312668 , # [-1.5375843295941822, 5.874506983837322] ], # [ 0.4120877206601512 , # [4.8660870490681996, -1.2138872657105046] ], # [ 1.4782880551917223 , # [5.693297909529692, 4.938349753203479] ], # [ 0.4721888376272143 , # [6.556709105012925, 1.0470135495294646, -5.415906557801467] ], # [ 1.3969295933872528 , # [1.7701308884840654, -4.126382784320171, 3.712795339141683] ], # [ 0.17927038692452002 , # [-6.498125924286288, 7.297829204670113] ], # ] ) # results = list() # count = 0 # while True: # count += 1 # a = random.randint(0,1) # b = random.randint(0,1) # outputs = network.getOutput( [ a, b] ) # if len(results)>=500: # del results[0] # if (a or b) and not (a and b): # network.adjustWeights( [1] ) # if outputs[0]>0.5: # results.append( True ) # else: # results.append( False ) # else: # network.adjustWeights( [0] ) # if outputs[0]<0.5: # results.append( True ) # else: # results.append( False ) # ratio = 0.0 # for result in results: # if result: # ratio += 1.0 # ratio /= len(results) # print( ratio ) # if len(results)>90 and ratio==1.0: # break; # print( count ) # # network.printStructure()
import numpy as np from matplotlib import pyplot as plt 'Esta funcion calcula el RMS de una señal' def RMS(xn): n=len(xn) rms=np.sqrt((1/n)*sum(np.square(abs(xn)))) return(rms)
#!/usr/bin/env python def is_odd(n): return n % 2 ==1 print filter(is_odd,[1, 2, 3, 4, 5, 6, 9, 10, 15])
#!/usr/bin/env python L = range(1,101) L = range(1,101) def is_s(n): if n ==1: return False if n==2: return True else: for i in range(2,n): if n%i==0: return False return True print filter(is_s,L)
import random import time def insertionsort(mylist): n=len(mylist) for i in range(1,n): key=mylist[i] j=i-1 while mylist[j]>key and j>-1: mylist[j+1]=mylist[j] j=j-1 mylist[j+1]=key def bubblesort(mylist): n=len(mylist) for i in range(n): for j in range(n-i-1): if mylist[j]>mylist[j+1]: temp=mylist[j] mylist[j]=mylist[j+1] mylist[j+1]=temp def selectionsort(mylist): n=len(mylist) for i in range(n): for j in range(i,n): if mylist[i]>mylist[j]: temp=mylist[i] mylist[i]=mylist[j] mylist[j]=temp def calc1(mylist): start=time.time() bubblesort(mylist) end=time.time() exec_time=end-start list1.append(exec_time) start=time.time() insertionsort(mylist) end=time.time() exec_time=end-start list2.append(exec_time) start=time.time() selectionsort(mylist) end=time.time() exec_time=end-start list3.append(exec_time) def calc2(mylist): start=time.time() bubblesort(mylist) end=time.time() exec_time=end-start list4.append(exec_time) start=time.time() insertionsort(mylist) end=time.time() exec_time=end-start list5.append(exec_time) start=time.time() selectionsort(mylist) end=time.time() exec_time=end-start list6.append(exec_time) def calc3(mylist): start=time.time() bubblesort(mylist) end=time.time() exec_time=end-start list7.append(exec_time) start=time.time() insertionsort(mylist) end=time.time() exec_time=end-start list8.append(exec_time) start=time.time() selectionsort(mylist) end=time.time() exec_time=end-start list9.append(exec_time) tc=int(input()) list1=[] list2=[] list3=[] list4=[] list5=[] list6=[] list7=[] list8=[] list9=[] for i in range(tc): mylist=[] size=int(input()) for i in range(size): b=random.randrange(1,100) mylist.append(b) calc1(mylist) mylist.sort() calc2(mylist) mylist.reverse() calc3(mylist) print(list1) print(list2) print(list3) print(list4) print(list5) print(list6) print(list7) print(list8) print(list9)
''' The classification module allows users to evaluate and visualize classifiers ''' import logging import os import numpy as np import sklearn.metrics as metrics import matplotlib.pyplot as plt _logger = logging.getLogger() def evaluate_model(fitted_model, X_test: np.array, y_test: np.array, show_roc: bool = False) -> np.array: '''Will predict and evaluate a model against a test set Args: fitted_model (model): The already fitted model to be tested. Sklearn and Keras models have been tested X_test (np.array): The test set to calculate the predictions with y_test (np.array): The output test set to evaluate the predictions against show_roc (bool): This will plot the ROC curve in case of a binary classifier Returns: np.array: The predicted (y_pred) values against the model ''' y_pred = fitted_model.predict(X_test) print(metrics.classification_report(y_test, y_pred)) cf = metrics.confusion_matrix(y_test, y_pred) print(cf) accuracy = metrics.accuracy_score(y_test, y_pred) * 100 print('Accuracy score:', accuracy) if(show_roc == True): # Verify that we are having a binary classifier if(len(fitted_model.classes_)!=2): raise AttributeError('Showing a ROC curve is only possible for binary classifier, not for multi class') plot_roc_curve(y_test, y_pred) return y_pred def plot_roc_curve(y_pred: np.array, y_test: np.array): '''Will plot the Receiver Operating Characteristic (ROC) Curve for binary classifiers Args: y_pred (np.array): The predicted values of the test set y_test (np.array): The actual outputs of the test set Returns: float: The ROC_AUC value ''' # calculate the fpr and tpr for all thresholds of the classification fpr, tpr, threshold = metrics.roc_curve(y_test, y_pred) roc_auc = metrics.auc(fpr, tpr) plt.title('Receiver Operating Characteristic') plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc) plt.legend(loc = 'lower right') plt.plot([0, 1], [0, 1],'r--') plt.xlim([0, 1]) plt.ylim([0, 1]) plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.show() return roc_auc
# -*- coding: utf-8 -*- """ Created on Thu Nov 23 15:54:58 2017 @author: Edu Description: Bamboo is a Pandas DataFrame wrapper used for RedPandas. In adition of having the raw DataFrame, it also stores aditionally information. A Bamboo object contains: A pandas DataFrame "dataFrame" which represents the dataset. A String list "features" that has the features that are going to be used. A String "target" which is out target feature. An int list "n_nulls" that correspond to the number of nulls that a feature had initially in its dataset. It doesn't represent the current number of nulls in it. A Report list "reports" which contains all the analysis done. """ from Report import Report from sklearn.tree import DecisionTreeRegressor from sklearn.neighbors import KNeighborsRegressor from sklearn.ensemble import RandomForestRegressor class Bamboo: def __init__(self, name, dataFrame, features, target=None, n_nulls=None): self.name = name self.dataFrame = dataFrame self.features = features self.target = target self.n_nulls = n_nulls self.reports = [] self.regressor = None def reportBasicInfo(self, printOnScreen=True): featuresType = [] featuresMin = [] featuresMax = [] featuresMean = [] for feature in self.features: featuresType.append(type(self.dataFrame[feature].iloc[0]).__name__) featuresMin.append(self.dataFrame[feature].min()) featuresMax.append(self.dataFrame[feature].max()) if type(self.dataFrame[feature].iloc[0]).__name__ != 'str': featuresMean.append(self.dataFrame[feature].mean()) else: featuresMean.append('none') name='BasicInfo'+str(self.numberOfReports('Basic')+1) report = Report(name, cols=zip(self.features, featuresType, featuresMin, featuresMax, featuresMean, self.n_nulls), headers=["Feature","Type","Min","Max","Mean","Num Nulls"], typeReport='Basic') if printOnScreen: report.showReport(); self.reports.append(report) def reportInfoRelevancies(self, printOnScreen=True): name = 'RelevanciesInfo'+str(self.numberOfReports('Relevancies')+1) report = Report(name, cols = zip(self.features, self.regressor.feature_importances_), headers=["Feature","Relevancy"], typeReport='Relevancies') if printOnScreen: report.showReport(); self.reports.append(report) def setupRegressor(self, criterion='mae', max_depth=0, n_estimators=0, n_neighbors=0, random_state=0, mode='DecisionTree', weights='uniform'): if mode == 'DecisionTree': regressor = DecisionTreeRegressor(criterion=criterion, max_depth=max_depth, random_state=random_state) if mode == 'KNN': regressor = KNeighborsRegressor(n_neighbors, weights=weights) if mode == 'RandomForest': regressor = RandomForestRegressor(n_estimators=n_estimators, max_depth = max_depth, criterion='mae', random_state=random_state) regressor.fit(self.dataFrame[self.features], self.dataFrame[self.target]) self.regressor = regressor def numberOfReports(self, typeReport='All'): count = 0 for report in self.reports: if report.typeReport == typeReport or typeReport == 'All': count = count + 1 return count
""" URL: https://leetcode.com/problems/regular-expression-matching/ Description: Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like . or *. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa" p = "a*" Output: true Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". Example 3: Input: s = "ab" p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)". Example 4: Input: s = "aab" p = "c*a*b" Output: true Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab". Example 5: Input: s = "mississippi" p = "mis*is*p*." Output: false """ import re class Solution: def is_match(self, s, p): """ :type s: str :type p: str :rtype: bool """ if re.compile('^' + p + '$').match(s): return True return False attempt = Solution() print(attempt.is_match('aa', 'a')) # False print(attempt.is_match('aa', 'a*')) # True print(attempt.is_match('ab', '.*')) # True print(attempt.is_match('aab', 'c*a*b')) # True print(attempt.is_match('mississippi', 'mis*is*p*.')) # False """ First attempt finished successfully with Runtime: 120 ms, faster than 23.26% of Python3 online submissions for Regular Expression Matching. However I'm going to work on giving more performance Second attempt resulted in increasing speed by only 3% with overall 26% !! Seeking new approach. Third attempt: Runtime: 96 ms, faster than 31.70% of Python3 online submissions for Regular Expression Matching. Fourth attempt: Runtime: 80 ms, faster than 45.93% of Python3 online submissions for Regular Expression Matching. """
import inputs import turtle as t t.setup(700,700) t.shape("turtle") t.color("red") while True: events = inputs.get_gamepad() for event in events: if event.code == 'BTN_SOUTH' and event.state == 1: print('Equis!') t.forward(50) if event.code == 'BTN_NORTH' and event.state == 1: print('Triangulo!') t.backward(50) if event.code == 'BTN_WEST' and event.state == 1: print('Cuadrado!') t.left(90) if event.code == 'BTN_EAST' and event.state == 1: print('Circulo!') t.left(-90) if event.code == 'BTN_TR' and event.state == 1: print('Triger Derecho Superior!') t.penup() if event.code == 'BTN_THUMBR' and event.state == 1: print('Centro Analogico Derecho!') if event.code == 'BTN_TL' and event.state == 1: print('Triger Izquierdo Superior!') t.pendown() if event.code == 'BTN_THUMBL' and event.state == 1: print('Centro Analogico Izquierdo!') if event.code == 'BTN_START' and event.state == 1: print('Select!') if event.code == 'BTN_SELECT' and event.state == 1: print('Start!') if event.code == 'ABS_HAT0X' and event.state == 1: print('D Right!') if event.code == 'ABS_HAT0Y' and event.state == 1: print('D Down!') if event.code == 'ABS_HAT0X' and event.state == -1: print('D Left!') if event.code == 'ABS_HAT0Y' and event.state == -1: print('D Up!') if event.code == 'ABS_Z' and event.state > 10: print('Analogico Posterior izquierdo ' + str(event.state)) if event.code == 'ABS_RZ' and event.state > 10: print('Analogico Posterior derecha ' + str(event.state)) if event.code == 'ABS_Y' and event.state > 150: print('Analogico Principal Baja ' + str(event.state)) if event.code == 'ABS_Y' and event.state < 50: print('Analogico Principal Sube ' + str(event.state)) if event.code == 'ABS_X' and event.state > 200: print('Analogico Principal Derecha ' + str(event.state)) if event.code == 'ABS_X' and event.state < 50: print('Analogico Principal Izquierda ' + str(event.state)) if event.code == 'ABS_RY' and event.state > 200: print('Analogico Secundario Baja ' + str(event.state)) if event.code == 'ABS_RY' and event.state < 50: print('Analogico Secundario Sube ' + str(event.state)) if event.code == 'ABS_RX' and event.state > 200: print('Analogico Secundario Derecha ' + str(event.state)) if event.code == 'ABS_RX' and event.state < 50: print('Analogico Secundario Izquierda ' + str(event.state))
for a in range(1,1000): for b in range(1,1000): for c in range(1,1000): if (a**2)+(b**2) == (c**2): if a+b+c == 1000: print(a*b*c)
import random import tkinter from PIL import ImageTk, Image import time from simpleimage import SimpleImage DEFAULT_FILE = 'images/fam.jpg' CANVAS_WIDTH = 700 CANVAS_HEIGHT = 600 def main(): keep_going = True filename = get_file() image = SimpleImage(filename) canvas = make_canvas(CANVAS_WIDTH, CANVAS_HEIGHT, 'Final Project: Editing Fun!') pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) while keep_going: keep_going = show_menu(image, canvas) image = SimpleImage(filename) def get_file(): # Read image file path from user, or use the default file filename = input('Enter image file (or press enter for default): ') if filename == '': filename = DEFAULT_FILE return filename def show_menu(image, canvas): time.sleep(1/2) print('Choose how to edit the image:') print(' 1. Make more red') print(' 2. Make more blue') print(' 3. Make more green') print(' 4. Make more yellow') print(' 5. Play with color') print(' 6. Random color change') print(' 7. Flip image horizontally') print(' 8. Flip the image vertically') print(' 9. Gradual color change (yellow to blue)') print(' 10. Gradual color change (yellow-pink)') print(' 99. Move Image ') print(' 0. Stop editing the image and end') selection = int(input('Which is your choice: ')) if (selection == 0): keep_going = False else: keep_going = True edit_picture(selection, image, canvas) return keep_going def edit_picture(selection, image, canvas): if (selection == 1): more_red(image, canvas) #image.show() if (selection == 2): more_blue(image, canvas) #image.show() if (selection == 3): more_green(image, canvas) #image.show() if (selection == 4): more_yellow(image, canvas) #image.show() if (selection == 5): custom_color(image, canvas) #image.show() if (selection == 6): random_color(image, canvas) #image.show() if (selection == 7): mirror = flip_horizontal(image, canvas) #mirror.show() if (selection == 8): image = flip_vertical(image, canvas) #image.show() if (selection == 9): gradual_change(image, canvas) if (selection == 10): gradual_change2(image, canvas) if (selection == 99): move_pic(image, canvas) def gradual_change(image,canvas): for i in range(40): for pixel in image: blue_value = (20 - i) red_value = i pixel.red = pixel.red-(red_value*2) pixel.green = pixel.green pixel.blue = pixel.blue-(blue_value*2) pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image = pimg, anchor=tkinter.NW) canvas.update() #canvas.create_image(10, 20, image = pimg, anchor=tkinter.NW) #input('Hit Enter to continue') def gradual_change2(image,canvas): #img = Image.open('filename.png') for i in range(37): for pixel in image: blue_value = (20 - i) red_value = i # pixel.red = pixel.red pixel.red = pixel.red pixel.green = pixel.green-(red_value*1.5) pixel.blue = pixel.blue-(blue_value*1.5) pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image = pimg, anchor=tkinter.NW) canvas.update() def make_canvas(width, height, title): """ Creates and returns a drawing canvas of the given int size with a blue border, ready for drawing. """ top = tkinter.Tk() top.minsize(width=width, height=height) top.title(title) canvas = tkinter.Canvas(top, width=width + 1, height=height + 1) canvas.pack() return canvas def custom_color(image, canvas): red_value = int(input('Pick a number between 0 and 20 for the red: ')) blue_value = int(input('Pick a number between 0 and 20 for the blue: ')) green_value = int(input('Pick a number between 0 and 20 for the green: ')) for pixel in image: pixel.red = pixel.red*(red_value/10) pixel.green = pixel.green*(green_value/10) pixel.blue = pixel.blue*(blue_value/10) pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() time.sleep(1) def random_color(image, canvas): red_value = random.randint(1,20) blue_value = random.randint(1,20) green_value = random.randint(1,20) for pixel in image: pixel.red = pixel.red * (red_value / 10) pixel.green = pixel.green * (green_value / 10) pixel.blue = pixel.blue * (blue_value / 10) pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() time.sleep(1) def more_blue(image, canvas): for pixel in image: pixel.red = pixel.red*0.4 pixel.green = pixel.green*0.4 pixel.blue = pixel.blue*1.7 pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() return canvas def more_red(image, canvas): for pixel in image: pixel.red = pixel.red*1.2 pixel.green = pixel.green*0.5 pixel.blue = pixel.blue*0.5 pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() return canvas def more_green(image, canvas): for pixel in image: pixel.red = pixel.red*0.4 pixel.green = pixel.green*1.6 pixel.blue = pixel.blue*0.4 pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() return canvas def more_yellow(image, canvas): for pixel in image: pixel.red = pixel.red*1.6 pixel.green = pixel.green*1.6 pixel.blue = pixel.blue*0.1 pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() return canvas def flip_vertical(image, canvas): width = image.width height = image.height #Create new image to contain the new reflected image mirror = SimpleImage.blank(width, height) for y in range(height): for x in range(width): pixel = image.get_pixel(x,y) mirror.set_pixel(x,height - (y+1),pixel) pimg = ImageTk.PhotoImage(mirror.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() time.sleep(1) return mirror def flip_horizontal(image, canvas): width = image.width height = image.height #Create new image to contain the new reflected image mirror = SimpleImage.blank(width, height) for y in range(height): for x in range(width): pixel = image.get_pixel(x,y) mirror.set_pixel(width - (x+1),y,pixel) pimg = ImageTk.PhotoImage(mirror.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() time.sleep(1) return mirror def move_pic(image, canvas): #canvas = make_canvas(700, 600, 'Final Project: Morphing Picture') pimg = ImageTk.PhotoImage(image.pil_image) img_tk = canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) change_x=3 change_y =7 count = 0 while (count < 7): #update world canvas.move(img_tk, change_x,change_y) if (hit_bottom(canvas, img_tk, pimg)): change_y = change_y*-1 count = count + 1 if (hit_side(canvas, img_tk, pimg)): change_x *= -1 count = count + 1 if (hit_top(canvas, img_tk, pimg)): change_y *= -1 count = count + 1 if (hit_other_side(canvas, img_tk, pimg)): change_x *= -1 count += 1 canvas.update() #pause time.sleep(1/70.) #canvas.update() #canvas.mainloop() def hit_bottom(canvas, object, pimg): return canvas.coords(object)[1] > CANVAS_HEIGHT - pimg.height() def hit_side(canvas, object, pimg): return canvas.coords(object)[0]>CANVAS_WIDTH - pimg.width() def hit_top(canvas, object, pimg): return canvas.coords(object)[1] <= 0 def hit_other_side(canvas, object, pimg): return canvas.coords(object)[0] <= 0 if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Created on Mon Jul 13 11:36:38 2020 @author: Harry """ import heapq import numpy as np import random as rr import IPython class Node: def __init__(self, parent=None, pos=None): self.parent = parent self.pos = pos self.f = 0 self.manhattan = 0 self.cost = 0 def __eq__(self, other): return self.pos == other.pos #for heap def __lt__(self, other): return self.f < other.f or self.cost > other.cost def __gt__(self, other): return self.f > other.f class doubleLL: def __init__(self): self.front = None self.size = 0 def insert(self, newPos): #first node to be added to the list if self.front is None: newNode = Node(); newNode.pos = newPos; print("newNode was ", newNode.pos) print("startNode parent is?", newNode.parent) self.front = newNode; return #self.size += 1; else: temp = self.front; while temp.next is not None: #print("temp before adding prev is", temp.parent) #prev = temp; #print("prev node: ",prev.pos); temp = temp.next; newNode = Node(); newNode.pos = newPos; #print("newNode's parent is ", newNode.parent.pos) #print("newNode is ", newNode.pos) temp.next = newNode; newNode.parent = temp; #self.size += 1; def searchDLL(self,searchNode): retVal = 0; temp = self.front; while temp is not None: if(temp == searchNode): retVal = 1; temp = temp.next; return retVal; def printDLL(self,goalNode): path = [] temp = goalNode; #path.append(temp.pos); print("path appended: ", temp.pos) while temp is not None: path.append(temp.pos); print("path appended: ", temp.pos) temp = temp.parent; #print("temp's parent is ", temp.parent.pos) #print("temp is ", temp.pos) #print("temp is ", temp.pos) return path; class singleLL: def __init__(self): self.front = None; def insert(self, newNode): if self.front == None: newNode.next = None; self.front = newNode; else: newNode.next = self.front; def printLL(self,frontNode): while frontNode is not None: print(frontNode) frontNode = frontNode.next; class priorotyQueueNodes: def __init__(self): self.list = [] #self.Node = Node; self.size = 0 #inserts desired Node into priority queue and decides value by F value def insert(self,insertNode): self.list.append(Node(insertNode,insertNode.pos)) self.size += 1 #self.list[self.size].Node = Node; j = self.size #print("nodes size", self.size) while j // 2 > 0: # print("j = ", j) #checking f value to properly add nodes to priority queue k = self.list[j // 2] # print("k = ", k.pos) if self.list[j-1].f < k.f: self.list[j // 2] = self.list[j-1] self.list[j-1] = k #if we have a tied f value then check the g vlaue elif self.list[j-1].f == k.f: #let larger g value have higher priority, so switch if k has bigger g if k.cost > self.list[j-1].cost: self.list[j // 2] = self.list[j-1] self.list[j-1] = k j //= 2 def delete(self): retVal = self.list[0] if self.size != 1: self.list[0] = self.list[self.size]; #print("delete has been entered") self.size -= 1 i = 1 while (i * 2) <= self.size: lastChild = self.Child(i) #switch position if current node has bigger f or has same f but smaller g(ie tie break) if self.list[i].f > self.list[lastChild].f or ((self.list[i].f == self.list[lastChild].f) and (self.list[i].cost < self.list[lastChild].cost)): temp = self.list[i] self.list[i] = self.list[lastChild] self.list[lastChild] = temp i = lastChild self.insert(retVal); return retVal def searchQ(self, searchNode): temp = self.list; i = 0; ret = 0; if self.size == 0: return 0 while(i < self.size): if(temp[i] == searchNode): #print("cost of the node is ", searchNode.cost) return searchNode.cost; else: ret = -1 i += 1; return ret; #hopefully i can return this stupid pos shit cause im losing my patience def Child(self,i): if i * 2 + 1 > self.size: return i * 2 else: if self.list[i*2].f >= self.list[i*2+1].f: return i * 2 + 1 else: return i * 2 def printHeap(self): i = 1; while(i <= self.size): if self.size == 0: print("empty list") else: print(self.list[i]) #print("i inside printHeap is " + str(i)) i += 1 def repeatedBackward(maze, start, end): rows,cols = np.shape(maze) #create empty maze emptyMaze = [[0 for i in range(rows)] for j in range(cols // 2)] #print("size of empty maze " , len(emptyMaze)) #print(emptyMaze) #create robot with vision and update maze agent = start #moves available to us North = (1, 0) South = (0, 1) East = (-1, 0) West = (0, -1) actions = (South,North,East,West) if maze[start[0]][start[1]] == 1: return "Path could not be found 1 " #generating moves so we can initially update the maze before I call A star for the first time for move in actions: neighbor = (agent[0] + move[0], agent[1] + move[1]) #within range? if neighbor[1] > (len(maze[len(maze)-1]) -1) or neighbor[0] > (len(maze) - 1) or neighbor[1] < 0 or neighbor[0] < 0: continue #now that we know that its within range time to update neighbors if maze[neighbor[0]][neighbor[1]] == 1: emptyMaze[neighbor[0]][neighbor[1]] = 1 #print(emptyMaze) #implement same counter here its taking way too long outer_iterations = 0 max_iterations = (len(maze[0]) ** 2) #now that it is initialized call A* on it and find the agent path #iterate until agent is at destination #initialize the agents moved block's list this is what I will use to find the path the agent took movedBlocks = [] #problem here is that this shit won't work if start is also the end if(start == end): movedBlocks.append(agent); while agent != end: agentPath = [] currentNode = Astar(emptyMaze,end, agent) if(outer_iterations == max_iterations): return "Path could not be found 2" outer_iterations += 1 #print("a star has returned: ", agentPath[0]) if agentPath is None: return "Path could not be found 3" curr = currentNode while curr is not None: agentPath.append(curr.pos) curr = curr.parent agentPath = agentPath[::-1] #added the node the agent is at to the moved block now moving to next step #remove first item since we added it to the moved Blocks list #problem here #movedBlocks.append(agent); #print("mover Block is ", movedBlocks[0]) #iterate thru the path aStar returned i = 0 numOFiters = 0; #iterator variable to iterate thru the agentPath list while i < len(agentPath): agent = agentPath[i] #print("agent is at ", agent) #generating next moves for agent and checking if we encounter a 1 for move in actions: neighbor = (agent[0] + move[0], agent[1] + move[1]) #within range? if neighbor[1] > (len(maze[len(maze)-1]) -1) or neighbor[0] > (len(maze) - 1) or neighbor[1] < 0 or neighbor[0] < 0: continue #now that we know that its within range time to update neighbors if maze[neighbor[0]][neighbor[1]] == 1: emptyMaze[neighbor[0]][neighbor[1]] = 1 #print(emptyMaze) #now to check if we can keep following this path agentPath's next item shall be our next move so #check i + 1 if(i+1) != len(agentPath): nextItem = agentPath[i+1] #print("next item is ", nextItem) if emptyMaze[nextItem[0]][nextItem[1]] == 1: #print("empty maze value: ", emptyMaze[nextItem[0]][nextItem[1]]) #stop the loop i = len(agentPath) #since the agent path isn't blocked we can keep going movedBlocks.append(agent); agentPath.remove(agent); numOFiters += 1 #print("num of iterations: ",numOFiters) #print("exited i loop") return movedBlocks def repeatedForward(maze, start, end): rows,cols = np.shape(maze) if maze[start[0]][start[1]] == 1: return "Path could not be found" #print("create empty maze") emptyMaze = [[0 for i in range(rows)] for j in range(cols)] # print("size of empty maze " , len(emptyMaze)) # print(emptyMaze) #create robot with vision and update maze agent = start #moves available to us North = (1, 0) South = (0, 1) East = (-1, 0) West = (0, -1) actions = (South,North,East,West) #generating moves so we can initially update the maze before I call A star for the first time for move in actions: neighbor = (agent[0] + move[0], agent[1] + move[1]) #within range? if neighbor[1] > (len(maze[len(maze)-1]) -1) or neighbor[0] > (len(maze) - 1) or neighbor[1] < 0 or neighbor[0] < 0: continue #now that we know that its within range time to update neighbors if maze[neighbor[0]][neighbor[1]] == 1: emptyMaze[neighbor[0]][neighbor[1]] = 1 #print(emptyMaze) #now that it is initialized call A* on it and find the agent path #iterate until agent is at destination #initialize the agents moved block's list this is what I will use to find the path the agent took movedBlocks = [] #problem here is that this shit won't work if start is also the end if(start == end): movedBlocks.append(agent); aStarCounter = 1; while agent != end: agentPath = [] currentNode = Astar(emptyMaze,agent,end) agentPath = [] curr = currentNode while curr is not None: agentPath.append(curr.pos) curr = curr.parent agentPath = agentPath[::-1] if agentPath is None: return "Path could not be found" print("a star has returned: ", agentPath[0]) #added the node the agent is at to the moved block now moving to next step if emptyMaze[start[0]][start[1]] == 1: return "Path could not be found" agentPath.remove(agent); #remove first item since we added it to the moved Blocks list #problem here #movedBlocks.append(agent); #print("mover Block is ", movedBlocks[0]) #iterate thru the path aStar returned print("Iterating thru the returned A star path for the", str(aStarCounter)," time...\n") aStarCounter += 1; i = 0 numOFiters = 0; #iterator variable to iterate thru the agentPath list while i < len(agentPath): agent = agentPath[i] print("agent is at ", agent) #generating next moves for agent and checking if we encounter a 1 for move in actions: neighbor = (agent[0] + move[0], agent[1] + move[1]) #within range? if neighbor[1] > (len(maze[len(maze)-1]) -1) or neighbor[0] > (len(maze) - 1) or neighbor[1] < 0 or neighbor[0] < 0: continue #now that we know that its within range time to update neighbors if maze[neighbor[0]][neighbor[1]] == 1: emptyMaze[neighbor[0]][neighbor[1]] = 1 #print(emptyMaze) #now to check if we can keep following this path agentPath's next item shall be our next move so #check i + 1 if(i+1) != len(agentPath): nextItem = agentPath[i+1] #print("next item is ", nextItem) if emptyMaze[nextItem[0]][nextItem[1]] == 1: #print("empty maze value: ", emptyMaze[nextItem[0]][nextItem[1]]) #stop the loop i = len(agentPath) #since the agent path isn't blocked we can keep going movedBlocks.append(agent); agentPath.remove(agent); numOFiters += 1 #print("num of iterations: ",numOFiters) #print("exited i loop") return movedBlocks def generatePossibleMoveset(actions, maze , current_node): possibleMoves = [] for move in actions: # Adjacent squares # Get node position currentState = (current_node.pos[0] + move[0], current_node.pos[1] + move[1]) #print("checking boundaries of maze") if currentState[1] > (len(maze[len(maze)-1]) -1) or currentState[0] > (len(maze) - 1) or currentState[1] < 0 or currentState[0] < 0: continue #print("boundaries were checked"" #print("here in moves") if maze[currentState[0]][currentState[1]] != 0: continue #print("moves wasn't skipped by blocked cell check") new_node = Node(current_node, currentState) # Append possibleMoves.append(new_node) return possibleMoves def determineValidity(possibleMoves, expanded, visited, current_node, end): for move in possibleMoves: #print("checking if move was already expanded") if len([possibleMove for possibleMove in expanded if possibleMove == move]) > 0: continue #print("wasn't skipped") # Calculate and store the cost, manhattan distance and f values move.cost = current_node.cost + 1 move.manhattan = calculateManhattan(move, end) move.f = calculateF(move, end) #print("checking if in visited list") possibleMove = 0 if len([node for node in visited if move.pos == node.pos and move.cost > move.cost]) > 0: continue #print("not in visited list") heapq.heappush(visited, move) return visited def determineValidity2(possibleMoves, expanded, visited, current_node, end, adaptive, updateCost,iterativeNode): for move in possibleMoves: #print("checking if move was already expanded") if len([possibleMove for possibleMove in expanded if possibleMove == move]) > 0: continue #print("wasn't skipped") # Calculate and store the cost, manhattan distance and f values move.cost = current_node.cost + 1 move.manhattan = calculateManhattan(move, end) if adaptive == 1: move.f = updateF(move, end, iterativeNode, updateCost); else: move.f = calculateF(move, end) #print("checking if in visited list") possibleMove = 0 if len([possibleMove for possibleMove in visited if move.pos == possibleMove.pos]) > 0: if(move.cost > possibleMove.cost): continue #print("not in visited list") # Add the child to the open list heapq.heappush(visited, move) return visited #adaptive a-Star updates heuristic after first run def adaptive(maze, start, end): counter2 = 0 rows,cols = np.shape(maze) if maze[start[0]][start[1]] == 1: return "Path could not be found" #create empty maze emptyMaze = [[0 for i in range(rows)] for j in range(cols)] #print("size of empty maze " , len(emptyMaze)) #print(emptyMaze) #create robot with vision and update maze agent = start #moves available to us North = (1, 0) South = (0, 1) East = (-1, 0) West = (0, -1) actions = (South,North,East,West) #generating moves so we can initially update the maze before I call A star for the first time for move in actions: neighbor = (agent[0] + move[0], agent[1] + move[1]) #within range? if neighbor[1] > (len(maze[len(maze)-1]) -1) or neighbor[0] > (len(maze) - 1) or neighbor[1] < 0 or neighbor[0] < 0: continue #now that we know that its within range time to update neighbors if maze[neighbor[0]][neighbor[1]] == 1: emptyMaze[neighbor[0]][neighbor[1]] = 1 #print(emptyMaze) #now that it is initialized call A* on it and find the agent path #iterate until agent is at destination #initialize the agents moved block's list this is what I will use to find the path the agent took movedBlocks = [] #problem here is that this shit won't work if start is also the end if(start == end): movedBlocks.append(agent); agentPath = [] currentNode = Astar(emptyMaze,agent,end) agentPath = [] curr = currentNode while curr is not None: agentPath.append(curr.pos) curr = curr.parent agentPath = agentPath[::-1] if agentPath is None: return ("Path could not be found") #print("a star has returned: ", agentPath[0]) #added the node the agent is at to the moved block now moving to next step if emptyMaze[start[0]][start[1]] == 1: return "Path could not be found" #initalize that variable to be our new start newStart = (); i = 0 numOFiters = 0; #iterator variable to iterate thru the agentPath list while i < len(agentPath): agent = agentPath[i] #print("agent is at ", agent) #generating next moves for agent and checking if we encounter a 1 for move in actions: neighbor = (agent[0] + move[0], agent[1] + move[1]) #within range? if neighbor[1] > (len(maze[len(maze)-1]) -1) or neighbor[0] > (len(maze) - 1) or neighbor[1] < 0 or neighbor[0] < 0: continue #now that we know that its within range time to update neighbors if maze[neighbor[0]][neighbor[1]] == 1: emptyMaze[neighbor[0]][neighbor[1]] = 1 #print(emptyMaze) #now to check if we can keep following this path agentPath's next item shall be our next move so #check i + 1 if(i+1) != len(agentPath): nextItem = agentPath[i+1] #print("next item is ", nextItem) if emptyMaze[nextItem[0]][nextItem[1]] == 1: #print("empty maze value: ", emptyMaze[nextItem[0]][nextItem[1]]) #stop the loop newStart = agent i = len(agentPath) #since the agent path isn't blocked we can keep going movedBlocks.append(agent); agentPath.remove(agent); numOFiters += 1 #say we encounter a block this is where we should update the nodes and call our new function iterativeNode = currentNode; updateCost = 0 #initialize vars so we can update the cost and f values accordingly while iterativeNode is not None: if newStart == currentNode.pos: updateCost = currentNode.cost break else: iterativeNode = iterativeNode.parent # now that i found the update value time to call A star again #call new A* star fucntion with update cost and iterative as params as well while agent != end: adaptiveNode = adaptiveA(emptyMaze,agent,end,iterativeNode,updateCost) if(counter2 == 20): return "path not found" curr = adaptiveNode while curr is not None: agentPath.append(curr.pos) curr = curr.parent while i < len(agentPath): agent = agentPath[i] #print("agent is at ", agent) #generating next moves for agent and checking if we encounter a 1 for move in actions: neighbor = (agent[0] + move[0], agent[1] + move[1]) #within range? if neighbor[1] > (len(maze[len(maze)-1]) -1) or neighbor[0] > (len(maze) - 1) or neighbor[1] < 0 or neighbor[0] < 0: continue # now that we know that its within range time to update neighbors if maze[neighbor[0]][neighbor[1]] == 1: emptyMaze[neighbor[0]][neighbor[1]] = 1 #print(emptyMaze) #now to check if we can keep following this path agentPath's next item shall be our next move so #check i + 1 if(i+1) != len(agentPath): nextItem = agentPath[i+1] #print("next item is ", nextItem) if emptyMaze[nextItem[0]][nextItem[1]] == 1: #print("empty maze value: ", emptyMaze[nextItem[0]][nextItem[1]]) #stop the loop newStart = agent i = len(agentPath) #since the agent path isn't blocked we can keep going movedBlocks.append(agent); agentPath.remove(agent); numOFiters += 1 while iterativeNode is not None: if newStart == currentNode.pos: updateCost = currentNode.cost break else: iterativeNode = iterativeNode.parent #after first pass of a start we need to update heuristics somehow #maybe call in A star in first pass # after that if not found create a new function which has our expanded list as a param #use the expanded list to update those nodes before we go again #problem here #movedBlocks.append(agent); #print("mover Block is ", movedBlocks[0]) #iterate thru the path aStar returned #print("num of iterations: ",numOFiters) #print("exited i loop") counter2 += 1 return movedBlocks def adaptiveA(maze, start, end, iterativeNode, updateCost): # Create start and end node start = Node(None, start) start.cost = start.manhattan = start.f = 0 end = Node(None, end) end.cost = end.manhattan = end.f = 0 # Initialize both open and closed list visited = [] expanded = [] # Tried using priority queue did not work rip #caved in and just used heapq too little time ;-; heapq.heapify(visited) heapq.heappush(visited, start) counter = 0 stopCondition = (len(maze) * len(maze[0]))*2 North = (1, 0) South = (0, 1) East = (-1, 0) West = (0, -1) actions = (South,North,East,West) # Loop until you find the path to the goal visitedSize = len(visited) while visitedSize > 0: counter += 1 if counter > stopCondition: #kept getting infinite loops return None # Get the current node currentState = heapq.heappop(visited) expanded.append(currentState) # Found the goal if currentState == end: return currentState # Generate children adaptive = 1 possibleMoves = generatePossibleMoveset(actions, maze , currentState); # put into own function to reduce clutter # Loop through children visited = determineValidity2(possibleMoves, expanded, visited, currentState, end, adaptive, updateCost,iterativeNode) visitedSize = len(visited) return None def updateF(node,targetNode, iterativeNode, updateCost): #set hvalue and g value gVal = node.cost; hVal = calculateManhattan(node,targetNode) #calc fValue temp = iterativeNode fVal = 0 while temp is not None: if temp == targetNode: fVal = gVal + hVal + updateCost else: fVal = gVal + hVal return fVal def Astar(maze, start, end): # Initialize both open and closed list visited = [] expanded = [] # Create start and end node start = Node(None, start) start.cost = start.manhattan = start.f = 0 end = Node(None, end) end.cost = end.manhattan = end.f = 0 # Tried using priority queue did not work rip #caved in and just used heapq too little time ;-; heapq.heapify(visited) heapq.heappush(visited, start) counter = 0 stopCondition = (len(maze) * len(maze[0]))*2 North = (1, 0) South = (0, 1) East = (-1, 0) West = (0, -1) actions = (South,North,East,West) # Loop until you find the path to the goal visitedSize = len(visited) while visitedSize > 0: counter += 1 if counter > stopCondition: #kept getting infinite loops return None # Get the current node currentState = heapq.heappop(visited) expanded.append(currentState) # Found the goal if currentState == end: return currentState # Generate possible next state possibleMoves = generatePossibleMoveset(actions, maze , currentState); # put into own function to reduce clutter # Loop through next states to find valid options to add to visited list visited = determineValidity(possibleMoves, expanded, visited, currentState, end) visitedSize = len(visited) return None def calculateManhattan(node,targetNode): #intialize cordinates xCord_cell = node.pos[0]; yCord_cell = node.pos[1]; xCord_target = targetNode.pos[0]; yCord_target = targetNode.pos[1]; #calc difference xVal = abs(xCord_cell - xCord_target) yVal = abs(yCord_cell - yCord_target) #calc absolute values plus the sum #xVal = abs(xVal) #yVal = abs(yVal) hValue = xVal + yVal #return val return hValue #F(s) = G(s) + H(s) def calculateF(node,targetNode): #set hvalue and g value gVal = node.cost; hVal = calculateManhattan(node,targetNode) #calc fValue fVal = gVal + hVal return fVal import timeit def main(): maze3 = [[0,0,0,0,0], [0,0,1,0,0], [0,0,1,1,0], [0,0,1,1,0], [0,0,0,1,0]] start = (0,0) end = (4,4) pathStr = 'E:/Coding/python work/project1/arrs/randGrid/' + str(1) + '.txt' with open(pathStr, 'r') as f: forwardMaze = [[int(num) for num in line.split(' ') * 2] for line in f] print("Repeated forward...") path = repeatedForward(forwardMaze, (10,10), end) path.insert(0, (0,0)) print(path) print("\n\n\n") print("Repeated backward...") path = repeatedBackward(maze3, start, end) print(path) print("\n\n\n") print("Repeated adaptive...") path = adaptive(maze3, start, end) print(path) i = 0; ForwardrunTimeList = [] while i < 50: pathStr = 'E:/Coding/python work/project1/arrs/randGrid/' + str(i) + '.txt' print(pathStr) with open(pathStr, 'r') as f: forwardMaze = [[int(num) for num in line.split(' ') * 2] for line in f] startTime = timeit.default_timer() start = (5,7) #end = (len(maze)-1, len(maze[0])-1) #path = astar(maze, start, end) end = (10,10) path = repeatedForward(forwardMaze, start, end) print(path) #path = repeatedBackward(maze3, start, end) # print("repeated Backward:") #print(path) stopTime = timeit.default_timer() print('Time: ', stopTime - startTime) totalTime = stopTime - startTime #add time to runTime list ForwardrunTimeList.append(totalTime) i += 1 BackwardrunTimeList = [] #running repeated backward on the 50 mazes generated i = 0 while i < 50: pathStr = 'E:/Coding/python work/project1/arrs/randGrid/' + str(i) + '.txt' print(pathStr) with open(pathStr, 'r') as f: backwardMaze = [[int(num) for num in line.split(' ') * 2] for line in f] startTime = timeit.default_timer() start = (5,7) #end = (len(maze)-1, len(maze[0])-1) #path = astar(maze, start, end) end = (10,10) path = repeatedBackward(backwardMaze, start, end) print(path) #path = repeatedBackward(maze3, start, end) # print("repeated Backward:") #print(path) stopTime = timeit.default_timer() print('Time: ', stopTime - startTime) totalTime = stopTime - startTime #add time to runTime list BackwardrunTimeList.append(totalTime) i += 1 AdaptiverunTimeList = [] #running repeated backward on the 50 mazes generated i = 0 while i < 50: pathStr = 'E:/Coding/python work/project1/arrs/randGrid/' + str(i) + '.txt' print(pathStr) with open(pathStr, 'r') as f: Maze = [[int(num) for num in line.split(' ') * 2] for line in f] startTime = timeit.default_timer() start = (0,0) #end = (len(maze)-1, len(maze[0])-1) #path = astar(maze, start, end) end = (4,4) path = adaptive(Maze, start, end) print(path) #path = repeatedBackward(maze3, start, end) # print("repeated Backward:") #print(path) stopTime = timeit.default_timer() print('Time: ', stopTime - startTime) totalTime = stopTime - startTime #add time to runTime list AdaptiverunTimeList.append(totalTime) i += 1 ForwardrunTimeList = ForwardrunTimeList[::] print("Forward runtime list is ", ForwardrunTimeList) BackwardrunTimeList = BackwardrunTimeList[::] print("Backward runtime list is ", BackwardrunTimeList) AdaptiverunTimeList = AdaptiverunTimeList[::] print("Adaptive runtime list is ", AdaptiverunTimeList) if __name__ == "__main__": main();
#imports import json #dictionaries rules = {} first = {} follow = {} def get_rules_line(operator, line): if '|' in line: for part in line.split('|'): get_rules_line(operator, part) else: rules[operator].append(line) def get_first(operator, rule): if rule[0].islower() or rule[0] == '0': first[operator].append(rule[0]) else: if len(first[str(rule[0])]) == 0: init_first(rule[0]) init_first(operator) else: for first_term in first[rule[0]]: if first_term == '0': if len(rule[1:]) >= 1: get_first(operator, rule[1:]) else: first[operator].append('0') else: first[operator].append(first_term) def get_follow(operator): for key in rules.keys(): for rule in rules[key]: if operator in rule: #if the searching operator is the last index or the next character is empty string and last index #i.e S->ABC0 if searching for C considering 0 as the empty string it is the last index. if rule.find(operator) == len(rule)-1 or (rule[rule.find(operator)+1] == '0' and rule.find(operator)+1 == len(rule)-1): if len(follow[key]) == 0: get_follow(key) else: follow[operator].extend(follow[key]) else: index = rule.find(operator) + 1 run = True while index < len(rule) and run: run = False temp = rule[index] if temp.islower(): follow[operator].append(temp) break else: for fll in first[temp]: if fll == '0': run = True else: follow[operator].append(fll) index += 1 def init_first(char): for rule in rules[char]: get_first(char, rule) def make_unique_list(list_val): return list(set(list_val)) # reading the rules from file number_of_rules = 0 with open('input_rules.txt', "r") as f: for line in f: rules[line[0]] = [] first[line[0]] = [] follow[line[0]] = [] if number_of_rules == 0: follow[line[0]].append('$') number_of_rules += 1 get_rules_line(line[0], line[3:].replace("\n", "")) for left in rules.keys(): init_first(left) for left in rules.keys(): get_follow(left) print() print("Rules.") print("----------------------------------------------") for left in rules.keys(): print(left + ": " + str(make_unique_list(rules[left]))) print() print("First.") print("----------------------------------------------") for left in first.keys(): print(left + ": " + str(make_unique_list(first[left]))) print() print("Follow.") print("----------------------------------------------") for left in follow.keys(): print(left + ": " + str(make_unique_list(follow[left])))
#comments in python #print("start print- first Hellooo") #i=input("enter you name") #print("your name" +i) #readData = input("enter name2"); print(readData) #datatypes in python #Numer, string, list, tuples, dictionary #working on variables #i=10 #print(i) #i="name" #print(i) # exercise 1 #name = input("Enter Name") #age = input("enter age") #location = input("enter location") #print("User Name is " +name+", is " +age+" old and lives in " +location) # exercise 2 name = input("Enter Name") engmarks = input("enter english marks") matmarks = input("enter maths marks") scmarks = input("enter science marks") avg = (int(engmarks)+int(matmarks)+int(scmarks))/3 print ("Hi " +name+ " your marks "+str(avg)+"%")
str1 =" testing world " #print(str1[6]) #print(str1[1:5]) #print(len(str1)) #print(str1.upper()) #print(str1.lower()) #print(str1.capitalize()) #print(len(str1.strip())) #print(str1.replace("t","s")) """ count=0 for i in str1: if(i =='t'): count +=1 print(count) """ print(reversed(str1))
import numpy puzzle = [ [0,0,0,0,1,0,0,7,0], [0,0,4,0,6,5,0,9,0], [8,0,6,0,0,0,0,0,0], [2,0,7,0,9,3,1,0,0], [0,9,0,8,0,1,0,4,0], [0,0,3,7,5,0,9,0,2], [0,0,0,0,0,0,8,0,7], [0,7,0,6,4,0,5,0,0], [0,3,0,0,8,0,0,0,0] ] def checkcell(x,y,test_num): global puzzle # find which cell we are in cur_cell = {"x": (x//3) * 3, "y": (y//3) * 3} # check cells for row in range(cur_cell["y"], cur_cell["y"]+3): for col in range(cur_cell["x"], cur_cell["x"]+3): if puzzle[row][col] == test_num: return False # check row for i in range(9): # if puzzle row and column = testnum if puzzle[y][i] == test_num: return False # check column for i in range(9): if puzzle[i][x] == test_num: return False return True def sudoku_backtrace(): global puzzle for row in range(9): # for every row for col in range(9): # for every column cur_value = puzzle[row][col] # current value of the selected cell if cur_value == 0: for canidate_number in range(1,10): # test every possible number if checkcell(col, row, canidate_number): # if checkcell returns true puzzle[row][col] = canidate_number # apply the number to the cell sudoku_backtrace() # recursion! puzzle[row][col] = 0 # if backtrace fails, reset and and go back a step return print(numpy.matrix(puzzle)) input("Enter to try for another result ") # print(checkcell(1,0,9)) sudoku_backtrace() print("Finished!")
import pandas as pd from pyTruthTable import * #Import all methods from pyTruthTable # intialise firs columns. df = pd.DataFrame({'A':[True, True, False, False], 'B':[True, False, True, False]}) # Create other collumns of the dataframe calling methods df = df.join(l_implies(df, 0 ,1)) # Thrid column: a->b df = df.join(l_not(df, 1)) # Forth column: not b df = df.join(l_and(df, 0, 1)) # Fith column: a and b df = df.join(l_or(df, 0, 1)) # Sixth column: a or b df = df.join(l_equals(df, 4, 5)) # Seventh column: fith column <-> sixth column print(df)
from common.util import * from typing import List # --- Day 6: Custom Customs --- # As your flight approaches the regional airport where you'll switch to a much larger plane, # customs declaration forms are distributed to the passengers. # The form asks a series of 26 yes-or-no questions marked a through z. # All you need to do is identify the questions for which anyone in your group answers "yes". # Since your group is just you, this doesn't take very long. # However, the person sitting next to you seems to be experiencing a language barrier and asks if you can help. # For each of the people in their group, you write down the questions for which they answer "yes", one per line. For example: # abcx # abcy # abcz # In this group, there are 6 questions to which anyone answered "yes": a, b, c, x, y, and z. # (Duplicate answers to the same question don't count extra; each question counts at most once.) # Another group asks for your help, then another, and eventually you've collected answers from every group on the plane # (your puzzle input). Each group's answers are separated by a blank line, and within each group, # each person's answers are on a single line. For example: # abc # a # b # c # ab # ac # a # a # a # a # b # This list represents answers from five groups: # The first group contains one person who answered "yes" to 3 questions: a, b, and c. # The second group contains three people; combined, they answered "yes" to 3 questions: a, b, and c. # The third group contains two people; combined, they answered "yes" to 3 questions: a, b, and c. # The fourth group contains four people; combined, they answered "yes" to only 1 question, a. # The last group contains one person who answered "yes" to only 1 question, b. # In this example, the sum of these counts is 3 + 3 + 3 + 1 + 1 = 11. # For each group, count the number of questions to which anyone answered "yes". What is the sum of those counts? def part1(data: List[str]) -> int: count = 0 questions = set() for i, item in enumerate(data): if item != "": for char in item: questions.add(char) if i == len(data) - 1 or item == "": count += len(questions) questions = set() return count data = get_data("day06", line_parser) print(part1(data)) # --- Part Two --- # As you finish the last group's customs declaration, you notice that you misread one word in the instructions: # You don't need to identify the questions to which anyone answered "yes"; # you need to identify the questions to which everyone answered "yes"! # Using the same example as above: # abc # a # b # c # ab # ac # a # a # a # a # b # This list represents answers from five groups: # In the first group, everyone (all 1 person) answered "yes" to 3 questions: a, b, and c. # In the second group, there is no question to which everyone answered "yes". # In the third group, everyone answered yes to only 1 question, a. Since some people did not answer "yes" to b or c, they don't count. # In the fourth group, everyone answered yes to only 1 question, a. # In the fifth group, everyone (all 1 person) answered "yes" to 1 question, b. # In this example, the sum of these counts is 3 + 0 + 1 + 1 + 1 = 6. # For each group, count the number of questions to which everyone answered "yes". What is the sum of those counts? def part2(data: List[str]) -> int: from functools import reduce count = 0 questions = [] for i, item in enumerate(data): temp_set = set() if item != "": for char in item: temp_set.add(char) questions.append(temp_set) temp_set = set() if i == len(data) - 1 or item == "": count += len(reduce(lambda a, b: a & b, questions)) questions = [] return count data = get_data("day06", line_parser) print(part2(data))
print(1 + 1) print(3 - 2) print(5 * 2) print(6 / 3) print("-" * 15) print(2 ** 3) # 2^3 = 8 print(5 % 3) print(5 // 3) # 1 print(10 // 3) # 3 print("-" * 15) print(10 > 3) # True print(4 >= 7) print(3 == 3) print(3 != 5) print(3 + 4 == 7) print("-" * 15) print(not (1 != 3)) print((3 > 0) and (3 < 5)) print((3 > 0) & (3 < 5)) print((3 > 0) or (3 > 5)) print((3 > 0) | (3 > 5)) print("-" * 15) print(5 > 4 > 3) print(5 > 4 > 3) print("-" * 15) print(2 + 3 * 4) print((2 + 3) * 4) number = 2 + 3 * 4 number = number + 2 print(number) number += 2 print(number) number %= 2 print(number)
# 표준 체중 구하기 # def std_weight(height, gender): # if gender == "man": # weight = round(float(height * height * 22/10000), 2) # elif gender == "woman": # weight = round(float(height * height * 21/10000), 2) # result = "키 {0}cm {1}의 표준 체중은 {2}kg 입니다.".format(height, gender, weight) # return result # # info = input().split() # result = std_weight(int(info[0]), info[1]) # print(result) def std_weight(height, gender): # 키는 m단위 (실수) if gender == "남자": return height * height * 22 else: return height * height * 21 height = 175 gender = "남자" weight = round(std_weight(height / 100, gender), 2) print("키 {0}cm {1}의 표준 체중은 {2}kg 입니다.".format(height, gender, weight, 2))
import numpy as np import collections def khatrirao(matrices, skip_matrix=None, reverse=False): """Khatri-Rao product of a list of matrices This can be seen as a column-wise kronecker product. (see [1]_ for more details). Parameters ---------- :param matrices: ndarray list list of matrices with the same number of columns, i.e.:: for i in len(matrices): matrices[i].shape = (n_i, m) :param skip_matrix: None or int, optional, default is None if not None, index of a matrix to skip :param reverse: bool, optional if True, the order of the matrices is reversed Returns ------- khatri_rao_product: matrix of shape ``(prod(n_i), m)`` where ``prod(n_i) = prod([m.shape[0] for m in matrices])`` i.e. the product of the number of rows of all the matrices in the product. >>> import numpy as np >>> a = np.array([[1.,3.],[2.,4.]]) >>> b = np.array([[5,6],[7,8],[9,10]]) >>> np.sum(khatrirao((a,b), reverse=True), 1)[2] 31.0 """ matrices = list(matrices) if skip_matrix is not None: if skip_matrix > -1: matrices = [matrices[i] for i in range(len(matrices)) if i != skip_matrix] else: raise ValueError('Wrong skip_matrix: {}'.format(skip_matrix)) if matrices[0].ndim == 1: matrices[0] = np.reshape(matrices[0], [1, -1]) n_columns = matrices[0].shape[1] # Optional part, testing whether the matrices have the proper size for i, matrix in enumerate(matrices): if matrix.ndim != 2: raise ValueError('All the matrices must have exactly 2 dimensions!' 'Matrix {} has dimension {} != 2.'.format( i, matrix.ndim)) if matrix.shape[1] != n_columns: raise ValueError('All matrices must have same number of columns!' 'Matrix {} has {} columns != {}.'.format( i, matrix.shape[1], n_columns)) n_factors = len(matrices) if reverse: matrices = matrices[::-1] # Note: we do NOT use .reverse() which would reverse matrices # even outside this function start = ord('a') common_dim = 'z' target = ''.join(chr(start + i) for i in range(n_factors)) source = ','.join(i + common_dim for i in target) operation = source + '->' + target + common_dim return np.einsum(operation, *matrices).reshape((-1, n_columns)) def perm_matrix(x): """Returns a matrix corresponding to a given permutation vector""" n = len(x) return np.eye(n, n)[:, x]
import sqlite3 conn = sqlite3.connect('rpg_db.sqlite3') cur = conn.cursor() # How many total Characters are there? result_1 = cur.execute("SELECT COUNT(*) FROM charactercreator_character;").fetchall()[0][0] print(f" How many total Characters are there? Answer: {result_1}") # How many of each specific subclass? result_2 = cur.execute("SELECT COUNT(*) FROM charactercreator_fighter;").fetchall()[0][0] result_3 = cur.execute("SELECT COUNT(*) FROM charactercreator_mage;").fetchall()[0][0] result_4 = cur.execute("SELECT COUNT(*) FROM charactercreator_cleric;").fetchall()[0][0] result_5 = cur.execute("SELECT COUNT(*) FROM charactercreator_thief;").fetchall()[0][0] result_6 = cur.execute("SELECT COUNT(*) FROM charactercreator_necromancer;").fetchall()[0][0] print(f" How many of each specific subclass? fighter:{result_2}; mage:{result_3}; cleric:{result_4}; thief:{result_5}; necromancer:{result_6} ") # How many total Items? result_7 = cur.execute(" SELECT COUNT(*) FROM armory_item;").fetchall()[0][0] print(f" How many total Items? Answer: {result_7}") # How many of the Items are weapons? How many are not? result_8 = cur.execute(" SELECT COUNT(*) FROM armory_item, armory_weapon WHERE item_id == item_ptr_id; ").fetchall()[0][0] print(f" How many of the Items are weapons? Answer: {result_8}") ###
#!/usr/bin/env python """ IN COLLABORATION WITH AKHIL DATLA """ import arcade as game import sys import time import math import random """AKHIL'S CODE: SHAPE LOGIC""" # dist returns the distance between two points def dist(x1, y1, x2, y2): d = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) return d # slope returns the slope of the line between two points def slope(x1, y1, x2, y2): if (x2 - x1) == 0: return None else: s = (y2 - y1)/(x2 - x1) return s # isPerpendicular returns true if the lines are perpendicular def isPerpendicular(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2): s1 = slope(ax1, ay1, ax2, ay2) s2 = slope(bx1, by1, bx2, by2) if (s1 == None and s2 == 0) or (s1 == 0 and s2 == None): return True elif (s1 * s2) == -1: return True else: return False # isParallelogram returns true if the coordinates represent a parallelogram def isParallelogram(ax1, ay1, bx1, by1, cx1, cy1, dx1, dy1): # compute lengths length_ab = dist(ax1, ay1, bx1, by1) length_bc = dist(bx1, by1, cx1, cy1) length_cd = dist(cx1, cy1, dx1, dy1) length_da = dist(dx1, dy1, ax1, ay1) # compute slopes slope_ab = slope(ax1, ay1, bx1, by1) slope_bc = slope(bx1, by1, cx1, cy1) slope_cd = slope(cx1, cy1, dx1, dy1) slope_da = slope(dx1, dy1, ax1, ay1) if ((length_ab == length_cd) and (slope_ab == slope_cd)) or \ ((length_bc == length_da) and (slope_bc == slope_da)): return True else: return False # Same as code above but takes in tuples def isParallelogramTuple(coordA, coordB, coordC, coordD): # compute lengths ax1, ay1 = coordA bx1, by1 = coordB cx1, cy1 = coordC dx1, dy1 = coordD length_ab = dist(ax1, ay1, bx1, by1) length_bc = dist(bx1, by1, cx1, cy1) length_cd = dist(cx1, cy1, dx1, dy1) length_da = dist(dx1, dy1, ax1, ay1) # compute slopes slope_ab = slope(ax1, ay1, bx1, by1) slope_bc = slope(bx1, by1, cx1, cy1) slope_cd = slope(cx1, cy1, dx1, dy1) slope_da = slope(dx1, dy1, ax1, ay1) if ((length_ab == length_cd) and (slope_ab == slope_cd)) or \ ((length_bc == length_da) and (slope_bc == slope_da)): return True else: return False # print(isParallelogram(2, 4, 8, 4, 6, 0, 0, 0)) """ADITYA'S CODE: USER INTERFACE""" # Define Constants HEIGHT = 750 WIDTH = 750 rows = 20 scale = 30 rowsVal = [] columnVal = [] code = [] lines = [] debug = True debugExec = False realindex = 0 undocount = 0 # Colors class Colors: black = (0, 0, 0) gray = (130, 130, 130) white = (150, 150, 150) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) colors = [gray, white, red, green, blue] # Finds Distance Between Two Points def exactDist(x1, y1, x2, y2): return math.sqrt((x1 - x2)**2 + (y1 - y2)**2) # Draws Graph def drawGrid(): global HEIGHT, WIDTH, rows, scale, size for i in range(2): game.draw_xywh_rectangle_filled(0, 0, WIDTH, HEIGHT, Colors.black) x = 0 y = 0 size = WIDTH // rows for i in range(rows): x += size y += size rowsVal.append(x) columnVal.append(y) game.draw_line(x, HEIGHT, x, 0, Colors.gray, 0.3) game.draw_line(WIDTH, y, 0, y, Colors.gray, 0.3) game.draw_line(WIDTH // 2, 0, WIDTH // 2, HEIGHT, Colors.white, 2) game.draw_line(0, HEIGHT // 2, WIDTH, HEIGHT // 2, Colors.white, 2) # Class holding all points and connections between them class Point: def __init__(self): self.points = [] self.count = 0 # Add a point def append(self, coord): self.points.append(tuple(coord)) # check if points make a parrallelogram using akhil's code def check(self): if len(self.points) == 4: print("Is Parrallelogram: {}".format(isParallelogramTuple(self.points[0], self.points[1], self.points[2], self.points[3]))) def plot(self): values = input("Enter where you want to plot the point in this format: x, y\n") x, y = values.split(", ") realX = (int(x) + (rows // 2)) * size realY = (int(y) + (rows // 2)) * size self.points.append((realX, realY)) if debug: print("{}, {}".format(realX, realY)) code.append("game.draw_circle_filled({}, {}, self.radius, Colors.blue)\n".format(realX, realY)) # Connect Points def connect(self): global lines, size, realindex record = 420420 index = 0 if len(self.points) > 0: for c, v in enumerate(self.points): if exactDist(v[0], v[1], self.points[-1][0], self.points[-1][1]) < record and self.points[-1] != v: record = exactDist(v[0], v[1], self.points[-1][0], self.points[-1][1]) index = c # print("Record: {}".format(record)) if debug: print("Close to ({}, {}) at index {}".format(self.points[index][0] // size - (rows // 2), self.points[index][1] // size - (rows // 2), index)) if index <= len(self.points) - 2: if debug: print("Index - 1: {}, Index + 1: {}".format(exactDist(self.points[index-1][0] , self.points[index-1][1], self.points[-1][0], self.points[-1][1]), exactDist(self.points[index+1][0], self.points[index+1][1], self.points[-1][0], self.points[-1][1]))) if index <= len(self.points) - 2: if exactDist(self.points[index-1][0], self.points[index-1][1], self.points[-1][0], self.points[-1][1]) > exactDist(self.points[index+1][0], self.points[index+1][1], self.points[-1][0], self.points[-1][1]): self.points.insert(index+1, self.points[-1]) realindex = index + 1 if debug: print("index <; -1 >; insterting at {}".format(index+1)) else: self.points.insert(index, self.points[-1]) realindex = index if debug: print("index <; +1 >; inserting at {}".format(index)) else: print(index) if exactDist(self.points[index-1][0], self.points[index-1][1], self.points[-1][0], self.points[-1][1]) > exactDist(self.points[1][0], self.points[1][1], self.points[-1][0], self.points[-1][1]): self.points.insert(1, self.points[-1]) realindex = 1 if debug: print("index >; -1 >; inserting at {}".format(1)) else: self.points.insert(-2, self.points[-1]) realindex = -2 if debug: print("index >; -1 <; inserting at {}".format(-2)) if debug: print("Popped: ({}, {})".format(self.points[-1][0] // size - (rows // 2), self.points.pop()[1] // size - (rows // 2))) print() else: self.points.pop() for c, v in enumerate(self.points): if debug: print("({}, {})".format(v[0] // size - (rows // 2), v[1] // size - (rows // 2))) lines.append("game.draw_line({}, {}, {}, {}, Colors.colors[point.count])\n".format(v[0], v[1], self.points[c - 1][0], self.points[c - 1][1])) # Clear the Grid and saved values def clear(self): global lines, code, undocount for i in range(3): self.points = [] lines = [] code = [] game.start_render() for i in range(10): game.draw_xywh_rectangle_filled(0, HEIGHT, WIDTH, 0, Colors.black) game.finish_render() print("Reset") undocount = 0 point = Point() # Make the game window class Game(game.Window): def __init__(self, width, height, title): super(Game, self).__init__(width, height, title) self.radius = 3 # Add point where mouse was pressed def on_mouse_press(self, x, y, button, modifier): global code, lines if button == game.MOUSE_BUTTON_LEFT: lines = [] difference = 100 indexR = 1 indexC = 1 # Place point at nearest grid space for count, val in enumerate(columnVal): if abs(y - val) < difference: indexC = count difference = abs(y - val) difference = 100 for count, val in enumerate(rowsVal): if abs(x - val) < difference: indexR = count difference = abs(x - val) # print("Placing at ({}, {})".format(rowsVal[indexR], columnVal[indexC])) code.append("game.draw_circle_filled({}, {}, self.radius, Colors.blue)\n".format(rowsVal[indexR], columnVal[indexC])) point.append((rowsVal[indexR], columnVal[indexC])) point.connect() point.check() def on_key_press(self, key, modifiers): global undocount """Called whenever a key is pressed. """ # Reset Screen if key == game.key.P: point.plot() point.connect() if key == game.key.R: point.clear() # Undo last Action if key == game.key.U: if undocount >= 10: point.clear() if debugExec: print("Before:") print(code) print(lines) print("After:") code.pop() lines.pop(realindex) point.points.pop(realindex) if debugExec: print(code) print(realindex) print(lines) point.connect() for i in range(2): game.draw_xywh_rectangle_filled(WIDTH, HEIGHT, 0, 0, Colors.black) undocount += 1 point.check() def update(self, delta_time): pass # Execute all drawing commands def on_draw(self): drawGrid() for c in code: exec(c) for line in lines: exec(line) # Make screen screen = Game(HEIGHT, WIDTH, "Make a Shape!") # Run code game.run()
import math a = float(input('Längd katet 1: ').replace(',', '.')) b = float(input('Längd katet 2: ').replace(',', '.')) c = math.sqrt(a**2 + b**2) print(f'Hypotenusan är {c}')
import os INSTRUCTIONS = '''Welcome to 'Who wants to be a millionaire'! This came consists of 15 questions, that gets progressively harder, but also comes with greater rewards. As long as you answer correctly you earn more money, but if you answer wrong, you lose what you have earned. After questions 5 and 10 you get a guarantee that you will get at least that amount, even if you fail a later question. You are free to give up at any time (by answering with 'q') and you walk away with what you have earned. Press return to begin... ''' class Question(): '''Class for storing a question with muliple answers, whith functions for printing the question to stdout, validating the answer, and getting the correct answer''' def __init__(self, question, choices, correct_answer, prize): self.question = question self.choices = choices self.correct_answer = correct_answer self.prize = prize def print(self): '''Prints the question and alternatives''' print(self.question) for i in range(len(self.choices)): print(f'{i + 1}. {self.choices[i]}') def validate_answer(self, answer): '''Validate if the input answer is correct''' return int(answer) == self.correct_answer def get_correct(self): '''Return the correct answer''' return self.choices[self.correct_answer - 1] def load_questions(path = os.path.dirname(__file__)): '''Read from different files and construct the questions''' # Add dir separator to path if necessary if not path.endswith(os.sep): path = path + os.sep questions = [] # Open files for reading with open(path + 'questions.txt', 'r') as question_file, \ open(path + 'choices.txt', 'r') as choice_file, \ open(path + 'answers.txt', 'r') as answer_file, \ open(path + 'prize.txt', 'r') as prize_file: # Iterate through the files and construct questions for _ in range(15): question = question_file.readline().strip() choices = [] for _ in range(4): choices.append(choice_file.readline().strip()) answer = int(answer_file.readline().strip()) prize = int(prize_file.readline().strip()) questions.append(Question(question, choices, answer, prize)) return questions def get_answer(): '''Reads and validates user input''' while True: answer = input('==> ') if answer in ('q', '1', '2', '3', '4'): return answer print('Ogiltigt svar, försök igen') def main(): # Try to load questions, exit on failiure try: questions = load_questions() except (IOError, FileNotFoundError) as e: print('Failed to load questions:', e) exit(1) # At the beginning, the player isn't guaranteed any prize guaranteed = 0 # Print instructions and wait for the player to start the game input(INSTRUCTIONS) for index, question in enumerate(questions): # Print the question and wait for answer print(f'Question {index + 1} for {question.prize}') question.print() answer = get_answer() # Exit the game if the player demands, and shaw the prize for the previous question if answer == 'q': print(f'Thanks for playing, you get to take {0 if index == 0 else questions[index-1].prize} home.') break # Check if the answer is correct if question.validate_answer(answer): # If it's the last question if index == 14: print('YOU WON!!!!! YOU\'RE A MILLIONAIRE!!!!!!!!!!') else: print('Right answer!\n') # Update the guaranteed prize if at question 5 or 10 (index 4 resp 9) if index % 5 == 4: guaranteed = question.prize else: # Wrong answer, print out the prize, the correct answer and then exit print('Sorry, that is the wrong answer, ', end='') if guaranteed == 0: print('you will go home empty handed.') else: print(f'you get to take {guaranteed} home.') print(f'The right answer was {question.get_correct()}') break main()
import math def mean(array): return sum(array) / len(array) def variance(array): m = mean(array) diffs = [(n - m) ** 2 for n in array] return mean(diffs) def stddev(array): return math.sqrt(variance(array))
from typing import Union, Literal class A: ... # value undefined a = c # E Cannot determine type of 'c'(unresolved reference 'c') # any a = 1 a = "s" # ok b: int = "hjzs" # E Incompatible type in assignment(expression has type 'Literal['hjzs']', variable has type 'int') b = a # E Incompatible type in assignment(expression has type 'Literal['s']', variable has type 'int') b = A() # E Incompatible type in assignment(expression has type 'A', variable has type 'int') # type[A] and A c: A = A # E Incompatible type in assignment(expression has type 'Type[A]', variable has type 'A') c = A() # t1 = "s" # if A: # t1 = A() # t2: int = t1 t3: int = "s" # E Incompatible type in assignment(expression has type 'Literal['s']', variable has type 'int') t4: int = t3 # ok d: Literal[1] = 1
import hashlib import os def hashFile(path): """Hashes a file and returns the hashvalue""" m = hashlib.md5() try: file = open(path, "r") for chunk in iter(lambda: file.read(4096), b""): m.update(chunk) return m.hexdigest() except Exception as e: print e exit -1 def hashDir(path): """Hashes a directory and returns the hashvalue""" hash = "" for root, dirs, files in os.walk(path): for names in sorted(files): try: filepath = os.path.join(root, names) hash += hashFile(filepath) except Exception as e: print e exit -1 return hash
class HistoryManager(): def __init__(self, maxSize=100): """ Initialize HistoryManager which saved maximal maxSize states. The maxSize+1 insertion removes the first """ self.history = [] # Position is a value contains the index of the state in a continues way. # That means even when the first entries get deleted because of maxSize # self.position do not get decreased by this. self.position = -1 # the index of the current position in history list self.__idx = -1 # self.listLen contains maxSize self.listLen = maxSize # If this gets true, no other entry can be make in history self.__lockHistory = False def canUndo(self): return self.__idx >0 def canRedo(self): return self.__idx < len(self.history)-1 def undo(self): if self.canUndo(): self.__idx -=1 self.position -= 1 def redo(self): if self.canRedo(): self.__idx +=1 self.position += 1 def currentState(self): """ Get latest state saved in history""" if len(self.history) > 0: return self.history[self.__idx] else: return None def _insert(self,element): """ Insert element at the current position """ # remove newer elements del self.history[self.__idx + 1:] # Remove the oldest element if there are too many elements if self.__idx == self.listLen: del self.history[0] else: self.__idx += 1 self.history.append(element) self.position += 1 def lockHistory(self, fun): """ Lock history for the whole method fun. As a result no history can be inserted whil fun is executed. """ if self.__lockHistory: return self.__lockHistory = True fun() self.__lockHistory = False def insertFunc(self, fun): """ Insert an element in history using the function fun. While fun is working insertFunc is locked, so no other element can be added in history. As a result recursivly insertion of history is stopped. The function fun will be called with in insertion function which can be called to insert an element in history. E.g.: def createNewElement(text): # Nothing happend, because insertFunc is locked historymanager.insertFunc(lambda insertF: insertF(text)) return text historymananger.insertFunc(lambda insertF: insertF(createNewElement("bla")) # Only one string will be insert When inserting a new state old state gets removed if the limit of entries is reached. Also states newer than the current one (e.g. by using undo()) get removed (so you can't do a redo() anymore) """ if self.__lockHistory: return self.__lockHistory = True fun(self._insert) self.__lockHistory = False def clear(self): self.position = -1 self.__idx = -1 self.history = []
def countingValleys(steps: int, path: str) -> int: """ :param steps: the number of steps on the hike :param path: a string describing the path :return: the number of valleys traversed """ level, valleys = 0, 0 for i in range(steps): if path[i] == 'U': level += 1 if not level: valleys += 1 else: level -= 1 return valleys if __name__ == '__main__': print(countingValleys(int(input()), str(input())))
from bisect import bisect_left, insort_left from typing import List def median(arr: List[int], days: int) -> int: """ :return: median of arr """ return arr[days // 2] if days % 2 else ((arr[days // 2] + arr[days // 2 - 1]) / 2) def activityNotifications(expenditure: List[int], d: int) -> int: """ :param expenditure: daily expenditures :param d: the lookback days for median spending :return: the number of notices sent """ notifications = 0 heap = sorted(expenditure[:d]) for i in range(d, len(expenditure) - 1): if expenditure[i] >= 2 * median(heap, d): notifications += 1 del heap[bisect_left(heap, expenditure[i-d])] insort_left(heap, expenditure[i]) return notifications if __name__ == '__main__': nd = input().split() n = int(nd[0]) _days = int(nd[1]) print(activityNotifications(list(map(int, input().rstrip().split())), _days))
from typing import List def maximumToys(prices: List[int], k: int) -> int: """ :param prices: the toy prices :param k: Mark's budget :return: the maximum number of toys """ maximum_toys = 0 prices.sort() for maximum_toys in range(len(prices)): if k > prices[maximum_toys]: k -= prices[maximum_toys] else: break return maximum_toys if __name__ == '__main__': nk = input().split() n = int(nk[0]) amount = int(nk[1]) print(maximumToys(list(map(int, input().rstrip().split())), amount))
from Calculator.Calculator import addition from Calculator.Calculator import division import getSamp #Pulled From Example Files def sample_mean(data, sample_size): if(sample_size>0) and (sample_size <= data.len()): total = 0 # check that get sample returns the proper number of samples # check that sample size is not 0 # check that sample size is not larger than the population # https://realpython.com/python-exceptions/ # https://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception sample = getSamp(data, sample_size) num_values = len(sample) for num in sample: total = addition(total,num) return division(total, num_values) else: raise Exception("Sample must be larger than 0 and no more than the sample size") #TO DO implement unit test that tests this exception
''' Created on Nov 27, 2016 @author: Marlon_2 ''' name = input("What is your name? ") if name == "Alice": print ("Good morning", name + "!") elif name == "Bob": print ("Good morning", name + "!") else: print ("Who are you?", "I don't know", name + ".")
import sys input = sys.stdin.readline def union(a, b): a = find(a) b = find(b) if a > b: arr[a] = b else: arr[b] = a return def find(num): if arr[num] == num: return num num = find(arr[num]) return num n, m = map(int, input().split()) arr = [i for i in range(n+1)] print(arr) for i in range(m): op, a, b = map(int, input().split()) if op: if find(a) == find(b): print("yes") else: print("no") else: union(a, b) # 7 8 # 0 1 3 # 1 1 7 # 0 7 6 # 1 7 1 # 0 3 7 # 0 4 2 # 0 1 1 # 1 1 1 # 0 7 2 # 0 6 3
""" Name: Celeste Sila Date: April 27, 2021 Module: 9.3 Description: Update and delete records from pysports database. GitHub Repository: https://github.com/celestesila/csd-310 """ import mysql.connector #from mysql.connector import errorcode config = { "user": "pysports_user", "password": "MySQL8IsGreat!", "host": "127.0.0.1", "database": "pysports", "raise_on_warnings": True } def show_players(cursor, title): # inner join query cursor.execute("SELECT player_id, first_name, last_name, team_name FROM player INNER JOIN team ON player.team_id = team.team_id") # get results players = cursor.fetchall() print("\n -- {} --".format(title)) # display the results for player in players: print(" Player ID: {}\n First Name: {}\n Last Name: {}\n Team Name: {}\n".format(player[0], player[1], player[2], player[3])) # connect to pysports database db = mysql.connector.connect(**config) cursor = db.cursor() # insert player query add_player = ("INSERT INTO player(first_name, last_name, team_id)" "VALUES(%s, %s, %s)") # player data fields player_data = ("Smeagol", "Shire Folk", 1) # insert new player record cursor.execute(add_player, player_data) # commit insert to database db.commit() # show all records in player table show_players(cursor, "DISPLAYING PLAYERS AFTER INSERT") # update newly inserted record update_player = ("UPDATE player SET team_id = 2, first_name = 'Gollum', last_name = 'Ring Stealer' WHERE first_name = 'Smeagol'") # execute update query cursor.execute(update_player) # show all records in player table show_players(cursor, "DISPLAYING PLAYERS AFTER UPDATE") # delete query delete_player = ("DELETE FROM player WHERE first_name = 'Gollum'") cursor.execute(delete_player) # show all records in player table show_players(cursor, "DISPLAYING PLAYERS AFTER DELETE") input("\n\n Press any key to continue... ") db.close()
# Update the appointments from tkinter import * import tkinter.messagebox import sqlite3 #Connect to database conn = sqlite3.connect('database.db') #Cursor to move around the database c = conn.cursor() class Application1: def __init__(self, master): self.master = master #Creating the Frames in the master self.left = Frame(master, width=800, height=720, bg='medium sea green',bd=15,relief="groove") self.left.pack(side=LEFT) #Heading label self.heading = Label(master, text=" UPDATE APPOINTMENTS ", font=('consolas 35 bold'),fg='green', bg='white',bd=10,relief="groove") self.heading.place(x=114,y=18) # Search criteria --> name self.name = Label(master, text = "Enter Patient's Name",fg='white',bg='medium sea green', font=('arial 18 bold')) self.name.place(x=18,y=110) #Entry for the Name self.namenet = Entry(master, width=20,font=('arail',14,'bold'),bg="lemonchiffon",bd=7) self.namenet.place(x=460,y=110) #Search button self.search = Button(master, text="Search", font=('arail',14,'bold'), width=17,height=1,bg='lightpink', bd=10,command=self.search_db) self.search.place(x=460,y=165) #Function to search def search_db(self): self.input = self.namenet.get() #Execute sql sql = "SELECT * FROM appointments WHERE name LIKE ?" self.res = c.execute(sql, (self.input,)) for self.row in self.res: self.name1 = self.row[1] self.age = self.row[2] self.gender = self.row[3] self.location = self.row[4] self.phone = self.row[5] self.time = self.row[6] #Creating the update form self.uname = Label(self.master, text="Patient's Name",fg='white',bg='medium sea green', font=('arial 18 bold')) self.uname.place(x=18, y=240) self.uage = Label(self.master, text="Age",fg='white',bg='medium sea green', font=('arial 18 bold')) self.uage.place(x=18, y=310) self.ugender = Label(self.master, text="Gender",fg='white',bg='medium sea green', font=('arial 18 bold')) self.ugender.place(x=18, y=380) self.ulocation = Label(self.master, text="Location",fg='white',bg='medium sea green', font=('arial 18 bold')) self.ulocation.place(x=18, y=450) self.utime = Label(self.master, text="Appointment Time",fg='white',bg='medium sea green', font=('arial 18 bold')) self.utime.place(x=18, y=520) self.uphone = Label(self.master, text="Phone Number",fg='white',bg='medium sea green', font=('arial 18 bold')) self.uphone.place(x=18, y=590) #Enteries for each Label====================================== #==============Filling the search result in the entry box to update========== self.ent1 = Entry(self.master, font=('arail',14,'bold'),bg="lemonchiffon",bd=7 , width=20) self.ent1.place(x=460,y=240) self.ent1.insert(END, str(self.name1)) self.ent2 = Entry(self.master, font=('arail',14,'bold'),bg="lemonchiffon",bd=7 , width=20) self.ent2.place(x=460,y=310) self.ent2.insert(END, str(self.age)) self.ent3 = Entry(self.master, font=('arail',14,'bold'),bg="lemonchiffon",bd=7 , width=20) self.ent3.place(x=460,y=380) self.ent3.insert(END, str(self.gender)) self.ent4 = Entry(self.master, font=('arail',14,'bold'),bg="lemonchiffon",bd=7 , width=20) self.ent4.place(x=460,y=450) self.ent4.insert(END, str(self.location)) self.ent5 = Entry(self.master, font=('arail',14,'bold'),bg="lemonchiffon",bd=7 , width=20) self.ent5.place(x=460,y=520) self.ent5.insert(END, str(self.time)) self.ent6 = Entry(self.master, font=('arail',14,'bold'),bg="lemonchiffon",bd=7 , width=20) self.ent6.place(x=460,y=590) self.ent6.insert(END, str(self.phone)) #Button to execute update self.update = Button(self.master, text="Update", font=('arail',14,'bold'), width=17,height=1,bg='green', bd=10,command=self.update_db) self.update.place(x=431,y=639) #Button to delete self.delete = Button(self.master, text="Delete", font=('arail',14,'bold'), width=17, height=1,bg='red',bd=10,command=self.delete_db) self.delete.place(x=146,y=639) def update_db(self): #Declaring the variable to update self.var1 = self.ent1.get()#Updated name self.var2 = self.ent2.get()#Updated age self.var3 = self.ent3.get()#Updated gender self.var4 = self.ent4.get()#Updated location self.var5 = self.ent5.get()#Updated time self.var6 = self.ent6.get()#Updated phone #Updating the Database query = " UPDATE appointments SET name=?, age=?, gender=?, location=?, phone=?, scheduled_time=? WHERE name LIKE ?" c.execute(query, (self.var1, self.var2, self.var3, self.var4, self.var6, self.var5, self.namenet.get(),)) conn.commit() tkinter.messagebox.showinfo("UPDATED", "Successfully Updated.") def delete_db(self): #Deleting the appointment sql2 = " DELETE FROM appointments WHERE name LIKE ? " c.execute(sql2, (self.namenet.get(),)) conn.commit() tkinter.messagebox.showinfo("SUCCESS", "Deleted Sucessfully") self.ent1.destroy() self.ent2.destroy() self.ent3.destroy() self.ent4.destroy() self.ent5.destroy() self.ent6.destroy()
''' Define a Python function descending(l) that returns True if each element in its input list is at most as big as the one before it. For instance: >>> descending([]) True >>> descending([4,4,3]) True >>> descending([19,17,18,7]) False ''' #Program def descending(l): x=0 if len(l)<=1 or (len(l)==2 and l[0]>=l[1]): return True else: if l[0]<=l[1]: return descending(l[1:]) else: return False
''' A list rotation consists of taking the first element and moving it to the end. For instance, if we rotate the list [1,2,3,4,5], we get [2,3,4,5,1]. If we rotate it again, we get [3,4,5,1,2]. Write a Python function rotatelist(l,k) that takes a list l and a positive integer k and returns the list l after k rotations. If k is not positive, your function should return l unchanged. Note that your function should not change l itself, and should return the rotated list. Here are some examples to show how your function should work. >>> rotatelist([1,2,3,4,5],1) [2, 3, 4, 5, 1] >>> rotatelist([1,2,3,4,5],3) [4, 5, 1, 2, 3] >>> rotatelist([1,2,3,4,5],12) [3, 4, 5, 1, 2] ''' #Program def rotatelist(l,k): if k<0: return l else: return l[k%len(l):]+l[:k%len(l)]
#simple solution def isAnagram1(str1,str2): str1 = str1.replace(' ','').lower() str2 = str2.replace(' ','').lower() return sorted(str1) == sorted(str2) # solution interviewer looking for by appying the logic def isAnagram2(str1,str2): str1 = str1.replace(' ','').lower() str2 = str2.replace(' ','').lower() if len(str1) != len(str2): return False count1 = {} count2 = {} for letter in str1: if letter in count1: count1[letter] += 1 else: count1[letter] = 1 for letter in str2: if letter in count2: count2[letter] += 1 else: count2[letter] = 1 return count1 == count2
""" Simple crypto voting based on paillier crypto system based on http://security.hsr.ch/msevote/seminar-papers/HS09_Homomorphic_Tallying_with_Paillier.pdf Implemented by Nur (nur858@gmail.com) For purely educational purpose. """ import paillier def cast_vote(choice,pk, tally): c = paillier.encrypt(pk, choice) if tally ==0: return c return paillier.p_add(tally, c, pk) def count_vote(tally, pk, sk, base): tally = paillier.decrypt(pk, sk, tally) count = [] while tally: count.append(tally%base) tally = tally/base return count def find_base(voters): return 10 **len(str(voters)) def main(): numvoters = 5 #total number of voters. b = find_base(numvoters) sA = b**0 # symbol for candidate A sB = b**1 # symbol for candidate B sC = b**2 # symbol for candidate C pk, sk = paillier.keygen(128) votecount = cast_vote(sA,pk, 0) votecount = cast_vote(sB,pk, votecount) votecount = cast_vote(sA,pk, votecount) votecount = cast_vote(sA,pk, votecount) votecount = cast_vote(sC,pk, votecount) result = count_vote(votecount, pk, sk, b) print "Candidate A got: {0} votes" .format(result[0]); print "Candidate B got: {0} votes" .format(result[1]); print "Candidate C got: {0} votes" .format(result[2]); if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ Created on Sat Sep 5 12:25:59 2020 @author: Hillina Mesfin #This program prompts the user to enter their first and last name #At the end the code will print out a greeting """ first_name = input ("What is your first name? ") last_name = input ("What is your last name? ") print ("Hello," , first_name , last_name + "!")
class Bottles: def song(self): return self.verses(99,0) def verses(self, last, first): o = self.verse(last) for i in range (last-1, first-1, -1): o += "\n" + self.verse (i) return o def verse(self, number = None): bottle_number = self.bottleNumberFactory(number) next_bottle_number = self.bottleNumberFactory(bottle_number.successor()) result = \ "{0} {1} of beer on the wall, ".format(bottle_number.quantity().capitalize(), bottle_number.container()) + \ "{0} {1} of beer.\n".format(bottle_number.quantity(), bottle_number.container()) + \ "{0}, ".format(bottle_number.action()) + \ "{0} {1} of beer on the wall.\n".format(next_bottle_number.quantity(), next_bottle_number.container()) return result def bottleNumberFactory(self, number): if number == 0: return BottleZero(number) elif number == 1: return BottleOne(number) elif number == 6: return BottleSixPack(number) else: return BottleNumber(number) class BottleNumber: def __init__(self, number): self.number = number def container(self): return "bottles" def quantity(self): return str(self.number) def action(self): return "Take {0} down and pass it around".format(self.pronoun()) def pronoun(self): return "one" def successor(self): return self.number - 1 class BottleOne(BottleNumber): def container(self): return "bottle" def pronoun(self): return "it" class BottleZero(BottleNumber): def quantity(self): return "no more" def action(self): return "Go to the store and buy some more" def successor(self): return 99 class BottleSixPack(BottleNumber): def container(self): return "six-pack" def quantity(self): return str(1)
def encipher(): print('Enter your text to be ciphered:') message = list(input()) print('Enter your shift') c = int(input()) cipher=[] for x in range(message.__len__()): if ord(message[x]) == 0: cipher.append(" ") elif ord(message[x]) in range(65,90): cipher.append(chr((((ord(message[x]) + c)-13) % 26)+65)) elif ord(message[x]) in range(97, 122): cipher.append(chr((((ord(message[x]) + c)-19) % 26)+97)) else: cipher.append(message[x]) print(''.join(map(str, message)), "becomes:") print(''.join(map(str, cipher))) def decipher(): print('Enter your enciphered text:') cipher = list(input()) print('Enter your shift') c = int(input()) message=[] for x in range(cipher.__len__()): if ord(cipher[x]) == 0: message.append(" ") elif ord(cipher[x]) in range(65,90): message.append(chr((((ord(cipher[x]) - c)-13) % 26)+65)) elif ord(cipher[x]) in range(97, 122): message.append(chr((((ord(cipher[x]) - c)-19) % 26)+97)) else: message.append(cipher[x]) print('"'+''.join(map(str, cipher))+'"', "deciphers to:") print(' '+''.join(map(str, message))) def dictionary_solve(): print("unfinished") print("Enter to return...") input() def credits(): print("Created by X, X, X, X, and X") print("Acknowledgments: .... ") print("Enter to return...") input() while "sky" != "Blue": print("\tZhCipher 2021") print("1\tEncipher") print("2\tDecipher") print("3\tDictionary Solve") print("4\tCredits") menu = int(input()) if menu == 1: encipher() elif menu == 2: decipher() elif menu == 3: dictionary_solve() elif menu == 4: credits()