blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
2675e7a9424696fc2a057cca1ff8d093a6139c2f
potroshit/Data_science_basic_1
/class_work1/classwork1_Мезенцева.py
257
3.984375
4
name = [ "k", "s", "e", "n", "i", "a", 16] print(name) #проверка print(name[1:-1]) #задание 1 name.append("10п") print(name) #задание 2 surname = "Mezenceva" surname = list(surname) name = name + surname print(name) #задание 3
398472bec52a37a71af162adce1b17ec71fb388a
MouseOnTheKeys/small_projects
/recursion_palindrom.py
853
3.765625
4
# -*- coding: utf-8 -*- """ Created on Mon May 19:30:57 2020 @author: Nenad Bubalo 1060/19 Domaci zadatak 13: 1. U programskom jeziku Python, napisati funkciju koja rekurzivno proveravada li je dati string palindrom. String je palindrom ako se s desna na levo i s leva na desno isto čita """ # Funkcija koja rekurzivno proverava string def palindrom(x): if len(x) < 2: return True else: if x[0] == x[-1]: return palindrom(x[1:-1]) else: return False if __name__ == "__main__": # Unos trazenog stringa niska = str(input('Uneti zeljeni "string":')) if palindrom(niska) == True: print('Provera "stringa" !!! \nTrazeni string je Palindrom.\n') else: print('Provera "stringa" !!! \nTrazena string NIJE Palindrom.\n')
c6d950474777fdc034c6b0d086478eb3f9de12c1
skynette/30-days-code-challenge-day-1
/day1.py
219
3.546875
4
def twofer(name="you"): # Enter your code here. Read input from STDIN. Print output to STDOUT if name: return("One for {}, one for me.".format(name)) else: return("One for you, one for me.")
95bf80fc821ee37718c25869f217b5da8a3e83f6
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_22_ao_53/S04_Ex33.py
195
3.703125
4
""" Leia o tamanho do lado de um quadrado e imprima como resultado sua área. """ tam = float(input("Lado do quadrado: ")) area = tam * tam print("Resultado de sua área = {:.2f}".format(area))
e103f7dc1bdb8ddfeaccba17c2661cf1692aae2c
jocelinoFG017/IntroducaoAoPython
/02-Livros/IntroduçãoAProgramaçãoComPython/CapituloII/Exercicio2.1.py
252
3.875
4
""" Exercicio 2.1 Converta as seguintes expressões matemáticas para que possam ser calculadas usando o interpretador python. 10 + 20 x 30 4² ÷ 30 (9⁴ + 2) x 6-1 """ # Resposta print(10+20*30) print(4**2/30) print((9**4 +2)* 6-1)
24b16e3a48c7688365a31738ad2e12f2f41bc5dc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex03.py
247
4.1875
4
""" .3. Faça um algoritmo utilizando o comando while que mostra uma contagem regres- siva na tela, iniciando em 10 e terminando em 0. Mostrar uma mensagem 'FIM!' após a contagem. """ i = 10 while i >= 0: print(i) i = i - 1 print('FIM')
12b0ad3a799b83888c413ba1499b78b3cbe05170
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex08.py
725
4.15625
4
""" Faça um programa que leia 2 notas de um aluno, verifique se as notas são válidas e exiba na tela a média destas notas. Uma nota válida deve ser, obrigatoriamente, um valor entre 0.0 e 10.0, onde caso a nota possua um valor válido, este fato deve ser informado ao usuário e o programa termina. """ nota1 = float(input("Informe a nota1: ")) nota2 = float(input("Informe a nota2: ")) media = (nota1+nota2)/2 if (nota1 >= 0.0) and (nota1 <= 10.0) and (nota2 >= 0.0) and (nota2 <= 10.0): print(f"Nota1 válida = {nota1}") print(f"Nota2 válida = {nota2}") print("Média = {:.2f}".format(media)) else: print("Uma das notas é inválida") print("Tente outra vez com valores válidos de 0.0 a 10.0")
6e253a61bbec738313c6751af19db42204402edf
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_22_ao_53/S04_Ex27.py
287
3.578125
4
""" Leia um valor de área em hectares e apresente-o em metros quadrados m². A fórmula de conversão é: M = H * 10.000, sendo M a área em m² e H a área em hectares. """ area = float(input("Valor da hectares: ")) convert = area * 10.000 print("Em m² fica: {:.4f}".format(convert))
677274c5c2e5ef86e3090e5501182c28e1d7acf3
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex21.py
1,216
4.15625
4
""" Escreva o menu de opções abaixo. Leia a opção do usuário e execute a operação escolhida. Escreva uma mensagem de erro se a opção for inválida. Escolha a opção: 1 - Soma de 2 números. 2 - Diferença entre 2 números. (maior pelo menor). 3 - Produto entre 2 números. 4 - Divisão entre 2 números (o denominador não pode ser zero). opção = """ print(" ---- Informe sua escolha abaixo ---- ") print("1 - Soma ") print("2 - Diferença (M-m)") print("3 - Produto ") print("4 - Divisão ") op = int(input("Escolha de opção: ")) if (op > 0) and (op < 5): n1 = int(input("1º Número: ")) n2 = int(input("2º Número: ")) if op == 1: print("{} + {} = {}".format(n1, n2, n1+n2)) elif op == 2: if n1 > n2: print("{} - {} = {}".format(n1, n2, n1 - n2)) else: print("{} - {} = {}".format(n1, n2, n2 - n1)) elif op == 3: print("{} * {} = {}".format(n1, n2, n1 * n2)) else: # numerador = n1 denominador = n2 if denominador == 0: print("O denominador(n2) não pode ser zero") else: print("{} / {} = {:.2f}".format(n1, n2, n1 / n2)) else: print("Opção inválida.")
6bdaa9fca5f74779af13721837fc1bf30625af36
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_22_ao_41/S05_Ex28.py
1,237
4.15625
4
""" .28. Faça um programa que leia três números inteiros positivos e efetue o cálculo de uma das seguintes médias de acordo com um valor númerico digitado pelo usuário. - (a) Geométrica : raiz³(x * y * z) - (b) Ponderada : (x + (2 * y) + (3 * z)) / 6 - (c) Harmônica : 1 / (( 1 / x) + (1 / y) + (1 / z)) - (d) Aritmética: (x + y + z)/3 """ x = int(input("Informe o valor de X: ")) y = int(input("Informe o valor de Y: ")) z = int(input("Informe o valor de Z: ")) print("A - Geométrica") print("B - Ponderada") print("C - Harmônica") print("D - Aritmética") op = input("Escolha uma média acima: ") geometrica = (x * y * z) ** (1/3) ponderada = (x + (2 * y) + (3 * z)) / 6 harmonica = 1 / (( 1 / x) + (1 / y) + (1 / z)) aritmetica = (x + y + z)/3 if op == "A" or op == "a": print("A - Geométrica escolhida \n") print("Média = {:.2f}".format(geometrica)) elif op == "B" or op == "b": print("B - Ponderada escolhida \n") print("Média = {:.2f}".format(ponderada)) elif op == "C" or op == "c": print("C - Harmônica escolhida \n") print("Média = {:.2f}".format(harmonica)) elif op == "D" or op == "d": print("D - Aritmética escolhida \n") print("Média = {:.2f}".format(aritmetica))
a3922a8d8afbea816fa87015c6fd318ef1eb4efc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_1_ao_21/S04_Ex18.py
307
3.875
4
""" Leia um valor de volume em metros cúbicos m³ e apresente-o convertido em litros. A formula de conversão é: L = 1000*M, sendo L o volume em litros e M o volume em metros cúbicos. """ volume = float(input("Valor Volume(m³): ")) convert = volume*1000 print("Em Litros fica: {:.2f}".format(convert))
031f74a6547ec84a7815735874badd864e191acf
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_22_ao_41/S06_Ex29.py
309
3.609375
4
""" .29. Faça um programa para calcular o valor da série, para 5 termos. - S = 0 + 1/2! + 1/4! + 1/6 +... """ from math import factorial soma = 0 termos = 5 for i in range(1, termos + 1): if i % 2 == 0: # Condição para encontrar valores pares soma = soma + 1/factorial(i) print(soma)
cf90f34f7fac4c7ec15afdb130ccc715ca5b9598
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex06.py
412
3.984375
4
""" Escreva um programa que, dado dois números inteiros, mostre na tela o maior deles, assim como a diferença existente entre ambos. """ n1 = int(input("Informe um número: ")) n2 = int(input("Informe outro número: ")) dif = 0 if n1 > n2: print(f"O maior: {n1}") dif = n1 - n2 print(f"A diferença: : {dif}") else: print(f"O maior: {n2}") dif = n2 - n1 print(f"A diferença: {dif} ")
28473894237479028f7090828351d147a1f439b5
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_22_ao_41/S06_Ex24.py
345
4
4
""" .24. Escreva um programa que leia um número inteiro e calcule a soma de todos os divisores desse numero, com exceção dele próprio. EX: a soma dos divisores do número 66 é 1 + 2 + 3 + 6 + 11 + 22 + 33 = 78 """ n = int(input('Informe um numero: ')) soma = 0 for i in range(1, n): if n % i == 0: soma = soma + i print(soma)
ab98f9c6ff4f60984dba33b33038588020bae6bc
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex13.py
645
4.21875
4
""" Faça um algoritmo que calcule a média ponderada das notas de 3 provas. A primeira e a segunda prova tem peso 1 e a terceira tem peso 2. Ao final, mostrar a média do aluno e indicar se o aluno foi aprovado ou reprovado. A nota para aprovação deve ser igual ou superior a 60 pontos. """ nota1 = float(input("nota1: ")) nota2 = float(input("nota2: ")) nota3 = float(input("nota3: ")) divisor = ((nota1 * 1) + (nota2 * 1) + (nota3 * 2)) dividendo = 1 + 1 + 2 media = divisor/dividendo if media >= 6.0: print("Aprovado") print("Media = {:.2f}".format(media)) else: print("Reprovado") print("Media = {:.2f}".format(media))
47d4adf6d6e33bc0578eaf576cb5d81821261d60
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex04.py
354
4.09375
4
""" Faça um programa que leia um número e, caso ele seja positivo, calcule e mostre: - O número digitado ao quadrado - A raiz quadrada do número digitado """ n = float(input("Informe um número: ")) rq = pow(n, 1/2) if n >= 0: print("{} ao quadrado é = {:.2f}: ".format(n, n ** 2)) print("Raiz Quadrada de {} é = {:.2f}: ".format(n, rq))
51f0f4a8aecd6bdff88482d13c6813501689f2b4
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção05-Estruturas_Lógicas_e_Condicionais/Exs_1_ao_21/S05_Ex17.py
602
3.921875
4
""" Faça um programa que calcule e mostre a área de um trapézio. Sabe-se que: - A = ((baseMaior + baseMenor)*altura)/2 Lembre-se a base MAIOR e a base menor devem ser números maiores que zero. """ baseMaior = float(input("BaseMaior: ")) baseMenor = float(input("BaseMenor: ")) altura = float(input("Altura: ")) if baseMaior > 0: if baseMenor > 0: area = ((baseMaior + baseMenor) * altura) / 2 print("A área do trapézio é = {:.2f}".format(area)) else: print("A baseMenor deve ser maior que zero(0)") else: print("A baseMaior deve ser maior que zero(0)")
efef90bd4f05f5d84f10e44e9422e3329e1d3e98
jocelinoFG017/IntroducaoAoPython
/02-Livros/IntroduçãoAProgramaçãoComPython/CapituloV/Exercicio5.2.py
182
4.40625
4
""" # O programa do livro x =1 while x <= 3: print(x) x = x +1 #Modifique o programa para exibir os números de 1 a 100 """ x = 50 while x <= 100: print(x) x = x +1
bb84e63b12ca692da1a1277fa62b6400bfe278a2
jocelinoFG017/IntroducaoAoPython
/02-Livros/IntroduçãoAProgramaçãoComPython/CapituloIV/Exercicio4.3.py
754
3.9375
4
""" Escreva um programa que leia três números e que imprima o maior e o menor """ n1 = int(input()) n2 = int(input()) n3 = int(input()) if (n1>n2) and (n1>n3): # n1 > n2 and n3 if (n2>n3): #n1>n2>n3 print("maior:",n1) print("menor:",n3) if (n3>n2): # n1>n3>n2 print("maior:", n1) print("menor:", n2) if (n2>n1) and (n2 > n3):# n2> n1 and n3 if (n1>n3): #n2>n1>n3 print("maior:",n2) print("menor:",n3) if (n3>n1): # n2>n3>n1 print("maior:", n2) print("menor:", n1) if (n3>n1) and (n3 > n2): # n3 > n1 and n2 if (n1>n2): #n3>n1>n2 print("maior:",n3) print("menor:",n2) if (n2>n1): # n3>n2>n1 print("maior:", n3) print("menor:", n1)
d80274fec662b690fff77f8900d4c6b5c25bb132
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção10-Expressões_Lambdas_e_Funções_Integradas/MinAndMax.py
1,784
4.28125
4
""" Min() e Max() max() -> retorna o maior valor ou o maior de dois ou mais elementos # Exemplos lista = [1, 2, 8, 4, 23, 123] print(max(lista)) tupla = (1, 2, 8, 4, 23, 123) print(max(tupla)) conjunto = {1, 2, 8, 4, 23, 123} print(max(conjunto)) dicionario = {'a': 1, 'b': 2, 'c': 8, 'd': 4, 'e': 23, 'f': 123} print(max(dicionario.values())) # Faça um programa que receba dois valores e retorna o maior valor vlr1 = int(input("VALOR 1: ")) vlr2 = int(input("VALOR 2: ")) print(max(vlr1, vlr2)) print(max(1, 34, 15, 65, 12)) print(max('a', 'abc', 'ab')) print(max('a', 'b','c', 'g')) min() -> Contrário do max() # outros exemplos nomes = ['Arya', 'Joel', 'Dora', 'Tim', 'Ollivander'] print(max(nomes)) print(min(nomes)) print(max(nomes, key=lambda nome: len(nome))) print(min(nomes, key=lambda nome: len(nome))) """ musicas = [ {"titulo": "Thunderstruck", "tocou": 3}, {"titulo": "Dead Skin Mask", "tocou": 2}, {"titulo": "Back in Black", "tocou": 4}, ] print(max(musicas, key=lambda musica: musica['tocou'])) print(min(musicas, key=lambda musica: musica['tocou'])) # DESAFIO! imprimir o titulo da musica mais e menos tocada print('desafio') print(max(musicas, key=lambda musica: musica['tocou'])['titulo']) print(min(musicas, key=lambda musica: musica['tocou'])['titulo']) # DESAFIO! imprimir o titulo da musica mais e menos tocada sem usar o min(), max() e lambda print('desafio 2') max = 0 for musica in musicas: if musica['tocou'] > max: max = musica['tocou'] for musica in musicas: if musica['tocou'] == max: print(musica['titulo']) min = 99999 for musica in musicas: if musica['tocou'] < min: min = musica['tocou'] for musica in musicas: if musica['tocou'] == min: print(musica['titulo'])
a7b48d30123753ea5c87b79acff9e6ef0c1e0fba
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex15.py
239
3.921875
4
""" .15.Faça um programa que leia um número inteiro positivo impar N e imprima todos os números impares de 0 até N em ordem crescente. """ n = int(input('Informe um numero: ')) for i in range(0, n): if i % 2 == 1: print(i)
0d330f98177358d5bf90bae0b6b73d6c73668a4a
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex08.py
333
3.875
4
""" .8. Escreva um programa que leia 10 números e escreva o menor valor lido e o maior valor lido. """ maior = 0 menor = 999999 for i in range(0, 5): num = int(input(f'Informe o valor {i+1}: ')) if num > maior: maior = num if num < menor: menor = num print(f'maior = {maior}') print(f'menor = {menor}')
0f387b4432f970d10a67347d58f4e1aa6983b75d
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_22_ao_53/S04_Ex48.py
289
3.765625
4
""" Leia um valor inteiro em segundos, e imprima-o em horas, minutos e segundos. """ x = int(input()) hora = x // 3600 resto = x % 3600 minutos = resto // 60 resto= resto % 60 seg = resto // 1 print("{}h:{}m:{}s".format(hora, minutos, seg)) # print("{} horas : {} min: {} seg".format())
d57e86a7d82801e5c0485ffa94211f0025e08acf
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção04-Váriaveis_e_tipos_de_dados/Exs_1_ao_21/S04_Ex16.py
336
3.890625
4
""" Leia um valor de comprimento em polegadas e apresente-o convertido em centimetros. a formula de conversão é: C = P*2.54, sendo C o comprimento de centimetros e P o comprimento em polegadas. """ comprimento = float(input("Valor Comprimento(pol): ")) convert = comprimento * 2.54 print("Em centimetros fica: {:.2f}".format(convert))
79b58db5b932f19b7f71f09c37c3942554507803
RjPatil27/Python-Codes
/Sock_Merchant.py
840
4.1875
4
''' John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n = 7 socks with colors arr = [1,2,1,2,3,2,1] . There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2 . Write code for this problem. ''' from __future__ import print_function def main(): n = int(input().strip()) c = list(map(int, input().strip().split(' '))) pairs = 0 c.sort() c.append('-1') i = 0 while i < n: if c[i] == c[i + 1]: pairs = pairs + 1 i += 2 else: i += 1 print(pairs) if __name__ == '__main__': main()
bbc6900a6123bd2cfe9c1bb832bee170e7c025d8
RjPatil27/Python-Codes
/PrimeNo.py
419
4.0625
4
# Python Program - Check Prime Number or Not print("Enter 'x' for exit.") num = input("Enter any number: ") if num == 'x': exit(); try: number = int(num) except ValueError: print("Please, enter a number...exiting...") else: for i in range(2, number): if number%i == 0: print(number, "is not a prime number.") break; else: print(number, "is a prime number.") break;
6fc26692c43e63efbce1678792fff2845a3953a5
VIKGO123/Using-Pandas-library-in-python
/csvshow.py
374
3.53125
4
import matplotlib.pyplot as plt import csv x=[] y=[] with open('test.csv','r') as csvfile: plots=csv.reader(csvfile)#reads file for row in plots: #accessing row by row x.append((row[0])) #accessing first element of row y.append((row[1])) #accessing 2nd element of row plt.plot(x,y,label='File') plt.xlabel('x') plt.ylabel('y') plt.show()
05432b48af09dc9b89fded6fb53181df2645ee53
Mat4wrk/Working-with-Dates-and-Times-in-Python-Datacamp
/1.Dates and Calendars/Putting a list of dates in order.py
569
4.375
4
"""Print the first and last dates in dates_scrambled."" # Print the first and last scrambled dates print(dates_scrambled[0]) print(dates_scrambled[-1]) """Sort dates_scrambled using Python's built-in sorted() method, and save the results to dates_ordered.""" """Print the first and last dates in dates_ordered.""" # Print the first and last scrambled dates print(dates_scrambled[0]) print(dates_scrambled[-1]) # Put the dates in order dates_ordered = sorted(dates_scrambled) # Print the first and last ordered dates print(dates_ordered[0]) print(dates_ordered[-1])
df540eae1ad91815ed2a578cc9fbf175b0fcb7e9
vytran0710/CS106.K21.KHCL
/TH/TH1/Bai 3/Bai3_IDS.py
1,117
3.609375
4
from collections import defaultdict class Graph: def __init__(self,vertices): self.V = vertices self.graph = defaultdict(list) def addEdge(self,u,v): self.graph[u].append(v) def DLS(self,src,target,maxDepth): if src == target : return True if maxDepth <= 0 : return False for i in self.graph[src]: if(self.DLS(i,target,maxDepth-1)): return True return False def IDDFS(self,src, target, maxDepth): for i in range(maxDepth): if (self.DLS(src, target, i)): return True return False g = Graph (10); g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 3) g.addEdge(1, 4) g.addEdge(2, 5) g.addEdge(2, 6) g.addEdge(3, 7) g.addEdge(4, 8) g.addEdge(5, 9) target = 0; maxDepth = 1; src = 0 if g.IDDFS(src, target, maxDepth) == True: print ("Found target within max depth") else : print ("Not Found target within max depth") #Tham khao: https://www.geeksforgeeks.org/iterative-deepening-searchids-iterative-deepening-depth-first-searchiddfs/
dbd92d328c883c792554926aae4de04d22ccb149
changzheng1993/map
/recommend.py
8,834
3.59375
4
# CS 61A Spring 2015 # Name: Zheng Chang # Login: cs61a-aep """A Yelp-powered Restaurant Recommendation Program""" from abstractions import * from utils import distance, mean, zip, enumerate, sample from visualize import draw_map from data import RESTAURANTS, CATEGORIES, USER_FILES, load_user_file from ucb import main, trace, interact def find_closest(location, centroids): """Return the item in CENTROIDS that is closest to LOCATION. If two centroids are equally close, return the first one. >>> find_closest([3, 4], [[0, 0], [2, 3], [4, 3], [5, 5]]) [2, 3] """ "*** YOUR CODE HERE ***" return min(centroids, key=lambda x: distance(location, x)) def group_by_first(pairs): """Return a list of pairs that relates each unique key in [key, value] pairs to a list of all values that appear paired with that key. Arguments: pairs -- a sequence of pairs >>> example = [ [1, 2], [3, 2], [2, 4], [1, 3], [3, 1], [1, 2] ] >>> group_by_first(example) [[2, 3, 2], [4], [2, 1]] """ # Optional: This implementation is slow because it traverses the list of # pairs one time for each key. Can you improve it? keys = [] for key, _ in pairs: if key not in keys: keys.append(key) return [[y for x, y in pairs if x == key] for key in keys] def group_by_centroid(restaurants, centroids): """Return a list of lists, where each list contains all restaurants nearest to some item in CENTROIDS. Each item in RESTAURANTS should appear once in the result, along with the other restaurants nearest to the same centroid. No empty lists should appear in the result. """ "*** YOUR CODE HERE ***" pairs = [] # list of pair of centroid and restraurant for restaurant in restaurants: location = restaurant_location(restaurant) # find the closest centroid by location of the restaurant centroid = find_closest(location, centroids) if centroid is not None: pairs.append([centroid, restaurant]) return group_by_first(pairs) # group restaurants by centroid def find_centroid(restaurants): """Return the centroid of the locations of RESTAURANTS.""" "*** YOUR CODE HERE ***" # list of locations of restaurants locations = [restaurant_location(restaurant) for restaurant in restaurants ] latitudes = [location[0] for location in locations] # list of latitude of location list longitudes = [location[1] for location in locations] # list of longitude of locations return [mean(latitudes), mean(longitudes) ] # mean of latitude list and longitude list def k_means(restaurants, k, max_updates=100): """Use k-means to group RESTAURANTS by location into K clusters.""" assert len(restaurants) >= k, 'Not enough restaurants to cluster' old_centroids, n = [], 0 # Select initial centroids randomly by choosing K different restaurants centroids = [restaurant_location(r) for r in sample(restaurants, k)] while old_centroids != centroids and n < max_updates: old_centroids = centroids "*** YOUR CODE HERE ***" # group restaurants by the closest centroid centroid_restaurants = group_by_centroid(restaurants, centroids) # get the centroid of the each grouped restaurants centroids = [find_centroid(x) for x in centroid_restaurants] n += 1 return centroids def find_predictor(user, restaurants, feature_fn): """Return a rating predictor (a function from restaurants to ratings), for USER by performing least-squares linear regression using FEATURE_FN on the items in RESTAURANTS. Also, return the R^2 value of this model. Arguments: user -- A user restaurants -- A sequence of restaurants feature_fn -- A function that takes a restaurant and returns a number """ reviews_by_user = {review_restaurant_name(review): review_rating(review) for review in user_reviews(user).values()} xs = [feature_fn(r) for r in restaurants] ys = [reviews_by_user[restaurant_name(r)] for r in restaurants] "*** YOUR CODE HERE ***" mean_x = mean(xs) mean_y = mean(ys) lst = zip(xs, ys) Sxx, Syy, Sxy = 0, 0, 0 for each in lst: x = each[0] y = each[1] Sxx += (x-mean_x)*(x-mean_x) Syy += (y-mean_y)*(y-mean_y) Sxy += (x-mean_x)*(y-mean_y) b = Sxy / Sxx a = mean_y - b*mean_x r_squared = (Sxy*Sxy) /(Sxx*Syy) def predictor(restaurant): return b * feature_fn(restaurant) + a return predictor, r_squared def best_predictor(user, restaurants, feature_fns): """Find the feature within FEATURE_FNS that gives the highest R^2 value for predicting ratings by the user; return a predictor using that feature. Arguments: user -- A user restaurants -- A dictionary from restaurant names to restaurants feature_fns -- A sequence of functions that each takes a restaurant """ reviewed = list(user_reviewed_restaurants(user, restaurants).values()) "*** YOUR CODE HERE ***" # find the predictor of max r_squared max_predictor = max([find_predictor(user, reviewed, feature_fn) for feature_fn in feature_fns], key=lambda x: x[1] ) # return the predictor function return max_predictor[0] def rate_all(user, restaurants, feature_functions): """Return the predicted ratings of RESTAURANTS by USER using the best predictor based a function from FEATURE_FUNCTIONS. Arguments: user -- A user restaurants -- A dictionary from restaurant names to restaurants """ # Use the best predictor for the user, learned from *all* restaurants # (Note: the name RESTAURANTS is bound to a dictionary of all restaurants) predictor = best_predictor(user, RESTAURANTS, feature_functions) "*** YOUR CODE HERE ***" all_ratings = {} reviewed = list(user_reviewed_restaurants(user, restaurants).keys()) rating = 0 for each in restaurants.keys(): # if the restaurant is reviewed, use the rating reviewed by the user if each in reviewed: rating = user_rating(user, each) # use the best predictor to predict the rating for the non-reviewed restaurant else: rating= predictor(restaurants[each]) all_ratings[each] =rating return all_ratings def search(query, restaurants): """Return each restaurant in RESTAURANTS that has QUERY as a category. Arguments: query -- A string restaurants -- A sequence of restaurants """ "*** YOUR CODE HERE ***" return [x for x in restaurants if query in restaurant_categories(x)] def feature_set(): """Return a sequence of feature functions.""" return [restaurant_mean_rating, restaurant_price, restaurant_num_ratings, lambda r: restaurant_location(r)[0], lambda r: restaurant_location(r)[1]] @main def main(*args): import argparse parser = argparse.ArgumentParser( description='Run Recommendations', formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument('-u', '--user', type=str, choices=USER_FILES, default='test_user', metavar='USER', help='user file, e.g.\n' + '{{{}}}'.format(','.join(sample(USER_FILES, 3)))) parser.add_argument('-k', '--k', type=int, help='for k-means') parser.add_argument('-q', '--query', choices=CATEGORIES, metavar='QUERY', help='search for restaurants by category e.g.\n' '{{{}}}'.format(','.join(sample(CATEGORIES, 3)))) parser.add_argument('-p', '--predict', action='store_true', help='predict ratings for all restaurants') args = parser.parse_args() # Select restaurants using a category query if args.query: results = search(args.query, RESTAURANTS.values()) restaurants = {restaurant_name(r): r for r in results} else: restaurants = RESTAURANTS # Load a user assert args.user, 'A --user is required to draw a map' user = load_user_file('{}.dat'.format(args.user)) # Collect ratings if args.predict: ratings = rate_all(user, restaurants, feature_set()) else: restaurants = user_reviewed_restaurants(user, restaurants) ratings = {name: user_rating(user, name) for name in restaurants} # Draw the visualization restaurant_list = list(restaurants.values()) if args.k: centroids = k_means(restaurant_list, min(args.k, len(restaurant_list))) else: centroids = [restaurant_location(r) for r in restaurant_list] draw_map(centroids, restaurant_list, ratings)
619f65ba890f6fa2e891f197581b739f02baae40
Jmwas/Pythagorean-Triangle
/Pythagorean Triangle Checker.py
826
4.46875
4
# A program that allows the user to input the sides of any triangle, and then # return whether the triangle is a Pythagorean Triple or not while True: question = input("Do you want to continue? Y/N: ") if question.upper() != 'Y' and question.upper() != 'N': print("Please type Y or N") elif question.upper() == 'Y': a = input("Please enter the opposite value: ") print("you entered " + a) b = input("Please enter the adjacent value: ") print("you entered " + b) c = input("Please enter the hypotenuse value: ") print("you entered " + c) if int(a) ** 2 + int(b) ** 2 == int(c) ** 2: print("The triangle is a pythagorean triangle") else: print("The triangle is not a pythagorean triangle") else: break
6273ea18be6a76f5d37c690837830f34f7c516e4
cahill377979485/myPy
/正则表达式/命名组.py
1,351
4.46875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Python 2.7的手册中的解释: (?P<name>...) Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. So the group named id in the example below can also be referenced as the numbered group 1. For example, if the pattern is (?P<id>[a-zA-Z_]\w*), the group can be referenced by its name in arguments to methods of match objects, such as m.group('id') or m.end('id'), and also by name in the regular expression itself (using (?P=id)) and replacement text given to .sub() (using \g<id>). """ import re # 将匹配的数字乘以 2 def double(matched): value = int(matched.group('value')) return str(value * 2) def double2(matched): value = int(matched.group(1)) return str(value * 2) s = 'A23G4HFD567' # 用命名group的方式 print(re.sub('(?P<value>\\d+)', double, s)) # ?P<value>的意思就是命名一个名字为value的group,匹配规则符合后面的/d+,具体文档看上面的注释 # 用默认的group带数字的方式 print(re.sub('(\\d+)', double2, s))
bf359f264311bd83105764a70207a67360835493
valerie-bernstein/Moon-and-Magnetotail
/x_rotation_matrix.py
300
3.703125
4
import numpy as np def x_rotation_matrix(theta): #rotation by the angle theta (in radians) about the x-axis #returns matrix of shape (3,3) rotation_matrix = np.array([[1, 0, 0], [0, np.cos(theta), np.sin(theta)], [0, -np.sin(theta), np.cos(theta)]]) return rotation_matrix
6b1aa9476e1deb167321b3c37c88e8c517b13e8a
sivaprasad0/AssignmentsDaily
/Aug11/palindrome.py
237
3.859375
4
name=input("enter a palindrme: ") l= len(name) i=0 count=0 for i in range(0,(l+1)//2): if name[i]==name[l-1-i]: pass else: count=count+1 break if count==0: print(name," is palindrome") else: print(name,"is not a palindrome")
0c6fcfa855bc02ebc378e1f5d0c1e5bc5014d5b1
HeloiseKatharine/Bioinformatica
/Atividade 1/3.py
821
4.125
4
''' Crie um programa em python que receba do usuário uma sequência de DNA e retorne a quantidade de possíveis substrings de tamanho 4 (sem repetições). Ex.: Entrada: actgactgggggaaa Após a varredura de toda a sequência achamos as substrings actg, ctga, tgac, gact, ctgg, tggg, gggg, ggga, ggaa, gaaa, logo a saída do programa deve ser: Saída: 10 ''' seq = input('Digite a sequência de DNA: ')#recebe a sequência de DNA tam_seq = len(seq) #tamanho da string seq tam_sub = 4 #declarando o tamanho da substring dic_sub = dict() for i in range(tam_seq - tam_sub + 1): #percorre toda a string sub = seq[i:i+tam_sub] #percorre a sequência de acordo com o tamanho da substring if(sub in dic_sub): dic_sub[sub] += 1 else: dic_sub[sub] = 1 quant = len(dic_sub.keys()) print (quant)
7a3f6276f0a8346e840ab8069e1802370a2abcf5
JimmyBowden/IT780
/C4.py
1,484
3.546875
4
#Jimmy Bowden #IT780 #C4 import csv #-----------------Var #-----------------Functions def readNameCSV(): myList = [] fName = 'People.csv' with open(fName, 'r') as inFile: line = inFile.readline() while line != "": nameList = line.split(",") myList.append(nameList[0]) line = inFile.readline() #print(myList) return myList def readRatingCSV(nameList): myRatingDict = {} myFinalDict = {} for item in nameList: myFinalDict[item] = {} #print(myFinalDict) fName = 'Ratings.csv' with open(fName, 'r') as inFile: line = inFile.readline() count = 0 while line != "": ratingList = line.split(",") val = ratingList[2].strip() myFinalDict[ratingList[1]][ratingList[0]] = float(val) #myFinalDict[ratingList[1]] ({ratingList[0] : float(val)}) #print(ratingList[0], ratingList[2]) #myList.append(nameList[0]) line = inFile.readline() count = count + 1 #print(count) return myFinalDict def orderDictionary(myDict): myDictList = [] for key in myDict: temp = () temp = [myDict[key], key[0]] myDictList.append(temp) sortedDictList = sorted(myDictList, reverse=True) return sortedDictList #-----------------Main dictList = readNameCSV() myDict = readRatingCSV(dictList) #sortedDictList = orderDictionary(myDict) #print(myDict)
0d43af9ffd13bc33c8691eba0cb4a01ec2f2efae
JimmyBowden/IT780
/C8.py
4,778
3.734375
4
#Jimmy Bowden #C8.py from math import sqrt import C4 class myRecommender: def __init__(self): from math import sqrt def manhattan(self, rating1, rating2): """Computes the Manhattan distance. Both rating1 and rating2 are dictionaries """ distance = 0 commonRatings = False for key in rating1: if key in rating2: distance += abs(rating1[key] - rating2[key]) commonRatings = True if commonRatings: return distance else: return -1 #Indicates no ratings in common def minkowski(self, rating1, rating2, r): distance = 0 commonRatings = False for key in rating1: if key in rating2: distance += pow((abs(float(rating1[key]) - float(rating2[key]))), r) commonRatings = True if commonRatings: distance = pow(distance,(1/r)) return distance else: return -1 #Indicates no ratings in common def euclidean(self, rating1, rating2): distance = 0 commonRatings = False for key in rating1: if key in rating2: distance += (rating1[key] - rating2[key]) ** 2 commonRatings = True if commonRatings: distance = sqrt(distance) return distance else: return -1 #Indicates no ratings in common def computeNearestNeighbor(self, username, users, r, Pearson = False): """creates a sorted list of users based on their distance to username""" distances = [] for user in users: if user != username: if Pearson == True: #print(user) distance = self.pearson(users[user], users[username]) else: distance = self.minkowski(users[user], users[username], r) distances.append((distance, user)) # sort based on distance -- closest first distances.sort(reverse=Pearson) return distances def recommend(self, username, users, r, Pearson = False): """Give list of recommendations""" # first find nearest neighbor if Pearson == True: nearest = self.computeNearestNeighbor(username, users, r, True)[0][1] else: nearest = self.computeNearestNeighbor(username, users, r)[0][1] recommendations = [] # now find bands neighbor rated that user didn't neighborRatings = users[nearest] userRatings = users[username] for artist in neighborRatings: if not artist in userRatings: recommendations.append((artist, neighborRatings[artist])) #print(recommendations) # using the fn sorted for variety - sort is more efficient return sorted(recommendations, key=lambda artistTuple: artistTuple[1], reverse = True) def pearson(self, rating1, rating2): sum_xy = 0 sum_x = 0 sum_y = 0 sum_x2 = 0 sum_y2 = 0 n = 0 for key in rating1: if key in rating2: n += 1 x = rating1[key] y = rating2[key] sum_xy += x * y sum_x += x sum_y += y sum_x2 += pow(x, 2) sum_y2 += pow(y, 2) if n == 0: return 0 # now compute denominator denominator = (sqrt(sum_x2 - pow(sum_x, 2) / n) * sqrt(sum_y2 - pow(sum_y, 2) / n)) if denominator == 0: return 0 else: return (sum_xy - (sum_x * sum_y) / n) / denominator def mainRun(self): dictList = C4.readNameCSV() myDict = C4.readRatingCSV(dictList) myInput = input("Enter a name: ").capitalize() manTest1 = computeNearestNeighbor(myInput, myDict, 1) manTest2 = recommend(myInput, myDict, 1) print("Manhattan:") print("Nearest Neighhbors: ", manTest1) print("Recommendations: ", manTest2) print("") euTest1 = computeNearestNeighbor(myInput, myDict, 2) euTest2 = recommend(myInput, myDict, 2) print("Eucledian:") print("Nearest Neighhbors: ", euTest1) print("Recommendations: ", euTest2) print("") pearTest1 = computeNearestNeighbor(myInput, myDict, 1, True) pearTest2 = recommend(myInput, myDict, 1, True) print("Pearson:") print("Nearest Neighhbors: ", pearTest1) print("Recommendations: ", pearTest2) print("") #-----------------------------Main--------------------------------- #mainRun()
068596b0d357250adba6202530cd94d150e71532
dpdi-unifor/juicer
/juicer/scikit_learn/util.py
1,439
4
4
import numpy as np def get_X_train_data(df, features): """ Method to convert some Pandas's columns to the Sklearn input format. :param df: Pandas DataFrame; :param features: a list of columns; :return: a DataFrame's subset as a list of list. """ column_list = [] for feature in features: # Validating OneHotEncode data existence if isinstance(df[feature].iloc[0], list): column_list.append(feature) columns = [col for col in features if col not in column_list] tmp1 = df[columns].to_numpy() if (len(column_list) > 0): tmp2 = df[column_list].sum(axis=1).to_numpy().tolist() output = np.concatenate((tmp1, tmp2), axis=1) elif len(features) == 1: output = tmp1.flatten() else: output = tmp1 return output.tolist() def get_label_data(df, label): """ Method to check and convert a Panda's column as a Python built-in list. :param df: Pandas DataFrame; :param labels: a list of columns; :return: A column as a Python list. """ # Validating multiple columns on label if len(label) > 1: raise ValueError(_('Label must be a single column of dataset')) # Validating OneHotEncode data existence if isinstance(df[label[0]].iloc[0], list): raise ValueError(_('Label must be primitive type data')) y = df[label].to_numpy().tolist() return np.reshape(y, len(y))
ce47e80b7965d38045d0c2a6aac967fca7435217
sophiezeng1215/Algorithms
/Algorithm/Binary Tree Preorder Traversal.py
766
3.9375
4
#Time O(n), space O(n) #append node.val, use a stack to store node.right(only), and then move node to the left, and # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == []: return stack = [] vals = [] node = root while stack or node: if node: vals.append(node.val) stack.append(node.right) node = node.left else: node = stack.pop() return vals
eea37504d1e1776291a20d3517bb601bc31e1970
sophiezeng1215/Algorithms
/Algorithm/Reverse Linked List.py
536
3.859375
4
#Use "prev" and 'temp' = node.next; return prev #Time O(n), space O(1) # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ node = head prev = None while node: temp = node.next node.next = prev prev = node node = temp return prev
c78396501abd25be740492c42842b70d60532af0
yugalsherchan1991/python-project
/funcitons.py
2,133
4
4
#%% def evalQuadratic(a, b, c, x): ''' a, b, c: numerical values for the coefficients of a quadratic equation x: numerical value at which to evaluate the quadratic. ''' return (a * x*x) + (b * x) + c evalQuadratic (1,2,3,4) # %% def f(x,y): x = x + y print ("In f(x,y) : x and y: ",x ,y) return x x = 2 y = 2 f(x,y) # %% def a(x): return x + 1 a(a(a(6))) # %% def a(x, y, z): if x: return y else: return z a(3>2,a,b) # %% def b(q, r): return a(q>r, q, r) b(2,3) # %% x = 12 def g(x): x = x + 1 def h(y): return x + y return h(6) g(x) # %% str1 = "exterminate!" #str1.count('e') #str1.upper #str1.upper() str1 = str1.replace('e','*') str1 # %% str2 = "number one - the larch" #str2 = str2.capitalize() #str2.swapcase() str2.find('') #str2.replace("one", "seven") #str2.find('!') # %% str = "basically that is not that hard" str.replace('that', 'which') # %% #Recursive method for iteration def multi(base,exp): if exp <= 0: return 1 else: return base * multi(base, exp-1) multi(-1.99,0) # %% """ Write an iterative function iterPower(base, exp) that calculates the exponential base,exp by simply using successive multiplication. For example, iterPower(base, exp) should compute base,exp by multiplying base times itself exp times. Write such a function below. """ def iterPower(base,exp): result = 1 while exp > 0: result *= base exp -= 1 return result iterPower(4,5) # %% def gcd(a,b): ''' a and b is positive integer value returns: a positive interger the greated common divisor of a and b. ''' testvalue = min(a, b) while a % testvalue != 0 or b % testvalue != 0: testvalue -= 1 return testvalue gcd(9,12) # %% #This is the recursive solution to find the GCD between two integers a and b def gcdRecur(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if b == 0: return a else: return gcdRecur(b,a%b) gcdRecur(9,12) # %%
dfaf1ef03730da91c867e734c4c33efb86310c06
mbernste/bio-sequence-tools
/bio_sequence/rand_seq.py
800
3.796875
4
#!/usr/bin/python import sys import random from sequence import Sequence import fasta NUCLEOTIDES = ['A', 'C', 'T', 'G'] def randNucleotide(): i = random.randint(0, 3) return NUCLEOTIDES[i] def randNucleotideExlude(excludedNucleotides): pickFrom = [nucl for nucl in NUCLEOTIDES if nucl not in excludedNucleotides] i = random.randint(0, len(pickFrom)-1) return pickFrom[i] def genSequence(length): seq = "" for i in range(0, length): seq += randNucleotide() return seq def randomSequence(name, length): seq = genSequence(length) return Sequence(name, seq) def main(): name = sys.argv[1] length = int(sys.argv[2]) seq = randomSequence(name, length) print fasta.formatSequenceToFasta(seq) if __name__ == "__main__": main()
498986037d33c74ded5f9aba97d7448979aca830
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 32/remove nth node.py
545
3.53125
4
# username: shantanugupta1118 # Day 32 of 100 Days # 19. Remove Nth Node From End of List # https://leetcode.com/problems/remove-nth-node-from-end-of-list/ class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: start, curr = [], head while curr: start.append(curr) curr = curr.next for i in range(n-1): start.pop() if len(start) == 1: return start[0].next start[-2].next = start[-1].next return head
52f97e7f4eccf88f0eb1930ee8a8527b6420eaa7
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 8/xor-equality.py
316
3.546875
4
MOD = 10**9+7 def equality(n, x=2): res = 1 x %= MOD if x==0: return 0 while n>0: if n&1 != 0: res = (res*x)%MOD n = n>>1 x = (x*x)%MOD return res def main(): for _ in range(int(input())): n = int(input()) print(equality(n-1)) main()
3e5f2ef814933ff40deb61305404d9c6c1e055b6
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 27/106. Construct Binary Tree from Inorder and Postorder Traversal.py
2,749
3.90625
4
# Github: Shantanugupta1118 # DAY 27 of DAY 100 # 106. Construct Binary Tree from Inorder and Postorder Traversal # https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ # Solution 2-- class TreeNode: def __init__(self, val): self.val = val self.left = None self.right= None class Solution: def search(self, inorder, val, n): i = 0 while i<n: if inorder[i] == val: return i i += 1 return i def buildTree(self, inorder, postorder): def constructTree(inorder): nonlocal postIdx if postIdx<0: return None if inorder==[]: return None val = postorder[postIdx] postIdx -= 1 inorder_Idx = self.search(inorder, val, len(inorder)) left_ele = inorder[:inorder_Idx] right_ele = inorder[inorder_Idx+1:] root = TreeNode(val) root.right = constructTree(right_ele) root.left = constructTree(left_ele) return root postIdx = len(postorder)-1 return constructTree(inorder) inorder = [9, 3, 15, 20, 7] postorder = [9, 15, 7, 20, 3] print(Solution().buildTree(inorder, postorder)) # Solution 2--- """ class Node: def __init__(self, val): self.val = val self.left = None self.right = None class Solution: postIdx = 0 s = [] def search(self, inorder, val, n): i = 0 while i < n: if inorder[i] == val: return i i += 1 return i def buildTree(self, inorder, postorder, start, end, n): if start > end: return val = postorder[self.postIdx] inoIdx = self.search(inorder, val, n) self.postIdx -= 1 self.buildTree(inorder, postorder, inoIdx+1, end, n) self.buildTree(inorder, postorder, start, inoIdx-1, n) self.s.append(val) def constructTree(self, preorder, start, end): if start > end: return None node = Node(preorder[start]) i = start while i <= end: if preorder[i] > node.val: break i += 1 node.left = self.constructTree(preorder, start+1, i-1) node.right = self.constructTree(preorder, i, end) return node def preOrder(self, inorder, postorder): n = len(postorder) self.postIdx = n-1 self.buildTree(inorder, postorder, 0, n-1, n) return self.constructTree(self.s, 0, len(self.s)-1) inorder = [9, 3, 15, 20, 7] postorder = [9, 15, 7, 20, 3] print(Solution().preOrder(inorder, postorder)) """
f7da868b7a723c2ff02967a213fd6bc11cbddc04
ManojKumarPatnaik/100-Days-Code-Challenge
/Day 20/215. Kth Largest Element in an Array.py
607
3.71875
4
# Contribution By: Shantanu Gupta # Github: Shantanugupta1118 # DAY 20 of DAY 100 # 215. Kth Largest Element in an Array - Leetcode # https://leetcode.com/problems/kth-largest-element-in-an-array/ from heapq import * ''' First Approach without inbuilt fnc ''' ''' def k_largest(arr, k): heap = [] for i in arr: heappush(heap, -i) for i in range(k): a = heappop(heap) return a*-1 ''' ''' Second Approach using built in fnc''' def k_largest(arr, k): heapify(arr) return nlargest(k, arr)[-1] arr = list(map(int, input().split())) k = int(input()) print(k_largest(arr, k))
e3ac99530b606e0675d1f5cef956d063808e26b7
alphapk/Python_learnings
/Add_two_nums.py
291
4.09375
4
__author__ = 'Praveen Kumar Anbalagan' #Program to add two numbers #get input from the user num1 = input('Enter the 1st number: ') num2 = input('Enter the 2nd number: ') #add two numbers sum = float(num1)+float(num2) #print the sum print('The sum of {0} and {1} is {2}'.format(num1,num2,sum))
e6779f734aa8b8ca02d9b43933825ca90f5c6bdb
ItamarMu/university-stuff
/Introduction to CS - Python/HW1/s1.py
247
3.78125
4
import time num = eval(input("Please enter a positive integer: ")) m = num cnt = 0 t0 = time.clock() while m>0: if m%10 == 0: cnt+=1 m = m//10 t1 = time.clock() print(num, "has", cnt, "zeros") print("Running time: ", t1-t0, "sec")
8058a5f3841dc1d7147b0cdfbd3b5f43cd95b1ac
ItamarMu/university-stuff
/Introduction to CS - Python/HW4/elp.py
318
3.828125
4
import time def elapsed(expression,number=1): ''' computes elapsed time for executing code number of times (default is 1 time). expression should be a string representing a Python expression. ''' t1=time.clock() for i in range(number): eval(expression) t2=time.clock() return t2-t1
87302ce1cb35e41aa75795d92b9568222deeb3bc
valeeero/Hillel_HW
/Home_work_7/Home_work_7.py
3,667
3.6875
4
# 1 from collections import OrderedDict user_info = OrderedDict({'Имя': 'Валерий', 'Фамилия': 'Лысенко', 'Рост': 184, 'Вес': 81, 'Пол': 'Мужской'}) print(user_info, id(user_info)) first_user_info = list(user_info.items())[0] last_user_info = list(user_info.items())[-1] user_info.move_to_end(key=first_user_info[0]) user_info.move_to_end(key=last_user_info[0], last=False) second_user_info = list(user_info.items())[1] del user_info[second_user_info[0]] user_info['new_key'] = 'new_value' print(user_info, id(user_info)) # 2 student = {"name": "Emma", "class": 9, "marks": 75} info_marks = student.get("marks") print("key_marks: ", info_marks) # 3 p = {"name": "Mike", "salary": 8000} print(p.get("age")) # 4 sample = {"1": ["a", "b"], "2": ["c", "d"]} print(sample.get("2")[1]) # 5 list_1 = ["Украина-Киев", "Россия-Сочи", "Беларусь-Минск", "Япония-Токио", "Германия-Мюнхен"] list_2 = ["Киев", "Токио", "Минск"] countryes = [] cityes = [] for item_country in list_1: country = item_country for item_city in list_2: city = item_city if country.find(city) != -1: countryes.append(country.split("-")[0]) cityes.append(city) else: continue dict_ = dict(zip(countryes, cityes)) print(dict_) # 6 if __name__ == '__main__': value = [] de_value = [] txt = input("Введите текст для шифровки: ") keys = {'а': 574, 'б': 242, 'в': 334, 'г': 394, 'д': 324, 'е': 584, 'ж': 264, 'з': 344, 'и': 284, 'й': 404, 'к': 414, 'л': 484, 'м': 374, 'н': 564, 'о': 594, 'п': 504, 'р': 364, 'с': 384, 'т': 494, 'у': 444, 'ф': 572, 'х': 242, 'ц': 332, 'ч': 392, 'ш': 322, 'щ': 582, 'ь': 262, 'ы': 342, 'э': 282, 'ю': 402, 'я': 412, 'А': 482, 'Б': 372, 'В': 562, 'Г': 592, 'Д': 502, 'Е': 362, 'Ж': 382, 'З': 492, 'И': 442, 'Й': 578, 'К': 248, 'Л': 338, 'М': 398, 'Н': 328, 'О': 588, 'П': 268, 'Р': 348, 'С': 288, 'Т': 408, 'У': 418, 'Ф': 488, 'Х': 378, 'Ц': 568, 'Ч': 598, 'Ш': 508, 'Щ': 368, 'Ь': 388, 'Ы': 498, 'Э': 448, 'Ю': 575, 'Я': 245, 'a': 335, 'b': 395, 'c': 325, 'd': 585, 'e': 265, 'f': 345, 'g': 285, 'h': 405, 'i': 415, 'j': 485, 'k': 375, 'l': 565, 'm': 595, 'n': 505, 'o': 365, 'p': 385, 'q': 495, 'r': 445, 's': 577, 't': 247, 'u': 337, 'v': 397, 'w': 327, 'x': 587, 'y': 267, 'z': 347, 'A': 287, 'B': 407, 'C': 417, 'D': 487, 'E': 377, 'F': 567, 'G': 597, 'H': 507, 'I': 367, 'J': 387, 'K': 497, 'L': 447, 'M': 573, 'N': 243, 'O': 333, 'P': 393, 'Q': 323, 'R': 583, 'S': 263, 'T': 343, 'U': 283, 'V': 403, 'W': 413, 'X': 483, 'Y': 373, 'Z': 563, ' ': 593, '.': 503, ',': 363, '!': 383, '?': 493, '0': 571, '1': 241, '2': 331, '3': 391, '4': 321, '5': 581, '6': 261, '7': 341, '8': 281, '9': 401, '+': 411, '-': 481, '<': 371, '>': 561, '@': 591, '#': 501, '$': 361, '%': 381, '^': 491, '&': 441, '*': 579, '(': 249, ')': 339, '_': 399, '=': 329, '~': 589, '`': 269, '"': 349, ':': 289, ';': 409, '[': 419, ']': 489, '{': 379, '}': 569} txt = list(txt) for item in txt: for key in keys: if key == item: value.append(keys[key]) de_value.append(key) decrypted_value = "".join(de_value) print(value) print(decrypted_value) # 7 dict_vlaue = {i : i ** 3 for i in range(1, 11)} print(dict_vlaue) # 8 text = str(input("Введите текст: ")) my_dict = {i: text.count(i) for i in text} print(my_dict)
908ca14a8df570182f00437af6406410e2340953
CrazyDi/Python2
/Week2/screensaver_my.py
10,990
3.875
4
import math import random import pygame class Vec2d: """ Класс вектора """ def __init__(self, x, y): self._vector = (x, y) def __get__(self, instance, owner): # получение значения вектора return self._vector def __getitem__(self, index): # получение координаты вектора по индексу return self._vector[index] def __str__(self): # переопеределение печати экземпляра класса return str(self._vector) def __add__(self, other): # сумма двух векторов return Vec2d(self[0] + other[0], self[1] + other[1]) def __sub__(self, other): # разность двух векторов return Vec2d(self[0] - other[0], self[1] - other[1]) def __mul__(self, other): # умножение вектора на число и скалярное умножение векторов if isinstance(other, Vec2d): return Vec2d(self[0] * other[0], self[1] * other[1]) else: return Vec2d(self[0] * other, self[1] * other) def __len__(self): # длина вектора return int(math.sqrt(self[0]**2 + self[1]**2)) def int_pair(self): # получение пары (x, y) return self._vector class Polyline: """ Класс замкнутых линий """ def __init__(self, speed=2): self._points = [] self._speeds = [] self._screen = (800, 600) self._speed = speed def __len__(self): return len(self._points) def __get__(self, instance, owner): return self._points def __getitem__(self, index): return self._points[index] speed = property() # свойство количество точек сглаживания @speed.setter def speed(self, value): self._speed = value if value > 0 else 1 @speed.getter def speed(self): return self._speed def add_point(self, point, speed): # добавление в ломаную точки и ее скорости self._points.append(point) self._speeds.append(speed) def delete_point(self, index=None): # удаление точки по индексу if index is None: index = len(self._points) - 1 del self._points[index] del self._speeds[index] def set_points(self): # пересчет координат точек на скорость for i in range(len(self._points)): self._points[i] = self._points[i] + self._speeds[i] * self._speed if self._points[i][0] > self._screen[0] or self._points[i][0] < 0: self._speeds[i] = Vec2d(- self._speeds[i][0], self._speeds[i][1]) if self._points[i][1] > self._screen[1] or self._points[i][1] < 0: self._speeds[i] = Vec2d(self._speeds[i][0], - self._speeds[i][1]) def draw_points(self, display, style="points", width=3, color=(255, 255, 255)): # рисование точек и линий if style == "line": for i in range(-1, len(self._points) - 1): pygame.draw.line(display, color, (int(self._points[i][0]), int(self._points[i][1])), (int(self._points[i + 1][0]), int(self._points[i + 1][1])), width) elif style == "points": for i in self._points: pygame.draw.circle(display, color, (int(i[0]), int(i[1])), width) class Knot(Polyline): """ Класс кривой """ def __init__(self, count): super().__init__() self._count = count self._points_knot = [] count = property() # свойство количество точек сглаживания @count.setter def count(self, value): self._count = value if value > 0 else 1 @count.getter def count(self): return self._count # сглаживание кривой def _get_point(self, points, alpha, deg=None): if deg is None: deg = len(points) - 1 if deg == 0: return points[0] return points[deg] * alpha + self._get_point(points, alpha, deg - 1) * (1 - alpha) def _get_points(self, base_points): alpha = 1 / self._count res = [] for i in range(self._count): res.append(self._get_point(base_points, i * alpha)) return res def _get_knot(self): self._points_knot = [] if len(self) >= 3: for i in range(-2, len(self) - 2): ptn = [(self[i] + self[i + 1]) * 0.5, self[i + 1], (self[i + 1] + self[i + 2]) * 0.5] self._points_knot.extend(self._get_points(ptn)) def add_point(self, point, speed): # добавление в ломаную точки и ее скорости (переопределенная) super().add_point(point, speed) self._get_knot() def delete_point(self, index=None): # удаление точки по индексу (переопределенная) super().delete_point(index) self._get_knot() def set_points(self): # пересчет координат точек на скорость (переопределенная) super().set_points() self._get_knot() # рисование точек и линий (переопределенная) def draw_points(self, display, style="points", width=3, color=(255, 255, 255)): # self._get_knot() if style == "line": for i in range(-1, len(self._points_knot) - 1): pygame.draw.line(display, color, (int(self._points_knot[i][0]), int(self._points_knot[i][1])), (int(self._points_knot[i + 1][0]), int(self._points_knot[i + 1][1])), width) elif style == "points": for i in self: pygame.draw.circle(display, color, (int(i[0]), int(i[1])), width) # Отрисовка справки def draw_help(): gameDisplay.fill((50, 50, 50)) font1 = pygame.font.SysFont("courier", 24) font2 = pygame.font.SysFont("serif", 24) data = [["F1", "Show Help"], ["R", "Restart"], ["P", "Pause/Play"], ["Num+", "More points"], ["Num-", "Less points"], ["Backspace", "Delete last point"], ["Num*", "More speed"], ["Num/", "Less speed"], ["", ""], [str(poly.count), "Current points"], [str(poly.speed), "Current speed"]] pygame.draw.lines(gameDisplay, (255, 50, 50, 255), True, [ (0, 0), (800, 0), (800, 600), (0, 600)], 5) for i, text in enumerate(data): gameDisplay.blit(font1.render( text[0], True, (128, 128, 255)), (100, 100 + 30 * i)) gameDisplay.blit(font2.render( text[1], True, (128, 128, 255)), (200, 100 + 30 * i)) # Основная программа if __name__ == "__main__": # инициализация окна pygame.init() gameDisplay = pygame.display.set_mode((800, 600)) pygame.display.set_caption("MyScreenSaver") working = True # маркер работы poly = Knot(35) show_help = False # маркер отображения помощи pause = True # маркер паузы hue = 0 # оттенок color_line = pygame.Color(0) # цвет # цикл работы программы while working: # отлавливаем событие с клавиатуры и мышки for event in pygame.event.get(): # если нажат крестик закрытия окна, меняем маркер работы программы if event.type == pygame.QUIT: working = False # отлавливаем событие с клавиатуры if event.type == pygame.KEYDOWN: # Esc - меняем маркер работы программы if event.key == pygame.K_ESCAPE: working = False # R - обнуляем данные if event.key == pygame.K_r: poly = Knot(35) # P - меняем маркер движения if event.key == pygame.K_p: pause = not pause # Num+ - увеличиваем количество точек сглаживания if event.key == pygame.K_KP_PLUS: poly.count += 1 # F1 - открытие/закрытие окна помощи if event.key == pygame.K_F1: show_help = not show_help # Num- - уменьшаем количество точек сглаживания if event.key == pygame.K_KP_MINUS: poly.count -= 1 # Backspace - удаление последней добавленной точки if event.key == pygame.K_BACKSPACE: poly.delete_point() # Num* - увеличиваем скорость движения кривой if event.key == pygame.K_KP_MULTIPLY: poly.speed += 1 # Num / - уменьшаем скорость движения кривой if event.key == pygame.K_KP_DIVIDE: poly.speed -= 1 # отлавливаем событие с мыши - клик любой кнопкой - добавляем точку в # полилайн и генерируем скорость для этой точки if event.type == pygame.MOUSEBUTTONDOWN: point_event = Vec2d(event.pos[0], event.pos[1]) speed_event = Vec2d(random.random(), random.random()) poly.add_point(point_event, speed_event) # отрисовка окна gameDisplay.fill((0, 0, 0)) # заполняем окно черным цветом hue = (hue + 1) % 360 # меняем оттенок линии color_line.hsla = (hue, 100, 50, 100) # формируем новый цвет с учетом нового оттенка poly.draw_points(gameDisplay) # рисуем точки poly.draw_points(gameDisplay, "line", 3, color_line) # рисуем линию # draw_points(get_knot(points, steps), "line", 3, color) # если стоит маркер движения - сдвигаем точки на скорость if not pause: poly.set_points() # если стоит маркер окна помощи - показываем окно помощи if show_help: draw_help() pygame.display.flip() # перерисовка окна # выход из программы pygame.display.quit() pygame.quit() exit(0)
b98ec4d5a55d11ad62cbf8fc725774719669a7e7
junbaih/OthelloGame
/model.py
7,831
3.703125
4
## global constant , with value of 1 and -1 easy to switch around EMPTY = 0 BLACK = 1 WHITE = -1 ##exception class GameOverError(Exception): pass class InvalidMoveError(Exception): pass #### Class part with methods make a move if it is valid and flip accessble discs #### get the number of certain color disc and so on class game_board: def __init__(self,row,col,first_turn,start_disc,win_rule): self.board = self._start_board(row,col,start_disc) self.num_of_row = len(self.board) self.num_of_col = len(self.board[1]) self.turn = first_turn self.rule = win_rule def count_disc(self,color:'BLACK/WHITE')->int: '''count the disc with specified color''' self.count = 0 for row in self.board: self.count+=row.count(color) return self.count def board_row(self)->int: '''return the dimension of the game board''' return self.num_of_row def board_column(self)->int: '''as the same as board_row method''' return self.num_of_col def turn_swift(self)->None: '''swift a turn''' self.turn = -self.turn def current_turn(self)->int: '''show current turn ''' return self.turn def move_and_flip(self,row,col)->None: '''drop a disc and flip all plausible discs''' if self.check_game_over(): raise GameOverError if (row,col) in self._get_valid_list(self.turn): self._flip(row,col,0,1,self.turn) self._flip(row,col,0,-1,self.turn) self._flip(row,col,1,1,self.turn) self._flip(row,col,1,-1,self.turn) self._flip(row,col,-1,0,self.turn) self._flip(row,col,1,0,self.turn) self._flip(row,col,-1,1,self.turn) self._flip(row,col,-1,-1,self.turn) self.board[row-1][col-1] = self.turn else: raise InvalidMoveError def check_game_over(self)->bool: '''return if a game is over''' return self._get_valid_list(WHITE)==[] \ and self._get_valid_list(BLACK)==[] def no_move_swift(self)->None: '''if there is not valid move for another players in next turn, no turn swift is made, otherwise, turn changes into another player ''' if self._get_valid_list(-self.turn)==[]: self.turn = self.turn else: self.turn_swift() def winner(self)->int: '''print the winner for the game''' if self.check_game_over(): if self.rule == '>': if self.count_disc(BLACK)>self.count_disc(WHITE): return BLACK elif self.count_disc(BLACK)<self.count_disc(WHITE): return WHITE elif self.count_disc(BLACK)==self.count_disc(WHITE): return elif self.rule == '<': if self.count_disc(BLACK)>self.count_disc(WHITE): return WHITE elif self.count_disc(BLACK)<self.count_disc(WHITE): return BLACK elif self.count_disc(BLACK)==self.count_disc(WHITE): return ## private functions, including create initial board, which will be an ## attribute when creating the class; check if a disc call be flip ## check if a move is valid; create a valid move list and check if a ## place is on board def _create_empty_board(self,num_of_rows:int,num_of_cols:int)->None: ''' create a board with all empty cells ''' self.board = [] for row in range(num_of_rows): self.board.append([]) for column in range(num_of_cols): self.board[row].append(0) def _start_board(self,num_of_rows:int, num_of_cols:int,start_disc:'BLACK or WHITE')->'board': ''' create a initial board, with specified color disc in top left and bottom right ''' self._create_empty_board(num_of_rows,num_of_cols) top_left_center = bottom_right_center = start_disc top_right_center = bottom_left_center = -start_disc self.board[int(num_of_rows/2-1)][int(num_of_cols/2-1)] = top_left_center self.board[int(num_of_rows/2)][int(num_of_cols/2)] = bottom_right_center self.board[int(num_of_rows/2-1)][int(num_of_cols/2)] = top_right_center self.board[int(num_of_rows/2)][int(num_of_cols/2-1)] = bottom_left_center return self.board def _flip(self,row,col,rowdelta,coldelta,turn)->None: ''' check if discs in one giving direction can be flipped ''' if self._valid_check(row,col,rowdelta,coldelta,turn): next_row =row+rowdelta next_col = col+coldelta while self._check_on_board(next_row,next_col)== True: if self.board[next_row-1][next_col-1] !=turn: self.board[next_row-1][next_col-1] = turn next_row+=rowdelta next_col+=coldelta else: break else: pass def _get_valid_list(self,turn)->list: ''' get a valid move list by scan the board and check each cell ''' valid_list = [] for row in range(len(self.board)): for col in range(len(self.board[1])): if self._check_valid_move(row+1,col+1,turn): valid_list.append((row+1,col+1)) return valid_list def _check_valid_move(self,row,col,turn)->bool: ''' check a certain cell in all 8 directions to see if it could be a valid move ''' if self._valid_check(row,col,0,1,turn) \ or self._valid_check(row,col,0,-1,turn) \ or self._valid_check(row,col,1,0,turn) \ or self._valid_check(row,col,-1,0,turn) \ or self._valid_check(row,col,1,-1,turn) \ or self._valid_check(row,col,1,1,turn) \ or self._valid_check(row,col,-1,-1,turn) \ or self._valid_check(row,col,0-1,1,turn): return True return False def _valid_check(self,row:int,col:int,rowdelta:int,coldelta:int,turn)->bool: '''check a cell in one direction to see if it is movable in that direction ''' if not self._check_on_board(row,col): raise InvalidMoveError drow_position = self.board[row-1][col-1] cell_count = 0 if drow_position != 0: return False while True: row+=rowdelta col+=coldelta cell_count+=1 if self._check_on_board(row,col) and self.board[row-1][col-1]==-turn: pass if self._check_on_board(row,col) and self.board[row-1][col-1]==0: return False if self._check_on_board(row,col) and self.board[row-1][col-1]== turn: if cell_count == 1: return False return True if not self._check_on_board(row,col): break def _check_on_board(self,row,col)->bool: '''check if the specifie position is on board''' return 0<row<=len(self.board) and 0<col<=len(self.board[1])
9174bbd6390284af1d29bca9e5b6d783367b5302
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__011.py
332
3.71875
4
# pintando parede larg = float(input('Qual é a largura da parede que você deseja pintar?')) alt = float(input('E qual é a altura desta mesma parede?')) area = float((larg*alt)) tinta = float((area/2)) print('Você precisará pintar {} m² de área de parede\nE para isso precisará usar {} L de tinta'.format(area, tinta))
c3912498bdd7197cd60c10943fefc448909f27f5
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__037.py
628
4.125
4
# conversor de bases numéricas n = int(input('Digite um número inteiro: ')) print('''Escolha umda das bases para a conversão:' [ 1 ] converter para BINÁRIO [ 2 ] converter para OCTAL [ 3 ] converter para HEXADECIMAL''') opção = int(input('Sua opção: ')) if opção == 1: print('{} convertido para BINÁRIO é igual a {}'.format(n, bin(n)[2:])) elif opção == 2: print('{} convertido para OCTAL é igual a {}'.format(n, oct(n)[2:])) elif opção == 3: print('{} convertido para HEXADECIMAL é igual a {}'.format(n, hex(n)[2:])) else: print('Você precisa digitar uma das opções acima!')
b27eb11a268eb165af970993edad89d4f4c7694a
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__059.py
1,526
4.15625
4
# criando um menu de opções from time import sleep n1 = float(input('Digite um número qualquer: ')) n2 = float(input('Digite mais um número: ')) print(' [ 1 ] somar\n' ' [ 2 ] multiplicar\n' ' [ 3 ] maior\n' ' [ 4 ] novos números\n' ' [ 5 ] sair do programa') opção = int(input('>>>>> Qual é a sua opção? ')) while opção !=5: if opção > 5 or opção == 0: print('Opção inválida. Tente novamente!') if opção == 1: soma = n1+n2 print('A soma de {:.2f} com {:.2f} resulta em {:.2f}.'.format(n1, n2, soma)) elif opção == 2: multi = n1*n2 print('A multiplicação de {:.2f} com {:.2f} resulta em {:.2f}.'.format(n1, n2, multi)) elif opção == 3: if n1 > n2: maior = n1 else: maior = n2 print('O maior número entre {:.2f} e {:.2f} é {:.2f}.'.format(n1, n2, maior)) elif opção == 4: print('Informe os números novamente:') n1 = float(input('Primeiro valor: ')) n2 = float(input('Segundo valor: ')) sleep(1) print('-==-'*8) print(' [ 1 ] somar\n' ' [ 2 ] multiplicar\n' ' [ 3 ] maior\n' ' [ 4 ] novos números\n' ' [ 5 ] sair do programa') opção = int(input('>>>>> Qual é a sua opção? ')) if opção == 5: print('Finalizando...') sleep(1) print('-==-'*8) print('Fim do programa. Volte sempre!')
4e42cfc44d1e1a84c11fb66682b1d7760e262b25
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__018.py
357
4.03125
4
# seno, cosseno e tangente import math a = float(input('Digite o ângulo que você deseja:')) print('O SENO do ângulo de {} vale {:.2f}'.format(a, math.sin(math.radians(a)))) print('O COSSENO do ângulo de {} vale {:.2f}'.format(a, math.cos(math.radians(a)))) print('A TANGENTE do ângulo de {} vale {:.2f}'.format(a, math.tan(math.radians(a))))
044b28a4f77671479e15a7620c9b0b6feb37ece6
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__085.py
487
3.671875
4
lista = list() pares = list() impares = list() for c in range(1, 8): n = int(input(f'Digite o {c}º valor: ')) lista.append(n) print('--' * 50) print(f'Você digitou os valores: {lista}') for v in range(0, len(lista)): if lista[v] % 2 == 0: pares.append(lista[v]) else: impares.append(lista[v]) print(f'Os valores pares digitados foram: {sorted(pares)}') print(f'Os valores ímpares digitados foram: {sorted(impares)}') print('--' * 50)
54d1c9b14fecd247df7d3230fa4a3125e40e3ab0
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__005.py
191
4.09375
4
# sucessor e antecessor num = int(input('Digite um número qualquer:')) n1 = num-1 n2 = num+1 print('Analisando seu número, o antecessor é {} e o sucessor é {}'.format(n1, n2))
6b2d874c613182e7e45222686b4824aa40e2521f
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__031.py
267
3.578125
4
# custo da viagem d = float(input('Qual é a distância da sua viagem em km? ')) p1 = d*0.5 p2 = d*0.45 if d<= 200: print('O preço da sua passagem será de R${:.2f}'. format(p1)) else: print('O preço da sua passagem será de R${:.2f}'.format(p2))
2cdc4ee9ce0f59cf33147284a9d7b165a599284d
EstephanoBartenski/Aprendendo_Python
/Teoria/teoria__Classes_4.py
1,093
4.0625
4
# atributos class Pessoa: num_de_pessoas = 0 @classmethod def num_de_pessoas_(cls): return cls.num_de_pessoas @classmethod def add_pessoa(cls): cls.num_de_pessoas += 1 def __init__(self, nome): self.nome = nome Pessoa.add_pessoa() p1 = Pessoa('João') p2 = Pessoa('Zuleide') p3 = Pessoa('Orimberto') # print(Pessoa.num_de_pessoas) print(Pessoa.num_de_pessoas_()) # Pessoa.num_de_pessoas = 55 # print(Pessoa.num_de_pessoas) # print(p1.num_de_pessoas) # print(p1.num_de_pessoas) # aquele num de pessoas que eu deixei lá em cima, fora/antes no init # vale pra galera toda!! não vai mudar de pessoa pra pessoa # então posso chamar aquilo pra qualquer pessoa # e mudar a qualquer tempo, fazendo a classe+aquilo recebe tal # aí posso fazer contagem hehe # mas a ideia de constante é a mais útil mesmo, tipo gravidade sl # algo que é sempre -9.8 m/s² # class methods # a ideia é que fazem referência à classe inteira (método da classe), # e não algum outor método dessa classe
0eed0a6a10c8b1a522b927c0afd10d5dcf34a5b1
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__047.py
387
4.0625
4
# contando pares for contagem in range(2,52,2): print(contagem, end=' ') # outra forma de fazer for contagem in range(1,51): if (contagem%2) == 0: print(contagem, end=' ') # neste segundo método, a interação é feita de 1 em 1, mesmo que o resultado não seja mostrado. No primeiro método, só # foi feito metade do serviço (isso ocupa menos processador)
2517c1c7c6ada14bb1bdef025828624a676573cd
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__051.py
527
3.796875
4
# progressão artimética print('='*30) print(' 10 TERMOS DE UMA PA ') print('='*30) a1 = int(input('Digite o primeiro termo: ')) r = int(input('Razão: ')) for c in range(0, 10): c = a1 + c * r print(c, end=' ') print('->', end=' ') print('ACABOU') # refazendo # an = a1 + (n - 1) * r a1 = int(input('Primeiro termo: ')) r = int(input('Razão da PA: ')) n = 0 for n in range(1, 11): an = a1 + (n - 1) * r n += 1 print('{} --> '.format(an), end='') print('FIM', end='')
5dd2a28ae62cf46d8a3d296ddbbc8df758527596
EstephanoBartenski/Aprendendo_Python
/Teoria/teoria__lista_5.py
801
3.875
4
'''pessoal = [['Joana', 33], ['Marcelo', 45], ['Otávio', 50], ['Jorge', 12], ['Bárbara', 14]] print(pessoal[1]) print(pessoal[1][1]) print(pessoal[1][0]) print() turma = list() turma.append(pessoal[:]) print(turma) print(turma[0]) print(turma[0][4]) print(turma[0][4][1])''''' galera = list() dado = list() for c in range(0, 3): dado.append(str(input('Nome: '))) dado.append(int(input('Idade: '))) galera.append(dado[:]) dado.clear() print(galera) print() totmaior = totmenor = 0 for p in galera: if p[1] >= 18: print(f'{p[0]} é maior de idade.') totmaior += 1 else: print(f'{p[0]} é menor de idade.') totmenor +=1 print(f'Há {totmaior} pessoas maiores de idade e {totmenor} pessoas menores de idade.')
73a76de770942df37edb4958c3bb3267b4335dd6
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__060.py
423
4.09375
4
# calculando um fatorial num = int(input('Digite um número para calcular seu fatorial: ')) c = num f = 1 # pra começar uma multiplicação limpa, assim como usamos 0 pra começar uma soma limpa print('Calculando {}! = '.format(num), end='') while c > 0: print('{}'.format(c), end='') print(' x ' if c > 1 else ' = ', end='') f *= c c -= 1 print(f) # lembrando que no math tem um factorial
7473b81569f4aa4ff56d53372a670e3816876131
natrajitpoint/python
/classmethod.py
590
3.78125
4
class employee: def setdata(self,eno, ename, esal): self.eno = eno self.ename = ename self.esal = esal def getdata(self): print("\n*** Employee Info ***\nEmployee Id : {}\n\ Employee Name : {}\nEmployee Salary : {}"\ .format(self.eno,self.ename,self.esal)) #main e1 = employee() e2 = employee() e1.setdata(1001, 'Srinivas',35000) x = int(input("Enter employee Id : ")) y = input("Enter employee name : ") z = float(input("Enter employee salary : ")) e2.setdata(x,y,z) e1.getdata() e2.getdata() e3 = employee() e3.getdata()#error
3cdb31a1ce22e86265fd5ad8e5e4b4c9fe08e6ea
natrajitpoint/python
/insertexecute.py
804
3.5
4
import pymysql # Open database connection conn = pymysql.connect(host="localhost", user="root", passwd="itpoint", db="DB5to6") # Create a Cursor object to execute queries. cur = conn.cursor() # Insert records into Books table insertquery = "Insert into books values(%s,%s,%s,%s)" #Accept Data from user bid = int(input("Enter Book Id : ")) name = input("Enter Book Name : ") author = input("Enter Author Name : ") price = float(input("Enter Book Price : ")) try: # Execute Query ret = cur.execute(insertquery, [bid, name, author,price]) conn.commit() print("%s rows inserted successfully...." %ret) except Exception as ex: conn.rollback() print(ex) finally: # disconnect from server conn.close()
b9908917407ec89e662b804ced360417491bcc98
mmalek06/amazon-interview
/AmazonInterviewPy/sum_of_two.py
275
4
4
find_sum_of_two([2, 1, 8, 4, 7, 3],3) def find_sum_of_two(A, val): pairs = dict() for cnt in range(0, len(A)): if (A[cnt] in pairs): return True the_other_number = val - A[cnt] pairs[the_other_number] = A[cnt] return False
e8d204ed131a1baa1f694ece35d9984700901ed2
averni/Simplify_with_Topology
/trianglecalculator.py
1,111
3.828125
4
#! /usr/bin/env python # encoding: utf-8 __author__ = 'asimmons' class TriangleCalculator(object): """ TriangleCalculator() - Calculates the area of a triangle using the cross-product. """ def __init__(self, point, index): # Save instance variables self.point = point self.ringIndex = index self.prevTriangle = None self.nextTriangle = None # enables the instantiation of 'TriangleCalculator' to be compared # by the calcArea(). def __cmp__(self, other): return cmp(self.calcArea(), other.calcArea()) ## calculate the effective area of a triangle given ## its vertices -- using the cross product def calcArea(self): # Add validation if not self.prevTriangle or not self.nextTriangle: print "ERROR:" p1 = self.point p2 = self.prevTriangle.point p3 = self.nextTriangle.point area = abs(p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1])) / 2.0 #print "area = " + str(area) + ", point = " + str(self.point) return area
790cdcb6e2eb5f734c6ccc27bc58596685a1a2a2
vijay092/Optimal-Control-RL
/minecraftControl/uquat.py
2,517
3.59375
4
""" A collection of operations on unit quaternions """ import numpy as np def normalize(q): norm = np.sqrt(np.dot(q,q)) return q/norm def vec_to_uquat(v): dt = np.array(v).dtype if dt == np.int or dt == np.float: dt = float else: dt = object input_array = np.zeros(4,dtype=dt) input_array[1:] = v return input_array def cast_as_uquat(q): if len(q) == 4: return q elif len(q) == 3: return vec_to_uquat(q) def mult(q,p): qQuat = cast_as_uquat(q) pQuat = cast_as_uquat(p) if qQuat.dtype == np.object or pQuat.dtype == np.object: dt = object else: dt = float rQuat = np.zeros(4,dtype=dt) r1 = qQuat[0] v1 = qQuat[1:] r2 = pQuat[0] v2 = pQuat[1:] rQuat[0] = r1*r2 - np.dot(v1,v2) rQuat[1:] = r1*v2 + r2*v1 + np.cross(v1,v2) return rQuat def inv(q): """ This simply conjugates the quaternion. In contrast with a standard quaterionion, you would also need to normalize. """ if q.dtype == np.object: dt = object else: dt = float qinv = np.zeros(4,dtype=dt) # Here is the main difference between a unit quaternion # and a standard quaternion. qinv[0] = q[0] qinv[1:] = -q[1:] return qinv def rot(q,v): """ This performs a rotation with a unit quaternion """ qinv = inv(q) res = mult(q,mult(v,qinv)) return np.array(res[1:]) def expq(v): """ This computes the quaternion exponentiation of a vector, v Input v: a vector in R^3 Output q: a unit quaternion corresponding to e^((0,v)) """ norm = np.sqrt(np.dot(v,v)) qr = np.cos(norm) qv = v * np.sinc(norm/np.pi) # Want v * sin(norm) / norm. As is, you'll get problems in the limit # of norm near 0. Thus, use the sinc function, which is # sinc(x) = sin(pi*x) / (pi*x) q = np.array([qr,qv[0],qv[1],qv[2]]) return q def cross_mat(v): """ Extract the skew symmetric matrix corresponding to a 3-vector """ dt = v.dtype M = np.zeros((3,3),dtype=dt) M[0,1] = -v[2] M[0,2] = v[1] M[1,2] = -v[0] M = M - M.T return M def mat(q): """ return the rotation matrix corresponding to unit quaternion """ dt = q.dtype r = q[0] v = q[1:] M = cross_mat(v) Msq = np.dot(M,M) R = r*r * np.eye(3) + np.outer(v,v) + 2 * r * M + Msq return R
5acdea7afe5a64f6aee54842b3800d8966f13686
gauravaror/programming
/reOrderList.py
1,274
3.734375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ fp = head headcopy = head sp = head while fp: #print(fp.val, sp.val) if fp.next: fp = fp.next.next sp = sp.next else: fp = fp.next # Reverse from slow pointer #print(sp.val) #return sp prev = None while sp: #print(sp.val) save = sp.next sp.next = prev prev = sp #print(save, sp.val) if save: sp = save else: break #sp = prev #print(sp.val, sp.next.val, sp.next.next) while headcopy and sp: save = headcopy.next headcopy.next = sp spsave = sp.next sp.next = save headcopy = save sp = spsave if headcopy: headcopy.next = None #print("jjhgg ",headcopy, sp) return head
089443a83c95a5caf8f211a18559963edbef9b8b
gauravaror/programming
/linked_list_in_binary_tree.py
1,956
3.859375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def tree_height(self, root): if root == None: return 0 left_height = self.tree_height(root.left) right_height = self.tree_height(root.right) return max(left_height, right_height) + 1 def list_leng(self, he): if he == None: return 0 return 1 + self.list_leng(he.next) def isSubPath(self, head: ListNode, root: TreeNode) -> bool: if self.list_leng(head) > self.tree_height(root): return False return self.isSubPath1(head, root) def justMatchPath(self, head: ListNode, root: TreeNode) -> bool: if head == None: return True if root == None: return False if head.val == root.val: if self.justMatchPath(head.next, root.left): return True if self.justMatchPath(head.next, root.right): return True return False def isSubPath1(self, head: ListNode, root: TreeNode) -> bool: if head == None: return True if root == None: return False if root.val == head.val: left_mpath = self.justMatchPath(head.next, root.left) if left_mpath: return True right_mpath = self.justMatchPath(head.next, root.right) if right_mpath: return True left_path = self.isSubPath1(head, root.left) if left_path: return True right_path = self.isSubPath1(head, root.right) if right_path: return True return left_path or right_path
4268f60fc2cfdff90d1da67a16d88544fbe7693f
gauravaror/programming
/myCalender1.py
1,340
3.65625
4
class MyCalendar: def __init__(self): self.starts = [] self.ends = [] def bs(self, array, target): start = 0 end = len(array) while start < end: mid = start + (end-start)//2 if array[mid] > target: end = mid else: start = mid + 1 return start def book(self, start: int, end: int) -> bool: if len(self.starts) == 0: self.starts.append(start) self.ends.append(end) return True starting_index = self.bs(self.starts, start) ending_index = self.bs(self.ends, end) new_meeting_index = self.bs(self.ends, start) #print(self.starts, self.ends, starting_index, ending_index, new_meeting_index) if new_meeting_index != starting_index: return False if starting_index != ending_index: return False if starting_index < len(self.starts) and self.starts[starting_index] > start and self.starts[ending_index] < end: return False self.starts.insert(starting_index, start) self.ends.insert(ending_index, end) return True # Your MyCalendar object will be instantiated and called as such: # obj = MyCalendar() # param_1 = obj.book(start,end)
1c741e95677effe1805363a8ac8a4b7ebce2c91b
gauravaror/programming
/binary-tree-level-order-traversal_2.py
882
3.796875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: answer = [] stack = [] current_level = 0 if not root: return [] stack.append((root,1)) while len(stack) > 0: #print(stack) elem = stack.pop(0) level = elem[1] node = elem[0] if node.left: stack.append((node.left, level+1)) if node.right: stack.append((node.right, level+1)) if current_level != level: answer.append([]) current_level = level answer[-1].append(node.val) answer.reverse() return answer
916ca7c13f04b1d9f401941a6cdba3a21e20f500
gauravaror/programming
/lrucache_double_linked_list_solution.py
2,048
3.5625
4
class Node: def __init__(self, key, val): self.key = key self.val = val self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.hh = {} self.head = Node(0,0) self.tail = Node(0,0) self.capacity = capacity self.limit = 0 def arrange_access(self, key: int) -> int: accessednode = self.hh[key] if self.tail != accessednode: prevn = accessednode.prev nextn = accessednode.next if prevn: prevn.next = nextn if nextn: nextn.prev = prevn if accessednode == self.head and nextn != None: self.head = nextn self.tail.next = accessednode accessednode.prev = self.tail self.tail = accessednode return accessednode.val def get(self, key: int) -> int: #print("get", key, self.head, self.tail, self.hh) if key in self.hh: return self.arrange_access(key) else: return -1 def put(self, key: int, value: int) -> None: #print("put", key,value, self.head, self.tail, self.hh) if key in self.hh: self.hh[key].val = value self.arrange_access(key) else: while self.limit >= self.capacity: remove_n = self.head del self.hh[remove_n.key] self.head = self.head.next self.limit -= 1 newnode = Node(key, value) oldtail = self.tail oldtail.next = newnode newnode.prev = oldtail self.tail = newnode self.hh[key] = newnode if self.limit == 0: self.head = newnode self.limit += 1 # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
15f3a8fbce221a05aff3f14531cb122b80f816cd
gauravaror/programming
/reconstructQueue_SORT_sol.py
287
3.53125
4
class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: people.sort(key=lambda h: (-h[0],h[1])) print(people) queue = [] for p in people: #print(queue) queue.insert(p[1], p) return queue
9527fc836db1dfa78746035db321aa262d9d6da9
gauravaror/programming
/tweet_count_per_frequency.py
1,385
3.515625
4
from collections import Counter class TweetCounts: def __init__(self): self.hours = Counter() self.days = Counter() self.minutes = Counter() def recordTweet(self, tweetName: str, time: int) -> None: minute = time//60 hour = time//3600 self.hours[tweetName+str(hour)] += 1 self.minutes[tweetName+str(minute)] += 1 self.days[tweetName+str(time)] += 1 def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]: start = startTime end = endTime use_counter = self.days if freq == 'hour': start = start //3600 end = end//3600 use_counter = self.hours elif freq == 'minute': start = start // 60 end = end //60 use_counter = self.minutes answer = [] for i in range(start, end+1): key = tweetName + str(i) print(use_counter, i , key) if key in use_counter: answer.append(use_counter[key]) #else: #answer.append(0) return answer # Your TweetCounts object will be instantiated and called as such: # obj = TweetCounts() # obj.recordTweet(tweetName,time) # param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)
ec08f2a7bd1c0a73cdd7a032d962b74b31e73549
gauravaror/programming
/avgwaittime.py
373
3.59375
4
class Solution: def averageWaitingTime(self, customers: List[List[int]]) -> float: currtime = 1 wait = 0 for arrival, prep in customers: if currtime < arrival: currtime = arrival currtime += prep wait += (currtime-arrival) return wait/len(customers)
66ba54e0e35f8db59e76f5df17dc5f4e392c47ba
gauravaror/programming
/reverseBits.py
317
3.578125
4
class Solution: def reverseBits(self, n: int) -> int: st = 1 num = 32 output = 0 while num >= 0: num -= 1 bit = n&st if bit: output += pow(2,num) st = st << 1 #print(st, num, output) return output
16ac1e3175ed3d36d0203505f5573c4223a7446e
gauravaror/programming
/maximum-product-of-splitted-binary-tree.py
1,416
3.5
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def dfs(self, node): left_tree = 0 right_tree = 0 if node.left: left_tree = self.dfs(node.left) if node.right: right_tree = self.dfs(node.right) left_prod = (self.total_sum-left_tree) left_prod *= left_tree right_prod = (self.total_sum-right_tree) right_prod = right_prod*right_tree if (left_prod) > self.maximum: self.maximum = left_prod if right_prod > self.maximum: self.maximum = right_prod return (node.val + left_tree + right_tree) def maxProduct(self, root: TreeNode) -> int: stack = [] total_sum = 0 stack.append(root) self.modulo = 1e9 + 7 while len(stack) > 0: elem = stack[0] stack.pop(0) total_sum = total_sum + (elem.val) if elem.left: stack.append(elem.left) if elem.right: stack.append(elem.right) self.maximum = 0 self.total_sum = total_sum self.dfs(root) print(total_sum, self.maximum) return int(self.maximum % self.modulo)
2454e54711aa57ac5fd43599a85ab5ab1584f44b
gauravaror/programming
/streamChecker.py
1,042
3.609375
4
class Trie: def __init__(self): self.chars = {} self.finishing = False #self.wrd = word def add(self, word): if len(word) == 0: self.finishing = True return if word[0] not in self.chars: self.chars[word[0]] = Trie() self.chars[word[0]].add(word[1:]) from collections import deque class StreamChecker: def __init__(self, words: List[str]): self.root = Trie() for word in words: self.root.add(word[::-1]) self.deque = deque() def query(self, letter: str) -> bool: self.deque.appendleft(letter) node = self.root for i in self.deque: if i in node.chars: node = node.chars[i] if node.finishing: return True else: return False # Your StreamChecker object will be instantiated and called as such: # obj = StreamChecker(words) # param_1 = obj.query(letter)
b00639462737fce6440a481c232abbd3ce6abf91
ccirelli2/mutual_fund_analytics_lab_sentiment_analysis
/scripts/functions_decorators.py
1,413
3.65625
4
""" Decorator functions for this program """ ############################################################################### # Import Python Libraries ############################################################################### import logging; logging.basicConfig(level=logging.INFO) from functools import wraps from datetime import datetime ############################################################################### # Decorators ############################################################################### def my_timeit(f): """ Decorator function to log function name and duration. Args: f: function Returns: """ @wraps(f) # see docs. retains info about f def wrapped(*args, **kwargs): logging.info(f'Starting function {f.__name__}') start = datetime.now() response = f(*args, **kwargs) duration = (datetime.now() - start).total_seconds() logging.info(f'{f.__name__} finished. Duration => {duration}') logging.info('\n\n') return response return wrapped
1a076304c384df34684971effecc69c702342683
jarroba/Curso-Python
/Casos Prácticos/6.2-math_stirling.py
565
3.6875
4
import math # 1 num = 100 primera_parte = math.sqrt(2 * math.pi * num) segunda_parte = math.pow(num/math.e, num) # == (num / math.e) ** num resultado = primera_parte * segunda_parte print("Por fórmula de Stirling: {numero}!= {resultado}".format(numero=num, resultado=resultado)) # 2 res_factorial = math.factorial(num) print("Por fórumula normal: {numero}! = {resultado}".format(numero=num, resultado=res_factorial))
a4644a5aa54ed966e76a12b18651173ba15682f9
jarroba/Curso-Python
/Casos Prácticos/5.5-funcion_return_none_espacio.py
234
3.59375
4
# 1 def espacio(velocidad, tiempo): resultado = velocidad * tiempo # 2 if resultado < 0: return None else: return resultado # 3 tiempo_retornado = espacio(120, -10) print(tiempo_retornado)
34b47f5f402c625167dd07b74dde3a50af7abb3e
jarroba/Curso-Python
/Casos Prácticos/4.15-tuplas.py
497
3.875
4
# 1 tupla1 = ("manzana", "rojo", "dulce") tupla2 = ("melocotón", "naranja", "ácido") tupla3 = ("plátano", "amarillo", "amargo") print(tupla1) # 2 lista_de_tuplas = [] lista_de_tuplas.append(tupla1) lista_de_tuplas.append(tupla2) lista_de_tuplas.append(tupla3) # 3 for fruta, color, sabor in lista_de_tuplas: print("La {fruta} es {color} " "y sabe a {sabor}".format(fruta=fruta, color=color, sabor=sabor))
042b6738c14747adbe173d1b09239927f92d2aa9
binit-singh/python-datastructures
/3_fibonacci_number/fibonacci_last_digit.py
581
4.0625
4
# Uses python3 def get_fibonacci_last_digit_naive(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current % 10 def get_fibonacci_last_digit_fast(n): if n < 1: return 1 previous_last = 0 current_last = 1 for _ in range(n-1): previous_last, current_last = current_last % 10, (previous_last + current_last) % 10 return current_last if __name__ == '__main__': n = int(input()) print(get_fibonacci_last_digit_fast(n))
688f45329b2e7371b61189f3cd3b2d5a77d3a0f5
codacy-acme/pythest
/main.py
1,029
3.640625
4
import httpoxy def square(a): """item_exporters.py contains Scrapy item exporters. Once you have scraped your items, you often want to persist or export those items, to use the data in some other application. That is, after all, the whole purpose of the scraping process. For this purpose Scrapy provides a collection of Item Exporters for different output formats, such as XML, CSV or JSON. More Info: https://doc.scrapy.org/en/latest/topics/exporters.html """ return a**a def square2(a): """item_exporters.py contains Scrapy item exporters. Once you have scraped your items, you often want to persist or export those items, to use the data in some other application. That is, after all, the whole purpose of the scraping process. For this purpose Scrapy provides a collection of Item Exporters for different output formats, such as XML, CSV or JSON. More Info: https://doc.scrapy.org/en/latest/topics/exporters.html """ return a**a x = 1 if x == 1: # indented four spaces print("x is 1.")
843061e943b25fa172636d9f77017ea2294aa96d
ramza007/Password-Locker
/credentials-test.py
2,276
3.765625
4
import unittest from credentials import Credentials class TestCredentials(unittest.TestCase): ''' test class that defines test cases for the credentials class ''' def setUp(self): ''' set up method that runs before each test case ''' self.new_credentials = Credentials("Google", "3344") def tearDown(self): ''' tear down method that does clean up after each test case has run. ''' Credentials.credentials_list = [] def test_credentials_instance(self): ''' method to test if new credentials have been instanciated properly ''' self.assertEqual(self.new_credentials.account_name, "Google") self.assertEqual(self.new_credentials.account_password, "3344") def test_save_credentials(self): ''' test case to test if credentials objects have been saved ''' self.new_credentials.save_credentials() # save new user self.assertEqual(len(Credentials.credentials_list), 1) def test_delete_credentials(self): ''' test delete credentials to test if we can remove a account from our list ''' self.new_credentials.save_credentials() test_credentials = Credentials("Google", "3344") test_credentials.save_credentials() self.new_credentials.delete_credentials() # to delete a credentials object self.assertEqual(len(Credentials.credentials_list), 1) def test_find_credentials_by_name(self): ''' test to check if credentials by the account name and can display information ''' self.new_credentials.save_credentials() test_credentials = Credentials("Google", "3344") test_credentials.save_credentials() # found_credentials = Credentials.find_by_number("0711491808") # self.assertEqual(found_credentials.credentials_name, # test_credentials.password) def test_display_all_credentials(self): ''' Test to check if all contacts can be viewed ''' self.assertEqual(Credentials.display_credentials(), Credentials.credentials_list) if __name__ == '__main__': unittest.main()
4885fd3b53635d85138d7987793f5159eab172bd
charboltron/artificial_intelligence
/genetic_8_queens/genetic_alg_8_queens.py
8,873
3.546875
4
#%% import sys import random import math import numpy as np import matplotlib.pyplot as plt test_boards = [[2,4,7,4,8,5,5,2],[3,2,7,5,2,4,1,1],[2,4,4,1,5,1,2,4],[3,2,5,4,3,2,1,3]] #constants/twiddle factors num_iterations = 10000 def print_board(board): for i in range(8, 0, -1): print('\n') for j in range(8): if board[j] == i: print(u' \u2655 ',end='') else: print(' ___ ', end='') def test(): fscores=[] for board in test_boards: fscore = get_fscore(board) print('fitness: ', fscore) fscores.append(fscore) fprobs = fitprobs(4, fscores) print(fprobs) def goal_state(board): if get_fscore(board) == 28: return True return False def randomize (board, n): for i in range(n): queens = random.randint(1,8) board[i] = queens return board population = [] def generate_population(population_size): population = [] for _ in range(population_size): board = [0,0,0,0,0,0,0,0] n = len(board) randomize(board, n) population.append(board) return population def get_fscore(board): fitness = 28 for i in range(len(board)-1): queen = i+1 # print(f'\nThis queen: ({queen}, {board[i]})') # print('Other queens: ', end='') for j in range(i+1, len(board)): # is_attack = '' other_queen = j+1 if(board[i] == board[j]): fitness -= 1 # is_attack = '<-A!' elif abs((board[i] - board[j])/((queen)-(other_queen))) == 1: fitness -= 1 # is_attack = '<-A!' # print(f'({other_queen}, {board[j]}){is_attack}, ', end='') return fitness def get_probs(population): fscores = [] for i in range(len(population)): fscore = get_fscore(population[i]) fscores.append(fscore) fprobs = fitprobs(len(population), fscores) return fscores, fprobs def fitprobs(pop_size, fs): denom = 0 probs = [] for i in range(pop_size): denom+=fs[i] if(denom > 0): for i in range(pop_size): s_i = fs[i]/denom probs.append(s_i) else: print("Error: Denom !>0 !") exit() return probs def get_avg_fitness(fs, pop_size): avg = 0 for i in range(pop_size): avg+=fs[i] avg = avg/pop_size return avg def cull_population(d, initial_popsize, pop_size, population): # print("population size before culling: ", len(d)) cull_size = pop_size-initial_popsize d = sorted(d, key=lambda x: x[0]) for i in range(cull_size): temp = d[i][1] for j in range(len(population)): if population[j] == temp: # print(f'deleting j = {population[j]}') del population[j] break del d[i] # print("population size after culling: ", len(d)) return d, pop_size-cull_size, population def fitness_proportionate_selection(d): sum_of_fitness = 0.0 bins = [] for i in d: sum_of_fitness+=i[0] # print(sum_of_fitness) # print(d) prev_prob = 0.0 d = sorted(d, key=lambda x: x[0]) for i in range(len(d)): # print(d[i][0]) if (i+1) == len(d): right_range = 1.0 else: right_range = prev_prob + d[i][0] bins.append([prev_prob, right_range]) prev_prob += d[i][0] # for bin in bins: # print(bin) return bins def select_from_population(bins, d): mom, dad = [],[] cnt = 0 while(mom == [] or dad == []): cnt+=1 x = random.randint(0, 100)/100 y = random.randint(0, 100)/100 x = .9999999 if x > .99 else x x = .0000001 if x < 0.01 else x y = .9999999 if y > .99 else y y = .0000001 if y < 0.01 else y # while(y == x): # y = random.randint(0, 100)/100 for i, bin in enumerate(bins): # print(bin) if x >= bin[0] and x <= bin[1]: mom = d[i] if y >= bin[0] and y <= bin[1]: dad = d[i] if cnt == 1000: print("wtf") print(mom, dad) exit() if mom == [] or dad == []: print("Empty list after selection! Exiting.") print(x, y, mom, dad) exit() return mom, dad def breed(d): bins = fitness_proportionate_selection(d) mom, dad = select_from_population(bins, d) # print(f'mom: {mom}, dad: {dad}') split = random.randint(1,7) # print(f'split = {split}') mom_genes_first = mom[1][0:split] dad_genes_first = dad[1][split:] dad_genes_secnd = dad[1][0:split] mom_genes_secnd = mom[1][split:] # print(f'{mom_genes_first} , {dad_genes_first}') # print(f'{dad_genes_secnd} , {mom_genes_secnd}') first_born = [0,0,0,0,0,0,0,0] secnd_born = [0,0,0,0,0,0,0,0] for i in range(8): if i < split: first_born[i] = mom_genes_first[i] secnd_born[i] = dad_genes_secnd[i] else: first_born[i] = dad_genes_first[split-i] secnd_born[i] = mom_genes_secnd[split-i] # print(f'M: {mom}, D: {dad}, C1: {first_born}, C2: {secnd_born}') return first_born, secnd_born def mutate(c1, c2, mutation_thresh): m1 = random.randint(0, 100)/100 m2 = random.randint(0, 100)/100 if m1 >= mutation_thresh: queen_to_mutate = random.randint(0, 7) c1[queen_to_mutate] = random.randint(1, 8) if m2 >= mutation_thresh: queen_to_mutate = random.randint(0, 7) c2[queen_to_mutate] = random.randint(1, 8) return c1, c2 def genetic_eight_queens(pop_size, m): f = open('out.txt', 'w') print(f'\nBegin up to {num_iterations} iterations: Breeding...') avg_fitness_to_pop = [] population = generate_population(pop_size) initial_pop_size = pop_size # print(fs) fittest = 0.0 board = [] fs, probs = get_probs(population) d = list(zip(probs, population)) for i in range(num_iterations): if initial_pop_size < pop_size: d, pop_size, population = cull_population(d, initial_pop_size, pop_size, population) if i%100==0: # print(pop_size) print(f'i:..{i} ') f.write(f'\nfittest member of population at iteration {i}: {d[len(d)-1]}. Score: {fittest}') # print(f'fittest = {fittest} board: {board}') # print(len(population)) fs, probs = get_probs(population) d = list(zip(probs, population)) # print(fs) avg_fitness_to_pop.append((i, get_avg_fitness(fs, pop_size))) for k in range(len(d)): if fs[k] > fittest: fittest = fs[k] board = d[k][1] d = sorted(d, key=lambda x: x[0]) child1, child2 = breed(d) child1, child2 = mutate(child1, child2, m) if goal_state(child1): print(f'\nGoal State has been found! After: {i} iterations.\n') print(f'This is the configuration of queens found {child1}\n') print_board(child1) return avg_fitness_to_pop, i elif goal_state(child2): print(f'\nGoal State has been found! After: {i} iterations.\n') print(f'This is the configuration of queens found {child2}\n') print_board(child2) return avg_fitness_to_pop, i population.append(child1) population.append(child2) pop_size+=2 print(f'No Goal State was found after {i} iterations.\n') return avg_fitness_to_pop, num_iterations def main(): # test() p = input("Please enter initial population size in the range (10, 1000): ") if int(p) < 10 or int(p) > 1000: print('You entered a bad population number. Exiting') exit() pop_size = int(p) m = input("Please enter mutation rate as a percentage in the range (0, 100): ") if int(m) < 0 or int(m) > 100: print('You entered a bad mutation percentage. Exiting') exit() mutation_thresh = (100 - int(m))/100 mutation_rate = int(m) #breeding frequencies avg1, is_til_goal = genetic_eight_queens(pop_size, mutation_thresh) print('\n') # pp = PdfPages('plot.pdf') # print(avg1) x1 = [avg[0] for avg in avg1] y1 = [avg[1] for avg in avg1] # print(x1) # print(y1) print("plot ready") plt.title(f'total iterations: {is_til_goal}| population size: {pop_size}| mutation rate: {mutation_rate} ') plt.xlabel('Generation') plt.ylabel('Average Fitness') plt.scatter(x1, y1) plt.show() if __name__ == "__main__": main() # %%
470d83e0c57151a4ac54e15c22a5a36befc592c5
JansherKhantajik/Python
/first program.py
613
4.03125
4
#print a program which input number from user and you will give 5 guess to equvalate with your answer print("Word of Guess Number, Input Your Guess that You have five chance") guess = int(input()) i=0 while (True): if (guess <15): print("Please Enter more then",guess) break elif guess <20 and guess >15: print("little More then",guess) elif guess <35 and guess >25: print("Enter less then",guess) elif guess <25 and guess >20: print("Congurate You Have Got it Number is Between 20 to 25 .. your guess ",guess) else: print("Invelid number") i=i+1 break
409ef68a67f735a647f22040ad7c1086cd991de2
sleevewind/practice
/0217/列表的复制.py
133
3.71875
4
# 可变类型和不可变类型 a = 12 b = a print('a={},b={}'.format(hex(id(a)), hex(id(b)))) # a=0x7ff95c6a2880,b=0x7ff95c6a2880
0b8fd9d19b5e21325b8499480ed594c2a33a9740
sleevewind/practice
/0217/列表的排序和反转.py
396
4.0625
4
# sort()直接对列表排序 nums = [6, 5, 3, 1, 8, 7, 2, 4] nums.sort() print(nums) # [1, 2, 3, 4, 5, 6, 7, 8] nums.sort(reverse=True) print(nums) # [8, 7, 6, 5, 4, 3, 2, 1] # sorted()内置函数, 返回新的列表, 不改变原来的列表 print(sorted(nums)) # [1, 2, 3, 4, 5, 6, 7, 8] # reverse() nums = [6, 5, 3, 1, 8, 7, 2, 4] nums.reverse() print(nums) # [4, 2, 7, 8, 1, 3, 5, 6]
f889d7e66bf7bd2b2dd2647cf64cdfe91189052e
sleevewind/practice
/0217/列表的增删改查.py
1,466
3.5625
4
# 操作列表, 一般包括 增删改查 heroes = ['镜', '嬴政', '露娜', '娜可露露'] # 添加元素的方法 # append heroes.append('黄忠') print(heroes) # 在列表最后面追加 # insert(index, object) 在指定位置插入 heroes.insert(1, '小乔') print(heroes) newHeroes = ['狄仁杰', '王昭君'] # extend(iterable) 添加可迭代对象 heroes.extend(newHeroes) print(heroes) # 删除元素 pop print(heroes) # ['镜', '小乔', '嬴政', '露娜', '娜可露露', '黄忠', '狄仁杰', '王昭君'] x = heroes.pop() # 删除并返回 print(x) # 王昭君 x = heroes.pop(2) # 删除指定下标的元素 print(x) # 嬴政 print(heroes) # ['镜', '小乔', '露娜', '娜可露露', '黄忠', '狄仁杰'] # remove heroes.remove('小乔') # 删除不存在的会报错 print(heroes) # ['镜', '露娜', '娜可露露', '黄忠', '狄仁杰'] # del关键字 这个功能强大, 列表删除少用 del heroes[2] print(heroes) # ['镜', '露娜', '黄忠', '狄仁杰'] # clear heroes.clear() print(heroes) # [] # 查询 heroes = ['镜', '小乔', '镜', '露娜', '娜可露露', '黄忠', '狄仁杰'] print(heroes.index('镜')) # 返回下标, 不存在元素报错 print(heroes.count('镜')) # 2, 返回个数 # in 运算符 flag = '小乔' in heroes print(flag) # True # 修改元素, 使用下标直接修改 heroes[1] = '镜' print(heroes) # ['镜', '镜', '镜', '露娜', '娜可露露', '黄忠', '狄仁杰']
bb22aef9984883cee87a02c39b509e7d496a4107
innovatorved/python-recall
/py51-python-cahching-by-funtools.py
386
3.578125
4
# python3 py51-python-cahching-by-funtools.py import time from functools import lru_cache @lru_cache(maxsize = 3) # save last 3 value def sleep_n_time(n): time.sleep(n) return n if __name__ == "__main__": print(sleep_n_time(3)) # it create an cahe for this same def for for reducing time and space print(sleep_n_time(3)) print(sleep_n_time(2))
2c55330c7204f8bceaa6eed1e9533f05a6e18b1e
innovatorved/python-recall
/py40-access-specifier-public-private.py
918
3.796875
4
# Access Specifier # public # protected # private class Student: public_var = "this variable is public" _protected_var = "this is private var" __private_var = "this is private var" def __init__(self ,public , protected , private): self.public = public self._protected = protected self.__private = private if __name__ == "__main__": ved = Student("Name : Ved Prakash Gupta" , "Age : 19" , "Mobile:7007868719") print(ved.public) # Output :'Name : Ved Prakash Gupta' print(ved._protected) # Output : 'Age : 19' print(ved.__private) # Output : """Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> ved.__private AttributeError: 'Student' object has no attribute '__private'""" print(ved._Student__private) # Output : 'Mobile:7007868719' # private variable acces by classs define
a32d740aaec9947b0f5b7d64a72a47f10a28718a
innovatorved/python-recall
/py49-genrators-ex1.py
288
3.609375
4
# python3 py49-genrators-ex1.py n = 10 def fib(a=0 , b = 1): for x in range(n): yield (a+b) a , b = b , b+a a = fib(0,1) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(a.__next__())
8207d31429cc76165b8136f1c186f7d0f39bd62b
innovatorved/python-recall
/py20 - enumeratefin.py
522
3.90625
4
#enumerate function a = ["ved" , "Prakash" , "Gupta" , "hello"] i = 1 for item in a: #print(item) if i%2 != 0: print(f"item {item}") i+= 1 #with enumerate function print(enumerate(a)) # Output : <enumerate object at 0x000002452601E700> print(list(enumerate(a))) # Output : [(0, 'ved'), (1, 'Prakash'), (2, 'Gupta'), (3, 'hello')] for index , item in enumerate(a): print(f"index is {index} and value is {item}") if index%2 != 0: print(f"item {item}")
7d828ae6dabb5d3283927d7ec88800acd45164d2
innovatorved/python-recall
/py6 - list.py
643
3.671875
4
# List Name = [ "Ved Gupta" ," Ramesh Prasad" , "Anand Kumar" "Shrish Guptas" , "Rishi sharma" ] Age = [20,56,89,12,45] print(type(Name),type(Age)) # Age.sort() print(Age) print(sum(Age)) print(min(Age)) print(max(Age)) print(len(Age)) Age.reverse() print(Age) Age.sort() print(Age) new = sorted(Age) print(new) """ <class 'list'> <class 'list'> [20, 56, 89, 12, 45] 222 12 89 5 [45, 12, 89, 56, 20] [12, 20, 45, 56, 89] [12, 20, 45, 56, 89] """ print(Age) new = Name.copy() print(new) print(new.count("Ved Gupta")) new.clear() print(new) """ [12, 20, 45, 56, 89] ['Ved Gupta', ' Ramesh Prasad', 'Anand KumarShrish Guptas', 'Rishi sharma'] 1 [] """
7f71835bcdea55a10aef9e2602161ea23d979484
innovatorved/python-recall
/start-dynamic/fibonachi-sequence.py
138
3.65625
4
# python3 fibonachi-sequence.py def fib_seq(n ,a=0,b=1): if n != 0: print(a+b) fib_seq(n-1 ,b,a+b) fib_seq(5)
382a67dd059c8a7b93b9e01bfeacc25424f32307
innovatorved/python-recall
/py17 - Fabonachi Sequence.py
306
3.71875
4
# Fabonachi Sequence # find fabonachi sequene def fab(n,a = 0 , b = 1): if n > 0: c = a+b print(c) fab(n-1,b,c) a = int(input("How much No . of sequence you want to find :")) fab(a) """ How much No . of sequence you want to find :10 1 2 3 5 8 13 21 34 55 89 """
d393755ca2b2661c053f02573f582213d0bd1f32
innovatorved/python-recall
/py48-genrators-yield.py
574
4.0625
4
# python3 py48-genrators-yield.py """ Iterable : __iter__() or __getitem__() Iterator : __next__() Iteration : """ # genrators are iteraators but you can only iterate ones def range_1_to_n(n) : for x in range(1 , n): yield x print(range_1_to_n(10)) num = range_1_to_n(10) print(num.__next__()) # 1 print(num.__next__()) # 2 # __iter__() a = "Ved Prakash Gupta" li = [1,2,3,4,5,6,7,8,9] a = iter(a) b = iter(li) print(a.__next__()) print(b.__next__()) print(a.__next__()) print(b.__next__()) print(a.__next__()) print(b.__next__())