text
stringlengths
37
1.41M
import unittest from app.office import Office from app.room import Room class Test_class_Office(unittest.TestCase): def test_office_is_subclass_of_Room(self): self.assertTrue(issubclass(Office, Room), msg='Office is not a subclass of Room') def test_office(self): office = Office('room_name', 'room_type') self.assertTrue(isinstance(office, Office), msg='office is not an instance of the Office class') if __name__ == '__main__': unittest.main()
import unittest from app.staff import Staff from app.person import Person class Test_class_Staff(unittest.TestCase): def test_staff_is_subclass_of_Person(self): self.assertTrue(issubclass(Staff, Person), msg='Staff is not a subclass of Person') def test_staff_is_instance_of_class_Staff(self): staff = Staff('name', 'position') self.assertTrue(isinstance(staff, Staff), msg='staff is not an instance of the Staff class') if __name__ == '__main__': unittest.main()
def factorielle(n): """retourne la factorielle de n. """ res=1 for i in range (1,n+1): ## Ici res contient (i-1)! res*= i ## Ici res contient i! return res def estPremier(n): res = True for k in range (1,n): ## Ici, res est vrai ssi les éléments dans [[2,k[[ ne divise pas n if n%k==0: res = False ## Ici, res est vrai ssi les éléments dans [[2,k+1[[ ne divise pas n ## Sortie de Boucle : res est vrai ssi les éléments dans [[2,n[[ ne divise pas n (def de nombre premier) return res def appartient(x,t): res = False for i in range(0,len(t)): ## Ici, res est faux ssi x n'appartient pas à t[0:i] if t[i]==x: res = True ## Ici, res est faux ssi x n'appartient pas à t[0:i+1] ## res est vrai ssi x appartient à t[0:i+1] ## Sortie de Boucle : res est faux ssi x n'appartient pas à t[0:n] ## res est vrai ssi x apartient à t[0:n] return res #print(appartient(3,[1,2,0,4,5])) def sansZero(t): nt = [] for i in range (0,len(t)): ## Ici if t[i]!=0: nt.append(t[i]) ### return nt ##### Faire exo 3
# Recherche d'une chaine dans une autre ## entrée m et t deux chaines str #Sortie : Bool si m appartient ou non à t def estPresentPlacei(m,t,i): res = True for j in range (0,len(m)): if t[i+j]==m[j]: None else: res = False return res def estPresent(m,t): res = False for i in range (0,len(t)-len(m)): if estPresentPlacei(m,t,i): res= True return res #print(estPresent("ont","bonjour")) def forQuiPlante(): """info help""" aparcourir = [1,2,3] for i in aparcourir: aparcourir.append(12) return "FIN" #print(forQuiPlante()) def puissance(x,n): res = 1 for i in range (0,n): ## res contient x**(i) res *= x ## res contient x**(i+1) return res #print(puissance(2,2)) def estTrié(t): res=True for i in range(1,len(t)): ### Ici res est vrai ssi t[0:i] est trié if t[i-1] > t[i]: res = False return res #print(estTrié([0,1,5,3,4,5])) def plusPetitDiviseur(n): """ Entrée : n entier > 1 Sortie : Le plus petit diviseur de n qui soit > 1 """ d=2 while n%d != 0: # ici, n n'est pas divisible par les éléments de [[2,d]]. d+=1 # ici, n n'est pas divisible par les éléments de [[2,d-1]]. return d print(plusPetitDiviseur(21))
def f(a,b): x = 0 y = a ## Ici, a= b*x +y while y>=b: ## Ici, a= b*x +y x+=1 y-=b ## Ici, a= b*x +y count+=1 return (x,y) def fLisible(a,b): """ Entrée : -a,b entiers Sortie : -couple (quotient,reste) ## OU (a//b , a%b) Effet : -Division euclidienne de a par b """ quotient = 0 reste = a if b<0: while abs(reste) <= b : quotient-=1 reste += b else: while abs(reste) >= b: quotient+=1 reste-=b return (quotient,reste) def fUltime(a,b): return (a//b, a%b) print(fLisible(35,-3)) print(fUltime(35,-3)) """ ## 1) 2,1 => 2,0 15,5 => 3,0 15,6 => 2,3 a = b*x + y dividende = diviseur*quotient +reste ## 4) Pour que l'algorithme termine, il faut que b =/= 0 ## 5) Soit b =/= 0, La quantité reste-b est : - Positive - Décroissante - Entière ## 7) Pour tout k € |N*, notons x(k) la valeur de x au rang k et y(k) la valeur de y au rang k. Pour tout k € |N*, Notons P(k) : "a = b*x(k) +y(k)". Montrons par récurrence sur k P(k). Init : Mq a = b*0+y(0). On a y(0) = a donc b*0+y(0)=a. P(0) est alors vraie. Hérédité : Soit k tq P(k) Montrons P(k+1): "a = b*x(k+1)+y(k+1)" b*(k+1)+y(k+1) = b*k + b + y(k)-b = b*k + y(k) = a ## Par hypothèse de récurrence Alors P(k+1). Conclusion : Pour tout k € |N*,P(k). Cette fonction renvoie donc bien le bon résultat. ## 8) La boucle s'éxécute a//b """
import os vendas = {} compras = {} def header(word="Gerenciador de Veiculos"): print("="*15) print(word) print("="*15) def menu(): # list with all the options from the menu options = { 1: "Comprar Veiculos", 2: "Listar Veiculos", 3: "Atualizar Veiculos", 4: "Vender Veiculos", 5: "Listar Compras", 6: "Listar Vendas", 0: "Sair"} header() for option in options: print("{}: {} ".format(option, options[option])) def addVeiculo(veiculos): header("Comprar Veiculo") try: nome = input("Digite o nome do Veiculo: ") qtd = int(input("Digite a quantidade de Veiculos: ")) ano = int(input("Digite o ano do Veiculo: ")) preco = float(input("Digite o preco do Veiculo: ")) if qtd <= 0 or ano <= 0 or preco <= 0: print("Valor invalida") if nome in veiculos: quant = veiculos[nome][0] - qtd veiculos[nome] = [ quant, ano, preco] quant = compras[nome][0] + qtd compras[nome] = [ qtd, ano, preco] else: veiculos[nome] = [ qtd, ano, preco] compras[nome] = [ qtd, ano, preco] except ValueError: print("Apenas numeros inteiros sao validos no numero.") print("Veiculo Adicionado") return veiculos def listVeiculo(veiculos, title="Listar Veiculo"): header(title) if len(veiculos) == 0 and title == "Listar Veiculo": print("Nenhum Veiculo previamente adicionado") for key in veiculos: msg = " " for el in veiculos[key]: msg += "{}, ".format(el) print("{}: {}".format(key, msg[:-2])) def atualizarVeiculo(veiculos): listVeiculo(veiculos) header("Atualizar Veiculo") if len(veiculos) == 0: print("Nenhum Veiculo previamente adicionado") return veiculos try: nome = input("Digite o nome de Veiculo para atualizar: ") if nome in veiculos: qtd = int(input("Digite a quantidade de Veiculos: ")) ano = int(input("Digite o ano do Veiculo: ")) preco = float(input("Digite o preco do Veiculo: ")) veiculos[nome] = [ qtd, ano, preco] return veiculos else: print("Veiculo nao existe.") return veiculos except ValueError: print("Insira um valor valido.") return veiculos def deleteVeiculo(veiculos): listVeiculo(veiculos) header("Vender Veiculo") if len(veiculos) == 0: print("Nenhum Veiculo previamente adicionado") return veiculos try: nome = input("Digite o nome de Veiculo para vender: ") if nome in veiculos: qtd = int(input("Digite a quantidade a vender: ")) if qtd <= 0: print("Quantidade invalida") elif qtd > veiculos[nome][0]: print("Quantidade superior a em estoque") return veiculos if nome in vendas.keys(): print("Had") vendas[nome][0] = vendas[nome][0] + qtd else: print("didn Have") vendas[nome] = veiculos[nome] vendas[nome][0] = qtd veiculos[nome][0] = veiculos[nome][0] - qtd print("Veiculo Vendido") else: print("Veiculo nao existe.") except ValueError: print("Insira um Veiculo valido") return veiculos def main(): veiculos= { "gol": [20, 2019, 28.900], "onix": [30, 2019, 27.800], "sandeiro": [22, 2016, 15.700], "hb20": [3, 2020, 38.500], "siena": [4, 2016, 18.200], "prima": [17, 2015, 14.300], "voyage": [20, 2020, 38.100], "uno": [12, 2019, 28.400] } aux_veiculos = {} while(True): menu() opcao = 0 try: opcao = int(input("Digite o opcao no gerenciador de veiculos: ")) except ValueError: print("Apenas as opcoes listadas sao validas.") if(opcao == 1): veiculos = addVeiculo(veiculos) elif opcao == 2: listVeiculo(veiculos) elif opcao == 3: veiculos = atualizarVeiculo(veiculos) elif opcao == 4: veiculos = deleteVeiculo(veiculos) elif opcao == 5: listVeiculo(compras, "Compras") elif opcao == 6: listVeiculo(vendas, "Vendas") elif opcao == 0: print("Saindo...") exit(0) else: print("Opcao invalida.") main()
nome = input("Digite seu nome: ") qtd_char = len(nome) if qtd_char <= 0: print("{} seu nome é nulo e invalido".format(nome)) elif qtd_char <= 4: print("{} seu nome é curto".format(nome)) elif qtd_char <= 6: print("{} seu nome é normal".format(nome)) else: print("{} seu nome é muito grande".format(nome))
def main(): while True: print(("=" * 6) + (" Menu ") + ("=" * 6)) print("1 - Continuar") print("0 - Sair") try: option = int(input("Digite a opcao: ")) except: print("Digite um valor inteiro.") if option < 0 or option > 1: print("Invalid option.") elif option == 0: break; elif option == 1: calculo = input("Digite o calculo: ") manager(calculo) def soma(a, b): try: print("Result {}".format(a + b)) except: print("Could not execute the soma") def subtracao(a, b): try: print("Result {}".format(a - b)) except: print("Could not execute the subtracao") def divisao(a, b): try: print("Result {}".format(a / b)) except: print("Could not execute the divisao") def multiplicacao(a, b): try: print("Result {}".format(a * b)) except: print("Could not execute the multiplicacao") def manager(conta): final = 0; if "+" in conta: valor = conta.split("+") num1 = int(valor[0]) num2 = int(valor[1]) soma(num1, num2) if "-" in conta: valor = conta.split("-") num1 = int(valor[0]) num2 = int(valor[1]) subtracao(num1, num2) if "/" in conta: valor = conta.split("/") num1 = int(valor[0]) num2 = int(valor[1]) divisao(num1, num2) if "*" in conta: valor = conta.split("*") num1 = int(valor[0]) num2 = int(valor[1]) multiplicacao(num1, num2) main()
def saudacao(nome, sobrenome): print("Hi, {} {}!".format(nome, sobrenome)) def main(): nome = input("Digite seu primeiro nome: ") sobrenome = input("Digite seu sobrenome: ") saudacao(nome, sobrenome) main()
L_total = [9, 5, 6, 4, 8, 12, 11, 15, 0, 1, 3, 2] L_par = [] L_impar = [] for number in L_total: if (number % 2) == 0: L_par.append(number) else: L_impar.append(number) print("Lista impar: {}".format(L_impar)) print("Lista par: {}".format(L_par))
# Napisati program kojim se ilustruje upotreba struktura podataka: # stek, skup, mapa, torke. # Skup imena = set() for ime in ['Milan', 'Jovan', 'Marko', 'Milos', 'Lazar', 'Marko']: imena.add(ime) print(imena) print(set(['Milan', 'Jovan', 'Marko', 'Milos', 'Lazar', 'Marko'])) # Stek stek = [] stek.append(1) stek.append(2) stek.append(3) print("Stek: ", stek) print("Elementi pop(): ") print(stek.pop()) print(stek.pop()) print(stek.pop()) # Mape prosek = {'Milan' : 9.45, 'Ana' : 9.87, 'Nikola' : 8.42} print(prosek, type(prosek)) print(prosek.keys()) print(prosek.values()) print('Milan' in prosek) print('Milos' in prosek) # Torke voce = ('apple', 'orange', 'banana', 'pear', 'kiwi') print(voce) print(voce[2:4]) try: voce[0] = 5 except TypeError: print("Tuple objekti su imutabilni!")
# Napisati program koji racuna odnos kardinalnosti skupova duze i sire za # zadati direktorijum. Datoteka pripada skupu duze ukoliko ima vise redova # od maksimalnog broja karaktera po redu, u suprotnom pripada skupu sire. # Sa standardnog ulaza se unosi putanja do direktorijuma. Potrebno je obici # sve datoteke u zadatom direktorijumu i njegovim poddirektorijumima # (koristiti funkciju os.walk()) i ispisati odnos kardinalnosti skupova # duze i sire. import os def obilazak(ime): brLinija = 0 najduza = 0 with open(ime, 'r') as f: for linija in f: brLinija += 1 if len(linija) > najduza: najduza = len(linija) if brLinija > najduza: return 1 else: return 0 putanja = input("Unesite putanju do direktorijuma: ") sire = 0 duze = 0 for (trendir, poddir, datoteke) in os.walk(putanja): for dat in datoteke: if obilazak(os.path.join(trendir, dat)) == 0: sire += 1 else: duze += 1 print("Duze: {}".format(duze)) print("Sire: {}".format(sire))
# Napisati program koji imitira rad bafera. Maksimalan broj elemenata # u baferu je 5. Korisnik sa standardnog ulaza unosi podatke do unosa # reci quit. Program ih smesta u bafer, posto se bafer napuni unosi se # ispisuju na standardni izlaz i bafer se prazni. buffer = [] i = 0 while True: unos = input() if unos == 'quit': break buffer.append(unos) i += 1 if i == 5: for unos in buffer: print(unos) buffer = [] i = 0
# Dati su novcici od 1, 2, 5, 10, 20 dinara. Napisati program koji # pronalazi sve moguce kombinacije tako da zbir svih novcica bude 50. # Sve rezultate ispisati na standardni izlaz koristeci datu komandu ispisa. import constraint problem = constraint.Problem() problem.addVariable("1 din", range(0, 51)) problem.addVariable("2 din", range(0, 26)) problem.addVariable("5 din", range(0, 11)) problem.addVariable("10 din", range(0, 6)) problem.addVariable("20 din", range(0, 3)) problem.addConstraint(constraint.ExactSumConstraint(50, [1, 2, 5, 10, 20]), ["1 din", "2 din", "5 din", "10 din", "20 din"]) resenje = problem.getSolutions() for r in resenje: print("-----------------") print("""1 din: {0:d}\n2 din: {1:d}\n5 din: {2:d}\n10 din: {3:d}\n20 din: {4:d}""".format(r["1 din"], r["2 din"], r["5 din"], r["10 din"], r["20 din"]))
# Napisati program koji sa standardnog ulaza ucitava # dva broja i na standardni izlaz ispisuje njihov zbir. a = int(input("Uneti prvi broj: ")) b = int(input("Uneti drugi broj: ")) suma = lambda a,b: a + b print("Suma: {}".format(suma(a, b)))
# Program implementira automat za prepoznavanje # ulaza sa parnim brojem 0. Prelasci se odredjuju # naredbama granjanja. import sys stanje = 'P' zavrsno = 'P' prelazi = { 'P':{'0':'N', '1':'P'}, 'N':{'0':'P', '1':'N'} } while True: try: c = input('Unesite 0 ili 1:') if(c != '0' and c != '1'): raise ValueError('Nije uneta ni 0 ni 1') except EOFError: break except ValueError as e: print(e) exit() stanje = prelazi[stanje][c] if stanje == zavrsno: print('Ima paran broj 0.') else: print('Ima neparan broj 0.')
# Sa standardnog ulaza se unose reci do reci quit. Napisati # program koji ispisuje unete reci eliminisuci duplikate. lista = [] while True: unos = input() if unos == 'quit': break lista.append(unos) skup = set(lista) print(skup)
import json import os from typing import Dict, List current_dir = os.path.dirname(__file__) data_path = 'data.json' abs_path = os.path.join(current_dir, data_path) def read_data() -> List[Dict]: """ Get all data from data.json file. Reads all data from the json file and returns a list containing all data. """ with open(abs_path, 'r') as file: json_text = file.read() data = json.loads(json_text) return data
""" Вариант 2, задача 2 Создать класс Fraction, который должен иметь два поля: числитель a и знаменатель b. Оба поля должны быть типа int. Реализовать методы: сокращение дробей, сравнение, сложение и умножение. Данная программа может выполнять операции непосредственно с дробями, например a,b,c - дроби, тогда: c = a + b, c = a * b, c.reduce(), операции сравнения: a < b, a > b, a == b, a != b, a <= b, a >= b. Для демонстрации работы с более двумя дробями реализована функция интерфейс, функция сравнения выводит результаты после сравнения по всем шести операциям сравнения """ class Fraction: def __init__(self, numerator, denominator): self.a = numerator self.b = denominator # НОЗ или нок, находит общий знаменатель def _nok(self, number1, number2): result_number = 0 if number1 >= 0 and number2 >= 0: result_number = int(number1 * number2 / self._nod(number1,number2)) elif number1 < 0: number1 = number1 * -1 return self._nok(number1,number2) else: number2 = number2 * -1 return self._nok(number1,number2) return result_number # нод по алгоритму Евклида def _nod(self, number1, number2): if number2 == 0: return int(number1) else: return self._nod(number2, number1 % number2) # приведение к наименьшему общему знаменателю def _make_common_denominator(self, fraction): nok = self._nok(self.b, fraction.b) multiplyer_1 = int(nok / self.b) multiplyer_2 = int(nok / fraction.b) self.a = self.a * multiplyer_1 self.b = self.b * multiplyer_1 fraction.a = fraction.a * multiplyer_2 fraction.b = fraction.b * multiplyer_2 # сокращение двух чисел def _reduce(self, numerator, denominator): nod = self._nod(numerator,denominator) res_numerator = int(numerator/nod) res_denominator = int(denominator/nod) return res_numerator, res_denominator # сокращение дроби def reduce(self): nod = self._nod(self.a,self.b) self.a = int(self.a/nod) self.b = int(self.b/nod) return self # сложение def __add__(self, fraction): #проверка на ноль if self.a == 0 and fraction.a != 0: res_numerator = fraction.a res_denominator = fraction.b res_number = Fraction(res_numerator, res_denominator) elif self.a != 0 and fraction.a == 0: res_numerator = self.a res_denominator = self.b res_number = Fraction(res_numerator, res_denominator) elif self.a == 0 and fraction.a == 0: res_numerator = 0 res_denominator = 1 # в результате должен получиться ноль. Запишу так, чтобы можно было выполнять поттом операции с числом ноль res_number = Fraction(res_numerator, res_denominator) # два числа с одинаковым заменателем elif self.b == fraction.b: res_numerator = self.a + fraction.a res_denominator = self.b res_number = Fraction(res_numerator, res_denominator) # числа с разными знаменателями else: self._make_common_denominator(fraction) res_numerator = self.a + fraction.a res_denominator = self.b # сократить res_numerator, res_denominator = self._reduce(res_numerator,res_denominator) res_number = Fraction(res_numerator, res_denominator) return res_number # операции сравнения: # x<y def __lt__(self, fraction): if self.b == fraction.b: return self.a < fraction.a else: self._make_common_denominator(fraction) result = (self.a < fraction.a) self.a, self.b = self._reduce(self.a, self.b) fraction.a, fraction.b = self._reduce(fraction.a, fraction.b) return result # x<=y def __le__(self, fraction): if self.b == fraction.b: return self.a <= fraction.a else: self._make_common_denominator(fraction) result = (self.a <= fraction.a) self.a, self.b = self._reduce(self.a, self.b) fraction.a, fraction.b = self._reduce(fraction.a, fraction.b) return result # x == y def __eq__(self, fraction): if self.b == fraction.b: return self.a is fraction.a else: self._make_common_denominator(fraction) return self.a is fraction.a result = (self.a is fraction.a) self.a, self.b = self._reduce(self.a, self.b) fraction.a, fraction.b = self._reduce(fraction.a, fraction.b) return result # x != y def __ne__(self, fraction): if self.b == fraction.b: return self.a is not fraction.a else: self._make_common_denominator(fraction) result = (self.a is not fraction.a) self.a, self.b = self._reduce(self.a, self.b) fraction.a, fraction.b = self._reduce(fraction.a, fraction.b) return result # x>y def __gt__(self, fraction): if self.b == fraction.b: return self.a > fraction.a else: self._make_common_denominator(fraction) result = (self.a > fraction.a) self.a, self.b = self._reduce(self.a, self.b) fraction.a, fraction.b = self._reduce(fraction.a, fraction.b) return result # x>= y def __ge__(self, fraction): if self.b == fraction.b: return self.a >= fraction.a else: self._make_common_denominator(fraction) result = (self.a >= fraction.a) self.a, self.b = self._reduce(self.a, self.b) fraction.a, fraction.b = self._reduce(fraction.a, fraction.b) return result # умножение дробей def __mul__(self, fraction): res_numerator = self.a * fraction.a res_denominator = self.b * fraction.b res_numerator, res_denominator = self._reduce(res_numerator, res_denominator) res_number = Fraction(res_numerator, res_denominator) return res_number # сравнение по всем операциям def compare(self, fraction): if self.__lt__(fraction): print("Первая дробь меньше второго.\n") if self.__le__(fraction): print("Первая дробь меньше или равна второй.\n") if self.__eq__(fraction): print("Первая дробь равна второй.\n") if self.__ne__(fraction): print("Первая дробь не равна второй.\n") if self.__gt__(fraction): print("Первая дробь больше второй.\n") if self.__ge__(fraction): print("Первая дробь больше или равна второй.\n") #функция введения нескольких дробей def enter_fractions(): lst = [] while 1: select = str(input("Ввести число? Введите да - y, нет - n.\n")) if select == 'y': fraction = enter_fraction() lst.append(fraction) elif select == 'n': break else: print("Нет такой команды. Попробуйте ввести ещё раз.\n") return lst # функция введения одной дроби def enter_fraction(): try: numerator = int(input("Введите числитель:\n")) denominator = int(input("Введите знаменатель:\n")) # Число является нулём, когда числитель равен нулю, а знаменатель не равен нулю if denominator != 0: enter_number = Fraction(numerator, denominator) return enter_number else: print("Знаменатель не должен быть равен нулю, на ноль делить нельзя.\n") return enter_fraction() except ValueError: print("Неверный ввод. Числитель и знаменатель должны быть целыми числами.\n") return enter_fraction() #интерфейс для ввода def input_interface(): print("Какие операции над дробями вы хотите произвести?\n" "1 - сложить дроби,\n" "2 - перемножить дроби,\n" "3 - сократить дробь,\n" "4 - сравнить две дроби,\n" "0 - выход из программы.\n") try: select = int(input()) except ValueError: print("Введенное значение должно быть числом от 0 до 4. Введите ещё раз. \n") return input_interface() # сложение if select == 1: # sum так запишем дробь, равную нулю, т.к. в знаменателе не может быть 0 result = Fraction(0, 1) fractions = enter_fractions() if not fractions: while not fractions: fractions = enter_fractions() for fraction in fractions: result = result + fraction result.reduce() if result.a == 0: print("sum = 0.\n") else: print("sum = ", result.a, "/", result.b, "\n") return result # произведение elif select == 2: result = Fraction(1,1) fractions = enter_fractions() if not fractions: while not fractions: fractions = enter_fractions() for fraction in fractions: result = result * fraction result.reduce() if result.a == 0: print("mul = 0.\n") else: print("mul = ", result.a, "/", result.b, "\n") return result # сокращение elif select == 3: result = enter_fraction() result.reduce() if result.a == 0: print("reduce = 0.\n") else: print("reduce = ", result.a, "/", result.b, "\n") return result # cравнение elif select == 4: first_fraction = enter_fraction() second_fraction = enter_fraction() first_fraction.compare(second_fraction) # выход elif select == 0: exit() else: print("Нет такого пункта меню. Введите число от 0 до 4.\n") return input_interface() def main(): input_interface() if __name__ == "__main__": main()
import turtle turtle.shape("turtle") ''' #노가다 turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) #좀 편함 for i in range(4): turtle.forward(100) turtle.right(90) #더 편함 def drawRec(size): for i in range(4): turtle.forward(size) turtle.right(90) ''' #ㄹㅇ 개편함 def drawSomething(size,angle): for i in range(angle): turtle.forward(size) turtle.right(360/angle) drawSomething(100, 5) drawSomething(200, 6) drawSomething(10, 100)
#Sumar los O primeros numeros import os #Declaracion de variables c=0 suma=0 z=int(os.sys.argv[1]) while(c<=z): print(c) suma += c c += 1 #fin_iteracion print("La suma de los O primeros numeros es:", suma) print("Fin del bucle")
#Sumar los Q primeros numeros import os #Declaracion de variables e=0 suma=0 v=int(os.sys.argv[1]) while(e<=v): print(e) suma += e e += 1 #fin_iteracion print("La suma de los Q primeros numeros es:", suma) print("Fin del bucle")
#Sumar los M primeros numeros import os #Declaracion de variables a=0 suma=0 x=int(os.sys.argv[1]) while(a<=x): print(a) suma += a a += 1 #fin_iteracion print("La suma de los M primeros numeros es:", suma) print("Fin del bucle")
def validator(*args): """ Checks if user input is an integer. Parameters: *args (String) : "+" Checks for positive integers; "-" Checks for negative integers; "" Checks for any integers; """ while True: try: user_input = int(input()) except ValueError: print("Please input a number!") else: if user_input < 0 and args[0] == '+': print("Please input a positive number!") pass elif user_input > 0 and args[0] == '-': print("Please input a negative number!") pass else: break return user_input
#Receta 4: Obtener una Cantidad Arbitraria de Elementos Mínimos y Máximos import heapq numeros = [7, 9, 1, 3, 5, 8, 7, 6, 2, 3, 1, 0, -8, -9, 5, -2] print(heapq.nsmallest(3,numeros)) print(heapq.nlargest(3,numeros)) print() productos = [ { 'nombre': 'Mouse', 'precio': 35 }, { 'nombre': 'Teclado', 'precio': 59 }, { 'nombre': 'Monitor', 'precio': 279 }, { 'nombre': 'Parlantes', 'precio': 120 }, { 'nombre': 'Smartphone', 'precio': 455 } ] mas_barato = heapq.nsmallest(2,productos,key=lambda p:['precio']) resultado = 'El Producto mas Barato es: {0}' print (resultado.format(mas_barato)) print() resultado = 'El Producto mas Caro es: {0}' mas_caro = heapq.nlargest(2,productos,key=lambda p: p['precio']) print(resultado.format(mas_caro))
import calendar print(calendar.weekheader(3)) print(calendar.firstweekday()) print(calendar.month(2020,11)) print(calendar.monthcalendar(2020,11)) print(calendar.calendar(2020)) dayOfTheWeek= calendar.weekday(2020,11,6) print(dayOfTheWeek) isLeapYear= calendar.isleap(2020) print(isLeapYear) howManyLeapDays= calendar.leapdays(2000, 2005) print(howManyLeapDays)
# The factorial of a positive integer n is defined as the product of the # sequence , n-1, n-2, ...1 and the factorial of 0 is defined as being 1. Solve # this using both loops and recursion. # # https://github.com/karan/Projects-Solutions/blob/master/README.md # # Lacey Sanchez # Recursion def find_factorial_rec(n): if n == 0: return 1 return n * find_factorial_rec(n - 1) # Loops def find_factorial_loop(n): ''' ''' if n == 0: return 1 elif n >= 1 and type(n) == int: factorial = 1 for i in range(1, n + 1): factorial *= i return factorial
from cs50 import SQL import sys # Wrong Usage Check if (len(sys.argv) != 2): print("Usage: python roster.py house") exit() db = SQL("sqlite:///students.db") # Execute the sqlit command to get a list and store it in memory. data = db.execute("SELECT first,middle,last,birth FROM students WHERE house = ? ORDER BY last,first;", sys.argv[1]) # Print the names and the date of birth for rows in data: first = rows['first'] middle = rows['middle'] last = rows['last'] birth = rows['birth'] if middle == None: middle = "" else: middle = middle+" " print(f"{first} {middle}{last}, born {birth}")
print('*'*30) marks = int(input('enter marks\t')) if marks >=70: print('you made it-you passed') if marks >=90: if marks == 100: print("distinction") elif marks >=98 or marks ==99: print('A++') elif marks >=95 <=97: print('print A-') elif marks >=91 <=94: print('A--') elif marks >=90: print('A grade') if marks >80 <=89: if marks >=86 <=89: print('good,step it up') elif marks >80 <=85: print('there is scope for improvemnt') elif marks ==80: print('try harder') else: print('sorry- u failed') print( 'dont be disheartened-failureis the stepping stone to success')
# An adventure game import time def room1(): global health print(" You arrive at your friends house after a long trip.") print(""" 'I'll pick you up at 8 tommorow morning' your mother shouted as she watched you head up the drive""") print(" 1: Wave goodbye") print(" 2: Ignore") direction = input("option: ") if direction.lower() == "1": print(""" You wave back and watch her drive off down the street then you walk up to huge door of your friends house""") part2_room1() if direction.lower() == "2": print(""" You ignore her and walk up to the huge door. You give a quick glance behind you to see that she is not very happy with you ignoring her, she drives off with the same expression.""") part2_room1() def part2_room1(): global time print(""" You feel a bit intimidated by the huge door and have to stand there for a second""") print(" 1: Knock on the door") print(" 2: Wait") direction = input("option: ") if direction.lower() == "1": print(""" You are greeted by your friend John""") part3_room1() if direction.lower() == "2": print(""" You wait outside the whole night in the cold and dark. You get picked up the next day. You didnt progress the story at all. GAME OVER!""") time.sleep(2) quit() def part3_room1(): print(""" John has been your best friend for as long as you can remember. You had done everything together from playing video games to going to school together.""") print(" 'Hay. You tuck sometime to get here, you ok?' John said in unusual happy manner") print(" 1: Yeah it was just the traffic. You know this city") print(" 2: You seem happy today do you.") direction = input("option: ") if direction.lower() == "1": print(""" 'Yeah, I guess your right. Come in' You step into the house and look around. The rooms of the house are huge, with enough space to fit a truck in.""") if direction.lower() == "2" print(""" He looked at you, now with a surprised look on his face. 'What a guy can't be happy when his friend comes to sleep over? Never mind just come inside' You step into the house and look around. The rooms of the house are huge, with enough space to fit a truck in.""") def part4_room1(): print(""" You sat down in the living room while John goes upstairs to get his nintendo console # Leave this at the bottom - it makes room1 run automatically when you # run your code. if __name__ == "__main__": room1()
#!/usr/bin/env python import re import sys from pyspark import SparkContext def main(): if len(sys.argv) != 2: sys.stderr.write('Usage: {} <search_term>'.format(sys.argv[0])) sys.exit() # Create the SparkContext sc = SparkContext(appName='SparkWordSearch') # Broadcast the requested term requested_movie = sc.broadcast(sys.argv[1]) # Load the input file source_file = sc.textFile('/user/guan/movies.csv') # Get the movie title from the second fields titles = source_file.map(lambda line: line.split(',')[1]) # Create a map of the normalized title to the raw title normalized_title = titles.map(lambda title: (re.sub(r'\s*\(\d{4}\)', '', title).lower(), title)) # Find all movies matching the requested_movie matches = normalized_title.filter(lambda x: requested_movie.value in x[0]) # Collect all the matching titles matching_titles = matches.map(lambda x: x[1]).distinct().collect() # Display the result print '{} Matching titles found:'.format(len(matching_titles)) for title in matching_titles: print title sc.stop() if __name__ == '__main__': main()
#!/usr/bin/env python # coding: utf-8 # **The Sparks Foundation** # **Data Science and Business Analytics Internship** # **Task-2 :Prediction using UnSupervised ML** # # **TASK :From the given ‘Iris’ dataset, predict the optimum number of clusters # and represent it visually** # **By-Priyanka Mohanta** # In[1]: # Importing the libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # In[2]: # Load the iris dataset data=pd.read_csv(r"C:\Users\kabya\Downloads\Iris.csv") # In[3]: #rename the iris dataset columns name data.columns=['ID','SL','SW','PL','PW','Species'] # In[4]: #check the dataset data # In[5]: #check the shape of the dataset data.shape # In[6]: data.info() # In[7]: #summery statistics for numerical columns data.describe() # In[8]: #check the first 5 rows data.head() # In[9]: #check the last 5 rows data.tail() # In[10]: #check the null value of this dataset data.isnull().sum() # In[11]: #Pearson's Correlation cor=data.corr() plt.figure(figsize=(10,5)) sns.heatmap(cor,annot=True,cmap='coolwarm') plt.show() # In[12]: ip=data.drop(['Species'],axis=1) from sklearn import cluster km=cluster.KMeans(n_clusters=3) km.fit(ip) k=km.predict(ip) print(k) data['predict']=k plt.figure(figsize=(12,5)) plt.scatter(data.SL,data.PL) plt.show() # In[14]: #centroid plt.figure(figsize=(12,5)) plt.scatter(data.SL,data.PL,c=k,s=50,cmap='viridis') plt.show() centroid=km.cluster_centers_ print(centroid) # In[15]: #find the optimum number of clusters for K Means x = ip.iloc[:, [0, 1, 2, 3]].values from sklearn.cluster import KMeans wcss = [] for i in range(1, 11): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) kmeans.fit(x) wcss.append(kmeans.inertia_) # In[16]: #visualization graph by using elbow method plt.plot(range(1, 11),wcss,marker='o',color='g') plt.title('The elbow method') plt.xlabel('Number of clusters') plt.ylabel('WCSS') # Within cluster sum of squares plt.show() # From this we choose the number of clusters as 3 # In[17]: # Applying kmeans clustering to the dataset kmeans = KMeans(n_clusters = 3,max_iter = 300, n_init = 10, random_state = 0) y_kmeans = kmeans.fit_predict(x) # In[19]: # Visualising the clusters plt.scatter(x[y_kmeans == 0, 0], x[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Iris-setosa') plt.scatter(x[y_kmeans == 1, 0], x[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Iris-versicolour') plt.scatter(x[y_kmeans == 2, 0], x[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Iris-virginica') # Plotting the centroids of the clusters plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:,1], s = 100, c = 'yellow', label = 'Centroids') plt.legend() plt.show() # **data_set_of_make_blobs** # In[20]: from sklearn.datasets.samples_generator import make_blobs X,y=make_blobs(n_samples=300,centers=4,cluster_std=0.6,random_state=0) data=pd.DataFrame(X,y) plt.scatter(X[:,0],X[:,1],s=50) plt.show() # In[21]: from sklearn import cluster km=cluster.KMeans(n_clusters=4) km.fit(X) yp=km.predict(X) data['predict']=yp plt.scatter(X[:,0],X[:,1],c=yp,s=50,cmap='viridis') plt.scatter(centroid[:,0],centroid[:,1],c='black',s=200) plt.show() centroid=km.cluster_centers_ print(centroid) # **THANK YOU** # In[ ]:
class Node: def __init__(self, value=None, next_node=None): self.value = value self.next = next_node class LinkedList: def __init__(self): self.head = None def add_to_head(self, value): self.head = Node(value, self.head) def remove(self, value): ''' Find and remove the node with the given value ''' if not self.head: print("Error: Value not found") elif self.head.value == value: # Remove head value self.head = self.head.next else: parent = self.head current = self.head.next while current: if current.value == value: # Remove value parent.next = current.next return current = current.next print("Error: Value not found") def contains(self, value): if not self.head: return False current = self.head while current: if current.value == value: return True current = current.next return False def print(self): current = self.head ll_str = "" while current: ll_str += f"{current.value}" current = current.next ll_str += " -> " ll_str += "None" print(ll_str) ll = LinkedList() ll.print() ll.add_to_head(1) ll.add_to_head(2) ll.add_to_head(3) ll.print() ll.remove(2) ll.print()
mes = int( input("Ingrese el mes de su elección [1-12]: ") ) estacion = None if (mes >= 1 and mes <= 2) or mes == 12: estacion = "Invierno" elif mes >= 3 and mes <= 5: estacion = "Primavera" elif mes >= 6 and mes <= 8: estacion = "Verano" elif mes >= 9 and mes <= 11: estacion = "Otoño" else: estacion = "Mes fuera de rango" print( "Estación:", estacion, "para el mes", mes)
print("Proporcione los siguientes datos del libro:") nombre = input("Proporcione el nombre del libro: ") id = int( input("Poporcione el ID:") ) precio = float( input("Proporcione el precio: $") ) envioGratuito = input("Indica si el envio es gratuito (True/False): ") if envioGratuito == "True": envioGratuito = True elif envioGratuito == "False": envioGratuito = False else: print("Ingresaste un valor invalido para el envio gratuito") envioGratuito = "Valor incorrecto, debe ser True/False" print(" ---> Datos del Libro <---") print("Nombre:", nombre) print("ID:", id) print("Precio:", precio) print("¿Tiene envio gratis?", envioGratuito)
# Clases # Sintaxis básica class Persona: # Constructor de la clase def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad # Crear un objeto, nueva instancia de la clase persona = Persona("Alejandra", 26) print(persona.nombre) print(persona.edad) print ("Tu nombre es {0} y tienes {1} años.".format(persona.nombre, persona.edad))
class Persona: def __init__(self, nombre): self.__nombre = nombre # Método sobreescrito de la clase padre object def __add__(self, otro): return self.__nombre + " " + otro.__nombre def __sub__(self, otro): return "Operación no soportada" p1 = Persona("Alex") p2 = Persona("Matty") # Nueva forma de trabajar el operador + print(p1 + p2) print(p1 - p2) # + es un ejemplo de sobrecarga # a = 2 # b = 3 # print(a + b) # st1 = "Hola " # st2 = "Mundo" # print(st1 + st2) # list1 = [1, 2] # list2 = [4, 5] # print( list1 + list2 )
from figura_geometrica import FiguraGeometrica from color import Color class Rectangulo(FiguraGeometrica, Color): def __init__(self, ancho, alto, color): FiguraGeometrica.__init__(self, ancho, alto) Color.__init__(self, color) def area(self): return self.get_alto() * self.get_ancho() def __str__(self): return super().__str__() + " y el color es " + self.get_color() + "." rectangulo = Rectangulo(5, 10, "Verde") print(rectangulo.area()) print(rectangulo.__str__())
##### # Tested on Windows 7 32-bit # With Python version 3.1.2 ##### for num in range(1, 101): # This builds a range of numbers # from 1 to 100 (because a range is not inclusive) if num % 3 == 0 and num % 5 == 0: # Checks to see if the number divides into both 3 and 5 with no remainder # Notice that it checks this first. That is important! print("FizzBuzz") elif num % 3 == 0: # Checks if the number divides into 3 with no remainder print("Fizz") elif num % 5 == 0: # Checks if the number divides into 5 with no remainder print("Buzz") else: # Nothing else matches so we just print the number print(num)
start = 10 end = 20 startc = 30 endd = 40 num= 22 test = (start<num<end) or (startc<num<endd) print(test) num2 = 11 test2 = (start<num2<end) or (startc<num2<endd) print(tes
def temperature(temp): print('What is the temperature in celsius?') temp = input() fahrenheit = int(temp) * 9/5 +32 return fahrenheit final = temperature('temp') print((f'The temperature is {final} in fahrenheit!'))
def factorial(number , accumulator=1): if number == 1: return accumulator return factorial(number - 1, number*accumulator) print(factorial(5))
import random def get_integer(prompt): while True: temp = input(prompt) if temp.isnumeric(): return int(temp) highest = 10 answer = random.randint(1,highest) print(answer) # TODO: Remove this line after testing print("Please guess number between 1 and 10: ") guess = get_integer("Enter the number : ") # if guess != answer: # if guess < answer: # print("Guess Higher... Guess Again") # else: # print("Guess Lower... Guess Again") # guess = int(input()) # if answer == guess: # print("Guess Successful") # else: # print("Not Correctly guessed") # else: # print("Got it in first Guess") if guess == answer: print("Guess Success") elif guess == 0: exit(0) else: while answer != guess: print("Try again") guess = get_integer("Enter the number : ") if guess == answer: print("Guess Success") break if guess == 0: break
# 01234567890123 parrot = "Norwegian Blue" print(parrot) # # print(parrot[3]) # #POSITIVE INDEX # print(parrot[3]) # print(parrot[4]) # print(parrot[9]) # print(parrot[3]) # print(parrot[6]) # print(parrot[8]) # #Negative Index # print() # print("Using Negative index") # print(parrot[-11]) # print(parrot[-10]) # print(parrot[-5]) # print(parrot[-11]) # print(parrot[-8]) # print(parrot[-6]) # #Subtract String Length # print() # print(len(parrot)) # parrot_string_length = len(parrot) # print(parrot[3-parrot_string_length]) # print(parrot[4-parrot_string_length]) # print(parrot[9-parrot_string_length]) # print(parrot[3-parrot_string_length]) # print(parrot[6-parrot_string_length]) # print(parrot[8-parrot_string_length]) # Slice # Second value in index is excluded # print(parrot[0:5]) # print(parrot[3:5]) # print(parrot[0:9]) # print(parrot[:9]) # print(parrot[-4:]) # print(parrot[10:14]) # print(parrot[10:]) # print(parrot[:6]+parrot[6:]) # print(parrot[:]) # # NEgative index in slices # print(parrot[-4:12]) # print(parrot[-4:-2]) #Strip String # 01234567890123 # parrot = "Norwegian Blue" # print(parrot[0:6:2]) #selects character in index 0,2,4,... # print(parrot[0:6:3]) #selects character in index 0,3,6,... # number = "9,223;372:036 854,775;807" # print(number[2::4]) #230878 # print(number[1::4]) # seperators = number[1::4] # values = "".join(char if char not in seperators else " " for char in number).split() # print([int(val) for val in values]) #Slice Backword letters = "abcdefghijklmnopqrstuvwxyz" backwards = letters[25::-1] print(backwards) #reverse the string backwards = letters[::-1] print(backwards) #qpo print(letters[16:13:-1]) #edcba print(letters[4::-1]) #last 8 character in rev order print(letters[:-9:-1]) print(letters[-4:]) print(letters[-1:]) print(letters[:1])
def fibonacci(number): """Fibonacci using for loop Args: number ([int]): [`n` th fibonacci number to be find] Returns: [int]: [return `n` th fibonacci number] """ if 0 <= number <= 1: return number first, second = 0,1 result = None for f in range(number-1): result = first + second first = second second = result return result for i in range(36): print(i, fibonacci(i))
# This is concept of TUPLE a = b = c = d = e = f = 12 print(a, b, c, d, e, f) # RHS is a Tuple x, y = 1, 2 print(x, y) data = 1, 2, 3 print(data.__class__) # Prints tuple x, y, z = data print(x, y, z) # Unpacking the list # We can unpack any sequence type data_list = [12, 13, 14] x, y, z = data_list print(x, y, z) # enumerate function returns the TUPLE for i in enumerate("abcdefgh"): print(i, i.__class__) index, character = (0, 'a') print(index, character) # enumerate function returns the TUPLE for i in enumerate("abcdefgh"): index, character = i print(index, character) table = ("Coffee table", 200, 100, 75, 34.50) print(table[1]*table[2]) name, length, width, height, price = table print(length*width) print() albums = [("a", "b", 1), ("c", "d", 2), ("e", "f", 3), ("g", "h", 4) ] for album in albums: name,track,year = album print(name, track, year) print() for name,track,year in albums: print(name, track, year)
alphabets = [ "a", "b", "c", "d", "e", "f", ] for alphabet in alphabets: print(alphabet) separator = " | " output = separator.join(alphabets) print(output) print(", ".join(alphabets))
import nltk File = open("D:\IFS\input\source.txt") # open file lines = File.read() # read all lines sentences = nltk.sent_tokenize(lines) # tokenize sentences nouns = [] # empty to array to hold all nouns for sentence in sentences: for word, pos in nltk.pos_tag(nltk.word_tokenize(str(sentence))): if ( pos == 'NNP'): nouns.append(word) print nouns
""" 写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。 """ """ 例1:2AF5换算成10进制: 第0位: 5 * 16^0 = 5 第1位: F * 16^1 =15*16^1= 240 第2位: A * 16^2= 10* 16^2=2560 第3位: 2 * 16^3 = 8192 结果就是:5 * 16^0 + 15 * 16^1 + 10 * 16^2 + 2 * 16^3 = 10997 例2:CE换算成10进制: 第0位:E*16^0=14*16^0=14 第1位:C*16^1=12*16^1=192 结果就是:14*16^0+12*16^1=206 """ while True: try: print(int(input(),16)) except: break
""" python实现顺序栈 1。目标:实现栈(后进先出) 2。设计 """ class ListStack: def __init__(self): """初始化一个空栈""" self.elems = [] def push(self, item): """入栈操作""" self.elems.append(item) def destack(self): """出栈操作""" if not self.elems: raise Exception('destack from a empty stack!') return self.elems.pop() if __name__ == '__main__': ls = ListStack() ls.push(100) ls.push(200) ls.push(300) print(ls.destack()) print(ls.destack()) print(ls.destack()) print(ls.destack()) print(ls.destack())
class MyClass: def __init__(self): self.__data = 10 def __func01(self): print("func01 被执行了") m01 = MyClass() # print(m01.__data) # 报错 type object 'MyClass' has no attribute '__data' print(m01.__dict__) m01._MyClass__func01() # 隐形变量的显示方式 但是不建议,是臭流氓做法 print(m01._MyClass__data) class A: @staticmethod def add(x, y): return x + y def __init__(self, a, b): self.a = a self.b = b def function01(self): print(A.add(self.a, self.b)) a = A(3,4) a.function01() # 7
def get_text(name): return "My name is, {0} and i don't like decorators".format(name) def p_decorate(func): def func_wrapper(name): return "<p>{0}</p>".format(func(name)) return func_wrapper def main(): name = (raw_input("Enter your name to demonstrate decorator")) print ("*******calling name without decorator*******") print (get_text(name)) print ("********calling name with decorator*********") my_get_text = p_decorate(get_text) print my_get_text(name) if __name__== "__main__" :main()
def convetor(num, word): # number 1 solution print("*********converting interger to a string**********") print("Data type before conversion") print (type(num)) print("Data type after conversion") mo = str(num) print (type(mo)) # number 2 solution print("*********converting string to integer**********") print("Data type before conversion") print (type(word)) print("Data type after conversion") modified = int(word) print (type(modified)) def numberThree(strOne, strTwo): one = int(strOne) two = int(strTwo) add = one + two print ('Total of two numbers :'), print(add) def numberFour(firstName, lastName): concate = firstName + ' ' +lastName print (concate) def numberFive(oneWord, secondWord2): firstlen = len(oneWord) secondlen = len(secondWord2) if (firstlen > secondlen): print ("Maximum lenth belongs to "), print (oneWord), print (" and it lenght is "), print (firstlen) elif (firstlen < secondlen): print ("Maximum lenth belongs to "), print (secondWord2), print (" and it lenght is "), print (secondlen) else: print ("Length for both String "), print (oneWord + " and " + secondWord2), print (" is same.") def numberSix (munber2): if (munber2%2)== 0: print (munber2 ), print (" is even number") else: print (munber2), print (" is odd number") def main(): num =int( raw_input("Enter a integer number and the converter will make it a string")) word = raw_input("Enter a integral numbers in string and the converter will make it an integer") convetor(num, word, ) # number 3 solution strOne= raw_input("Enter first integral numbers in string: ") strTwo = raw_input("Enter second integral numbers in string: ") numberThree(strOne,strTwo) # number 4 solution firstName = raw_input("Enter your first name: ") lastName = raw_input("Enter your second name: ") numberFour(firstName,lastName) #solution for number 5 oneWord= raw_input("Enter first word") secondWord2= raw_input("Enter second word") numberFive(oneWord,secondWord2) #solution for number 6 munber2 = int (raw_input(" Enter a number to verify if it is a even or odd number")) numberSix(munber2) if __name__== "__main__" :main()
class Vehicle: def __init__(self, **kwargs): self.var = kwargs def mile (self): print ("The car model") def year (self): print(" The year of the model") def get_param (self): return self.var def get_param (self, key): return self.var.get(key) def main (): truck = Vehicle(year='2004') print (truck.get_param('year')) bus = Vehicle(model='Honda', year='2013') print (bus.get_param('model')) print (bus.get_param('year')) if __name__ == "__main__": main()
import unittest def person_number(person_count: int) -> int: return person_count def get_pizza_number() -> int: return 2 def get_number_slice_by_people(people: int, pizza: int) -> int: default_slice_by_pizza = 8 return pizza * default_slice_by_pizza // people class TestOne(unittest.TestCase): def test_get_person_return_input_people_given(self): self.assertEqual(8, person_number(8)) def test_get_pizza_number(self): number_pizza = get_pizza_number() self.assertEqual(2, number_pizza) def test_number_slice_by_people_with_2_pizza_8_people(self): number_slice_by_people = get_number_slice_by_people(people=8, pizza=2) self.assertEqual(2, number_slice_by_people) def test_number_slice_by_people_with_2_pizza_7_people(self): self.assertEqual(2, get_number_slice_by_people(people=7, pizza=2))
def merge(arr,l,m,r): n1=m-l+1 n2=r-m left=[0]*n1 right=[0]*n2 i=0 j=0 while(i<n1): left[i]=arr[l+i] i=i+1 while(j<n2): right[j]=arr[m+1+j] j=j+1 i=0 j=0 k=l while i<n1 and j<n2: if left[i]<=right[j]: arr[k]=left[i] i=i+1 k=k+1 else: arr[k]=right[j] j=j+1 k=k+1 while i<n1: arr[k]=left[i] i=i+1 k=k+1 while j<n2: arr[k]=right[j] j=j+1 k=k+1 def mergeSort(arr,l,r): if l<r: m=(l+(r-1))/2 mergeSort(arr,l,m) mergeSort(arr,m+1,r) merge(arr,l,m,r) arr=[1000,2,323,324,99] mergeSort(arr,0,len(arr)-1) print(arr)
""" Provided with consumption data over a given period of time, the program output a classified list for all your products. structure of the excel must be: sku | nc where sku - item number nc - number of consumption """ import numpy as np import pandas as pd path = './sample_data/data.xlsx' class ABC(): def __init__(self, path): self.upper_boundary = 0 self.mid_boundary = 0 self.df = pd.read_excel(path) def train(self): df = self.df # create an array from consumption data for a given product array_x = df['nc'].to_numpy() # calculate the quartiles a_type = np.quantile(array_x, .8) b_type = np.quantile(array_x, .5) print(a_type) print(b_type) self.upper_boundary = a_type self.mid_boundary = b_type def categorize(self, nc): df = self.df category = ''; if nc >= self.upper_boundary: category = 'A' elif nc >= self.mid_boundary and nc < self.upper_boundary: category = 'B' else: category = 'C' return f"{category}"
# Extended Slices # [begin:end:step] # if begin and end are off-option statement and a step get positive value, # sequences are going to positive way with positive step. # if a step get negative value, then sequences are going to reverse way # with abs(value) def reverse(str=''): return str[::-1]
# Learning Sets and Frozen sets in python # Sets # The data type "set", which is a collection type, has been part of Python since version 2.4. # A set contains an unordered collection of unique and immutable objects. # The set data type is, as the name implies, a Python implementation of the sets # as they are known from mathematics. This explains, why sets unlike lists # or tuples can't have multiple occurrences of the same element. first_set = set([(1, 2, 3)]) print(first_set) cities = set(("Paris", "Lyon", "London","Berlin","Paris","Birmingham")) print(cities) # Frozen sets # Though sets can contain only immutable objects as there elements cities.add("Samburg") print(cities) cities = frozenset(["Incheon", "Frankfurt", "Orlando", "New Jersey"]) # cities.add("James") print(type(cities)) # SET operations # ADD Operation colors = {'red', 'green'} colors.add('blue') print(colors) # Cleaning the SET colors.clear() print(colors) # Making a shallow copy more_cities = {"Winterthur", "Schaffhausen", "St. Gallen"} backup_cities = more_cities.copy() more_cities.clear() print(more_cities) print(backup_cities) # Difference X = {"a", "b", "c", "d"} Y = {"c", "d", "e"} Z = {"a", "m", "n"} print(X - Y - Z) # alternative X.difference(Y).difference(Z) X = {"a", "b", "c", "d"} X.difference_update(Y) print(X) # Removing an element from a set X.discard("b") print(X) # Using remove, but remove will generate an error in case the element does not exist # X.remove("b") # UNION x = {"a","b","c","d","e"} y = {"c","d","e","f","g"} z = x | y # Alternatively use .union(set object) to do UNION print(z) # INTERSECTION z = x & y # Alternativey use .intersection(set object) to do INTERSECTION print(z) # Checking if the sets are DISJOINT print(x.isdisjoint(y)) # Checking SUBSET print(x.issubset(x.union(y))) # Checking SUPERSET print(x.issuperset({"a"})) # Removing an arbitrary element from the SET print(x.pop()) # Looping through the SET for e in x.intersection(y): print(e)
# Formatting in python from math import sqrt print("Art: %5d, Price is %8.2f" %(432, 345.69)) print("Art: {a:<5d}, Price is {b:<8.2f}".format(a=432, b=3456.7967)) def print_sqrts(start, end): """ Printing pretty formatted strings :param start: :param end: :return None: """ for i in range(start, end+1): print("Square root of {0} is {1:<5.2}".format(i, sqrt(i))) return None print_sqrts(start=1, end=10) print(print_sqrts.__doc__) # This option signals the use of a comma for a thousands separator. print("{0:,}".format(456789012)) # a, b, *_ = (1, 2, 3, 8, 4, 5, 6) # print(_) # String methods used for formatting # 1. center() s = "Python" print(s.center(10, "*")) # 2. ljust() print(s.ljust(10, "#")) # 3. rjust() print(s.rjust(10, "^")) # 4. zfill() is same as rjust() print(s.zfill(10)) # Formatted String literals price = 12.234 print(f"The price is {price*2:5.6f}")
import numpy as np dim_0 = np.array(24) dim_1 = np.array([1,2,3]) dim_2 = np.array([[1,2,3],[1,2,3]]) dim_3 = np.array([[[1,2,3],[1,2,3]],[[1,2,3],[1,2,3]]]) print(dim_0) print(dim_1) print(dim_2) print(dim_3) #print dimensions print(dim_0.ndim) print(dim_1.ndim) print(dim_2.ndim) print(dim_3.ndim) #creating array with min dim arr = np.array([1,2,3],ndmin = 5) print(arr) print("The dimension of array", arr.ndim)
import numpy as np a = np.array([1,2,3,4,5]) ar = np.array([[1,2,3,4,5],[1,2,3,4,5]]) arr = np.array([[[1,2,3,4,5],[1,2,3,4,5]],[[1,2,3,4,5],[1,2,3,4,5]]]) #iterating a one dimension array for x in a: print(x) #iterating two dimension array for x in ar: print(x) #printing every single array element in two dimensional array for x in ar: for y in x: print(y) #iterating three dimensional array for x in arr: print(x) #printing every single array element in three dimensional array for x in arr: for y in x: for z in y: print(z)
print("User input") print("*************************************") p = int(input("Enter the Prime number P: ")) q = int(input("Enter the Prime number Q: ")) e = int(input("Enter tha value for e: ")) m = int(input("Enter the value for M: ")) print("************************************") def rsa(): n = p*q pi_n = (p-1) * (q-1) print("the value of n is: "+str(n)) print("the value of pi_of_n is:"+str(pi_n)) if e < pi_n: div = e else: div = pi_n for i in range(1,div): if (e % i == 0) and (pi_n % i == 0): gcd = i if gcd == 1: print("proceeded RSA alogoritm") k = 1 while ((pi_n *k) + 1) % e != 0: k += 1 d = (pi_n * k + 1) / e print(d) encrypt = (m ** e) % n print("Encrypted cipher text is: "+str(encrypt)) decrypt = (encrypt**d) % n print("Decrypted plain text is: "+str(decrypt)) else: print("invalid e value finded so please enter correct details") rsa()
class inheritdemo: def __init__(self,text): self.text=text class hello(inheritdemo): def quote(self): print("it is coming from hello class") class hi(inheritdemo): def quote1(self): print("it is coming from hi class") text1=hello("hello") text2=hi("hi") print(text1.text) print(text2.text)
""" 给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符 '*' 匹配零个或多个前面的那一个元素 所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。 说明: s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。 示例 1: 输入: s = "aa" p = "a" 输出: false 解释: "a" 无法匹配 "aa" 整个字符串。 示例 2: 输入: s = "aa" p = "a*" 输出: true 解释: 因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 "aa" 可被视为 'a' 重复了一次。 示例 3: 输入: s = "ab" p = ".*" 输出: true 解释: ".*" 表示可匹配零个或多个('*')任意字符('.')。 示例 4: 输入: s = "aab" p = "c*a*b" 输出: true 解释: 因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。 示例 5: 输入: s = "mississippi" p = "mis*is*p*." 输出: false """ class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ def match(i, j): if (i, j) in info_dict: return info_dict[i, j] if not p[j:]: res = not s[i:] else: first_match = bool(s[i:]) and p[j] in (s[i], '.') if len(p[j:]) >= 2 and p[j + 1] == '*': # 在不加括号时候, and优先级大于or res = match(i, j + 2) or (first_match and match(i + 1, j)) else: res = first_match and match(i + 1, j + 1) info_dict[i, j] = res return res info_dict = dict() return match(0, 0)
""" 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。   示例: 给定 1->2->3->4, 你应该返回 2->1->4->3. """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ # 画图写迭代过程,最后可以简化某些步骤 if not head: return head res = ListNode(0) res.next = head pre, left, right = res, head, head.next while left and right: pre.next = right left.next = right.next right.next = left right = left.next if right: pre, left, right = left, left.next, right.next else: break return res.next
""" 题目已被锁 """ class Solution(object): def generateSentences(self, synonyms, text): """ :type synonyms: List[List[str]] :type text: str :rtype: List[str] """ def dfs(n): if n == length: result.add(" ".join(word_list)) return dfs(n + 1) if word_list[n] in synonym_dict: tmp = word_list[n] for word in synonym_dict[tmp]: word_list[n] = word dfs(n + 1) word_list[n] = tmp result = set() synonym_dict = dict() for synonym in synonyms: if synonym[0] not in synonym_dict and synonym[1] not in synonym_dict: synonym_dict[synonym[0]] = synonym_dict[synonym[1]] = set() elif synonym[0] not in synonym_dict: synonym_dict[synonym[0]] = synonym_dict[synonym[1]] elif synonym[1] not in synonym_dict: synonym_dict[synonym[1]] = synonym_dict[synonym[0]] synonym_dict[synonym[0]].add(synonym[0]) synonym_dict[synonym[0]].add(synonym[1]) word_list = text.split(" ") length = len(word_list) dfs(0) return sorted(result)
""" 有一个长度为 arrLen 的数组,开始有一个指针在索引 0 处。 每一步操作中,你可以将指针向左或向右移动 1 步,或者停在原地(指针不能被移动到数组范围外)。 给你两个整数 steps 和 arrLen ,请你计算并返回:在恰好执行 steps 次操作以后,指针仍然指向索引 0 处的方案数。 由于答案可能会很大,请返回方案数 模 10^9 + 7 后的结果。   示例 1: 输入:steps = 3, arrLen = 2 输出:4 解释:3 步后,总共有 4 种不同的方法可以停在索引 0 处。 向右,向左,不动 不动,向右,向左 向右,不动,向左 不动,不动,不动 示例  2: 输入:steps = 2, arrLen = 4 输出:2 解释:2 步后,总共有 2 种不同的方法可以停在索引 0 处。 向右,向左 不动,不动 示例 3: 输入:steps = 4, arrLen = 2 输出:8   提示: 1 <= steps <= 500 1 <= arrLen <= 10^6 """ class Solution(object): def numWays(self, steps, arrLen): """ :type steps: int :type arrLen: int :rtype: int """ length = min(arrLen, steps) pre = [0] * length pre[0] = 1 for _ in range(steps): cur = list() for i in range(length): cnt = pre[i] if i - 1 >= 0: cnt += pre[i - 1] if i + 1 < length: cnt += pre[i + 1] cur.append(cnt) pre = cur return pre[0] % 1000000007
""" 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组。 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] """ class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # # out of time # length = len(nums) # nums_dict = dict() # res = set() # for i in range(length): # if nums[i] in nums_dict: # for pair in nums_dict[nums[i]]: # if i != pair[0] and i != pair[1]: # res.add(tuple(sorted((nums[i], nums[pair[0]], nums[pair[1]])))) # for j in range(i + 1, length): # tmp = 0 - nums[i] - nums[j] # if tmp in nums_dict: # nums_dict[tmp].append((i, j)) # else: # nums_dict[tmp] = [(i, j)] # return list(res) def get_two_sum(nums, target): nums_set = set() res = set() for i in nums: if target - i in nums_set: res.add((i, target - i)) else: nums_set.add(i) return res nums.sort() if len(nums) == 0 or nums[-1] < 0: return list() res = list() for i in range(len(nums) - 2): if nums[i] > 0: break if i > 0 and nums[i - 1] == nums[i]: continue for pair in get_two_sum(nums[i + 1:], -nums[i]): res.append((nums[i], ) + pair) return res
""" 给你一个整数数组 nums,请你返回其中位数为 偶数 的数字的个数。   示例 1: 输入:nums = [12,345,2,6,7896] 输出:2 解释: 12 是 2 位数字(位数为偶数)  345 是 3 位数字(位数为奇数)   2 是 1 位数字(位数为奇数)  6 是 1 位数字 位数为奇数)  7896 是 4 位数字(位数为偶数)   因此只有 12 和 7896 是位数为偶数的数字 示例 2: 输入:nums = [555,901,482,1771] 输出:1 解释: 只有 1771 是位数为偶数的数字。   提示: 1 <= nums.length <= 500 1 <= nums[i] <= 10^5 """ class Solution(object): def findNumbers(self, nums): """ :type nums: List[int] :rtype: int """ res = 0 for num in nums: if len(str(num)) % 2 == 0: res += 1 return res
# 일반적인 병합 정렬 알고리즘 def merge_sort(a) : n = len(a) if n <= 1 : # 종료조건 return # 그룹을 나누어 각각 병합 정렬을 호출 mid = n // 2 g1 = a[:mid] g2 = a[mid:] merge_sort(g1) # g1 = [3, 6, 8, 9, 10] merge_sort(g2) # g2 = [1, 2, 4, 5, 7] # print('mid : ', mid) # print('g1 : ', g1) # print('g2 : ', g2) # 두 그룹을 하나로 병합 i1 = 0 # g1의 idx i2 = 0 # g2의 idx ia = 0 # a의 idx while i1 < len(g1) and i2 < len(g2) : if g1[i1] < g2[i2] : a[ia] = g1[i1] i1 += 1 ia += 1 else : a[ia] = g2[i2] i2 += 1 ia += 1 # print('a :', a) # 아직 남아있는 자료들을 결과에 추가 while i1 < len(g1) : a[ia] = g1[i1] i1 += 1 ia += 1 while i2 < len(g2) : a[ia] = g2[i2] i2 += 1 ia += 1 d = [6, 8, 3, 9, 10, 1, 2, 4, 7, 5] merge_sort(d) print(d)
import gevent from gevent import socket ''' Implementation 1 ''' urls = ["www.google.com","www.agrostar.in","www.facebook.com"] jobs = [gevent.spawn(socket.gethostbyname,url) for url in urls ] gevent.joinall(jobs,timeout=2) print([job.value for job in jobs]) ''' Instead we could also write code as below Implementation 2 ''' import socket urls = ["www.google.com","www.agrostar.in","www.facebook.com"] print([socket.gethostbyname(url) for url in urls]) ''' Difference between implementations: In first implementation gevent has its own socket lib implementation which works asynchronously. When we call spawn(), it calls method gethostbyname(), and switches its execution for calling next gethostbyname() method, and so in a asynchronous way. In the second method, we call synchronously . '''
class Point: x = 0 y = 0 def __init__(self, init_x, init_y): """ Create a new point at the given coordinates. """ self.x = init_x self.y = init_y def get_x(self): return self.x def get_y(self): return self.y def distance_from_origin(self): return ((self.x ** 2) + (self.y ** 2)) ** 0.5 def __repr__(self): return "x=" + str(self.x) + ", y=" + str(self.y) def __eq__(self, otherPoint): if self.x == otherPoint.get_x() and self.y == otherPoint.get_y(): return True else: return False class Rectangle: lowerLeft = Point(0,0) upperLeft = Point(0,1) upperRight = Point(1,1) lowerRight = Point(1,0) height = 0 width = 0 def __init__(self, lowerLeftPoint, height, width): self.lowerLeft = lowerLeftPoint self.height = height self.width = width self.upperLeft = Point(self.lowerLeft.get_x(), self.lowerLeft.get_y() + height) self.upperRight = Point(self.lowerLeft.get_x() + width, self.lowerLeft.get_y() + height) self.lowerRight = Point(self.lowerLeft.get_x() + width, self.lowerLeft.get_y()) def __repr__(self): return "I am a rectangle with lower left point at: " + str(lowerLeft) + " , width: " + self.width + ", height: " + self.height def getArea(self): return self.height * self.width def getAreaFromPoints(self): width = self.lowerLeft.get_x() - self.lowerRight.get_x() if (width < 0): width *= -1 height = self.lowerLeft.get_y() - self.upperLeft.get_y() if (height < 0): height *= -1 if (width * height == 0): print("Width: " + str(width) + ", height: " + str(height)) return width * height def checkMyAssumptions(self): if (self.getArea() == self.getAreaFromPoints()): return "width * heigth == point width * point height calculations" else: string1 = "Something differs between assumed width and height versus point positions" #string2 = "Width * Height = " + str(width * height) + ", and pointwid return string1 def __eq__(self, otherRect): isTrue = True if (self.lowerLeft != otherRect.lowerLeft): isTrue = False if (self.lowerRight != otherRect.lowerRight): isTrue = False if (self.upperLeft != otherRect.upperLeft): isTrue = False if (self.upperRight != otherRect.upperRight): isTrue = False return isTrue myPoint = Point(1,1) print(myPoint) print(myPoint.distance_from_origin()) myRect = Rectangle(Point(0,0), 1, 1) print("My rectangle's area: " + str(myRect.getArea())) print("My rectangle's assumed area from my method getPointFromArea(): " + str(myRect.getAreaFromPoints())) print(myRect.checkMyAssumptions()) print("Lower left point: " + str(myRect.lowerLeft)) print("Upper left point: " + str(myRect.upperLeft)) print("Upper right point: " + str(myRect.upperRight)) print("Lower left point: " + str(myRect.lowerRight))
import time print("----------ATM MACHINE----------") print("Welcome to xxxx ATM") print("Swipe Your Card please") amount=10000 #your password is 2222 y="2222" print("_________________") x=input("enter your pin") print("checking........................!!") time.sleep(1) if x==y: print("________________") print("1.Cash Withdrawl") print("2.check enquiry") print("3.check balance") print("4.print receipt") print("5.Mini Statement") print("6.Exit") print("________________") choice=int(input("enter your choice")) if choice==1: print("a.Current Account") print("b.Saving Account") print("________________") ch=input("choose between a and b") if ch=='a': wdraw=int(input("enter the amount to be withdraw:")) print("Transaction Successful") print("Collect Your Amount") print("your remain balance is",amount-wdraw) print("Thanks for using SBI ATM") else: sdraw=int(input("enter the amount to be withdraw:")) print("Transaction Successful") print("collect your amount") print("your remain balance is",amount-wdraw) print("Thanks for using SBI ATM") elif choice==2: print(f"Your Current Balance is {amount}") print("Thanks For using SBI ATM") elif choice==3: print(f"Remaining Balance is {amount}") print("Thanks for using ATM") elif choice==4: yn=input("Would you want to print the receipt of remaining balance i.e.{amount} yes/no") if yn=='yes': print("collect your Receipt") elif yn=='no': print("thanks for using SBI ATM") else: print("error 404") elif choice==5: print("collect your mini statement of your current balance") print("Thanks for using SBI ATM") elif choice==6: exit() else: print("wrong choice") else: print("Wrong Pin ,Try After Sometime")
import wikipedia_utils """ Returns a key-value dictionary of the extractable values from the wikipedia infobox. """ def getInfobox(page): # Download the raw page content and then parse it into nested dictionaries. page = wikipedia_utils.GetWikipediaPage(page) parsedPage = wikipedia_utils.ParseTemplates(page["text"]) # Identify the wikipedia template been used so we can key by this template below to # find the dictionary representing the infobox. templates = dict(parsedPage["templates"]) infobox = None for key in templates.keys(): # Look for the word 'box' in the keys. Wikipedia is not 100% on the use of the # term 'infobox' (for example, the "GNF Protein box" template, as of January 2015) # hence the more general term 'box' has to be searched for. if 'box' in key.lower(): infobox = templates.get(key) break # If there is no infobox, log a message for debugging later. if (infobox == None): print 'there was no infobox on this page!' return infobox
# coding=utf-8 # 如何对字符串进行左,右,居中对齐 # 使用str.ljust(),str.rjust(), str.center()进行对齐 # 使用内置的format方法 s = 'abc' print s.ljust(20) print s.ljust(20, '=')# 以=作为填充物进行填充,字符靠左 print s.rljust(20) print s.rjust(20, '=')# 以=作为填充物进行填充,字符靠右 print s.center(20) print s.center(20, '=')#以=作为填充物,字符居中 print format(s, '<20')#做对齐 print format(s, '>20') print format(s, '^20')#居中
######################################## # @AUTHOR TAYLOR ROMAIN # # @DATE 3-6-2021 # # __main__.py # ######################################## import matplotlib.pyplot as plt import math import numpy as np from math import log10, floor from tabulate import tabulate headers = ['Temperature (K)', "1/T", "Volume of HCL", "Moles of H+", "Moles of Borax", "Molarity of Borax", "Natural Log of Borax", "3 Natural Log of Borax", "Natural Log of Equilibrium Expression"] # List's to store data. OneOverT = [] Celsius_To_Kelvin = [] Ln_K = [] Volume_Of_HCL_Used = [] MOLES_H_PLUS = [] MOLES_BORAX = [] MOLARITY_OF_BORAX = [] NATURAL_LOG_OF_BORAX = [] THREE_NATURAL_LOG_OF_BORAX = [] NATURAL_LOG_EQUILIBRIUM_EXPRESION = [] # Constants. MOLARITY_OF_HCL = 0.4680 def main(): print("Press x to stop entering data.") while True: #Take in input from the console. temperature = input( "Temperature in Celsius of Sample #".__add__(str(OneOverT.__len__() + 1))) try: temperature = float(temperature) # Celsius to Kelvin Conversion CelsiusToKelvin = (temperature + 273.15) #1/T Calculation Divided_Temperature = 1 / CelsiusToKelvin # Add the data to the lists declared above. OneOverT.append(Divided_Temperature) Celsius_To_Kelvin.append(CelsiusToKelvin) except ValueError: #Check if the input is equal to the termination value 'x', # if so break the loop. if temperature == "x": break else: print("Only Int & Float values are accepted. Try again.") print("Press x to stop entering data.") while True: buret_readings = input( "(Final Burette Reading in mL) insert ',' (Initial Burette Reading in mL) for Sample #".__add__( str(Volume_Of_HCL_Used.__len__() + 1))).split(',') try: final_reading = buret_readings[0] initial_reading = buret_readings[1] Volume_Of_HCL_Used_L = (float(final_reading) - float(initial_reading)) / 1000 Volume_Of_HCL_Used.append(Volume_Of_HCL_Used_L) except ValueError: if temperature == "x": break else: print("Only Int & Float values are accepted. Try again.") except IndexError: break; calculate() def calculate(): for i in range(0, Volume_Of_HCL_Used.__len__()): MOLES_H_PLUS.append(float((Volume_Of_HCL_Used[i]) * MOLARITY_OF_HCL)) for i in range(0, MOLES_H_PLUS.__len__()): MOLES_BORAX.append(float((MOLES_H_PLUS[i]) / 2)) for i in range(0, MOLES_BORAX.__len__()): MOLARITY_OF_BORAX.append(float((MOLES_BORAX[i]) / 0.00500)) for i in range(0, MOLES_BORAX.__len__()): NATURAL_LOG_OF_BORAX.append(float(np.log(MOLARITY_OF_BORAX[i]))) for i in range(0, NATURAL_LOG_OF_BORAX.__len__()): THREE_NATURAL_LOG_OF_BORAX.append(float((3 * np.log(MOLARITY_OF_BORAX[i])))) for i in range(0, THREE_NATURAL_LOG_OF_BORAX.__len__()): NATURAL_LOG_EQUILIBRIUM_EXPRESION.append(float(math.log(4) + THREE_NATURAL_LOG_OF_BORAX[i])) printDataShowGraph() def printDataShowGraph(): plt.scatter(OneOverT, NATURAL_LOG_EQUILIBRIUM_EXPRESION) x = np.array(OneOverT) y = np.array(NATURAL_LOG_EQUILIBRIUM_EXPRESION) m, b = np.polyfit(x, y, 1) plt.plot(x, x * m + b) print("y=",m,"x+",b) plt.xlim(min(OneOverT) - 0.0001, max(OneOverT) + 0.0001) plt.ylim(min(NATURAL_LOG_EQUILIBRIUM_EXPRESION) - 1, max(NATURAL_LOG_EQUILIBRIUM_EXPRESION) + 1) plt.xlabel("1/T (Kelvin)") plt.ylabel("Ln K") plt.title("Change in Equilibrium Constant with Temperature") plt.show() data = zip(Celsius_To_Kelvin, OneOverT, Volume_Of_HCL_Used, MOLES_H_PLUS, MOLES_BORAX, MOLARITY_OF_BORAX, NATURAL_LOG_OF_BORAX, THREE_NATURAL_LOG_OF_BORAX, NATURAL_LOG_EQUILIBRIUM_EXPRESION) print("\n") print(tabulate(data, headers=headers, floatfmt=".5f")) main()
class Animal: def __init__(self, e,a): self.especie = e self.edad = a def correr (self): print("soy un {}." "Estory corriendo".format(self.especie)) def crecer (self, edad = 0): if (self.edad + edad) > 14: self.vivo = False else: self.edad += edad self.vivo = True perro = Animal ("perro",3) print( "Hola soy un {}" "tengo {} años".format(perro.especie, perro.edad)) perro.crecer(10) print( "Hola soy un {}" "tengo {} años".format(perro.especie, perro.edad)) perro.crecer(2) if perro.vivo: print("Hola soy un {}" "tengo {} años".format(perro.especie, perro.edad)) else: print("ME MORI....RIP") perro.crecer(-10) if perro.vivo: print("Hola soy un {}" "tengo {} años".format(perro.especie, perro.edad)) else: print("ME MORI....RIP")
class Duck: def __init__(self,nombre): self.duck_nombre = nombre def quack (Self): print("Quack") def walk (self): print("walks like a duck") donald = Duck ("donal") donald.quack() donald.walk() print("cual es tu nombre", donald.duck_nombre)
#!/usr/bin/python3 """ function that queries the Reddit API and returns the number of subscribers (not active users, total subscribers) for a given subreddit. If an invalid subreddit is given, the function should return 0. """ import requests def number_of_subscribers(subreddit): main_url = 'https://www.reddit.com/' sub_reddit = 'r/{}/about.json'.format(subreddit) header = { 'User-Agent': 'MAZTRO', 'From': 'youremail@domain.com' } response = requests.get(main_url + sub_reddit, headers=header) if ('error' in response.json().keys()): return 0 return (response.json()['data']['subscribers'])
from benchmark import benchmark def iterate_digits(x): result = [] while x > 0: result.insert(0, x % 10) x = x // 10 return result def is_valid_password(x): digits = str(x) if len(digits) != 6: return False has_two_consecutive = False for i, j in zip(digits, digits[1:]): if i == j: has_two_consecutive = True if i > j: # decreasing, works since ASCII numbers return False return has_two_consecutive def has_only_n_consecutive(x, n): s = '' for e in x: if len(s) == 0 or s[0] == e: s += e else: if len(s) == n: return True s = e if s != '': return len(s) == n return False def is_valid_password_adjacents_exactly_len_2(x): digits = str(x) if len(digits) != 6: return False for i, j in zip(digits, digits[1:]): if i > j: # decreasing return False return has_only_n_consecutive(digits, 2) @benchmark def day4a(l, u): passwords = [x for x in range(l, u + 1) if is_valid_password(x)] return len(passwords) @benchmark def day4b(l, u): passwords = [x for x in range(l, u + 1) if is_valid_password_adjacents_exactly_len_2(x)] return len(passwords) lower = 264793 upper = 803935 print('day4a = ' + str(day4a(lower, upper))) # 966 print('day4b = ' + str(day4b(lower, upper))) # 628
import time def benchmark(func): """ A timer decorator """ def function_timer(*args, **kwargs): """ A nested function for timing other functions """ start = time.time() value = func(*args, **kwargs) end = time.time() runtime = end - start msg = "Benchmark: {func} took {time}s" print(msg.format(func=func.__name__, time=round(runtime, 3))) return value return function_timer
"""Escreva um programa que leia um valor em metros e o exiba convertido em milímetros""" metros = int(input("Por favor informe uma quantidade em metro: ")) m = metros km = metros / 1000 h = metros / 100 dam = metros / 10 dm = metros * 10 cm = metros * 100 milimetros= (metros*1000) print('A medida de {:.1f}m corresponde a'.format(m)) print('{}km'.format(km)) print('{}hm'.format(h)) print('{}dam'.format(dam)) print('{}dm'.format(dm)) print('{}cm'.format(cm)) print('{}mm'.format(milimetros))
n = int(input("Quantos dias alugado ? ")) x = float(input('Quantos km rodados ? ')) dia = 60 km = 0.15 total = (dia * n) + (x * km) print('Total a pagar é de R$: {:.2f}'.format(total))
n = str(input('Digite uma frase: ')).strip().lower() print('A letra A aparece {} vezes na frase.'.format(n.count('a'))) print('A primeira letra A aparece na posição {}. '.format(n.find('a')+1)) print('A ultima letra A apareceu na posição {}.'.format(n.rfind('a')+1))
#!python # # SpellingBee solver. Words containing only letters from a string, # and word must contain first letter. # from english_words import english_words_alpha_set from typing import List, Tuple, Dict import sys class SpellingBee: def __init__(self, letters: str): self.letters = letters.lower() if len(self.letters) != 7: raise Exception("String of letters to form words from must be of length 7" ) self._all_words = english_words_alpha_set # results available as fields self.names, self.words = self.find_words() self.all_letter_words = self.max_word() self.candidate_suffixes = SpellingBee.possible_suffixes(self.letters) self.inflections, self.inflection_max_words = self.inflected_words() @staticmethod def _vowel(c: str) -> bool: return c in 'aeiouy' @staticmethod def _append_suffix(w: str, sfx: str) -> str: ''' Append suffix to word, but don't just append if words ends with vowel and suffix starts with vowel. ''' if SpellingBee._vowel(sfx[0]) and SpellingBee._vowel( w[-1] ): return w[0:-1] + sfx else: return w + sfx @staticmethod def _max_word(w: str) -> bool: ''' Is this a maximal word? ''' return len(set(w)) == 7 def score(self) -> int: ''' Calculate the score for the word list, which must exist. ''' score = lambda x: 0 if len(x) <= 3 else 1 if len(x) == 4 else (len(x) + 7) if len(set(x)) == 7 else len(x) return sum([score(w) for w in self.words]) def find_words(self) -> Tuple[List[str], List[str]]: ''' Get lists of words and names, in member variables. ''' # words must be at least 4 letters and contain the first letter in the target self._all_words = english_words_alpha_set only = filter(lambda x: len(x) >= 4 and self.letters[0] in x.lower(), self._all_words) # check if only target letters by translating into Nones all_letters = self.letters + self.letters.upper() x = str.maketrans("", "", all_letters) self._result = sorted( [ w for w in only if not w.translate(x) ] ) # Names are capitalized, and aren't valid names = [ w for w in self._result if str.isupper(w[0]) ] words = [ w for w in self._result if str.islower(w[0]) ] return (names, words) def consider(self, additional: str) -> List[str]: ''' Consider words with additional letter not in set at end, e.g., an ending "e" that gets dropped for a suffix. ''' add_only = filter(lambda x: len(x) >= 4 and self.letters[0] in x.lower() and x[-1] == additional, self._all_words) add_x = str.maketrans("", "", self.letters + additional) add_result = sorted( [ w for w in add_only if not w.translate(add_x) ] ) return add_result def max_word(self) -> List[str]: # Was the word with all letters found? all_letters_words = [w for w in self._result if SpellingBee._max_word(w) ] return all_letters_words # this dictionary does not deal with inflection. The problem is the inverse of # stemming and lematization: adding additional words to lemmas based on available # suffixes. Doing this properly requires categorizing words in parts of speech. # Could use NLTK to do this. It also has a larger dictionary. # suffixes by part of speech (POS) suffixes = { "noun": ["er", "ion", "ity", "ment", "nes", "or", "sion", "ship", "th", "s"], "adj": ["able", "ible", "al", "ant", "ary", "ful", "ic", "ious", "ous", "ive", "les", "y"], "verb": ["ed", "en", "er", "ing", "ize", "ise", "d", "s"], "adv": ["ly", "ward", "wise"] } @staticmethod def possible_suffixes(letters: str) -> Dict[str, List[str]]: ''' Get possible suffixes based on target letters. ''' good_set = set(letters) candidate_suffixes = {} for pos,suffix_list in SpellingBee.suffixes.items(): candidates = [ s for s in suffix_list if len(good_set & set(s)) == len(s) ] if candidates: candidate_suffixes[pos] = candidates return candidate_suffixes def inflected_words(self) -> Tuple[Dict[str, List[str]], List[str]]: ''' if the required letter is in a suffix, then there might be valid inflections with the suffix for lemmas that DON'T have the required letter. Find those suffixes. ''' sfx_list: List[str] = [] for sfx in self.candidate_suffixes.values(): l = [ x for x in sfx if self.letters[0] in x ] sfx_list.extend(l) # if there are such suffixes ... inflections = {} max_words = [] if len(sfx_list) > 0: # get words with only target letters (except the required letter) and min length: # I suspect this list is always non-zero. good_set = set(self.letters) others = [x for x in self._all_words if self.letters[0] not in x and len(good_set & set(x)) == len(set(x))] for s in sfx_list: # combine the (possible) lemma with the suffix, taking into account vowels l = sorted( [SpellingBee._append_suffix(w, s) for w in others if len(SpellingBee._append_suffix(w, s)) >= 4] ) inflections[s] = l all_let_word = [ w for w in l if SpellingBee._max_word(w) ] max_words.extend( all_let_word ) return inflections, max_words if __name__ == '__main__': if len(sys.argv) != 2: print("Error: no target string") sys.exit(1) letters = sys.argv[1] bee = SpellingBee(letters) print("Letters: ", letters) print("Names:", len(bee.names)) print("\t", bee.names) print("Words:", len(bee.words)) print("\t", bee.words) print("Max Words:") print("\t", bee.all_letter_words) print("Predicted score =", bee.score()) print("Suffixes:") for k, v in bee.candidate_suffixes.items(): print("\t", k, v) print("Possible inflections:") for k, v in bee.inflections.items(): print("\t", k, v) print("Possible inflection max words:", bee.inflection_max_words)
# Python code to find the area of a circle def area(r): print("Radius entered: ",r) pi = 3.14 area = pi * (r**2) return area radius = float(input("Enter the radius of the circle: ")) print("Area of circle is: ", area(radius))
# Python code to reverse the list items list = [] num = int(input("Emter the elements to add in the list: ")) for i in range(0,num): element = int(input("Enter the element: ")) list.append(element) print("List items:",list) # Creating an empty list to store the reversed list rev_list = [] # storing the reversed list rev_list = list[::-1] print("Reversed list:",rev_list)
# Python code to print negative numbers in a list lst = [] num = int(input("Enter the number of elements to insert: ")) for i in range(0,num): ele = int(input("Enter both negative and positive numbers: ")) lst.append(ele) print("Entered list: ",lst) print("Negative number in list: ") for x in lst: if x<0: print(x,end=" ")
# Python code to find whether a number is prime or not def primeNumber(n): print("Number entered is: ",n) if (n<=1): print("Nither Prime nor composite") for i in range(2,n): if (n % i ==0): print("Not Prime") else: print("Prime") break num = int(input("Enter the number to check: ")) primeNumber(num)
# Python code to find the length of the list list = [] num = int(input("Enter the number of elements to add in list: ")) for i in range(0,num): element = int(input("Enter the element: ")) list.append(element) print("Length of the list is: ", len(list))
# Python code to remove unwanted elements form a list(here we are removing even numbers). # Creating a empty list lst =[] # Taking number of inputs num = int(input("Enter the number of elements to insert in list: ")) # Taking user inputs for i in range(0,num): ele= int(input("Enter the number:")) lst.append(ele) # Printing entered list print("Entered list: ",lst) # Removing unwanted elements form list for x in lst: if x % 2 == 0: lst.remove(x) # Printing new list print("New list after removing even numbers: ",lst)
# Python code to find the sum of array def sumOdArray(arr): sum = 0 for i in arr: sum = sum +i return sum # defining an empty array arr=[] # storing values in the empty array arr = [12,3,8,75] # storing array sum in ans variable ans = sumOdArray(arr) # printing sum of array print("Sum of array is: ",ans)
#coding=utf-8 """ date:2017-08-19 @author: ray 一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。 """ a = int(raw_input("请输入一个数:\n")) x = str(a) flag = True for i in range(len(x)/2): if x[i] != x[-i-1]: flag = False break if flag: print "%d 是一个回文数!" % a else: print "%d 不是一个回文数!" % a
#coding=utf-8 """ date:2017-08-19 @author: ray 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 """ ''' a = 2.0 b = 1.0 s = 0 for n in range(1,21): s += a / b t = a a = a + b b = t print s ''' a = 2.0 b = 1.0 l = [] for n in range(1,21): l.append(a / b) b,a = a,a + b print l print reduce(lambda x, y : x + y,l)
#coding=utf-8 """ date:2017-08-17 @author: ray 题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。 程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。 """ """ for n in range(100,1000): i = n/100 #百位上的数 j = n/10%10 #十位上的数 k = n%10 #各位上的数 if n == i**3 + j**3 + k**3: print n for x in range(1,10): for y in range(0,10): for z in range(0,10): s1 = x*100 + y*10 +z s2 = pow(x,3) + pow(y,3) + pow(z,3) if s1 == s2: print s1 """ for i in range(100,1000): s = str(i) if int(s[0])**3 + int(s[1])**3 + int(s[2])**3 == i: print i
# BiYing Pan(bp483) # CS 171-062 import random random.seed() # create a setupDoors() def setupDoors(): G = 'goat' G = 'goat' C = 'car' doors = ['G', 'G', 'C'] random.shuffle(doors) return doors # create a playerDoor() def playerDoor(): return random.randint(1,3) # create a montyDoor() def montyDoor(doors, player): doors = setupDoors() player= playDoor() montyDoor = 0 while montyDoor == doors['G'] and montyDoor != player: montyDoor = random.randint(1,3) return montyDoor # create a playRound() def playRound(): doors = setupDoors() player = playerDoor() if doors[player-1] == 'C': return True if doors[player-1] == 'G': return False if __name__ =='__main__': # print title print('Welcome to Monty Hall Analysis') print('Enter \'exit\' to quit.') # stop the program when user enter 'exit' by using the loop tests=0 while tests != 'exit': tests = input('How many tests should we run? ') try: switchWin = 0 stayWin = 0 tests = int(tests) i = 0 for i in range(tests): result = playRound() if result: stayWin += 1 else: switchWin += 1 stayWinPercent = stayWin/float(tests)*100 switchWinPercent = switchWin/float(tests)*100 print('Stay Won', stayWinPercent,'% of the time.') print('Switch Won', switchWinPercent,'% of the time.') except ValueError as e: if tests != 'exit': print('Please enter a number: ') print('Thank you for using this program')
#!/bin/python #coding=gb2312 from datetime import datetime import time import datetime as dt class DateTimeTool: def __init__(self): pass @staticmethod def today(): return datetime.today().strftime('%Y%m%d') @staticmethod def todayStr(): return datetime.today().strftime('%Y-%m-%d') @staticmethod def now(): return datetime.today().strftime('%Y-%m-%d %H:%M:%S') @staticmethod def sec2time(sec): return time.strftime('%Y-%m-%d', time.localtime(float(sec))) @staticmethod def year(): return datetime.today().strftime('%Y') @staticmethod def current(): return int(1000 * time.time()) @staticmethod def incDate(oldDateStr, dateFmt='%Y-%m-%d', incDay=1): oldDate = datetime.strptime(oldDateStr, dateFmt).date() newDate = oldDate + dt.timedelta(days=incDay) return newDate.strftime(dateFmt) @staticmethod def second2str(second): str = ""; try: min = int(second) / 60 second = int(second) % 60 if min != 0: str = u"%d" % min str += (u"%d" % second) except: return str return str if __name__ == '__main__': print DateTimeTool().today() print DateTimeTool().now() print DateTimeTool().current() print DateTimeTool.sec2time(1450575000) print DateTimeTool.incDate('2016-05-05', incDay=30)
# k-Nearest Neighbor (by myself) k = 1 # Pros: simple # Cons: # computationally intensive(have to iterate through all the points) # some features are more informative than others, but it's not easy to represent that in KNN. from scipy.spatial import distance from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score iris = datasets.load_iris() X = iris.data y = iris.target x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.5) def euc(a, b): """ Calculate the Euclidean distance between points a and b """ return distance.euclidean(a, b) class ScrappyKNN: """ A scrappy k-Nearest Neighbor classifier """ def __init__(self): """ Define what's in this class """ self.x_train = x_train self.y_train = y_train def fit(self, x_train, y_train): """ a function that train the model """ def predict(self, x_test): """ a function that predict a never-before-seen data x_test """ predictions = [] for row in x_test: label = self.closest(row) predictions.append(label) return predictions def closest(self, row): """ find the closest point to the test point """ label = y_train[0] shortest_dis = euc(row, self.x_train[0]) for i in range(len(x_train)): if euc(row, self.x_train[i]) <= shortest_dis: shortest_dis = euc(row, self.x_train[i]) label = y_train[i] return label my_classifier = ScrappyKNN() # training my_classifier.fit(x_train, y_train) # predit predictions = my_classifier.predict(x_test) # 计算正确率(直接调用了一个method) print(accuracy_score(predictions, y_test)) print("成功了,哈哈")
import random a = 30 b = int(input("how mant people might show up?")) c = random.randint(1,16) food = ("Turkey","Apple Pie","Mashed Potatoes","Mac & Cheese") total = a + b + c print("Welcome to my program for Thanksgiving!") asnwer = "n" while answer != "y": for item in food: print ("We need" + str(total) + " " + item) answer = input("Do you want to keep going? Type y to exit.")