text
stringlengths
37
1.41M
""" The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? """ from math import sqrt import pickle #loading the factor base #for primes up to 6000000, the size is 412849 infile = open("PrimesTo112PlusMillion.py", "r+") factor_base = pickle.load(infile) size = len(factor_base) #declaring an upper bound and an upper limit UPPER_BOUND = 15000 #UPPER_LIMIT = UPPER_BOUND *(UPPER_BOUND + 1)/2 #creating the list of the triangle numbers from 1 to the upper bound triangle_numbers = [(n * (n+1))/ 2 for n in range(10000, UPPER_BOUND + 1)] #print triangle_numbers #print len(triangle_numbers) divisor_counter = {n : 0 for n in triangle_numbers} #creating a function that can be used within the 'map' function. It will #check for divisibility by n def modder(x): return lambda n: 1 if x %n == 0 else 0 #creating a matrix whose ith row contains the ith triangle number mod each #divisor in the divisor list #initalizing the matrix, each -1 will later become a list (a row) corresponding #to a triangle number, and the entries in the list will be corresponding to #the triangle number mod a divisor, matrix = [-1 for x in triangle_numbers] #breaking up the factor base into manageable size: #The factor base will be divided into sublists of size 50,000. #chunks = # of these sublists chunks = size/50000 + 1 #The sublists of size 50,000 or less are called 'base[i]' base = [0 for k in range(chunks)] for k in range(chunks -1): print "chunk #: ", k base[k] = factor_base[k*50000 : (k+1)*50000] base[chunks - 1] = factor_base[(chunks - 1)* 50000 : ] #suspect list will contain the triangle numbers that might have #over 500 divisors suspect_list = [] #counter[i] = # of primes that divide into triangle_numbers[i] counter = [0 for k in triangle_numbers] print "Starting modding by the p's " #creating the rows of the matrix. for i in range(len(triangle_numbers)): for k in range(chunks): f = modder(triangle_numbers[i]) matrix[k] = map(f, base[k]) counter[i]+= sum(matrix[k]) if counter[i] >= 7 : #print "The", i, "-th triangle number,", triangle_numbers[i],\ # "has", temp, "distinct prime divisors" suspect_list.append(triangle_numbers[i]) divisor_counter[triangle_numbers[i]] = counter[i] print "Starting in on the suspect list." for n in suspect_list: #Trial division of N by primes in the factor base. Saving the primes that #evenly divide into N into the list called 'divisors' m = n divisors = [] for k in range(chunks): for p in base[k]: if m % p == 0: divisors.append(p) m = m / p #m is what is left after the primes from the factor base were divided out of N # if m is not equal to 1, higher powers of primes divided into m or m is a prime print "n: ", n, "m: ", m, "number of p: ", \ divisor_counter[n], "divisors: ", divisors infile.close()
""" The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. """ MAXIMUM = 1000000 chain_lengths = [0 for k in range(0, MAXIMUM +1 )] for i in range(1,MAXIMUM): stop = False counter = 1 k = i while not stop: if k %2 == 0: k = k/2 else: k = 3*k + 1 counter += 1 if k == 1: stop = True chain_lengths[i] = counter print "The longest chain length for all positive integers less than", MAXIMUM print "Is:", max(chain_lengths) print "It is produced by the starting number:",\ chain_lengths.index(max(chain_lengths))
""" Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. """ #loading up a file containing all the primes up to 10000, saving it into #the list 'factor_base' import pickle infile = open("PrimesTo10000.py", "r+") factor_base = pickle.load(infile) #narrowing down the list of potential amicable numbers up to 10000 by #removing all the primes long_list = [n for n in range(4, 10000)] potentials = [ n for n in long_list if not (n in factor_base)] #creating the list of divisors divisors = [k for k in range(1, 5001)] #creating a function that can be used within the 'map' function. It will #check for divisibility by n def modder(x): return lambda n: n if x %n == 0 else 0 global cache cache={} amicables = [] def memoizator(func): global cache cache={} def cache_updater(*args): global cache if args[0] in cache: return cache[args[0]] else: temp = func(*args) cache[args[0]] = temp return temp return cache_updater @memoizator def divisor_sum(n): f = modder(n) divisor_list = map(f, divisors) if n > 5000: x = sum(divisor_list) else: x = sum(divisor_list)- n return x for k in potentials: temp = divisor_sum(k) if temp != k : temp2 = divisor_sum(temp) if temp2 == k and not (k in amicables): amicables.append(k) amicables.append(temp) infile.close()
num = int(input("Enter the number: ")) print("prime number is") primes = [] for i in range(2, num + 1): for j in range(2, int(i ** 0.5) + 1): if i%j == 0: break else: primes.append(i) print(primes)
while True: # объявляем бесконечный цикл year = int(input("year: ")) if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: print(366) else: print(365) if input("Continue? (Y/n) ") == "n": # в конце цикла условие break
""" 1. Найти наибольшую цифру числа. 2. Найти количество четных и нечетных цифр в числе. """ number = int(input("Введите число: ")) biggest = 0 # переменная для хранения наибольшей цифры even = 0 # счетчик для четных чисел odd = 0 # счетчик для нечетных чисел while number > 0: # пока число больше 0 заходим в цикл last_digit = number % 10 # получаем последнюю цифру числа if last_digit % 2 == 0: # если кратное двум - четное even += 1 # увеличиваем счетчик четных else: odd += 1 # увеличиваем счетчик нечетных чисел if last_digit > biggest: # если цифра больше, чем хранимая наибольшая biggest = last_digit # перезаписываем number //= 10 # делим нацело на 10, обрезаем крайнюю цифру от числа print("biggest:", biggest) print("even:", even) print("odd:", odd)
""" Кортежи - неизменяемые списки, но могут содержать изменяемые элементы. Доступны методы списков count() и index() """ # Создание кортежа tuple_1 = () tuple_2 = tuple("hello") tuple_3 = (1, 2, 3) tuple_4 = 1, 2, 3 print(tuple_1, tuple_2, tuple_3, tuple_4) print(type(tuple_1), type(tuple_2), type(tuple_3), type(tuple_4))
""" Продолжение и доп примеры декораторов из lesson9/_5_decorators.py Дано функции hello и bye. Необходимо реализовать функционал, чтоб сообщения, выводимые функциями оборачивалось в html теги: [in] hello('Max') [out] <html> Hello, Max! </html> [in] bye('John') [out] <p> Bye, John! </p> """ def hello(name): print(f"Hello, {name}!") def bye(name): print(f"Bye, {name}!") # 1. Как реализовать харкодом (так делать не нужно) print("<html>") hello("Max") print("</html>") print("<p>") bye("John") print("</p>") # В таком случае для каждого оборачивания вызова функции нужно дописывать код # и если нужно будет изменить название тега, нужно изменить несколько строк # 2. Реализовать дополнительные функции декораторы, которые будут # внутри себя оборачивать вызов нужной функции в тег. # По сути, перенесем строки 36-38 и 40-42 в функции-декораторы def html_decorator(func): def wrapper(name): print("<html>") func(name) print("</html>") return wrapper def p_decorator(func): def wrapper(name): print("<p>") func(name) print("</p>") return wrapper # Теперь можно задекорировать нужные функции и они будут оборачиваться тегом @html_decorator def hello(name): print(f"Hello, {name}!") @p_decorator def bye(name): print(f"Bye, {name}!") # Теперь функцию можно просто вызывать, она расширится кодом декоратора hello("Max") bye("John") # Результат такой же, как и в 1 варианте, но более универсальный и правильный # Также, теперь можно комбинировать декораторы, например @html_decorator @p_decorator def say_name(name): print(f"My name is {name}!") say_name("Alex") # Результат будет такой: # <html> # <p> # My name is Alex! # </p> # </html> # Как работает декоратор ??? # При вызове задекорированной функции происходит следующее # Сначала вызывается функция-декоратор, в которую # как аргумент передается задекорированная функция # и результат пристаивается переменной с таким же именем. def show_name(name): print(name) print(show_name.__name__) show_name = html_decorator(show_name) # Декоратор возвращает ссылку на вложенную в него функцию, ее можно вызвать # т.е. по сути show_name - это ссылка на функцию wrapper из декоратора show_name("Max") # <html> # Max # </html> print(show_name.__name__) # wrapper
1 var_int = 25 var_float = 4.5 var_str = 'python' 2 var_big = var_int * 1.5 3 var_float = var_float - 1 4 result = var_big % var_float print (result) 5 var_str = "end" 6 print (var_int, var_float, var_big, var_str) 7 number = int(input("введите число :")) result = number // 10 + number % 10 print ("Число:", result)
# Создание списков (пустого и заполненного) # Первый способ my_list = [] my_list2 = [1, 'word', False, 2.0] print(my_list, type(my_list)) print(my_list2, type(my_list2)) # Второй способ empty_list = list() list_from_str = list('some list') print(empty_list) print(list_from_str) colors = ['red', 'green', 'blue', 'yellow'] # Доступ к элементам списка по индексу, начиная с нуля # (1й элемент - индекс 0, 2й элемент - индекс 1 и т.д.) # Положительный индекс - счет слева направо print(colors[0]) print(colors[2]) # Отрицательный индекс - счет справа налево print(colors[-1]) # Изменение элементов по индексу colors[-1] = 'black' print(colors) # Изменение по срезу colors[:2] = ['yellow', 'brown', 'pink'] print(colors) letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # Срезы [start:end:step]. # Срез с индекса start (включительно) до end (не включительно) с шагом end print(letters[1:5:2]) print(letters[:5]) # Отрицательный шаг означает реверс, т.е. справа налево print(letters[5:2:-1])
""" Необходимо написать простой калькулятор, который оперирует с двумя числами и оператором. В зависимости от введенного оператора, между числами проводится определенная операция. Результат выводится на экран. * обработать все возможные ошибки программы с помощью try-except """ try: number_1 = int(input("Введіть перше число: ")) operation = input('''Введіть символ: + додавання - віднімання * множення / ділення ''') number_2 = int(input("Введіть друге число: ")) if operation == "+": print(number_1 + number_2) elif operation == "-": print(number_1 - number_2) elif operation == "*": print(number_1 * number_2) elif operation == "/": print(number_1 / number_2) else: print("Введені дані не коректні") except ValueError: print("Введено не коректні дані") except ZeroDivisionError: print("Ділення на 0 неможливе")
""" 1. Записать в файл practice.txt: числа от 9 до 17 через пробел 2. Прочитать этот файл и вывести содержимое и тип содержимого на экран 3. В файл с новой строки записать такой текст: Some text 123, @!$!@SA 4. Прочитать файл и вывести в консоль: - количество заглавных букв. - количество строчных букв. - количество цифр. - количество спецсимволов. """ # 1. Записать в файл practice.txt: числа от 9 до 17 через пробел # 1 вариант with open("practice.txt", "w") as f: for i in range(9, 18): f.write(f"{i} ") # 2 вариант with open("practice.txt", "w") as f: for i in range(9, 18): print(i, end=" ", file=f) # 3 вариант (best) with open("practice.txt", "w") as f: digits = " ".join(str(i) for i in range(9, 18)) f.write(digits) # 2. Прочитать этот файл и вывести содержимое и тип содержимого на экран with open("practice.txt") as f: data = f.read() print(data, type(data)) # 3. В файл с новой строки записать такой текст: Some text 123, @!$!@SA with open("practice.txt", "a") as f: f.write("\nSome text 123, @!$!@SA") # or # print('\nSome text 123, @!$!@SA', file=f) # 4. with open("practice.txt") as f: data = f.read() counter_l = counter_u = counter_d = counter_s = 0 for i in data: if i.islower(): counter_l += 1 elif i.isupper(): counter_u += 1 elif i.isdigit(): counter_d += 1 elif not i.isspace(): counter_s += 1 print( f"Lowers: {counter_l}\n" f"Uppers: {counter_u}\n" f"Digits: {counter_d}\n" f"Specials: {counter_s}" ) # Все 4 пункта вместе with open("practice.txt", "w+") as f: # 1. digits = " ".join(str(i) for i in range(9, 18)) f.write(digits) # 2. f.seek(0) data = f.read() print(data, type(data)) # 3. f.write("\nSome text 123, @!$!@SA") # 4. f.seek(0) data = f.read() counter_l = counter_u = counter_d = counter_s = 0 for i in data: if i.islower(): counter_l += 1 elif i.isupper(): counter_u += 1 elif i.isdigit(): counter_d += 1 elif not i.isspace(): counter_s += 1 print( f"Lowers: {counter_l}\n" f"Uppers: {counter_u}\n" f"Digits: {counter_d}\n" f"Specials: {counter_s}" )
def even_range(start, end): current = start while current < end: yield current current += 2 for i in even_range(0, 10): print(i)
import functools def calc_values(x, y: int): print("X: {} Y: {}".format(x, y)) return x + y numbers = [2, 3, 5, 8, 13] # X becomes the sum of the elements then we add Y reduced_value = functools.reduce(calc_values, numbers) print(reduced_value)
import random class Character: def is_alive(self): if self.health > 0 or self.health == float('inf'): return True else: return False class Hero(Character): def __init__(self, name, health, power): self.name = name self.health = health self.power = power def attack(self, enemy): if random.random() <= 0.2: enemy.health -= (self.power * 2) print("--------------------------") print("Double damage!!!!!!!!!!!!") print("--------------------------") print(f"You do {self.power * 2} damage to the enemy." ) else: enemy.health -= self.power print(f"You do {self.power} damage to the enemy." ) def print_status(self): print(f"""{self.name}'s health: {self.health}, \n{self.name}'s power: {self.power}\n""") class Goblin(Character): def __init__(self, name, health, power): self.name = name self.health = health self.power = power def attack(self, enemy): enemy.health -= self.power print(f"goblin do {self.power} damage to the enemy.\n" ) def print_status(self): print(f"""\n{self.name}'s health: {self.health},\n{self.name}'s power: {self.power}""") class Zombie(Character): def __init__(self, name, health, power): self.name = name self.health = health self.power = power def attack(self, enemy): enemy.health -= self.power print(f"zombie do {self.power} damage to the hero" ) def print_status(self): print(f"""{self.name}'s health: {self.health}, \n{self.name}'s power: {self.power}\n""") class Medic(Character): def __init__(self, name, health, mana): self.name = name self.health = health self.mana = mana def recuperate(self, team): if random.random() <= 0.2: team.health = team.health + 2 self.mana -= 5 print("--------------------------") print(f"medic heal(+2) the hero." ) print("--------------------------") else: pass def print_status(self): print(f"""{self.name}'s health: {self.health}, \n{self.name}'s power: {self.power}\n""") class Shadow(Character): def __init__(self, name, health, power): self.name = name self.health = health self.power = power def attack(self, enemy): enemy.health -= self.power print(f"shadow do {self.power} damage to the enemy." ) def print_status(self): print(f"""{self.name}'s health: {self.health}, \n{self.name}'s power: {self.power}\n""") def defense(self, enemy): if random.random() <= 0.1 and attack(self, enemy): self.health = self.health class Sorceress(Character): def __init__(self, name, health, mana): self.name = name self.health = health self.mana = mana def attack(self, enemy): enemy.health = 100 print("-------------------------------------------------") print(f"sorceress broke infinite health (Health: 100) " ) print("-------------------------------------------------") def print_status(self): print(f"""{self.name}'s health: {self.health}, \n{self.name}'s power: {self.power}\n""") class Healer(Character): def __init__(self, name, health, mana): self.name = name self.health = health self.mana = mana def heal(self, hero): hero.health = 100 print("--------------------------------------") print(f"Healer healed Hero!!! (health: 100)" ) print("--------------------------------------") def print_status(self): print(f"""{self.name}'s health: {self.health}, \n{self.name}'s power: {self.power}\n""")
#Sum/Average Program #Your first and last name: Isaiah Bishop #Your student ID: 1288086 #Build on what you did in the 'List of Names' program #Instead of entering 10 names, enter 20 numbers (integers) #Instead of searching for a name in the list # Compute the sum of all 20 numbers # Compute the average for all 20 numbers #User interaction- #Enter a number: #The sum of the numbers you entered is: #The average of the numbers you entered is: numberlist = [] total = 0 for x in range (0,20): num = int(input ("Enter Number")) numberlist.append(num) for x in range (0,20): total = total + numberlist[x] print(total) print(total/len(numberlist))
class Evaluator: @staticmethod def zip_evaluate(words,coeffs): if not isinstance(words,list) and not isinstance(coeffs,list): raise TypeError if len(words)!=len(coeffs): raise ValueError words=tuple(words) for i in words: if not isinstance(i,str): raise TypeError coeffs=tuple(coeffs) for i in coeffs: if not isinstance(i,int) and not isinstance(i,float): raise TypeError lst=tuple(zip(words,coeffs)) result=0 for i in range(len(lst)): result+=lst[i][1]*len(lst[i][0]) return result @staticmethod def enumerate_evaluate(words,coeffs): if not isinstance(words,list) and not isinstance(coeffs,list): raise TypeError if len(words)!=len(coeffs): raise ValueError for i in words: if not isinstance(i,str): raise TypeError for i in coeffs: if not isinstance(i,int) and not isinstance(i,float): raise TypeError words=list(enumerate(words)) for i in range(len(words)): words[i]=list(words[i]) words[i][0]=coeffs[i] result=0 for i in range(len(words)): result+=len(words[i][1])*words[i][0] return result
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 3 15:29:27 2021 @author: ayoub """ import sys def number(x): if str(x).isdigit(): if int(x)==0: return "I'm zero." elif int(x)%2==0: return "I'm even." elif int(x)%2==1: return "I'm odd." return "ERROR" if __name__=='__main__' : if len(sys.argv) > 2: print("ERROR") if len(sys.argv)==1: print("") else: print(number(sys.argv[1]))
n = int(input()) inp = input().strip() sea_level = 0 valley = 0 for i in inp: if i == 'U': sea_level += 1 elif i == 'D': sea_level -= 1 if sea_level == 0: if prev < sea_level: valley += 1 prev = sea_level print(valley)
#!/usr/bin/env python # coding: utf-8 # ### Written by :Raksha Choudhary<br> # ### Data Science and Bussiness Analytics Internship<br> # ### GRIP The Sparks Foundation<br> # ### Task 1: Predic the percentage of marks that student expected to scores based upon the number of hours they spend # #### In this we use simple linear regression involving two variables # ### import libraries # In[3]: #importing all libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt # ### load Dataset # In[5]: #take data from link data="http://bit.ly/w-data" s_data=pd.read_csv(data) print("Data imported successfully") # In[6]: s_data.head(10) # ### Plot the graph for better visualisation # In[54]: #plot the distribution score s_data.plot(x="Hours",y="Scores",style="o",c='y') plt.title('Hours Vs Percentage') plt.xlabel('Hours Studied') plt.ylabel('Percentage Score') plt.style.use("dark_background") plt.legend(loc='upper left') plt.tight_layout() plt.show() # #### From the graph above we conclude that there is positive linear relation between "number of hours studied " and " percentage of score" # ### Preparing the data # In[11]: #prepare the data x= s_data.iloc[:,:-1].values y= s_data.iloc[:,1].values # #### In above we divide the data into attributes and labels.After that we split the data into test and train data by using split() method which is inbuilt in scikit learn # In[12]: #split into train and test data from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0) # #### random_state ensures that random numbers are generated in the same order.However if the person use a particular value (1 or 0)everytime the result will be same i.e same values in train and test datasets. # ### Training the algorithm # In[16]: #train the algorithm from sklearn.linear_model import LinearRegression reg = LinearRegression() reg.fit(x_train,y_train) print("Training Done!!!!") # In[17]: #plot regression line line = reg.coef_*x+reg.intercept_ # In[49]: #plot the test data plt.scatter(x,y,c='g') plt.plot(x,line,c='y') plt.style.use("dark_background") plt.tight_layout() plt.show() # ### Making predictions # In[19]: #making prediction print(x_test) y_pred = reg.predict(x_test) # In[20]: #Compare Actual Vs Predicted df = pd.DataFrame({'Actual':y_test,'Predicted':y_pred}) df # In[22]: # test your own data hours = np.array([8.63,4,6.0,9.81]) own_pred = reg.predict(hours.reshape(-1,1)) print("No. of hours={}".format(hours)) print("Predicted Scores={}".format(own_pred[0])) print("Predicted Scores={}".format(own_pred[1])) print("Predicted Scores={}".format(own_pred[2])) print("Predicted Scores={}".format(own_pred[3])) # ### Evaluting the model # In[23]: #Evalute the model from sklearn import metrics print("Mean absolute Error:",metrics.mean_absolute_error(y_test,y_pred)) # In[24]: from sklearn.metrics import r2_score print("R_squard:",metrics,metrics.r2_score(y_test,y_pred)) # In[25]: from sklearn.metrics import mean_squared_error print("Mean Squared Error:",mean_squared_error(y_test,y_pred)) # #### This step is important to compare how well different model perform on a particular dataset.For simplicity we uses mean square error. #
# ghost game from random import randint print ('Ghost game') feeling_brave = True score = 0 while feeling_brave: ghost_door = randint (1, 3) print (ghost_door) print('three doors ahead') print(' A ghost behind one') print (' which door do you open ?') door = input('1 ,2 ,3?') door_num = int (door) if door_num == ghost_door: print ("GHOST !") feeling_brave = False else: print (' no ghost!') print ('you enter the next room') score = score + 1 print ('RUN AWAY !') print (' Game over! you scored', score)
a = int(input("Täisarv: ")) if (a % 2) == 0: print( " {0} is even" .format(a)) else: print (" {0} is odd" .format(a))
x = 8 num = range(0, 13) for y in num: if y < 13: print("8 x ", y , "=", x * y)
a = int(input("Enter number of rows")) b=0 b = a+1 for i in range (1,b): for j in range (1 , b-i): print (" " , end=' ' ) for k in range (1,i+1): print ( k , end=' ') for l in range (k-1,0, -1): print (l , end = ' ') print ()
__author__ = 'Rushil' num = 0 num_list = [] a = 0 b = 1 while a < 4000000 or b < 4000000: num += 10 #noinspection PyAugmentAssignment a = a + b b = a + b if a%2 == 0: num_list.append(a) if b%2 == 0: num_list.append(b) print(sum(num_list))
#!/bin/python3 import sys time = input().strip() def am_to_pm(time): if time == '00:00:00AM': return '00:00:00' if time == '12:00:00PM': return '12:00:00' if time == '12:00:00AM': return '12:00:00' act_time = time[:-2] time_suff = time[-2:] if time_suff == 'AM': return act_time if time_suff == 'PM': str_act_time = act_time.split(':') hrs = int(str_act_time[0]) + 12 str_act_time[0] = str(hrs) return ':'.join(str_act_time) print(am_to_pm(time))
__author__ = 'Rushil' n_test = int(input()) points = [] def str_to_cood(str): return [tuple(str.split(' ')[:2]) , tuple(str.split(' ')[2:])] def get_sym_point(p_list): point_1 = p_list[0] point_2 = p_list[1] point_3_x = 2*int(point_2[0]) - int(point_1[0]) point_3_y = 2*int(point_2[1]) - int(point_1[1]) print(point_3_x , point_3_y) while n_test: a = input().strip() a = str_to_cood(a) points.append(a) n_test -= 1 for i in points: get_sym_point(i)
__author__ = 'Rushil' import math div_num = {1:1 , 2:2 , 3:2 , 4:3 , 5:2 , 6:4 , 7:2 , 8:4 , 9:3 , 10:4 , 11:2 , 12:6} def triang_num(n): return int((n*(n+1))/2) print(triang_num(5)) def main_1(): n = 1 while True: num = triang_num(n) s = 1 for i in range(1,num//2 + 1): if num % i == 0: s += 1 print(num , s) if s > 500: break n += 1 #(n)(n+1)/2 (n+1)(n+2)/2 def gen_un_ser(): for i in range(1,20): print('(%d)(%d)/2' % (i,i+1) , end = '\t') print(int((i *(i+1))/2)) gen_un_ser() def get_factors(t_num_n): for i in range(1,2*t_num_n): if i*(i+1) == 2*t_num_n: n = i return n,n+1 print(get_factors(36)) def get_stuff(n): c_tnum = int((n *(n+1))/2) return factors() + get_stuff(n-1)
import random options = ['Rock', 'Paper', 'Scissors'] computer = random.choice(options) user = input("Enter 'r' for Rock, 'p' for Paper & 's' for scissors: ") print("") if user == "r": print("You chose Rock!") if user == "p": print("You chose Paper!") if user == "s": print("You chose Scissors!") print(f"Computer played {computer}!") if user == "r" and computer == "Scissors": print("===> You won the game!") elif user == "p" and computer == "Rock": print("===> You won the game!") elif user == "s" and computer == 'Paper': print("===> You won the game!") elif user == "r" and computer == "Rock" or user == "p" and computer == "Paper" or user == "s" and computer == "Scissors": print("===> It's a draw.") else: print("===> Oops, Computer won the game.")
board = { 'A1':'A1','B1':'B1','C1':'C1',\ 'A2':'A2','B2':'B2','C2':'C2',\ 'A3':'A3','B3':'B3','C3':'C3' } status= 'Playing' turn = 1 def print_board(b): print() print(b['A1'] + '|' + b['B1'] + '|' + b['C1']) print('--+--+--') print(b['A2'] + '|' + b['B2'] + '|' + b['C2']) print('--+--+--') print(b['A3'] + '|' + b['B3'] + '|' + b['C3']) print() def outcome(b): global status status = 'Playing' if b['A1'] == b['B1'] == b['C1']: print(f'{player} Wins!') status ='Game Over' elif b['A1'] == b['A2'] == b['A3']: print(f'{player} Wins!') status ='Game Over' elif b['A2'] == b['B2'] == b['C2']: print(f'{player} Wins!') status ='Game Over' elif b['B1'] == b['B2'] == b['B3']: print(f'{player} Wins!') status ='Game Over' elif b['A3'] == b['B3'] == b['C3']: print(f'{player} Wins!') status ='Game Over' elif b['C1'] == b['C2'] == b['C3']: print(f'{player} Wins!') status ='Game Over' elif b['A1'] == b['B2'] == b['C3']: print(f'{player} Wins!') status ='Game Over' elif b['A3'] == b['B2'] == b['C1']: print(f'{player} Wins!') status ='Game Over' elif turn == 9: print("It's a Tie! That's worse than losing!") status = 'Game Over' else: status = 'Playing' while status == 'Playing': if turn % 2 == 1: player = 'X ' else: player = 'O ' print_board(board) print(f"It is {player}'s turn to play") play = input('Choose a position: ') if (play in ['A1','A2','A3','B1','B2','B3','C1','C2','C3']): if (board[play] in ['X ','O ']): print('Invalid Choice\nTry Again!') else: board[play] = player print_board(board) outcome(board) turn +=1 else: print('Invalid Choice\nTry Again!')
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ #import sys from math import sqrt,floor limit=28123 lowlimit=12 def primesUpTo(n): primes=[2] for x in range(3,n+1): for y in primes: # unfortunately with list comprehension cant figure out how to do sqrt break divs=[] if y>sqrt(x): break if x % y==0: divs.append(y) break if divs==[]: primes.append(x) return primes # this is divisors, I need proper divisors?? def divisors(n): # find factors of number n primes=primesUpTo(floor(sqrt(n))) factors=[1] # All factors must be smaller than sqrt for i in range(len(primes)): while n % primes[i]==0: factors.append(primes[i]) n=n/primes[i] return factors def properdivisors(n): ls=divisors(n) #properdiv=[a*b for a in ls for b in ls] # this double-counts tempdiv=[] i=0 while i<len(ls): for j in range(len(ls)): if n%(ls[i]*ls[j])==0: tempdiv.append(ls[i]*ls[j]) ls.pop(0) properdiv=[] [properdiv.append(x) for x in tempdiv if x not in properdiv] return properdiv def abundant(n): # return true if sum is greater than n false else if sum(properdivisors(n)) > n: return True return False # can now check for abundance, and write factors # was pretty sure upper limit entirely fine for table but got curious abt max # print(sys.maxsize) #lowlimit=12 #temp #limit=100 #temp abundants=[] #print(limit) #print(divisors(limit)) #print(properdivisors(limit)) #print("Is this abundant",abundant(limit)) for i in range(lowlimit,limit+1): if abundant(i): abundants.append(i) # we now have a list of all the abundant numbers up to the limit # we want to find all the numbers up to the limit which CAN be written as the # pairwise sum of two abundants # abundants is an ordered list print("abundants are",abundants) sumabt=[] # I want to remove duplicate operations, i.e. # I can pop out the first entry once I've multiplied it by everything # I use a while loop to stop when I've run out of list i=0 while i<len(abundants): # then I can multiply by all remaining abundants for j in range(len(abundants)): #print(abundants,abundants[i],abundants[j]) sumij=abundants[i]+abundants[j] # if I exceed limit the next one over also will so get out if sumij>limit: break else: sumabt.append(sumij) abundants.pop(0) # now got a list of all abundants sumabt.sort() print("Pairs within limit that are sums of abt",sumabt) ''' "Python has a language feature called List Comprehensions that is perfectly suited to making this sort of thing extremely easy" -- the internet''' #nonabtsum = [x for x in range(1,limit+1) if x not in sumabt] #print(sum(nonabtsum))
"""Our knot hashing algorithm""" import numpy import operator def convert(a, lengths, pos=0, skip=0): """Twist of ring, return array, pos, skip""" num_elements = len(a) for length in lengths: a = numpy.append(numpy.flip(a[0:length], 0), (a[length:])) a = numpy.append(a[(length + skip) % num_elements:], (a[0:(length + skip) % num_elements])) pos += length + skip skip += 1 return a, pos, skip def knot_hash(sparse): """Create hex hash""" kh = '' for s in sparse: h = hex(s) if len(h) == 4: kh += ('0') kh += (hex(s)[2:-1]) return kh def sparse_hash(arr): """Convert array into hash""" barr = [] for i in xrange(len(arr) / 16): barr.append(reduce(operator.xor, arr[i * 16:(i + 1) * 16])) return barr def hasher(num_elements, lengths): """Solution to problem 2""" arr = range(0, num_elements) pos = 0 skip = 0 for _ in xrange(64): arr, pos, skip = convert(arr, lengths, pos, skip) arr = numpy.append(arr[-pos % num_elements:], arr[0:-pos % num_elements:]) sparse = sparse_hash(arr) return knot_hash(sparse) def hash_string(string_to_hash): """Return the hash for this string""" converted = [ord(h) for h in string_to_hash] converted = numpy.append(converted, [17, 31, 73, 47, 23]) return hasher(256, converted)
def get_largest_num(list_of_nums): list_of_nums = list_of_nums.sort() last_index = len(list_of_nums) - 1 return list_of_nums[last_index] print(get_largest_num([5, 2, 17, 8, 3]))
# Link =>>> https://leetcode.com/problems/search-in-rotated-sorted-array # Given an integer array nums sorted in ascending order, and an integer target. # Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). # You should search for target in nums and if you found return its index, otherwise return -1. # Example 1: # Input: nums = [4,5,6,7,0,1,2], target = 0 # Output: 4 # Example 2: # Input: nums = [4,5,6,7,0,1,2], target = 3 # Output: -1 # Example 3: # Input: nums = [1], target = 0 # Output: -1 # 用到二分模板,但是这题的重点是找到MID,之后如何切,左点和右点 # 由题意我们得知,这个被分割的数组,是由两个单调递增的数组组成,且R数组所有的数字都比L数组最小的数字小 # 这样我们可以找到左右以后,用二分找到target class Solution: def search(self, nums, target): if not nums: return -1 l,r = 0, len(nums) -1 while l+1 < r: mid = (l+r) // 2 if nums[mid] == target: return mid if nums[l] < nums[mid]: # 说明,l -> mid 之间是持续递增 if nums[l]<= target< nums[mid]: # 说明, l-> mid-> m 之间 r = mid else: # 说明, target 再mid右边 l = mid else: # 说明 l, mid是在左右两边 if nums[mid] <= target<= nums[r]: # 说明 ,target在 mid 和r之间 l = mid else: r = mid if nums[l] == target: return l if nums[r] == target: return r return -1 Solution.search([4,5,6,7,0,1,2], 0)
#! /usr/bin/env python def ingresa_edades(edades=10): edadesValidadas=0 result=[] while edadesValidadas<edades: edadAsString=input("Inserte la edad de una persona: ") try: edad=int(edadAsString) edadesValidadas+=1 result.append(edad) except ValueError as e: print("La edad ingresada debe ser un numero...") print(e) return result def remueve_menores(edades, minoriaEdad=20): mayores=[] for edad in edades: if edad > minoriaEdad: mayores.append(edad) return mayores edades=ingresa_edades() mayores=remueve_menores(edades) print("Las edades proporcionadas con mayoria de edad son: ",mayores)
a=int(input("Give me one number: ")) b=int(input("Give me another number: ")) print("If you sum those numbers, the values is: ",a+b); print("If you rest those numbers, the values is: ",a-b); print("If you multiply those numbers, the values is: ",a*b); print("If you raise the first number to a power of the second number, the values is: ",a**b); if b == 0: print("The quotient for a number divided by 0 is undefined") else: print("If you devide the first number with the second number, the value is: ", a/b)
a=["Juan", "Pedro", "Pablo", "Luis", "Gerardo"] b=0 # A simple iteration arround the list print("Starting simple iterarion for",a) for x in a: print("Element[",b,"]=",x) b+=1 # An itteration modifying the elements into the original list print("Starting to modify the original list") b=0 for x in a[:]: a[b]=x+" D." b+=1 print("Now the list contains those elements",a) print("You can use 'break' or 'continue' when you are working with iterators in the same way you use it in another languages") print("The instruction 'pass' do nothing, it is usefull to set a functionality into a flow we don't want to implemet yet, but mainatain a correct structure into the code you can think on this like a similar function for a '//TODO:' comment in Java")
import csv class Lecturer: def __init__(self, course, lecturer): self.course = course self.lecturer = lecturer class Student: def __init__(self, course, user): self.course = course self.user = user class NumberStudents: def __init__(self, course, count): self.course = course self.count = count class NumberLecturers: def __init__(self, course, count): self.course = course self.count = count class LmuData: def __init__(self, user, course, lecturer): self.user = user self.course = course self.lecturer = lecturer class SameLecturers: def __init__(self, name): self.name = name class SameUser: def __init__(self, name): self.name = name class SameCourse: def __init__(self, name): self.name = name allUsers = list() allCourses = list() allLecturers = list() physicalPresence = list() oddCourses = list() evenCourses = list() with open('belegung-ws2019-anon.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') setUser = set() setCourse = set() setLecturer = set() index = 0 for row in csv_reader: user = row[0] lecturer = row[2] course = row[1] if user not in setUser: allUsers.append(user) setUser.add(user) if lecturer not in setLecturer: allLecturers.append(lecturer) setLecturer.add(lecturer) if course not in setCourse: allCourses.append(course) setCourse.add(course) print(len(allUsers)) print(len(allLecturers)) print(len(allCourses)) print(allCourses[99]) with open('belegung-ws2019-anon.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 take = list() for row in csv_reader: user = allUsers.index(row[0]) course = allCourses.index(row[1]) lecturer = allLecturers.index(row[2]) take.append(LmuData(user, course, lecturer)) line_count += 1 takes = "" for entries in take: takes += f'takes(User{entries.user}, Course{entries.course}, Lecturer{entries.lecturer})\n' with open('courses-lecturers.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 lecturers = list() for row in csv_reader: course = allCourses.index(row[0]) lecturer = allLecturers.index(row[1]) lecturers.append(Lecturer(course, lecturer)) line_count += 1 lec = "" for entries in lecturers: lec += f'taughtBy(course{entries.course}, lecturer{entries.lecturer})\n' sameLec = "" for i in range(len(allLecturers)): sameLec += f'sameLecturer(lecturer{i}, {i})\n' sameCourse = "" for i in range(len(allLecturers)): sameCourse += f'sameCourse(Course{i}, Course{i})\n' sameStu = "" for i in range(len(allUsers)): sameStu += f'User{i},' with open('courses-users.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 students = list() for row in csv_reader: course = allCourses.index(row[0]) user = allUsers.index(row[1]) students.append(Student(course, user)) line_count += 1 stu = "" for entries in students: stu += f'participate(Course{entries.course},User{entries.user})\n' # Wochenzyklen with open('courses-users.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 students = list() for row in csv_reader: course = allCourses.index(row[0]) user = allUsers.index(row[1]) if course % 2 == 0: evenCourses.append(Student(course, user)) if course % 2 == 1: oddCourses.append(Student(course, user)) line_count += 1 odd = "" for entries in oddCourses: odd += f'participate(Course{entries.course},User{entries.user})\n' even = "" for entries in evenCourses: even += f'participate(Course{entries.course},User{entries.user})\n' # Präsenzveranstaltungen <= 100 with open('courses-countStudents.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 numStu = list() for row in csv_reader: course = allCourses.index(row[0]) count = row[1] intCount = int(count) if intCount <= 100: physicalPresence.append(course) line_count += 1 # Präsenzveranstaltungen <= 100 with open('courses-users.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 setUser = set() physicalPresentStudents = list() physicalPresenceUsers = list() for row in csv_reader: course = allCourses.index(row[0]) user = allUsers.index(row[1]) if course in physicalPresence: if user not in setUser: physicalPresenceUsers.append(user) setUser.add(user) physicalPresentStudents.append(Student(course, user)) line_count += 1 # Präsenzveranstaltungen <= 100 AND Wochenzyklen with open('courses-users.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 evenPhysicalPresentStudents = list() oddPhysicalPresentStudents = list() for row in csv_reader: course = allCourses.index(row[0]) user = allUsers.index(row[1]) if course in physicalPresence: if course % 2 == 0: evenPhysicalPresentStudents.append(Student(course, user)) if course % 2 == 1: oddPhysicalPresentStudents.append(Student(course, user)) line_count += 1 oddPhyStu = "" for entries in oddPhysicalPresentStudents: oddPhyStu += f'participate(Course{entries.course},User{entries.user})\n' evenPhyStu = "" for entries in evenPhysicalPresentStudents: evenPhyStu += f'participate(Course{entries.course},User{entries.user})\n' phyUser = "" for entries in physicalPresenceUsers: phyUser += f'User{entries}\n' phyStu = "" for entries in physicalPresentStudents: phyStu += f'participate(Course{entries.course},User{entries.user})\n' numStudents = "" for entries in numStu: numStudents += f'numberParticipants(course{entries.course}, {entries.count})\n' kartCourses = "" for entries in numStu: kartCourses += f'Course{entries.course},' with open('courses-countLecturers.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 numLec = list() for row in csv_reader: course = allCourses.index(row[0]) count = row[1] numLec.append(NumberLecturers(course, count)) line_count += 1 numLecturers = "" for entries in numLec: numLecturers += f'numberLecturers(course{entries.course}, {entries.count})\n' with open('belegung-ws2019-anon.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 allUsers = list() allCourses = list() allLecturers = list() data = list() for row in csv_reader: user = row[0] course = row[1] lecturer = row[2] data.append(LmuData(user, course, lecturer)) line_count += 1 lmu = "" for entries in data: lmu += f'advisedBy({entries.user}, {entries.course}, {entries.lecturer})\n' # w = open("allData/courseLecturer.txt", "a") # w.write(lec) # w.close() # # w = open("allData/participate.csv", "a") # w.write(stu) # w.close() # # # w = open("allData/physicalPresentStudents.txt", "a") # w.write(phyStu) # w.close() # w = open("allData/odd<=100_Students.txt", "a") # w.write(oddPhyStu) # w.close() # # w = open("allData/even<=100_Students.txt", "a") # w.write(evenPhyStu) # w.close() # # w = open("allData/physicalPresentUseres.txt", "a") # w.write(phyUser) # w.close() # # w = open("allData/numberOfLecturers.txt", "a") # w.write(numLecturers) # w.close() # # w = open("allData/lmuData.txt", "a") # w.write(takes) # w.close() # # w = open("allData/sameLecturers.txt", "a") # # w.write(sameLec) # # w.close() w = open("allData/sameCourse.txt", "a") w.write(sameCourse) w.close() # # w = open("allData/allStudents.txt", "a") # w.write(sameStu) # w.close() # # w = open("allData/allCourses.txt", "a") # w.write(kartCourses) # w.close() # # w = open("allData/allUsers.txt", "a") # w.write(kartCourses) # w.close()
import math def reward_function(params): ''' Example of rewarding the agent to follow center line ''' # Read input parameters all_wheels_on_track = params['all_wheels_on_track'] # flag to indicate if the agent is on the track x = params['x'] # agent's x-coordinate in meters y = params['y'] # agent's y-coordinate in meters closest_objects = params['closest_objects'] # zero-based indices of the two closest objects to the agent's closest_waypoints = params['closest_waypoints'] # indices of the two nearest waypoints. distance_from_center = params['distance_from_center'] # distance in meters from the track center is_crashed = params['is_crashed'] # Boolean flag to indicate whether the agent has crashed. is_left_of_center = params['is_left_of_center'] # Flag to indicate if the agent is on the left side to the is_offtrack = params['is_offtrack'] # Boolean flag to indicate whether the agent has gone off track is_reversed = params['is_reversed'] # flag to indicate if the agent is driving clockwise (True) or heading = params['heading'] # agent's yaw in degrees objects_distance = params['objects_distance'] # list of the objects' distances in meters between 0 and objects_heading = params['objects_heading'] # list of the objects' headings in degrees between -180 and 180 objects_left_of_center = params['objects_left_of_center'] # list of Boolean flags indicating whether elements' objects objects_location = params['objects_location'] # list of object locations [(x,y) ...]. objects_speed = params['objects_speed'] # list of the objects' speeds in meters per second. progress = params['progress'] # percentage of track completed speed = params['speed'] # agent's speed in meters per second (m/s) steering_angle = abs(params['steering_angle']) # agent's steering angle in degrees steps = params['steps'] # number steps completed track_length = params['track_length'] # track length in meters. track_width = params['track_width'] # width of the track waypoints = params['waypoints'] # list of (x,y) as milestones along the track center # Read all 155 track coordinates (x,y) after racing lines optimization. racing_lines_coords = [[0.76561164, 2.79921096], [0.77433204, 2.695514 ], [0.7899877 , 2.59241502], [0.81253181, 2.49023377], [0.84155804, 2.38920145], [0.87670146, 2.28950824], [0.91814643, 2.19146346], [0.96598348, 2.09538003], [1.02110577, 2.00190733], [1.08483756, 1.91208936], [1.15889387, 1.82757667], [1.24544247, 1.75117454], [1.33865459, 1.67987295], [1.43751087, 1.61316408], [1.54114987, 1.55049121], [1.64906449, 1.49148807], [1.76077387, 1.43573189], [1.87582154, 1.38275015], [1.99379879, 1.33205039], [2.11442438, 1.28318436], [2.23741029, 1.23565791], [2.36252249, 1.18900726], [2.4895651 , 1.14282388], [2.61828891, 1.09677841], [2.74812923, 1.05069182], [2.87900506, 1.00439082], [3.00882722, 0.95892681], [3.13759114, 0.91473599], [3.26537475, 0.87215984], [3.39228501, 0.83154603], [3.51845045, 0.79324155], [3.64399906, 0.75760342], [3.76904579, 0.72500547], [3.89368577, 0.69584032], [4.01799202, 0.67049722], [4.14201662, 0.64930876], [4.26577987, 0.63273189], [4.38927914, 0.62123967], [4.51249029, 0.61526108], [4.63536749, 0.61516804], [4.75784381, 0.62127088], [4.87983294, 0.63381301], [5.0012315 , 0.65296781], [5.12192174, 0.67883876], [5.24177453, 0.71146186], [5.36065244, 0.75080957], [5.47841292, 0.79679602], [5.59491126, 0.84928294], [5.71000341, 0.90808645], [5.82354846, 0.97298407], [5.93541068, 1.0437221 ], [6.0454611 , 1.12002284], [6.15357859, 1.20159164], [6.25965028, 1.2881234 ], [6.36357148, 1.37930854], [6.46524502, 1.47483823], [6.56457998, 1.57440865], [6.66149006, 1.67772453], [6.75589138, 1.78450162], [6.84770001, 1.89446831], [6.93682919, 2.00736635], [7.02318639, 2.12295071], [7.1066703 , 2.24098868], [7.18716776, 2.36125827], [7.26455098, 2.483546 ], [7.33867494, 2.60764424], [7.40937528, 2.73334811], [7.47646688, 2.86045226], [7.53974339, 2.98874764], [7.59897815, 3.11801846], [7.65392713, 3.24803997], [7.70433455, 3.37857719], [7.7499424 , 3.50938546], [7.79050461, 3.64021332], [7.82580692, 3.77080829], [7.85569184, 3.90092577], [7.88008701, 4.03034055], [7.89903768, 4.15886077], [7.91272164, 4.28633872], [7.92128781, 4.41264156], [7.92447728, 4.53753961], [7.92201458, 4.66077418], [7.9133979 , 4.78198389], [7.89812233, 4.90076287], [7.87505235, 5.01638528], [7.8426419 , 5.12776564], [7.7991328 , 5.23341069], [7.74232044, 5.33103609], [7.66965414, 5.41671541], [7.58548525, 5.49133287], [7.49249755, 5.55565671], [7.39272914, 5.61057946], [7.28774798, 5.65703448], [7.17863584, 5.69567517], [7.06626291, 5.72714099], [6.95119881, 5.75168914], [6.83392084, 5.76948952], [6.71479951, 5.7804432 ], [6.59428145, 5.78486017], [6.4727123 , 5.78280876], [6.35041564, 5.77438996], [6.22767817, 5.75942619], [6.10480484, 5.73778469], [5.98210522, 5.70948046], [5.8598719 , 5.67464525], [5.73836377, 5.63350386], [5.61779372, 5.58636238], [5.49831957, 5.53359894], [5.38003826, 5.47565588], [5.26298308, 5.41303344], [5.1471238 , 5.34628486], [5.0323693 , 5.27601209], [4.91857262, 5.20286181], [4.80553743, 5.12752246], [4.69302581, 5.05072246], [4.5807927 , 4.97315917], [4.47306546, 4.89888131], [4.36498285, 4.8253982 ], [4.25624758, 4.75337765], [4.14656401, 4.68348892], [4.03567359, 4.6163249 ], [3.92335987, 4.55239151], [3.80945274, 4.49209756], [3.69383179, 4.43574605], [3.57642813, 4.38352817], [3.45722493, 4.33552102], [3.33625638, 4.29168982], [3.21360565, 4.25189567], [3.08940208, 4.21590815], [2.96381787, 4.18342069], [2.83706273, 4.15406719], [2.70937306, 4.12743907], [2.58099653, 4.10308575], [2.45215177, 4.08057666], [2.32301465, 4.05949102], [2.19837845, 4.03803371], [2.07480715, 4.01517768], [1.95267174, 3.99042323], [1.83230451, 3.96331844], [1.71408912, 3.93334796], [1.59845849, 3.8999487 ], [1.48596082, 3.86244333], [1.37725893, 3.82007563], [1.27302755, 3.77217454], [1.1744859 , 3.71757033], [1.08316271, 3.65504353], [1.00170501, 3.58283771], [0.93490907, 3.49914189], [0.88109283, 3.40790169], [0.83879464, 3.31160766], [0.80687151, 3.21193203], [0.78431647, 3.11008729], [0.77046979, 3.00693713], [0.76440624, 2.9031572 ], [0.76561164, 2.79921096]] # Calculate the min distance from the racing lines coords min_distance_obj = calc_min_distance_from_closest_point(x, y, racing_lines_coords) # Calculate 4 markers that are at varying distances away from the closest raceing line point marker_1 = 0.09 marker_2 = 0.15 marker_3 = 0.25 marker_4 = 0.5 # Give higher reward if the car is closer to raceing line point and vice versa if min_distance_obj["value"] <= marker_1: reward = 1.0 elif min_distance_obj["value"] <= marker_2: reward = 0.7 elif min_distance_obj["value"] <= marker_3: reward = 0.4 elif min_distance_obj["value"] <= marker_4: reward = 0.1 else: reward = 1e-3 # likely crashed/ close to off track if progress == 100: reward += 100.0 return float(reward) def calc_min_distance_from_closest_point(curr_x, curr_y, racing_lines_coords): # Calculate distance d²=(x1-x2)² + (y1-y2)² min_distance_from_current_coord = math.inf index_min_distance_from_current_coord = 0 for index, [x,y] in enumerate(racing_lines_coords): distance = (((curr_x - x)**2) + ((curr_y - y)**2))**0.5 if distance < min_distance_from_current_coord: min_distance_from_current_coord = distance index_min_distance_from_current_coord = index return {"index": index_min_distance_from_current_coord, "value":min_distance_from_current_coord}
import re class PasswordValidation: def __init__(self, user, password): self.user = user self.password = password def validate(self): username = self.user.cleaned_data.get('username') email = self.user.cleaned_data.get('email') lower = re.findall('[a-z]', self.password) upper = re.findall('[A-Z]', self.password) num = re.findall('[0-9]', self.password) specialChar = re.findall('[!@#$%^&*()]', self.password) if len(self.password) > 8 and \ lower and upper and num and len(specialChar) > 1 and \ self.password != username and self.password != email: print(specialChar) return True return False
# task1 # num1 = input("введите первое число: ") # num2 = input("введите второе число: ") # res = None # try: # num1 = int(num1) # num2 = int(num2) # res = num1 / num2 # print(res) # except ZeroDivisionError: # raise Exception('на ноль делить нельзя') # task2 # num1 = input("введите первое число: ") # num2 = input("введите второе число: ") # res = None # try: # num1 = int(num1) # num2 = int(num2) # res = num1 + num2 # print(res) # except ValueError: # raise Exception('нужно ввести число') # task3 # sodi = {'a': 1, 'b': 2, 'c': 3, 'd': 4} # try: # sodi['e'] # except KeyError: # raise Exception("В словаре нет такого ключа!") # task4 # slovo = input('введи лист: ') # try: # if slovo.startswith('[') and slovo.endswith(']'): # print(slovo) # elif slovo != slovo.startswith('['): # raise Exception('Данная программа принимает только List') # finally: # print() # task5 # listy = [1, 2, 3, 4, 5, 6, 8, 13] # try: # kol = listy[-1] # listy[9] # except IndexError: # raise Exception(f'{kol} - последний индекс')
car = {'make': 'BMW', 'model': '550i', 'year':1989} print(car) print(car['make']) d = {} d['one'] = 1 print(d) sum_1 = d['one'] + 8 print(sum_1)
""" Author: Rajiv Malhotra Program: set_membership.py Date: 10/14/20 Set Assignment """ def in_set(some_set, some_value): """ Function accepts a set and returns a boolean value stating if the element is in the set. :param some_set: This is a set :param some_value: This is a string :return: Boolean - True or False """ return some_value in some_set if __name__ == '__main__': my_set = set('0123456789') print("Is {} in {}? {}".format(5, my_set, in_set(my_set, str(5))))
import sys from typing import Pattern sys.path.append('W2') sys.path.append('W3') from W2_7_1 import neighbor_again from Seven import DistanceBetweenPatternAndStrings def MedianString(Dna, k): """Input: An integer k, followed by a collection of strings Dna. Output: A k-mer Pattern that minimizes d(Pattern, Dna) among all possible choices of k-mers. (If there are multiple such strings Pattern, then you may return any one.) Args: k (integer): k-mer Dna (list): list of strings Returns: integer: median """ distance = 9999 median = [] ptrn = "" for i in range(k): ptrn += "A" Patterns = neighbor_again([ptrn], k) for Pattern in Patterns: temp = DistanceBetweenPatternAndStrings(Pattern, Dna) if distance > temp: distance = temp median = [Pattern] elif distance == temp: median.append(Pattern) return median if __name__ == "__main__": # with open("W3/dataset_158_9 (3).txt") as inp: # input_items = inp.read().strip().splitlines() # k = input_items[0].strip() # k = int(k) # dna_sequences = input_items[1].strip().split() k = 7 dna_sequences = """CTCGATGAGTAGGAAAGTAGTTTCACTGGGCGAACCACCCCGGCGCTAATCCTAGTGCCC GCAATCCTACCCGAGGCCACATATCAGTAGGAACTAGAACCACCACGGGTGGCTAGTTTC GGTGTTGAACCACGGGGTTAGTTTCATCTATTGTAGGAATCGGCTTCAAATCCTACACAG""".split("\n") print(MedianString(dna_sequences, k))
# EXAMPLE-6 # Write a function named "translate" that performs RNA to amino acid translation. # # RNA codon table is simplified to contain only five codons: # 'UUU' -> 'Phenylalanine' # 'UUA' -> 'Leucine' # 'AUU' -> 'Isoleucine' # 'GUU' -> 'Valine' # 'UCU' -> 'Serine' # RNA sequence is represented as a string and its length is fixed to 15 # The function takes one argument: RNA sequence # RNA sequence should start with the START codon and end with one of the STOP codons # START -> 'AUG' # STOP -> 'UAA', 'UGA' or 'UAG' # If the sequence does not start with the START codon, return 'start codon not recognized' # If the sequence does not end with the STOP codon, return 'stop codon not recognized' # Otherwise, the sequence is a valid RNA sequence, perform the translation and return the amino acids as a list # # Hints: # # It is a good idea to define another function that translates a single codon into an amino acid # Since the length of the sequence is fixed you do not need to use recursion or iteration # Take a look at "list.index" function and slicing def determine(codon): if codon == "UUU": return 'Phenylalanine' elif codon == "UUA": return 'Leucine' elif codon == "AUU": return 'Isoleucine' elif codon == "GUU": return 'Valine' elif codon == "UCU": return 'Serine' def translate(rna): if rna[:3] != "AUG": return 'start codon not recognized' elif rna[-3:] != "UAA" and rna[-3:] != "UAG" and rna[-3:] != "UGA": return 'stop codon not recognized' else: return [determine(rna[3:6]),determine(rna[6:9]),determine(rna[9:12])] # SAMPLE INPUT/OUTPUTs: # == Input == print( translate('AUGUCUGUUAUUUGA') ) # == Output == # ['Serine', 'Valine', 'Isoleucine'] # == Input == print( translate('AAAUUUUUAAUUUGA') ) # == Output == # 'start codon not recognized' # == Input == print( translate('AUGUUUUUAAUUUGG') ) # == Output == # 'stop codon not recognized' # == Input == print( translate('AUGUUUUUAAUUUAA') ) # == Output == # ['Phenylalanine', 'Leucine', 'Isoleucine'] # SOLUTION: """ def translate(RNAseq): start_codon = 'AUG' stop_codons = ['UAA', 'UGA', 'UAG'] if RNAseq[0:3] != start_codon: return 'start codon not recognized' if RNAseq[12:15] not in stop_codons: return 'stop codon not recognized' aminoacids = [] aminoacids.append(translate_codon(RNAseq[3:6])) aminoacids.append(translate_codon(RNAseq[6:9])) aminoacids.append(translate_codon(RNAseq[9:12])) return aminoacids def translate_codon(codon): codon_table = ['UUU', 'Phenylalanine', 'UUA', 'Leucine', 'AUU', 'Isoleucine', 'GUU', 'Valine', 'UCU', 'Serine'] cIndex = codon_table.index(codon) return codon_table[cIndex+1] """
# EXAMPLE-3 # Write a script which will take the input as a list in the first line and 3 strings in the next 3 lines. # Elements of the list are either a string or an empty list. # You will put those 3 strings into the empty lists in the main list and print the output list. # SAMPLE INPUT/OUTPUTs: # == Input == # ['elma',[],'armut','uzum',[],'kayisi',[]] # portakal # kiraz # muz # == Output == # ['elma', ['portakal'], 'armut', 'uzum', ['kiraz'], 'kayisi', ['muz']] # == Input == # [[],'ceng','math','chem','hist',[],'phys',[],'elect','mine'] # stat # econ # eng # == Output == # [['stat'], 'ceng', 'math', 'chem', 'hist', ['econ'], 'phys', ['eng'], 'elect', 'mine'] lst = eval(input()) str1 = input() str2 = input() str3 = input() index = lst.index([]) lst[index] = [str1] index = lst.index([]) lst[index] = [str2] index = lst.index([]) lst[index] = [str3] print(lst) # SOLUTION: """ mylist = eval(input()) str1 = input() str1 = [str1] ind1 = mylist.index([]) mylist.remove([]) mylist.insert(ind1, str1) str2 = input() str2 = [str2] ind2 = mylist.index([]) mylist.remove([]) mylist.insert(ind2, str2) str3 = input() str3 = [str3] ind3 = mylist.index([]) mylist.remove([]) mylist.insert(ind3, str3) print(mylist) """
# Write a function named all_orderings which takes a list of size N and # returns all the permutations (orderings) of order N. # >>> all_orderings([1,2,3]) # [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] # >>> all_orderings(['a','b', True, False]) # [['a', 'b', True, False], ['a', 'b', False, True], ['a', True, 'b', False], ['a', True, False, 'b'], ['a', False, 'b', True], ['a', False, True, 'b'], ['b', 'a', True, False], ['b', 'a', False, True], ['b', True, 'a', False], ['b', True, False, 'a'], ['b', False, 'a', True], ['b', False, True, 'a'], [True, 'a', 'b', False], [True, 'a', False, 'b'], [True, 'b', 'a', False], [True, 'b', False, 'a'], [True, False, 'a', 'b'], [True, False, 'b', 'a'], [False, 'a', 'b', True], [False, 'a', True, 'b'], [False, 'b', 'a', True], [False, 'b', True, 'a'], [False, True, 'a', 'b'], [False, True, 'b', 'a']] def all_orderings(L): if len(L) == 1: return [L] R = [] for i in range(len(L)): subR = all_orderings(L[:i] + L[i+1:]) for e in subR: e.insert(0, L[i]) R.append(e) return R
from typing import List def list_equals(lst1: List, lst2: List) -> bool: return len(list(set(lst1).difference(set(lst2)))) == 0 and len(list(set(lst2).difference(set(lst1)))) == 0 def list_contains(lst: List, elements: List) -> bool: return all([elem in lst for elem in elements]) def list_to_str(sep: str, lst: List) -> str: return sep.join(lst) def list_drop_na(lst: List) -> List: return [x for x in lst if len(str(x)) > 0] def list_drop_len(lst: List, length: int) -> List: return [x for x in lst if len(str(x)) > length]
import pygame from pygame.sprite import Sprite import random #Список,в который будет содержать изображения вкусняшек yummie_img = [] def load_yum_img(): '''Функция загрузки изображений вкусняшек''' for i in range(3, 7): yummie_img.append(pygame.image.load('images/' + str(i) + '.png').convert_alpha()) class Yummie(Sprite): '''Класс представляющий одну вкусняшку''' def __init__(self, ai_settings, screen, hero): '''Инициализирует случайную вкусняшку и задает её начальную поцизию''' super().__init__() self.ai_settings = ai_settings self.screen = screen self.obj = random.randint(0, 3) self.image = yummie_img[self.obj] self.rect = self.image.get_rect() #Вкусняшка появляется в случайном месте над экраном self.rect.centerx = random.randint(10, ai_settings.screen_width - 10) self.rect.centery = random.randint(-ai_settings.screen_height, 0) #Сохранение точной позиции вкусняхи self.y = float(self.rect.y) def update(self): '''Осуществляет падение вниз вкусняшки''' self.y += self.ai_settings.speed_yummie self.rect.y = self.y def blitme(self): '''Выводит вкусняшку в текущем положении''' pygame.screen.blit(self.image, self.rect)
import pygame import math from time import sleep, time import random import copy pygame.init() class TicTacToeAI(): def __init__(self, competitor): self.competitor = competitor self.board = competitor.board def make_decision(self): original_board = self.competitor.board # print("ORIGINAL BOARD", original_board) board_copy = copy.deepcopy(original_board) # print("BOARD COPY", board_copy) # Make a winning move for i, row in enumerate(original_board): for j, item in enumerate(row): board_copy = copy.deepcopy(original_board) if item == '': board_copy[i][j] = 'o' logic = Logic(board_copy) result = logic.check(draw=False) if result: if result['winner_name'] == 'o': return i, j # If competitor wins, block him for i, row in enumerate(original_board): for j, item in enumerate(row): board_copy = copy.deepcopy(original_board) if item == '': board_copy[i][j] = 'x' logic = Logic(board_copy) result = logic.check(draw=False) if result: if result['winner_name'] == 'x': return i, j # move corners, choosing random corner corners = [(0, 0), (0, 2), (2, 2), (2, 0)] free_corners = list( filter(lambda item: original_board[item[0]][item[1]] == '', corners)) if free_corners: return random.choice(free_corners) if board_copy[1][1] == '': return (1, 1) sides = [(0, 1), (1, 0), (1, 2), (2, 1)] free_sides = list( filter(lambda item: original_board[item[0]][item[1]] == '', corners)) if free_sides: return random.choice(free_sides) def move(self): index = self.make_decision() # print(index) if index: self.competitor.board[index[0]][index[1]] = 'o' class Logic: def __init__(self, board): self.board = board def check(self, draw=True): # Checking rows for i, row in enumerate(self.board): item_for_check = row[0] row_is_correct = True for item in row: if item == '' or item != item_for_check: row_is_correct = False if row_is_correct == True: if draw: start_pos = ( self.position[0], self.position[1] + self.box_size*(i + 0.5)) end_pos = ( self.position[0] + self.size[0], self.position[1] + self.box_size*(i + 0.5)) line_color = self.x_color if item_for_check == 'x' else self.o_color pygame.draw.line(self.surface, line_color, start_pos, end_pos, self.line_width) return { "winner_name": item_for_check, "draw": False } # Checking colunns for j in range(len(self.board[0])): item_for_check = self.board[0][j] column_is_correct = True for i in range(len(self.board)): if self.board[i][j] == '' or self.board[i][j] != item_for_check: column_is_correct = False if column_is_correct: if draw: start_pos = ( self.position[0]+self.box_size*(j + 0.5), self.position[1]) end_pos = ( self.position[0]+self.box_size*(j + 0.5), self.position[1]+self.size[1]) line_color = self.x_color if item_for_check == 'x' else self.o_color pygame.draw.line(self.surface, line_color, start_pos, end_pos, self.line_width) return { "winner_name": item_for_check, "draw": False } diagonal_is_correct = True item_for_check = self.board[0][0] for i in range(len(self.board)): if self.board[i][i] == '' or item_for_check != self.board[i][i]: diagonal_is_correct = False if diagonal_is_correct: if draw: start_pos = ( self.position[0], self.position[1]) end_pos = ( self.position[0]+self.size[0], self.position[1]+self.size[1]) line_color = self.x_color if item_for_check == 'x' else self.o_color pygame.draw.line(self.surface, line_color, start_pos, end_pos, self.line_width) return { "winner_name": item_for_check, "draw": False } diagonal_is_correct = True item_for_check = self.board[0][len(self.board[0])-1] for i in range(len(self.board)): if self.board[i][len(self.board[0])-i-1] == '' or item_for_check != self.board[i][len(self.board[0])-i-1]: diagonal_is_correct = False if diagonal_is_correct: if draw: start_pos = ( self.position[0]+self.size[0], self.position[1]) end_pos = ( self.position[0], self.position[1]+self.size[1]) line_color = self.x_color if item_for_check == 'x' else self.o_color pygame.draw.line(self.surface, line_color, start_pos, end_pos, self.line_width) return { "winner_name": item_for_check, "draw": False } if self.is_full(): return { "winner_name": None, "draw": True } return None def is_full(self): for row in self.board: for item in row: if item == '': return False return True class Board(Logic): def __init__(self, position, size, bg_color, window): self.board = [['' for j in range(3)] for i in range(3)] self.surface = window self.position = position self.size = size self.box_size = self.size[0] / 3 self.bg_color = bg_color self.border_color = pygame.Color(13, 161, 146) self.x_color = (66, 66, 66) self.o_color = (224, 224, 224) self.border_width = 12 self.line_width = 24 self.turn = 'x' def get_winner(self): return self.check(draw=True) def get_index(self, mouse_position): position = (mouse_position[0]-self.position[0], mouse_position[1]-self.position[1]) for i in range(3): for j in range(3): if abs(self.box_size * (2 * j + 1) / 2-position[0]) <= (self.box_size - self.border_width) / 2 and abs(self.box_size * (2 * i + 1) / 2-position[1]) <= (self.box_size - self.border_width) / 2: return i, j return None def insert(self, position): # print("Insert") indexes = self.get_index(position) if indexes: i, j = indexes if not self.board[i][j]: self.board[i][j] = self.turn if not self.get_winner(): computer.move() self.get_winner() def draw_item(self, item, position): length = self.box_size*0.6 if item == 'x': start_pos = (position[0]-length/2, position[1]-length/2) pygame.draw.line(self.surface, self.x_color, (start_pos[0], start_pos[1]), ( start_pos[0] + length, start_pos[1] + length), self.line_width) pygame.draw.line(self.surface, self.x_color, (start_pos[0], start_pos[1]+length), ( start_pos[0] + length, start_pos[1]), self.line_width) elif item == 'o': pygame.draw.circle(self.surface, self.o_color, position, int(length/2), int(self.line_width*0.6)) def draw_grid(self): # pygame.draw.rect(self.surface, (255, 255, 100), ( # self.position[0], self.position[1], self.size[0], self.size[1])) # Drawing edges pygame.draw.line(self.surface, self.bg_color, (self.position[0], self.position[1]), ( self.position[0]+self.size[0], self.position[1]), self.border_width) pygame.draw.line(self.surface, self.bg_color, ( self.position[0]+self.size[0], self.position[1]), ( self.position[0]+self.size[0], self.position[1]+self.size[1]), self.border_width) pygame.draw.line(self.surface, self.bg_color, ( self.position[0]+self.size[0], self.position[1]+self.size[1]), ( self.position[0], self.position[1]+self.size[1]), self.border_width) pygame.draw.line(self.surface, self.bg_color, ( self.position[0], self.position[1]+self.size[1]), ( self.position[0], self.position[1]), self.border_width) # Drawing colums pygame.draw.line(self.surface, self.border_color, (self.position[0]+self.size[0]/3, self.position[1]), ( self.position[0]+self.size[0]/3, self.position[1]+self.size[1]), self.border_width) pygame.draw.line(self.surface, self.border_color, (self.position[0]+2*self.size[0]/3, self.position[1]), ( self.position[0] + 2*self.size[0] / 3, self.position[1] + self.size[1]), self.border_width) # Drawing rows pygame.draw.line(self.surface, self.border_color, (self.position[0], self.position[1]+self.size[1]/3), ( self.position[0] + self.size[0], self.position[1] + self.size[1] / 3), self.border_width) pygame.draw.line(self.surface, self.border_color, (self.position[0], self.position[1]+2*self.size[1]/3), ( self.position[0]+self.size[0], self.position[1]+2*self.size[1]/3), self.border_width) def draw(self): self.draw_grid() for i, row in enumerate(self.board): for j, item in enumerate(row): if item: self.draw_item(item, (int( self.position[0] + self.box_size*(2*j + 1) / 2), int(self.position[1] + self.box_size*(2*i + 1) / 2))) screen_size = width, height = 1024, 768 board_size = board_width, board_height = (600, 600) bg_color = (20, 189, 172) board_position = (width-board_width)//2, (height-board_height)//2 display_surface = pygame.display.set_mode(screen_size) pygame.display.set_caption('Tic Tac Toe') board = Board(board_position, board_size, bg_color, display_surface) computer = TicTacToeAI(board) pygame.font.init() winner_name_font = pygame.font.SysFont("Arial", int(screen_size[1]/3)) text_font = pygame.font.SysFont("Arial", 72) start_time = None while True: display_surface.fill(bg_color) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.MOUSEBUTTONUP: board.insert(event.pos) board.draw() winner = board.get_winner() if winner: if winner['winner_name']: winner_name = winner_name_font.render( winner['winner_name'].upper(), False, (66, 66, 66)) text = text_font.render("WON", False, (66, 66, 66)) elif winner['draw']: winner_name = winner_name_font.render('X O', False, (66, 66, 66)) text = text_font.render("DRAW", False, (66, 66, 66)) if not start_time: start_time = time() if time() - start_time > 1: display_surface.fill(bg_color) display_surface.blit( winner_name, ((screen_size[0]-winner_name.get_width())//2, (screen_size[1]-winner_name.get_height()-text.get_height())//2)) display_surface.blit( text, ((screen_size[0] - text.get_width()) // 2, (screen_size[1] - winner_name.get_height() - text.get_height()) // 2 + winner_name.get_height())) sleep(1) winner = None pygame.display.update()
# Sarah Sides # 7/10/18 # Student Database import time done = 1 want_to_view = 3 student_list = [] while done == 1: student_data = [] name = input("What is the name of the student? ") year = int(input("What grade year is the student currently in? Please enter a number. ")) grade = int (input("What is the number grade of the student? Please enter a number. ")) comment = input("Do you have any other comments about the student? ") done = int (input("Would you like to add another student? 1 - yes 2 - no ")) student_data.append(name) student_data.append(year) student_data.append(grade) student_data.append(comment) student_list.append(student_data) if done == 2: want_to_view = int(input ("Would you like to view the list of students? 1 - yes 2 - no ")) if want_to_view == 1: for student in student_list: print (student) time.sleep(1) print () print ("Thank you! Have a nice day!") if want_to_view == 2: print ("Thank you! Have a nice day!")
class State(object): def __init__(self, board, agent, opponent, agent_score, opponent_score): self.board = board self.agent = agent self.opponent = opponent self.agent_score = agent_score self.opponent_score = opponent_score def turn(self, board, agent_reward, opponent_reward): return State(board, self.opponent, self.agent, self.opponent_score + opponent_reward, self.agent_score + agent_reward) def opposite(self): return self.turn(self.board, 0, 0) def score(self, agent): if self.agent == agent: return self.agent_score else: return self.opponent_score def __eq__(self, other): return self.board == other.board and self.agent == other.agent def __lt__(self,other): return self.__hash__() > other.__hash__() def __hash__(self): return hash(self.board)
# -*- coding: utf-8 -*- def sort(*args, key=lambda x: x, reverse: bool = False, counter: list = [0]) -> list: """ Сортировка выбором. :param args: список значений :param key: функция, применяемая к каждому значению :param reverse: обратный порядок сортировки :param counter: количество итераций циклов :return: отсортированный список """ # Массив нужен для передачи по ссылке. # Переменную нужно обнулять каждый раз. counter[0] = 0 arr = [*args[0]] arr_length = len(arr) for i in range(arr_length): value = key(arr[i]) index = i for j in range(i + 1, arr_length): counter[0] += 1 if not reverse: if value > key(arr[j]): value = key(arr[j]) index = j else: if value < key(arr[j]): value = key(arr[j]) index = j t = arr[i] arr[i] = arr[index] arr[index] = t return arr
# This program will try to guess the word the user is thinking of within 16 guesses. def compPick(lower,higher,count): with open('usa.txt') as f: lines = f.readlines() index = round((higher+lower)/2) # Finds the number inbetween the two indexes guess = lines[round(index)] # Index number for the guess in the text file if count == 16: print("Your word is: "+ guess.upper() + "It took 16 trys to guess your word.") quit() else: print("Guess #"+ str(count) + ": " + guess.upper()) answer = input("Is this your word?(y/n):") if answer == "y": print("Your word is: " + guess.upper() + "It took " + str(count) + " trys to guess your word.") quit() print("Does your word come before or after " + guess.upper()) string = input("(b/a):") if string == "a": lower = index count += 1 compPick(lower,higher,count) elif string == "b": higher = index count += 1 compPick(lower,higher,count) def WordsInDictionary(): file = open("usa.txt", "r") data = file.read() words = data.split() num = len(words) return num def main(): num = WordsInDictionary() lower = 0 higher = num count = 1 compPick(lower,higher,count) main()
#Given a non-empty array of digits representing a non-negative integer, increment one to the integer. #The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. #You may assume the integer does not contain any leading zero, except the number 0 itself. class Solution: def plusOne(self, digits: List[int]) -> List[int]: sum = 1 for i in range(len(digits) - 1 , -1 , -1): sum += digits[i] if sum == 10: digits[i] = sum % 10 sum = 1 else: digits[i] = sum return digits digits.insert(0, 1) return digits
import sqlite3 class Database: def __init__(self, db): self.conn = sqlite3.connect(db) self.cur = self.conn.cursor() self.cur.execute("""CREATE TABLE IF NOT EXISTS cosing (Ref_No INTEGER PRIMARY KEY, INCI_name TEXT, INN TEXT, PhEur TEXT, CAS_No TEXT, EC_No TEXT, Chem_Name TEXT, Restriction TEXT, Function TEXT, Update_Date TEXT)""") self.conn.commit() def view(self): self.cur.execute("SELECT * FROM cosing") rows = self.cur.fetchall() return rows def search(self, inci=""): self.cur.execute("SELECT * FROM cosing WHERE INCI_name like ? OR CAS_No like ?", (inci, inci)) rows = self.cur.fetchall() return rows def __del__(self): self.conn.close()
#!/usr/bin/python3.5 # -*- coding: UTF-8 -*- import argparse import os """ rename a group of files """ def batch_rename(work_dir, old_ext, new_ext): """ rename a group of files """ for filename in os.listdir(work_dir): split_file = os.path.splitext(filename) file_ext = split_file[1] if old_ext == file_ext: newfile = split_file[0] + new_ext os.rename( os.path.join(work_dir, filename), os.path.join(work_dir, newfile) ) print("Rename is over") print(os.listdir(work_dir))
class Vector(list): def __init__(self, *v): super().__init__(v) def __abs__(self): from math import sqrt return sqrt(sum(x ** 2 for x in self)) def __add__(self, other): if len(self) != len(other): raise ValueError("Mismatching vetor lenghts ({} != {})".format(len(self), len(other))) return Vector(*[x + y for x, y in zip(self, other)]) def __sub__(self, other): return self + -other def __mul__(self, other): return Vector(*[other * x for x in self]) # __rmul__ = __mul__ def __rmul__(self, other): return self.__mul__(other) def __neg__(self): return Vector(*[-x for x in self]) a = Vector(1, 3, 5) b = Vector(1, 3) print(a) print(abs(a)) print(len(a)) print(a + b) print(a * 3) print(3 * a) print(a - b) print(-a) print(a[0], a[1], a[2])
def naj(xs): maximum = xs[0] for num in xs: if num > maximum: maximum = num return maximum def naj_abs(xs): maximum = abs(xs[0]) max_real = xs[0] for num in xs: if abs(num) > maximum: maximum = abs(num) max_real = num return max_real ### ^^^ Naloge rešujte nad tem komentarjem. ^^^ ### import unittest class TestVaje(unittest.TestCase): def test_naj(self): self.assertEqual(naj([1]), 1) self.assertEqual(naj([-1]), -1) self.assertEqual(naj([5, 1, -6, -7, 2]), 5) self.assertEqual(naj([1, -6, -7, 2, 5]), 5) self.assertEqual(naj([-5, -1, -6, -7, -2]), -1) self.assertEqual(naj([1, 2, 5, 6, 10, 2, 3, 4, 9, 9]), 10) self.assertEqual(naj([-10 ** 10, -10 ** 9]), -10 ** 9) def test_naj_abs(self): self.assertEqual(naj_abs([1]), 1) self.assertEqual(naj_abs([-1]), -1) self.assertEqual(naj_abs([10, 12, 9]), 12) self.assertEqual(naj_abs([0, 0, 0, 0, 0]), 0) self.assertEqual(naj_abs([5, 1, -6, -7, 2]), -7) self.assertEqual(naj_abs([1, -6, 5, 2, -7]), -7) self.assertEqual(naj_abs([-5, -1, -6, -7, -2]), -7) self.assertEqual(naj_abs([100, 1, 5, 3, -90, 3]), 100) self.assertEqual(naj_abs([-100, 1, 5, 3, -90, 3]), -100) self.assertEqual(naj_abs([-10 ** 10, -10 ** 9]), -10 ** 10) self.assertEqual(naj_abs([1, 2, 5, 6, 10, 2, 3, 4, 9, 9]), 10) self.assertEqual(naj_abs([1, 2, 5, 6, -10, 2, 3, 4, 9, 9]), -10) def test_ostevilci(self): self.assertEqual(ostevilci([]), []) self.assertEqual(ostevilci([1]), [(0, 1)]) self.assertEqual(ostevilci([5, 1, 4, 2, 3]), [(0, 5), (1, 1), (2, 4), (3, 2), (4, 3)]) def test_bmi(self): in_out = [ ([], []), ([('Ana', 55, 165), ('Berta', 60, 153)], [('Ana', 20.202020202020204), ('Berta', 25.63116749967961)]), ([('Ana', 55, 165), ('Berta', 60, 153), ('Cilka', 70, 183)], [('Ana', 20.202020202020204), ('Berta', 25.63116749967961), ('Cilka', 20.902385858042937)]), ] for i, o in in_out: for (nu, bu), (n, b) in zip(bmi(i), o): self.assertEqual(nu, n) self.assertAlmostEqual(bu, b) def test_bmi2(self): in_out = [ (([], [], []), []), ((['Ana', 'Berta'], [55, 60], [165, 153]), [('Ana', 20.202020202020204), ('Berta', 25.63116749967961)]), ((['Ana', 'Berta', 'Cilka'], [55, 60, 70], [165, 153, 183]), [('Ana', 20.202020202020204), ('Berta', 25.63116749967961), ('Cilka', 20.902385858042937)]), ] for i, o in in_out: for (nu, bu), (n, b) in zip(bmi2(*i), o): self.assertEqual(nu, n) self.assertAlmostEqual(bu, b) def test_prastevila(self): self.assertEqual(prastevila(10), 4) self.assertEqual(prastevila(11), 4) self.assertEqual(prastevila(12), 5) self.assertEqual(prastevila(50), 15) self.assertEqual(prastevila(100), 25) self.assertEqual(prastevila(1000), 168) # def test_prastevila_hard(self): # self.assertEqual(prastevila(10**6), 78498) # self.assertEqual(prastevila(10**7), 664579) def test_palindrom(self): self.assertEqual(palindom(''), True) self.assertEqual(palindom('a'), True) self.assertEqual(palindom('aa'), True) self.assertEqual(palindom('ab'), False) self.assertEqual(palindom('aba'), True) self.assertEqual(palindom('abc'), False) self.assertEqual(palindom('abcdefedcba'), True) self.assertEqual(palindom('abcdefgedcba'), False) self.assertEqual(palindom('pericarezeracirep'), True) self.assertEqual(palindom('perica'), False) def test_palindromska_stevila(self): self.assertEqual(palindromska_stevila(), 906609) def test_inverzije(self): self.assertEqual(inverzije([]), 0) self.assertEqual(inverzije([1]), 0) self.assertEqual(inverzije([1, 2]), 0) self.assertEqual(inverzije([2, 1]), 1) self.assertEqual(inverzije([3, 2, 1]), 3) self.assertEqual(inverzije([4, 3, 2, 1]), 6) self.assertEqual(inverzije([5, 4, 3, 2, 1]), 10) self.assertEqual(inverzije([1, 4, 3, 5, 2]), 4) self.assertEqual(inverzije([10, 3, 9, 2, 22, 42, 0, 88, 66]), 12) def test_an_ban_pet_podgan(self): self.assertEqual(an_ban_pet_podgan(["Maja"]), "Maja") self.assertEqual(an_ban_pet_podgan(["Maja", "Janja", "Sabina"]), "Maja") self.assertEqual(an_ban_pet_podgan(["Maja", "Janja", "Sabina", "Ina"]), "Ina") self.assertEqual(an_ban_pet_podgan(["Maja", "Janja", "Sabina", "Ina", "Jasna"]), "Jasna") self.assertEqual(an_ban_pet_podgan(["Maja", "Janja", "Sabina", "Ina", "Jasna", "Mojca"]), "Ina") self.assertEqual(an_ban_pet_podgan(["Maja", "Janja", "Sabina", "Ina", "Jasna", "Mojca", "Tina"]), "Maja") if __name__ == '__main__': unittest.main(verbosity = 2)
number = int(input("Vnesi število: ")) delitelj = 2 vsota = 1 while delitelj < number: if number % delitelj == 0: vsota += delitelj delitelj += 1 delitelj = 2 vsota2 = 1 while delitelj < vsota: if vsota % delitelj == 0: vsota2 += delitelj delitelj += 1 if vsota2 == number: print(vsota) else: print(number, "nima prijateljev")
#!/usr/bin/env python import dump import optparse as op import numpy import sys def diffDumps(fileName0,fileName1,allowedRelativeDifference,thresholdValue,out): """Checks to see if the two dump files differ """ dumpFile0=dump.Dump(fileName0) dumpFile1=dump.Dump(fileName1) #check headers [headersMatch,fatal]=diffHeader(dumpFile0,dumpFile1,allowedRelativeDifference ,thresholdValue,out) if fatal: out.write("Differences do not allow comparison of variables, stopping!\n") return False #check variables varsMatch=True for i in range(dumpFile0.numVars): tmp=diffVar(dumpFile0,dumpFile1,i,allowedRelativeDifference,thresholdValue ,out) if not tmp: varsMatch=False if not varsMatch or not headersMatch: out.write("files are not numerically identical\n") return False else: out.write("files are numerically identical\n") return True def diffHeader(dumpFile0,dumpFile1,allowedRelativeDifference,threshold,out): """Checks to see if the two file headers differ If the file headers do differ it prints to out where they differ Arguments: dumpFile0: one of the two dump files to be compared dumpFile1: the second of the two dump files to be compared allowedRelativeDifference: the allowed relative difference between two numerical values being compared between the two dump files. If the relative difference is less, no difference is reported. threshold: how large the variable must be before the difference is considered. Useful when comparing velocities for example. out: an output object which supports the a write() allowing output of the comparison to be written out. """ headersMatch=True fatal=False #check type if dumpFile0.type!=dumpFile1.type: out.write("file \""+dumpFile0.fileName+"\" has type \""+str(dumpFile0.type) +"\" while file \""+dumpFile1.fileName+"\" has type \"" +str(dumpFile1.type)+"\"\n") headersMatch=False #check versions if dumpFile0.version!=dumpFile1.version: out.write("file \""+dumpFile0.fileName+"\" has version \"" +str(dumpFile0.version)+"\" while file \""+dumpFile1.fileName +"\" has version \""+str(dumpFile1.version)+"\"\n") headersMatch=False #check time denomitator=abs(dumpFile0.time+dumpFile1.time)*0.5 if denomitator>threshold: relativeDifference=abs(dumpFile0.time-dumpFile1.time)/denomitator if relativeDifference>allowedRelativeDifference: out.write("file \""+dumpFile0.fileName+"\" has time \""+str(dumpFile0.time) +"\" while file \""+dumpFile1.fileName+"\" has time \"" +str(dumpFile1.time)+"\"\n") headersMatch=False #check timestep index if dumpFile0.timeStepIndex!=dumpFile1.timeStepIndex: out.write("file \""+dumpFile0.fileName+"\" has timeStepIndex \"" +str(dumpFile0.timeStepIndex)+"\" while file \""+dumpFile1.fileName +"\" has timeStepIndex \""+str(dumpFile1.timeStepIndex)+"\"\n") headersMatch=False #check delta_t_nm1half denomitator=abs(dumpFile0.delta_t_nm1half+dumpFile1.delta_t_nm1half)*0.5 if denomitator>threshold: relativeDifference=(abs(dumpFile0.delta_t_nm1half-dumpFile1.delta_t_nm1half) /denomitator) if relativeDifference>allowedRelativeDifference: out.write("file \""+dumpFile0.fileName+"\" has delta_t_nm1half \"" +str(dumpFile0.delta_t_nm1half)+"\" while file \""+dumpFile1.fileName +"\" has delta_t_nm1half \""+str(dumpFile1.delta_t_nm1half)+"\"\n") headersMatch=False #check delta_t_np1half denomitator=abs(dumpFile0.delta_t_np1half+dumpFile1.delta_t_np1half)*0.5 if denomitator>threshold: relativeDifference=(abs(dumpFile0.delta_t_np1half-dumpFile1.delta_t_np1half) /denomitator) if relativeDifference>allowedRelativeDifference: out.write("file \""+dumpFile0.fileName+"\" has delta_t_np1half \"" +str(dumpFile0.delta_t_np1half)+"\" while file \""+dumpFile1.fileName +"\" has delta_t_np1half \""+str(dumpFile1.delta_t_np1half)+"\"\n") headersMatch=False #check alpha denomitator=abs(dumpFile0.alpha+dumpFile1.alpha)*0.5 if denomitator>threshold: relativeDifference=(abs(dumpFile0.alpha-dumpFile1.alpha) /denomitator) if relativeDifference>allowedRelativeDifference: out.write("file \""+dumpFile0.fileName+"\" has alpha \"" +str(dumpFile0.alpha)+"\" while file \""+dumpFile1.fileName +"\" has alpha \""+str(dumpFile1.alpha)+"\"\n") headersMatch=False #check eosStringLen if dumpFile0.eosStringLen!=dumpFile1.eosStringLen: out.write("file \""+dumpFile0.fileName+"\" has eosStringLen \"" +str(dumpFile0.eosStringLen)+"\" while file \""+dumpFile1.fileName +"\" has eosStringLen \""+str(dumpFile1.eosStringLen)+"\"\n") #headersMatch=False #these are allowed to be different, but are still reported #check eosString, either gamma value, or a file path if dumpFile0.eosStringLen>0: if dumpFile0.eosString!=dumpFile1.eosString: out.write("file \""+dumpFile0.fileName+"\" has eosString \"" +str(dumpFile0.eosString)+"\" while file \""+dumpFile1.fileName +"\" has eosString \""+str(dumpFile1.eosString)+"\"\n") #headersMatch=False #file paths are allowed to be different, but are still reported else: if dumpFile0.gamma!=dumpFile1.gamma: out.write("file \""+dumpFile0.fileName+"\" has gamma \"" +str(dumpFile0.gamma)+"\" while file \""+dumpFile1.fileName +"\" has gamma \""+str(dumpFile1.gamma)+"\"\n") headersMatch=False #check av (artificial viscosity) denomitator=abs(dumpFile0.av+dumpFile1.av)*0.5 if denomitator>threshold: relativeDifference=(abs(dumpFile0.av-dumpFile1.av) /denomitator) if relativeDifference>allowedRelativeDifference: out.write("file \""+dumpFile0.fileName+"\" has av \""+str(dumpFile0.av)\ +"\" while file \""+dumpFile1.fileName+"\" has av \""\ +str(dumpFile1.av)+"\"\n") headersMatch=False #check avthreshold denomitator=abs(dumpFile0.avthreshold+dumpFile1.avthreshold)*0.5 if denomitator>threshold: relativeDifference=(abs(dumpFile0.avthreshold-dumpFile1.avthreshold) /denomitator) if relativeDifference>allowedRelativeDifference: out.write("file \""+dumpFile0.fileName+"\" has avthreshold \"" +str(dumpFile0.avthreshold)+"\" while file \""+dumpFile1.fileName +"\" has avthreshold \""+str(dumpFile1.avthreshold)+"\"\n") headersMatch=False #check global grid dimensions if dumpFile0.globalDims!=dumpFile1.globalDims: out.write("file \""+dumpFile0.fileName+"\" has globalDims \"" +str(dumpFile0.globalDims)+"\" while file \""+dumpFile1.fileName +"\" has globalDims \""+str(dumpFile1.globalDims)+"\"\n") headersMatch=False fatal=True #check boundary conditions if dumpFile0.boundaryConditions!=dumpFile1.boundaryConditions: out.write("file \""+dumpFile0.fileName+"\" has boundaryConditions \"" +str(dumpFile0.boundaryConditions)+"\" while file \""+dumpFile1.fileName +"\" has boundaryConditions \""+str(dumpFile1.boundaryConditions)+"\"\n") headersMatch=False fatal=True #check number of 1D zones if dumpFile0.num1DZones!=dumpFile1.num1DZones: out.write("file \""+dumpFile0.fileName+"\" has num1DZones \"" +str(dumpFile0.num1DZones)+"\" while file \""+dumpFile1.fileName +"\" has num1DZones \""+str(dumpFile1.num1DZones)+"\"\n") headersMatch=False fatal=True #check number of ghost cells if dumpFile0.numGhostCells!=dumpFile1.numGhostCells: out.write("file \""+dumpFile0.fileName+"\" has numGhostCells \"" +str(dumpFile0.numGhostCells)+"\" while file \""+dumpFile1.fileName +"\" has numGhostCells \""+str(dumpFile1.numGhostCells)+"\"\n") headersMatch=False fatal=True #check number of variables if dumpFile0.numVars!=dumpFile1.numVars: out.write("file \""+dumpFile0.fileName+"\" has numVars \"" +str(dumpFile0.numVars)+"\" while file \""+dumpFile1.fileName +"\" has numVars \""+str(dumpFile1.numVars)+"\"\n") headersMatch=False fatal=True #check information about all variables if dumpFile0.varInfo!=dumpFile1.varInfo: out.write("file \""+dumpFile0.fileName+"\" has varInfo \"" +str(dumpFile0.varInfo)+"\" while file \""+dumpFile1.fileName +"\" has varInfo \""+str(dumpFile1.varInfo)+"\"\n") headersMatch=False fatal=True #check if dumpFile0.varSize!=dumpFile1.varSize: out.write("file \""+dumpFile0.fileName+"\" has varSize \""\ +str(dumpFile0.varSize)\ +"\" while file \""+dumpFile1.fileName+"\" has varSize \""\ +str(dumpFile1.varSize)+"\"\n") headersMatch=False fatal=True #check number of dimensions if dumpFile0.numDims!=dumpFile1.numDims: out.write("file \""+dumpFile0.fileName+"\" has numDims \""\ +str(dumpFile0.numDims)\ +"\" while file \""+dumpFile1.fileName+"\" has numDims \""\ +str(dumpFile1.numDims)+"\"\n") headersMatch=False fatal=True return [headersMatch,fatal] def diffVar(dumpFile0,dumpFile1,var,allowedDifferance,threshold,out): """Checks if the variable, var, in the two dump files differ If the variables differ the difference is written to out Arguments: dumpFile0: one of the two dump files to be compared dumpFile1: the second of the two dump files to be compared var: the variable to compare allowedRelativeDifference: the allowed relative difference between two numerical values being compared between the two dump files. If the relative difference is less, no difference is reported. threshold: how large the variable must be before the difference is considered. Usefull when comparing velocities for example. out: an output object which supports the a write() allowing output of the comparison to be written out. """ match=True #set ghost cells based on which directions the variable is defined in ghostCellsInX0=1 if dumpFile0.varInfo[var][0]==-1: ghostCellsInX0=0 ghostCellsInX1=1 if dumpFile0.varInfo[var][1]==-1: ghostCellsInX1=0 ghostCellsInX2=1 if dumpFile0.varInfo[var][2]==-1: ghostCellsInX2=0 #read 1D part sizeX01=ghostCellsInX0*(dumpFile0.num1DZones+dumpFile0.numGhostCells) if dumpFile0.varInfo[var][0]==1 and dumpFile0.boundaryConditions[0]==0: sizeX01=ghostCellsInX0*(dumpFile0.num1DZones+dumpFile0.numGhostCells+1) sizeX1=1 sizeX2=1 for i in range(sizeX01): for j in range(sizeX1): for k in range(sizeX2): denomitator=abs(dumpFile0.vars[var][i][j][k]+dumpFile1.vars[var][i][j][k])*0.5 if denomitator>threshold: numerator=abs(dumpFile0.vars[var][i][j][k]-dumpFile1.vars[var][i][j][k]) relativeDiffernace=numerator/denomitator if relativeDiffernace>allowedDifferance: lineDiff="var "+str(dumpFile0.varNames[var])+" in zone ("+str(i)+","+str(j)+","+str(k)+\ ") has relative difference of {0:.2e} and magnitudes {1:.15e} and {2:.15e}.\n"\ .format(relativeDiffernace,dumpFile0.vars[var][i][j][k],dumpFile1.vars[var][i][j][k]) out.write(lineDiff) match=False #read multi-D part sizeX02=dumpFile0.varSize[var][0]+ghostCellsInX0*2*dumpFile0.numGhostCells sizeX1=dumpFile0.varSize[var][1]+ghostCellsInX1*2*dumpFile0.numGhostCells sizeX2=dumpFile0.varSize[var][2]+ghostCellsInX2*2*dumpFile0.numGhostCells for i in range(sizeX01,sizeX02): for j in range(sizeX1): for k in range(sizeX2): denomitator=abs(dumpFile0.vars[var][i][j][k]+dumpFile1.vars[var][i][j][k])*0.5 if denomitator>threshold: numerator=abs(dumpFile0.vars[var][i][j][k]-dumpFile1.vars[var][i][j][k]) relativeDiffernace=numerator/denomitator if relativeDiffernace>allowedDifferance: lineDiff="var "+str(dumpFile0.varNames[var])+" in zone ("+str(i)+","+str(j)+","+str(k)+\ ") has relative difference of {0:.2e} and magnitudes {1:.15e} and {2:.15e}.\n"\ .format(relativeDiffernace,dumpFile0.vars[var][i][j][k],dumpFile1.vars[var][i][j][k]) out.write(lineDiff) match=False return match def main(): parser=op.OptionParser(usage="Usage: %prog [options]" ,version="%prog 1.0" ,description="Tests to dump files to see if they differ.") #parse command line options (options,args)=parser.parse_args() if len(args)<2: print "must supply two files names" return False #test out some simple uses for this class diffDumps(args[0],args[1],5e-14,1e-17,sys.stdout) if __name__ == "__main__": main()
import turtle def drawSquare(x, sz): for i in range(4): x.forward(sz) x.left(90) wn = turtle.Screen() wn.bgcolor("Navy Blue") turt = turtle.Turtle() turt.color('yellow') turt.pensize(4) for i in range(5): drawSquare(turt, 40) turt.penup() turt.forward(-100) turt.pendown() wn.exitonclick()
def get_prep_words(filename): set_of_prep_words = set() f = open(filename, 'r') for line in f: line_strip = line.strip('\n') line_strip = line.strip() line_lowercase = line_strip.lower() set_of_prep_words.add(line_lowercase) f.close() return set_of_prep_words def remove_empty_spaces(list): c = list.count('') for i in range (0,c): list.remove('') def is_salt_pepper(string): s = 'salt' bp = 'black pepper' p = 'pepper' return s in string and (bp in string or p in string) def remove_prep_words(recipe_list, set_prep_words): from nltk.stem import WordNetLemmatizer wnl = WordNetLemmatizer() # used to get rid of plurals for r in recipe_list: ingredient_list = recipe_list[r] add_at_end = False for i in range(0, len(ingredient_list)): ingred = ingredient_list[i] #Convert to lowercase lower_ingred = ingred.lower() #for special case salt and pepper only if is_salt_pepper(lower_ingred): add_at_end = True ingredient_list[i] ='' else: #Remove prep words at beginning of ingredient string, second step lower_ingred_split =lower_ingred.split() new_ingred = '' for word in lower_ingred_split: no_punc_word = word.strip(',') no_punc_word = no_punc_word.strip(')') no_punc_word = no_punc_word.strip('(') if no_punc_word not in set_prep_words and not no_punc_word.isdigit(): #Remove plurals lemmatized_word = wnl.lemmatize(no_punc_word) if lemmatized_word not in set_prep_words: #once again, for good measure, in case missed variation new_ingred = new_ingred + lemmatized_word + '_' ingredient_list[i] = new_ingred.strip('_- ') if add_at_end: ingredient_list.append('salt') ingredient_list.append('black_pepper') remove_empty_spaces(ingredient_list)
# -*- coding: utf-8 -*- # %% 51 from collections import Counter text = 'python programming - introduction' cnt = Counter(text) print(cnt.most_common(3)) # %% 52 from collections import Counter import re text = """"Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers," said Cuong Do, Software Architect, YouTube.com. "Python plays a key role in our production pipeline. Without it a project the size of Star Wars: Episode II would have been very difficult to pull off. From crowd rendering to batch processing to compositing, Python binds all things together," said Tommy Burnette, Senior Technical Director, Industrial Light & Magic.""" tokens = re.findall(r"\w+", text) tokens = [token.lower() for token in tokens] cnt = Counter(tokens) print(cnt.most_common(3)) # %% 53 from collections import Counter fnames = [ '001_image.png', '002_image.png', '003_image.jpg', '004_image.png', '005_image.png', '006_image.png', '007_image.jpg', '008_image.png', '009_image.jpg', '010_image.jpg', '011_image.jpg', '012_image.png', '013_image.jpg', '014_image.jpg', '015_image.jpg', '016_image.png', '017_image.jpg', '018_image.jpg', '019_image.png', '020_image.png', '021_image.jpg', '022_image.jpg', '023_image.png', '024_image.png', '025_image.jpg', '026_image.png', '027_image.png', '028_image.jpg', '029_image.png', '030_image.png' ] extensions = [fname.split('.')[1] for fname in fnames] cnt = Counter(extensions) print(cnt) # %% 54 from collections import ChainMap stocks_1 = {'CDR': 400, 'PLW': 490} stocks_2 = {'PLW': 500, 'TEN': 550, 'BBT': 30} stocks = ChainMap(stocks_1, stocks_2) print(stocks) # %% 55 from collections import ChainMap stocks_1 = {'CDR': 400, 'PLW': 490} stocks_2 = {'PLW': 500, 'TEN': 550, 'BBT': 30} stocks = ChainMap(stocks_1, stocks_2) print(stocks['PLW']) # %% 56 from collections import ChainMap techs = {'Apple': 370, 'Samsung': 1100, 'Microsoft': 201} finance = {'Citigroup': 51, 'Allianz': 180} gaming = {'Sony': 76, 'Nintendo': 470, 'EA': 135} stocks = ChainMap(techs, finance, gaming) print(stocks['Samsung']) # %% 57 from collections import ChainMap techs = {'Apple': 370, 'Samsung': 1100, 'Microsoft': 201} finance = {'Citigroup': 51, 'Allianz': 180} gaming = {'Sony': 76, 'Nintendo': 470, 'EA': 135} stocks = ChainMap(techs, finance, gaming) techs['Microsoft'] = 210 print(stocks['Microsoft']) # %% 58 from collections import ChainMap techs = {'Apple': 370, 'Samsung': 1100, 'Microsoft': 201} finance = {'Citigroup': 51, 'Allianz': 180} gaming = {'Sony': 76, 'Nintendo': 470, 'EA': 135} stocks = ChainMap(techs, finance, gaming) print(sorted(list(stocks.keys()))) # %% 59 from collections import ChainMap default_settings = {'mode': 'eco', 'power_level': 7} user_settings = {'mode': 'sport', 'power_level': 10} settings = ChainMap(user_settings, default_settings) print(settings['mode']) # %% 60 from collections import ChainMap default_settings = {'mode': 'eco', 'power_level': 7} user_settings = {} settings = ChainMap(user_settings, default_settings) print(settings['mode']) stocks = ChainMap(stocks_1, stocks_2) print(stocks)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 13 16:43:52 2019 @author: trn2503 """ class QueueIsEmpty(Exception): pass class Queue: def __init__(self): self._queue = [] def add(self, item): self._queue.append(item) def pop(self): try: return self._queue.pop(0) except IndexError: raise QueueIsEmpty('There are no elements in the queue') class EmergencyQueue(Queue): def push(self, item): self.queue.insert(0, item) class NoisyQueue(Queue): def __call__(self): print('I am an extremely noisy queue! WAAAAAAAA') def add(self, item): Queue.add(self, item) print('Added the following item to queue:', item)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 14 15:33:06 2019 @author: trn2503 """ #a = list(map(lambda x:x*x, range(10))) #print(a) #Equivalent print('List comprehension example 1') a = [ x*x for x in range(10) ] print(a) #Cartesian product print('Another example, Cartesian product') b = [ (x,y) for x in range(4) for y in 'abc' ] print(b) c = [ (x,y) for x in range(6) if x%2 for y in range(6) if x>y ] print(c) #Filter #x = [A for b in B if C for d in D if E] #x=[] #for b in B: # if C: # for d in D: # if E: # x.append(A) #Dictionary comprehension {x:x*x for x in range(10)} {x*x for x in range(10)} #Lazy version of list comprehension -> Generators a = (n*n for n in range(10)) next(a) sum(n*n for n in range(10))
import obd import time connection = obd.OBD() # auto-connects to USB or RF port def obd_speed(): cmd = obd.commands.SPEED # select an OBD command (sensor) response = connection.query(cmd) # send the command, and parse the response print(response.value) # returns unit-bearing values thanks to Pint print(response.value.to("mph")) # user-friendly unit conversions return response.value.to("mph") print ("speed = : " + str(obd_speed()))
import logging logging.basicConfig(filename="new11.log", format='%(asctime)s %(message)s', filemode='w') logger=logging.getLogger() logger.setLevel(logging.DEBUG) logger.info("New file is created") a = int(input("Enter A : ")) b = int(input("Enter B : ")) if a>10 or b>10: logging.debug("A or B values are greaterthan the limit provide by the user") elif a<b: c = a + b logging.info("Add operation is performing") print(c) else: c = a-b logging.info("Subtraction operation is performing") print(c)
#!/usr/bin/env python import math import sys class Grid: """Representation of a sheet of grid paper. Initialized as a three-dimensional N x N x 1 grid. N must be a power of 2. Cells are numbered from 1 to N * N, going in order from left to right, then top to bottom, then front to back. """ def __init__(self, N): try: if not float(N).is_integer(): raise GridError("Grid length must be an integer") if N < 1 or (N & (N - 1) != 0): raise GridError("Grid length must be a power of 2") except (TypeError, ValueError): raise GridError("Invalid grid length: {}".format(N)) self.grid = [[[N * i + j + 1 for j in range(N)] for i in range(N)]] self.max_folds = math.log(N, 2) self.vertical_folds = 0 self.horizontal_folds = 0 def fold_top_to_bottom(self): """Fold the top edge of the grid down to the bottom edge.""" if self.vertical_folds >= self.max_folds: raise GridError("Too many vertical folds!") g = self.grid new_grid = [] for i in reversed(range(len(g))): sheet = [] for j in reversed(range(len(g[i]) // 2)): sheet.append(g[i][j]) new_grid.append(sheet) for i in range(len(g)): sheet = [] for j in range(len(g[i]) // 2, len(g[i])): sheet.append(g[i][j]) new_grid.append(sheet) self.grid = new_grid self.vertical_folds += 1 def fold_bottom_to_top(self): """Fold the top edge of the grid down to the bottom edge.""" if self.vertical_folds >= self.max_folds: raise GridError("Too many vertical folds!") g = self.grid new_grid = [] for i in reversed(range(len(g))): sheet = [] for j in reversed(range(len(g[i]) // 2, len(g[i]))): sheet.append(g[i][j]) new_grid.append(sheet) for i in range(len(g)): sheet = [] for j in range(len(g[i]) // 2): sheet.append(g[i][j]) new_grid.append(sheet) self.grid = new_grid self.vertical_folds += 1 def fold_right_to_left(self): """Fold the top edge of the grid down to the bottom edge.""" if self.horizontal_folds >= self.max_folds: raise GridError("Too many horizontal folds!") g = self.grid new_grid = [] for i in reversed(range(len(g))): sheet = [] for j in range(len(g[i])): sheet.append(g[i][j][: len(g[i][j]) // 2 - 1 : -1]) new_grid.append(sheet) for i in range(len(g)): sheet = [] for j in range(len(g[i])): sheet.append(g[i][j][: len(g[i][j]) // 2]) new_grid.append(sheet) self.grid = new_grid self.horizontal_folds += 1 def fold_left_to_right(self): """Fold the top edge of the grid down to the bottom edge.""" if self.horizontal_folds >= self.max_folds: raise GridError("Too many horizontal folds!") g = self.grid new_grid = [] for i in reversed(range(len(g))): sheet = [] for j in range(len(g[i])): sheet.append(g[i][j][len(g[i][j]) // 2 - 1 : : -1]) new_grid.append(sheet) for i in range(len(g)): sheet = [] for j in range(len(g[i])): sheet.append(g[i][j][len(g[i][j]) // 2 :]) new_grid.append(sheet) self.grid = new_grid self.horizontal_folds += 1 def flatten(self): """Return the grid as a one-dimensional array. The grid must have dimensions 1 x 1 x N. """ if (len(self.grid[0]) != 1) or (len(self.grid[0][0]) != 1): raise GridError("Cannot flatten grid until fully folded") return [sheet[0][0] for sheet in self.grid] def fold(self, sequence): """Fold the grid according to the given sequence. "T" folds the top edge of the grid down to the bottom edge. "B" folds the bottom edge of the grid up to the top edge. "R" folds the right edge of the grid across to the left edge. "L" folds the left edge of the grid across to the right edge. A valid sequence results in a 1 x 1 x N grid. """ if len(sequence) != 2 * self.max_folds: raise GridError("Invalid input: incorrect input length") fold_funcs = { "T": self.fold_top_to_bottom, "B": self.fold_bottom_to_top, "R": self.fold_right_to_left, "L": self.fold_left_to_right } for c in sequence: f = fold_funcs.get(c) if not f: raise GridError("Invalid input character: {}".format(c)) f() return self.flatten() class GridError(Exception): pass if __name__ == "__main__": if len(sys.argv) != 2: print("Error: expected single sequence argument") else: try: g = Grid(16) print(g.fold(sys.argv[1])) except GridError as e: print(e)
# Objective: demonstration of linear regression in Python for machine learning # Source: Siraj Raval, How to Make a Prediction - Intro to Deep Learning #1 # Notes: script prepared for Python 3.6.0 import pandas as pd from sklearn import linear_model import matplotlib.pyplot as plt # read data dataframe = pd.read_csv('.\data\data.csv', names=['Scores', 'Hours']) print("Show first few lines of imported dataframe:") print(dataframe.head()) x_values = dataframe[['Scores']] y_values = dataframe[['Hours']] # train model on data scores_reg = linear_model.LinearRegression() scores_reg.fit(x_values, y_values) # visualise results plt.scatter(x_values, y_values) plt.plot(x_values, scores_reg.predict(x_values)) plt.show()
UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) class Direction(object): def __init__(self, direction=UP): self._direction = direction def turn_up(self): return self._turn_direction(UP) def turn_down(self): return self._turn_direction(DOWN) def turn_left(self): return self._turn_direction(LEFT) def turn_right(self): return self._turn_direction(RIGHT) def _turn_direction(self, direction): if direction == self._direction: return False self._direction = direction return True @property def direction(self): return self._direction def __eq__(self, other): return self._direction == other.direction
import sys, string num = int(input()) if num % 13 == 0 : print('yes') else : print('no')
import sys, string num = int(input()) value = 0 while num : value += num%10 num //= 10 print(value)
#sum of n natural nos import sys num = int(input('enter N : ')) sum = 0 for i in range(1,num+1) : sum += i print(sum)
import sys, string, math n = int(input()) p = 1 for i in range(1,n+1) : p = p * i print(p)
number=int(input("enter the value:")) sum=[] for i in range(0,number): value=int(input('')) a=sum.append(value) print sum sum.sort() print(sum)
#check odd or even import sys num = int(input('enter a no : ')) if num%2==0 : print('Even') else : print('Odd')
''' Pivot data Pivoting data is the opposite of melting it. Remember the tidy form that the airquality DataFrame was in before you melted it? You'll now begin pivoting it back into that form using the .pivot_table() method! While melting takes a set of columns and turns it into a single column, pivoting will create a new column for each unique value in a specified column. .pivot_table() has an index parameter which you can use to specify the columns that you don't want pivoted: It is similar to the id_vars parameter of pd.melt(). Two other parameters that you have to specify are columns (the name of the column you want to pivot), and values (the values to be used when the column is pivoted). The melted DataFrame airquality_melt has been pre-loaded for you. INSTRUCTIONS 100 XP Print the head of airquality_melt. Pivot airquality_melt by using .pivot_table() with the rows indexed by 'Month' and 'Day', the columns indexed by 'measurement', and the values populated with 'reading'. Print the head of airquality_pivot. '''
''' Custom functions to clean data You'll now practice writing functions to clean data. The tips dataset has been pre-loaded into a DataFrame called tips. It has a 'sex' column that contains the values 'Male' or 'Female'. Your job is to write a function that will recode 'Male' to 1, 'Female' to 0, and return np.nan for all entries of 'sex' that are neither 'Male' nor 'Female'. Recoding variables like this is a common data cleaning task. Functions provide a mechanism for you to abstract away complex bits of code as well as reuse code. This makes your code more readable and less error prone. As Dan showed you in the videos, you can use the .apply() method to apply a function across entire rows or columns of DataFrames. However, note that each column of a DataFrame is a pandas Series. Functions can also be applied across Series. Here, you will apply your function over the 'sex' column. INSTRUCTIONS 100 XP Define a function named recode_sex() that has one parameter: sex_value. If sex_value equals 'Male', return 1. Else, if sex_value equals 'Female', return 0. If sex_value does not equal 'Male' or 'Female', return np.nan. NumPy has been pre-imported for you. Apply your recode_sex() function over tips.sex using the .apply() method to create a new column: 'sex_recode'. Note that when passing in a function inside the .apply() method, you don't need to specify the parentheses after the function name. Hit 'Submit Answer' and take note of the new 'sex_recode' column in the tips DataFrame! '''
''' Many-to-many data merge The final merging scenario occurs when both DataFrames do not have unique keys for a merge. What happens here is that for each duplicated key, every pairwise combination will be created. Two example DataFrames that share common key values have been pre-loaded: df1 and df2. Another DataFrame df3, which is the result of df1 merged with df2, has been pre-loaded. All three DataFrames have been printed - look at the output and notice how pairwise combinations have been created. This example is to help you develop your intuition for many-to-many merges. Here, you'll work with the site and visited DataFrames from before, and a new survey DataFrame. Your task is to merge site and visited as you did in the earlier exercises. You will then merge this merged DataFrame with survey. Begin by exploring the site, visited, and survey DataFrames in the IPython Shell. INSTRUCTIONS 100 XP Merge the site and visited DataFrames on the 'name' column of site and 'site' column of visited, exactly as you did in the previous two exercises. Save the result as m2m. Merge the m2m and survey DataFrames on the 'ident' column of m2m and 'taken' column of survey. Hit 'Submit Answer' to print the first 20 lines of the merged DataFrame! '''
''' Converting data types In this exercise, you'll see how ensuring all categorical variables in a DataFrame are of type category reduces memory usage. The tips dataset has been loaded into a DataFrame called tips. This data contains information about how much a customer tipped, whether the customer was male or female, a smoker or not, etc. Look at the output of tips.info() in the IPython Shell. You'll note that two columns that should be categorical - sex and smoker - are instead of type object, which is pandas' way of storing arbitrary strings. Your job is to convert these two columns to type category and note the reduced memory usage. INSTRUCTIONS 100 XP Convert the sex column of the tips DataFrame to type 'category' using the .astype() method. Convert the smoker column of the tips DataFrame. Print the memory usage of tips after converting the data types of the columns. Use the .info() method to do this. '''
''' The power of SQL lies in relationships between tables: INNER JOIN Here, you'll perform your first INNER JOIN! You'll be working with your favourite SQLite database, Chinook.sqlite. For each record in the Album table, you'll extract the Title along with the Name of the Artist. The latter will come from the Artist table and so you will need to INNER JOIN these two tables on the ArtistID column of both. Recall that to INNER JOIN the Orders and Customers tables from the Northwind database, Hugo executed the following SQL query: "SELECT OrderID, CompanyName FROM Orders INNER JOIN Customers on Orders.CustomerID = Customers.CustomerID" The following code has already been executed to import the necessary packages and to create the engine: import pandas as pd from sqlalchemy import create_engine engine = create_engine('sqlite:///Chinook.sqlite') INSTRUCTIONS 100 XP Assign to rs the results from the following query: select all the records, extracting the Title of the record and Name of the artist of each record from the Album table and the Artist table, respectively. To do so, INNER JOIN these two tables on the ArtistID column of both. In a call to pd.DataFrame(), apply the method fetchall() to rs in order to fetch all records in rs. Store them in the DataFrame df. Set the DataFrame's column names to the corresponding names of the table columns. ''' import pandas as pd from sqlalchemy import create_engine engine = create_engine('sqlite:///Chinook.sqlite') # Open engine in context manager con = engine.connect() # Perform query and save results to DataFrame: df with engine.connect() as con: rs = con.execute("SELECT Title, Name FROM Album INNER JOIN Artist on Album.ArtistID = Artist.ArtistID") df = pd.DataFrame(rs.fetchall()) df.columns = rs.keys() # Print head of DataFrame df print(df.head())
''' Loading and exploring a JSON Now that you know what a JSON is, you'll load one into your Python environment and explore it yourself. Here, you'll load the JSON 'a_movie.json' into the variable json_data, which will be a dictionary. You'll then explore the JSON contents by printing the key-value pairs of json_data to the shell. INSTRUCTIONS 100 XP Load the JSON 'a_movie.json' into the variable json_data within the context provided by the with statement. To do so, use the function json.load() within the context manager. Use a for loop to print all key-value pairs in the dictionary json_data. Recall that you can access a value in a dictionary using the syntax: dictionary[key]. ''' #Importing JSON package import json # Load JSON: json_data with open("a_movie.json") as json_file: json_data = json.load(json_file) # Print each key-value pair in json_data for k in json_data.keys(): print(k + ': ', json_data[k] )
# !/usr/bin/env python # -*-coding:utf-8 -*- """ # File : 练习题.py # Time :2021/4/18 10:15 # Author :yhy # version :python 3.7 """ l = [1, 3, 45, 39, 9, 66] def test1(list, n): print(list) for i in range(n): list.insert(0, list.pop()) print(list) def test2(list, n): print(list) for i in range(n): num=list[len(list)-1] list.remove(num) list.insert(0, num) print(list) test1([1, 3, 45, 39, 9, 66], 2) print("-------------") test2([1, 3, 45, 39, 9, 66], 2)
# -*- coding: utf-8 -*- import re # for validating an Email def validate_email(email): regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' if(re.search(regex,email)): return True else: print("Invalid Email") return False def validate_phone(phone): regex = "^(\d{10})$" if(re.search(regex,phone)): return True else: print("Invalid Phone") return False validate_phone('1234567890')
import random import pygame pygame.init() display = pygame.display.set_mode((400, 400)) display.fill((255, 255, 255)) pygame.display.update() font = pygame.font.Font(None, 18) t = None color = (0, 0, 0) health = int(100) enemyHealth = int(100) action = " " potion = True shot = int(0) attack = int(0) shield = False enemyAction = int(0) enemyPotion = True tempDamage = int(0) gear = ["Sword", "Bow", "Potion", "Shield", "Arrows"] arrows = int(3) enemyArrows = int(3) mouseX = 0 mouseY = 0 SWORD_ACCURACY = int(90) BOW_ACCURACY = int(60) SWORD_DAMAGE = int(10) BOW_DAMAGE = int(20) POTION_HEALTH = int(25) def text(t, color, coords, size): font = pygame.font.Font(None, size) t = font.render(t, 1, color) display.blit(t, coords) pygame.display.update() def conclusion(): if health > 0 and enemyHealth <= 0: print("You win! Congratulations!") else: print("You lose!") input("Press enter to exit.") #intro text("Welcome! In this turn-based battle,", (0, 0, 0), (50, 50), 20) text("you will fight against an enemy of equal strength.", (0, 0, 0), (50, 75), 20) text("Press 'Stats' to see your gear, info, and actions.", (0, 0, 0), (50, 100), 20) text("Your goal is to reduce the enemy's health to zero.", (0, 0, 0), (50, 125), 20) text("Press enter to continue.", (0, 0, 0), (50, 150), 20) input() display.fill((255, 255, 255)) pygame.display.update() #battle loop while health > 0 and enemyHealth > 0: action = " " #GUI pygame.draw.rect(display, (128, 128, 128), (150, 25, 100, 50)) text("Stats", (0, 0, 0), (175, 40), 20) pygame.draw.rect(display, (255, 0, 0), (50, 100, 100, 50)) text("Sword", (0, 0, 0), (75, 115), 20) pygame.draw.rect(display, (0, 0, 255), (250, 100, 100, 50)) text("Bow", (0, 0, 0), (275, 115), 20) pygame.draw.rect(display, (255, 255, 0), (50, 250, 100, 50)) text("Shield", (0, 0, 0), (75, 265), 20) pygame.draw.rect(display, (0, 255, 0), (250, 250, 100, 50)) text("Potion", (0, 0, 0), (275, 265), 20) pygame.display.update() #input action for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: mouseX = event.pos[0] mouseY = event.pos[1] if mouseX >= 150 and mouseX <= 250 and mouseY >= 25 and mouseY <= 75: action = "stats" elif mouseX >= 50 and mouseX <= 150 and mouseY >= 100 and mouseY <= 150: action = "attack" elif mouseX >= 250 and mouseX <= 350 and mouseY >= 100 and mouseY <= 150: action = "shoot" elif mouseX >= 50 and mouseX <= 150 and mouseY >= 250 and mouseY <= 300: action = "block" elif mouseX >= 250 and mouseX <= 350 and mouseY >= 250 and mouseY <=300: action = "potion" #result of action if action == "stats": print("Your health:", health) print("Enemy health:", enemyHealth) print("Gear:") for item in gear: print(item, end = ("; ")) print("Sword - 10 damage, 90% accuracy") print("Bow - 20 damage, 60% accuracy") if potion == True: print("Potion x1 - heals 25 health") print("Shield - halves the damage of the enemy's next attack\n and adds it to your next attack") print("Available actions: stats, attack, shoot, block, potion") action = " " elif action == "shoot" and arrows > 0: shot = random.randint(1, 100) print("You shoot at the enemy with a bow!") if shot <= BOW_ACCURACY: enemyHealth -= BOW_DAMAGE enemyHealth -= tempDamage print("Hit! Enemy's health:", enemyHealth, "\n") else: print("Miss! Enemy's health:", enemyHealth, "\n") arrows -= 1 print("Arrows left:", arrows) if arrows == 0: del gear[len(gear) - 1] elif action == "attack": attack = random.randint(1, 100) print("You swing at the enemy with a sword!") if attack <= SWORD_ACCURACY: enemyHealth -= SWORD_DAMAGE enemyHealth -= tempDamage print("Hit! Enemy's health:", enemyHealth, "\n") else: print("Miss! Enemy's health:", enemyHealth, "\n") elif action == "block": shield = True print("You ready your shield.\n") elif action == "potion": if potion == True and health <= 75: health += POTION_HEALTH print("You drank your potion! Current health:", health, "\n") potion = False del gear[2] elif potion == True and health > 75: print("You haven't lost enough health to use your potion!") action = " " else: print("You don't have a potion!\n") action = " " elif action == " ": action = " " else: print("Invalid command! Enter a new command.\n") action = " " tempDamage = 0 #enemy turn if action != " " and action != "stats" and enemyHealth > 0: #calculate move if enemyHealth <= 75 and enemyPotion == True: enemyAction = 3 elif enemyHealth + 20 <= health and enemyArrows > 0: enemyAction = 1 elif enemyArrows > 0: enemyAction = random.randint(1, 2) else: enemyAction = 2 if enemyAction == 1: print("The enemy shoots at you with a bow!") shot = random.randint(1, 100) if shot <= BOW_ACCURACY: if shield == False: health -= BOW_DAMAGE print("Hit! Your health:", health, "\n") elif shield == True: health -= BOW_DAMAGE / 2 tempDamage = BOW_DAMAGE / 2 print("Blocked hit! Your health:", health, "\n") else: print("Miss! Your health:", health, "\n") enemyArrows -= 1 print("Enemy arrows left:", enemyArrows) elif enemyAction == 2: print("The enemy swings at you with a sword!") attack = random.randint(1, 100) if attack <= SWORD_ACCURACY: if shield == False: health -= SWORD_DAMAGE print("Hit! Your health:", health, "\n") elif shield == True: health -= SWORD_DAMAGE / 2 tempDamage = SWORD_DAMAGE / 2 print("Blocked hit! Your health:", health, "\n") else: print("Miss! Your health:", health, "\n") else: enemyHealth += POTION_HEALTH enemyPotion = False print("The enemy drank a potion! Enemy health:", enemyHealth) shield = False #conclusion conclusion()
#87 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. def find_fib(num): first_num = 1 second_num = 2 total = 0 while second_num <= num: if second_num%2 == 0: total += second_num second_num += first_num first_num = second_num - first_num return total def fib_even_sum(): total = find_fib(4000000) print total # fib_even_sum()
""" Olympics. You're given list of lists where each list is the countries that won the gold, silver and bronze for that activity. Return the countries and their medal counts, prioritizing first gold, silver then bronze. If its a full tie in all 3 categories, alphabetize. sample input: [["ITA", "JPN", "AUS"], ["KOR", "TPE", "UKR"], ["KOR", "KOR", "GBR"], ["KOR", "CHN", "TPE"]] sample output: KOR 3 1 0 ITA 1 0 0 TPE 0 1 1 CHN 0 1 0 JPN 0 1 0 AUS 0 0 1 GBR 0 0 1 UKR 0 0 1 """ l = [["ITA", "JPN", "AUS"], ["KOR", "TPE", "UKR"], ["KOR", "KOR", "GBR"], ["KOR", "CHN", "TPE"]] from operator import itemgetter def default_list(l): results = {} for medal in l: # for each country as a key in dictionary, add name, and start gold silver and bronze count at 0 for country in medal: results.setdefault(country, {"name":country, "gold":0, "silver":0, "bronze":0}) # the first country in every sublist won gold, 2nd silver, 3rd bronze. use country name as key, increase gold count for that country. results[medal[0]]["gold"]+=1 results[medal[1]]["silver"]+=1 results[medal[2]]["bronze"]+=1 # print results # now that i have a tally of total count, I need to sort the result. Since I cant sort a dictionary I need to put everything in a list. sorted_result = [] for k, v in results.iteritems(): sorted_result.append(v) # print sorted_result # Now I need to perform the actual sorting sorted_list = sorted(sorted_result, key=itemgetter("name")) sorted_list = sorted(sorted_result, key=itemgetter("gold","silver","bronze"), reverse=True) # print sorted_list # The list is in the order I want, now I just need to make sure I print them out in the order I want for i in sorted_list: print i["name"], i["gold"], i["silver"], i["bronze"] default_list(l)
# Write a function that helps cashier to give change back in as little coins as possible. Input is change need to be given back, output is minimum # of coins needed. def change(amount): quarter = 0.25 q_count = 0 dime = 0.1 d_count = 0 nickel = 0.05 n_count = 0 penny = 0.01 p_count = 0 left = amount while left > 0: if left >= quarter: left -= quarter q_count += 1 print left if left >= dime: left -= dime d_count += 1 print left if left >= nickel: left -= nickel n_count += 1 print left if left >= 0: left -= penny p_count += 1 print left total = q_count + d_count + n_count + p_count # print left # print q_count # print d_count # print n_count # print p_count return "you need a minimum of " + str(total) + " coins." # print change(.35) def coinChange(centsNeeded, coinValues): minCoins = [[0 for j in range(centsNeeded + 1)] for i in range(len(coinValues))] minCoins[0] = range(centsNeeded + 1) for i in range(1,len(coinValues)): for j in range(0, centsNeeded + 1): if j < coinValues[i]: minCoins[i][j] = minCoins[i-1][j] else: minCoins[i][j] = min(minCoins[i-1][j], 1 + minCoins[i][j-coinValues[i]]) print minCoins return minCoins[-1][-1] coinValues = [1, 5, 10, 25] print coinChange(15,coinValues)
def str_to_num(string): int_list = [] final_num = 0 string_list = list(string) for char in string_list: if 48 <= ord(char) <= 57: int_list.append(ord(char)-48) else: return False for i in range(len(int_list)): value = int_list[-i-1] place = 10**i final_num += value*place return final_num print str_to_num("89")
""" Tree traversal. BFS and DFS (pre, in, post) """ class BinaryTree: def __init__(self,data): self.key = data self.leftChild = None self.rightChild = None def insertLeft(self,newNode): if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self,newNode): if self.rightChild == None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getRightChild(self): return self.rightChild def getLeftChild(self): return self.leftChild def setRootVal(self,obj): self.key = obj def getRootVal(self): return self.key def bfs(tree): l = [tree.key] while l: node = l.pop[0] if node.getLeftChild: l.append(node.getLeftChild().getRootVal()) if node.getRightChild: l.append(node.getRightChild().getRootVal()) def bfs(tree): r = BinaryTree('a') r.insertLeft('b') r.insertRight('c') r.getLeftChild().insertLeft('d') r.getLeftChild().insertRight('e') r.getRightChild().insertLeft('f') r.getRightChild().insertRight('g') # print r.getLeftChild().getRootVal() print r.key print bfs(r)
""" Little Bob loves chocolates and goes to the store with a $N bill with $C being the price of each chocolate. In addition, the store offers a discount: for every M wrappers he gives the store, hell get one chocolate for free. How many chocolates does Bob get to eat? Input Format: The first line contains the number of test cases T (<=1000). Each of the next T lines contains three integers N, C and M Output Format: Print the total number of chocolates Bob eats. Constraints: 2 <= N <= 100000 1 <= C <= N 2 <= M <= N Sample input 3 10 2 5 12 4 4 6 2 2 Sample Output 6 3 5 """ def chocolate_eaten(n,c,m): #1st attempt # count = n/c # new_count = count/m # remaining = new_count%m # if remaining < new_count and remaining != 0: # count += new_count+remaining # else: # return count + new_count # return count #2nd attempt # count = n/c # additional = count/m # wrapper = count - additional*m # total = count + additional # if total >= m: # total += total/m # return total #3rd attempt # count = n/c # wrapper = count # while wrapper >= m: # count += wrapper-m # wrapper -= m # return count #4th attempt count = n/c wrapper = count while wrapper/m: additional = wrapper/m wrapper = wrapper%m + additional count += additional return count print chocolate_eaten(10,2,5) print chocolate_eaten(12,4,4) print chocolate_eaten(27,3,2) for i in (range(input()))[1:]: list_i = i.split() n = list_i[0] c = list_i[1] m = list_i[2] count = n/c wrapper = count while wrapper/m: additional = wrapper/m wrapper = wrapper%m + additional count += additional print count
""" Implement a simple tree in 2 representations: - list of lists - nodes and references. """ # List of lists # example of list of lists: ['a',['b',['d', [], []],['e', [], []] ],['c',['f', [], []], [] ]] def BinaryTree(r): return [r, [], []] def insertLeft(root,newBranch): t = root.pop(1) if len(t) > 1: root.insert(1,[newBranch,t,[]]) else: root.insert(1,[newBranch, [], []]) return root def insertRight(root,newBranch): t = root.pop(2) if len(t) > 1: root.insert(2,[newBranch,[],t]) else: root.insert(2,[newBranch,[],[]]) return root def getRootVal(root): return root[0] def setRootVal(root,newVal): root[0] = newVal def getLeftChild(root): return root[1] def getRightChild(root): return root[2] # r = BinaryTree(3) # insertLeft(r,4) # insertLeft(getLeftChild(r),5) # insertRight(r,6) # insertRight(r,7) # left = getLeftChild(r) # right = getRightChild(r) # print left # print right # setRootVal(left,9) # print(r) # insertLeft(left,11) # print(r) # print(getRightChild(getRightChild(r))) # Nodes and references (The OOP way) class BinaryTree: def __init__(self,data): self.key = data self.leftChild = None self.rightChild = None def insertLeft(self,newNode): if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self,newNode): if self.rightChild == None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getRightChild(self): return self.rightChild def getLeftChild(self): return self.leftChild def setRootVal(self,obj): self.key = obj def getRootVal(self): return self.key # r = BinaryTree('a') # print(r.getRootVal()) # print(r.getLeftChild()) # r.insertLeft('b') # print(r.getLeftChild()) # print(r.getLeftChild().getRootVal()) # r.insertRight('c') # print(r.getRightChild()) # print(r.getRightChild().getRootVal()) # r.getRightChild().setRootVal('hello') # print(r.getRightChild().getRootVal())
weight = int(input("Please input your weight: ")) converter = input("(L)bs or (K)g: ") if converter.upper() == "L": print(f"you weigh {float(weight) * .45} kgs!") elif converter.upper() == "K": print(f"you weigh {float(weight) / .45} lbs!") else: print("I'm sorry, that is not a valid response.")
#!/usr/bin/python3 class Calendar: def __init__(self): self.to_do_list = ToDoList() # input_date=input("Please enter today's date in mm/dd/yy format: ") date='4/20/18' date=date.split('/') self.__month=int(date[0]); self.__day=int(date[1]); self.__year=int(date[2]); self.__day_names=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]; # self.__day_num=int(input("Please enter the day of the week today (1 for Monday and 7 for Sunday): ")); self.__day_num=5; def start_new_day(self): self.__day+=1; if ((self.__month == 1) or (self.__month == 3) or (self.__month == 5)or (self.__month == 7)or (self.__month == 8)or (self.__month == 10)or (self.__month == 12)) and (self.__day > 31): self.__day %= 31; self.__month+=1; elif (self.__month == 2) and (self.__day > 28): self.__day %= 28; self.__month+=1; elif ((self.__month == 4) or (self.__month == 6) or (self.__month == 9) or (self.__month == 11)) and (self.__day > 30): self.__day %= 30; self.__month+=1; if self.__month > 12: self.__month=self.__month % 12 self.__year+=1; self.__day_num+=1; if self.__day_num > 7: self.__day_num=self.__day_num % 7; print(self); def __repr__(self): return("\nToday's date is: "+str(self.__day_names[self.__day_num-1])+' '+str(self.__month)+'/'+str(self.__day)+'/'+str(self.__year)+'\n'+str(self.to_do_list)) class ToDoList: def __init__(self): self.__to_do=[]; self.__to_done=[]; def create_to_do_list_item(self): task=input("Enter the activity: ") self.__to_do.append(task); def check_to_do_list(self): for i in range(len(self.__to_do)): if (input("Did you "+str(self.__to_do[i])+'? (y/n) ') == 'y'): self.__to_done.append(self.__to_do[i]); for i in self.__to_done: if i in self.__to_do: self.__to_do.remove(i); print("\nUpdated To-Do List:\n"+str(self)) def __repr__(self): return("\nToday's accomplishment\n=========================\n"+print_nicely(self.__to_done)+'\nThings Left To Do\n=========================\n'+print_nicely(self.__to_do)) def print_nicely(lst): output='' for i in lst: output+=i+'\n' return(output) def main(): calendar = Calendar() while True: print("\nMain Menu:") print("1. Create New Calendar") print("2. Add To-Do List Item") print("3. Check Off To-Do List") print("4. Show Today's Calendar") print("5. Start the Next Day\n") answer = input("What would you like to do? ") if answer == '1': calendar = Calendar() elif answer == '2': calendar.to_do_list.create_to_do_list_item() elif answer == '3': calendar.to_do_list.check_to_do_list() elif answer == '4': print(repr(calendar)) elif answer == '5': calendar.start_new_day() if __name__=="__main__": main()
roman=input("Enter number in the simplified Roman system: ") total=0 for letter in range(len(roman)): if (roman[letter] == "M"): total+=1000 elif (roman[letter] == "D"): total+=500 elif (roman[letter] == "C"): total+=100 elif (roman[letter] == "L"): total+=50 elif (roman[letter] == "X"): total+=10 elif (roman[letter] == "V"): total+=5 elif (roman[letter] == "I"): total+=1 print(roman, "is", total)
side1=float(input("Length of first side: ")) side2=float(input("Length of second side: ")) side3=float(input("Length of third side: ")) if (side1 == side2 and side1 == side3): print(str(side1) + ", " + str(side2) + ", " + str(side3) + " form an equilateral triangle") elif (side1 == side2): if (abs(side1**2 + side2**2 - side3**2) <= 0.00001): print(str(side1) + ", " + str(side2) + ", " + str(side3) + " form an isosceles right triangle") else: print(str(side1) + ", " + str(side2) + ", " + str(side3) + " form an isosceles triangle") else: print(str(side1) + ", " + str(side2) + ", " + str(side3) + " form a triangle that is neither isosceles nor equilateral")
weightPounds=float(input("Please enter weight in pounds: ")); heightInches=float(input("Please enter height in inches: ")); weightKilos=(weightPounds*0.453592); heightMeters=(heightInches*0.0254); BMI=(weightKilos/heightMeters**2); print("BMI is: ", BMI);
print("Please enter a non-empty sequence of positive integers, each one in a separate line. End your sequence by typing 'done':") total=0 counter=0 num=input() while (num != 'done'): total+=int(num) counter+=1 num=input() print("The geometric mean is:", total**(1/counter))
years=int(input("Input number of years: ")) seconds=years*365*24*60*60 population=307357870 population=population+int((1/7)*seconds)+int((1/35)*seconds)-int((1/13)*seconds) print("Estimated population:", population)