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
e5a741e738040de2e2b62dd7515e2ae5afa31440
lucas-cavalcanti-ads/projetos-fiap
/1ANO/PYTHON/ListaExercicios/Lista02/Ex03.py
808
4.15625
4
teclado = input("Digite o primeiro numero: ") num1 = int(teclado) teclado = input("Digite o segundo numero: ") num2 = int(teclado) soma = num1 + num2 somar = str(soma) subtracao = num1 - num2 subtracaor = str(subtracao) multiplicacao = num1 * num2 multiplicacaor = str(multiplicacao) divisao = num1 / num2 divisaor = str(divisao) resto = num1 % num2 restor = str(resto) numero1 = str(num1) numero2 = str(num2) print("A soma de " + numero1 + " + " + numero2 + " e igual a: " + somar) print("A soma de " + numero1 + " + " + numero2 + " e igual a: " + subtracaor) print("A multiplicacao de " + numero1 + " + " + numero2 + " e igual a: " + multiplicacaor) print("A divisao de " + numero1 + " + " + numero2 + " e igual a: " + divisaor) print("O resto de " + numero1 + " + " + numero2 + " e igual a: " + restor)
818d2ff7650a21dd1d3eca826e0c9862e448e007
LeonardoARGR/Desafios-Python-Curso-em-Video
/Mundo-1/desafio-009.py
1,304
3.640625
4
cores = {'limpo': '\033[m', 'ciano': '\033[1;36m', 'roxo': '\033[1;35m', 'azul': '\033[1;34m'} n = int(input('Coloque um número para ver sua tabuada: ')) n1 = n * 1 n2 = n * 2 n3 = n * 3 n4 = n * 4 n5 = n * 5 n6 = n * 6 n7 = n * 7 n8 = n * 8 n9 = n * 9 n10 = n * 10 print(f'{cores["azul"]}============{cores["limpo"]}\n' f'{cores["ciano"]}{n} x 1{cores["limpo"]} = {cores["roxo"]}{n1}{cores["limpo"]}\n' f'{cores["ciano"]}{n} x 2{cores["limpo"]} = {cores["roxo"]}{n2}{cores["limpo"]}\n' f'{cores["ciano"]}{n} x 3{cores["limpo"]} = {cores["roxo"]}{n3}{cores["limpo"]}\n' f'{cores["ciano"]}{n} x 4{cores["limpo"]} = {cores["roxo"]}{n4}{cores["limpo"]}\n' f'{cores["ciano"]}{n} x 5{cores["limpo"]} = {cores["roxo"]}{n5}{cores["limpo"]}\n' f'{cores["ciano"]}{n} x 6{cores["limpo"]} = {cores["roxo"]}{n6}{cores["limpo"]}\n' f'{cores["ciano"]}{n} x 7{cores["limpo"]} = {cores["roxo"]}{n7}{cores["limpo"]}\n' f'{cores["ciano"]}{n} x 8{cores["limpo"]} = {cores["roxo"]}{n8}{cores["limpo"]}\n' f'{cores["ciano"]}{n} x 9{cores["limpo"]} = {cores["roxo"]}{n9}{cores["limpo"]}\n' f'{cores["ciano"]}{n} x 10{cores["limpo"]} = {cores["roxo"]}{n10}{cores["limpo"]}\n' f'{cores["azul"]}============{cores["limpo"]}')
4ccbdf4786b3193c3184f8738b5da13112ee2856
LeonardoARGR/Desafios-Python-Curso-em-Video
/Mundo-2/desafio-041.py
393
3.953125
4
import datetime ano = int(input('Que ano o atleta nasceu?: ')) idade = datetime.date.today().year - ano print(f'Quem nasceu em {ano} tem {idade} anos') if 0 < idade <= 9: print('Atleta MIRIM') elif 9 < idade <= 14: print('Atleta INFANTIL') elif 14 < idade <= 19: print('Atleta JUNIOR') elif 19 < idade <= 25: print('Atleta SÊNIOR') elif 25 < idade: print('Atleta MASTER')
146df0a1eabd265184c94297aedd218347f754ce
LeonardoARGR/Desafios-Python-Curso-em-Video
/Mundo-2/desafio-056.py
783
3.5625
4
médiaidade = 0 maioridadehomem = 0 nomevelho = '' mulheresmaisnovas = 0 for p in range(1, 5): print(f'{"=" * 9}{p}ª Pessoa{"=" * 9}') nome = str(input('Nome: ')).strip() idade = int(input('Idade: ')) sexo = str(input('Sexo [H/M]: ')).strip().upper() médiaidade += idade if p == 1 and sexo == 'H': maioridadehomem = idade nomevelho = nome if sexo == 'H' and idade > maioridadehomem: maioridadehomem = idade nomevelho = nome if sexo == 'M' and 0 < idade < 20: mulheresmaisnovas += 1 print(f'A média de idade deste grupo é de {médiaidade / 4 :.1f}') print(f'O homem mais velho é o {nomevelho}, e ele tem {maioridadehomem} anos') print(f'Nesse grupo temos {mulheresmaisnovas} mulheres com menos de 20 anos')
75578330aed370156506f96dbd89fce55a72287b
LeonardoARGR/Desafios-Python-Curso-em-Video
/Mundo-3/desafio-093.py
1,000
3.84375
4
# Declarando as variáveis. jogador = dict() gols = list() # Adicionando os valores ao dicionário "jogador". jogador['nome'] = str(input('Nome do jogador: ')).strip().title() partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou?: ')) # Pegando os gols de cada partida utilizando o FOR. for g in range(0, partidas): gols.append(int(input(f'Quantos gols na {g+1}ª partida?: '))) jogador['gols'] = gols[:] jogador['total'] = sum(gols) # Mostrando o dicionário print('-=-' * 30) print(jogador) # Mostrando na tela os valores de cada key do dicionário "jogador". print('-=-' * 30) for k, v in jogador.items(): print(f'O campo {k} tem o valor {v}.') # Mostrando na tela a quantidade de partidas jogadas e os gols de cada uma, e o total de gols. print('-=-' * 30) print(f'O jogador {jogador["nome"]} jogou {partidas} partidas.') for p in range(0, partidas): print(f' -> Na {p+1}ª partida, fez {jogador["gols"][p]} gols.') print(f'Foi um total de {jogador["total"]} gols.')
578d0f26d1f90ca422737d6201e56fe3de3d8adc
LeonardoARGR/Desafios-Python-Curso-em-Video
/Mundo-3/desafio-084.py
1,027
3.765625
4
dados = list() pessoas = list() maiornome = list() menornome = list() cont = maior = menor = -1 while True: dados.append(str(input('Nome: ')).strip()) dados.append(float(input('Peso: '))) if len(pessoas) == 0: maior = menor = dados[1] else: if dados[1] > maior: maior = dados[1] if dados[1] < menor: menor = dados[1] pessoas.append(dados[:]) dados.clear() escolha = str(input('Deseja continuar?: [S/N] ')).strip().upper()[0] if escolha not in 'SN': while escolha not in 'SN': escolha = str(input('Opção inválida. Deseja continuar?: [S/N] ')).strip().upper()[0] if escolha == 'N': break print('=' * 35) print(f'Você registrou {len(pessoas)} pessoas.') print(f'O maior peso é de {maior}Kg. Peso de ', end='') for p in pessoas: if p[1] == maior: print(p[0], end=' ') print() print(f'O menor peso é de {menor}Kg. Peso de ', end='') for p in pessoas: if p[1] == menor: print(p[0], end=' ')
34158e8e5e3089846814464a58d30a99a9963e5c
LeonardoARGR/Desafios-Python-Curso-em-Video
/Mundo-2/desafio-036.py
559
4
4
valordacasa = float(input('Qual é o valor da casa?: R$')) salário = float(input('Qual o seu salário?: R$')) anos = int(input('Por quantos anos você vai pagar a casa?: ')) print(f'Para pagar uma casa de R${valordacasa :.2f} em {anos} anos, a prestação mensal será de R${valordacasa / anos / 12 :.2f}') if valordacasa / anos / 12 > salário * 30 / 100: print(f'Desculpe, mas você não pode financiar essa casa, emprestimo NEGADO.') elif valordacasa / anos / 12 <= salário * 30 / 100: print(f'Você pode financiar a casa, emprestimo APROVADO.')
910adfeb6b500f702e90a782fbedb43fceaf939b
LeonardoARGR/Desafios-Python-Curso-em-Video
/Mundo-2/desafio-044.py
1,037
3.875
4
preço = float(input('Qual o preço do produto ou das compras?: ')) print('Escolha a forma de pagamento:') print('''1- À vista com dinheiro/cheque (10% de desconto) 2- À vista no cartão (5% de desconto) 3- 2x no cartão (preço normal) 4- 3x ou mais no cartão (20% de juros)''') escolha = int(input('Qual forma de pagamento você escolhe?: ')) if escolha == 1: print(f'O preço do produto à vista com dinheiro/cheque é de R${preço - (preço * 10 / 100)}') elif escolha == 2: print(f'O preço do produto à vista no cartão é de R${preço - (preço * 5 / 100)}') elif escolha == 3: print(f'O preço do produto dividido 2x no cartão não muda, ainda é R${preço} com parcelas de R${preço / 2}') elif escolha == 4: parcelas = int(input('Quantas parcelas?: ')) print(f'''O preço do produto dividido em {parcelas}x no cartão é de R${preço + (preço * 20 / 100) :.2f}, e as parcelas irão custar R${(preço + (preço * 20 / 100)) / parcelas :.2f}''') else: print('Esta opção de pagamento não existe')
382926b8adb929eb319e68152c815c25b60c1c88
LeonardoARGR/Desafios-Python-Curso-em-Video
/Mundo-3/desafio-097.py
380
3.703125
4
# Criando uma função que digita uma mensagem no meio de duas linhas. def escreva(msg): # Fazendo com que a linha tenha um tamanho que se adapta a mensagem. print('~' * (len(msg)+4)) print(f' {msg}') print('~' * (len(msg)+4)) # Programa pricipal - Usando a função "escreva" na prática. escreva('Gustavo Guanabara') escreva('Curso de Python no YouTube') escreva('CeV')
0bb3bd040ef8d9316111b4f82a9416b13e81ac75
LeonardoARGR/Desafios-Python-Curso-em-Video
/Mundo-1/desafio-007.py
357
3.609375
4
cores = {'limpo': '\033[m', 'verde': '\033[1;32m', 'vermelho': '\033[1;31m'} n1 = float(input('Primeira Nota: ')) n2 = float(input('Segunda Nota: ')) m = (n1+n2) / 2 if m < 5: print('A sua nota foi {}{}{}'.format(cores['vermelho'], m, cores['limpo'])) else: print('A sua nota foi {}{}{}'.format(cores['verde'], m, cores['limpo']))
cb47ef51e8c71a29c9f0d1345210b2242382be50
naodell/Project-Euler
/Page 1/problem_34.py
484
3.71875
4
''' 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. ''' import math number = 11 answer = 0 while(number < 2.6e6): digits = str(number) digitSum = 0 for digit in digits: digitSum += math.factorial(int(digit)) if number == digitSum: answer += number number += 1 print answer
baec9cad1d5d24f74935ccd2d537b33c11ca7093
naodell/Project-Euler
/Page 1/problem_38.py
1,128
4.03125
4
''' Take the number 192 and multiply it by each of 1, 2, and 3: 192 x 1 = 192, 192 x 2 = 384, 192 x 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3). The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? ''' number = 1 panDigits = ''.join([str(i) for i in range(1,10)]) while(number < 100000): ccNumber = 0 multiplier = 1 ccString = '' isPandigital = False while ccNumber < 1e10 and multiplier < number: ccString += str(number*multiplier) ccNumber = int(ccString) #print ccString, ''.join(sorted(ccString)) if ''.join(sorted(ccString)) == panDigits: isPandigital = True break multiplier += 1 if isPandigital: print number, ccNumber number += 1
ec7dc5024c1fd2c5fd017120e3b8ceb45b0fe2c8
naodell/Project-Euler
/Page 1/problem_44.py
957
3.703125
4
''' Pentagonal numbers are generated by the formula, P_n=n(3n-1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P_4 + P_7 = 22 + 70 = 92 = P_8. However, their difference, 70 - 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, P_j and P_k, for which their sum and difference are pentagonal and D = |P_k - P_j| is minimised; what is the value of D? ''' import numpy as np pentNums = [n*(3*n - 1)/2 for n in range(1,10000)] isOptimized = False count = 1 minDiff = 1e9 for i,n in enumerate(pentNums): for m in pentNums[:i]: pentSum = n + m pentDiff = abs(n - m) if pentSum > pentNums[-1]: break if pentSum in pentNums and pentDiff in pentNums: candidate = (n,m) if pentDiff < minDiff: minDiff = pentDiff print candidate print 'The value of D is {0}'.format(cadidate[0]-candidate[1])
a050956731ea15251b18a627eb6be527430f8032
naodell/Project-Euler
/Page 1/problem_16.py
268
3.75
4
''' 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? ''' bigNumber = pow(2, 1000) bigString = str(bigNumber) powSum = 0 for number in bigString: powSum += int(number) print bigNumber, powSum
5f9b05e919c0dda6fb13f10c86b418a135adf623
naodell/Project-Euler
/Page 1/problem_22.py
984
3.875
4
''' Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 x 53 = 49714. What is the total of all the name scores in the file? ''' alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' namesFile = open('names.txt', 'r') names = namesFile.read() nameList = sorted(names.split(',')) nameScores = [] for i,name in enumerate(nameList): score = 0 for letter in name: if letter in alphabet: score += alphabet.index(letter) + 1 score *= i+1 nameScores.append(score) print 'And the answer is ... {0}'.format(sum(nameScores))
40a915b242ccf97509ff90279b0ec32af81946b6
PierpaoloLucarelli/IR_door_alarm
/activity_monitor/MonitorFSM.py
3,340
3.515625
4
''' Author : Pierpaolo Lucarelli MonitorFSM class taht extends the FSM class. this class ir sesponsible for handling the I/O of the machine Give a certain type of input and the correct type of output will be send ''' from FSM import * class MonitorFSM(FSM): startState = 'deactivated' codeState = 0 #state of the code [0,1,2,3,accepted] def getNextValues(self, state, inp): if state == 'deactivated' or state == "deactivated-trans": if inp == "Up" or inp == "Down" or inp == "Left" or inp == "Right": self.check_code(inp) # print("Code state: %s" % self.codeState) if self.codeState == 0: return ("deactivated", "cross") elif self.codeState in (1,2,3): return ("deactivated-trans", "right_arrow") elif self.codeState == "accepted": self.codeState = 0 #when code is correct reset the code state to zero and ouput red circle return ("deactivated-in-trans", "empty_circle_red") elif inp != "IRSens": #for any input other than Sensor input and dirKeys print("unacepted input") self.codeState = 0 return("deactivated", "cross") #machine state back to start (deactivated) #from here machine is in activated sate elif state == "activated" or state == "activated-trans": if inp == "IRSens": return ("activated", "alarmed") #alarm is alarmed when IR signal is recieved if inp == "Up" or inp == "Down" or inp == "Left" or inp == "Right": self.check_code(inp) # print("Code state: %s" % self.codeState) if self.codeState == 0: return ("activated", "full_circle_green") #if code is incorrect return to activated state elif self.codeState in (1,2,3): return ("activated-trans", "left_arrow") elif self.codeState == "accepted": self.codeState = 0 #reset code check to zero for next code check return ("deactivated", "cross") elif inp != "IRSens" : #for any input other that IRsens and dirKeys self.codeState = 0 return ("activated", "full_circle_green") #return to activated state #this function gets called when a key is entered, check if the sequience of theese key is Up, Down, Left, Right def check_code(self,inp): if self.codeState == 0: if inp == "Up": self.codeState = 1 else: self.codeState = 0 elif self.codeState == 1: if inp == "Down": self.codeState = 2 else: self.codeState = 0 elif self.codeState == 2: if inp == "Left": self.codeState = 3 else: self.codeState = 0 elif self.codeState == 3: if inp == "Right": self.codeState = "accepted" #change state of codeState to accepted when sequence is correct else: self.codeState = 0 else: print ("Something went wrong in the code (test only)")
86aeb48adfad7762a2ac64e0fe85f50ee7af91b7
noahklein/daily-coding-problem
/088.py
428
4.09375
4
""" Implement division of two positive integers without using the division, multiplication, or modulus operators. Return the quotient as an integer, ignoring the remainder. """ def divides(a, b): if b == 0: raise ArithmeticError() if a < b: return 0 return 1 + divides(a - b, b) assert(divides(10, 1) == 10) assert(divides(0, 100) == 0) assert(divides(17, 4) == 4) assert(divides(100, 5) == 20)
5427437c4317a369825b00c755eb1a2b81ae4de5
3leonora/fourier-lab
/exercise1.py
1,622
3.59375
4
''' Exercise 1 Fouriertransform of function with a period of 2pi Dependencies: numpy, matplotlib Authors: @Eleonora Svanberg @Henrik Jörnling ''' #hej #Modules import numpy as np import matplotlib.pyplot as plt def xarray(N: int) -> np.ndarray: '''Array with x values''' return np.linspace(0., 2.*np.pi, N, endpoint=False) def gx(x: np.ndarray) -> np.ndarray: '''Gives np array with g(x) values''' return 3.*np.sin(2.*x)+2.*np.cos(5.*x) # a) N1 = 100 # number of data points N2 = 50 x1 = xarray(N1) x2 = xarray(N2) # b) gx1 = gx(x1) gx2 = gx(x2) # c) plt.plot(x1, gx1, label=f'N={N1}') # Plot signal g(x) vs x plt.plot(x2, gx2, label=f'N={N2}' ) plt.legend() plt.show() # d) Fgx1 = np.fft.rfft(gx1) # Fouriertransfor F(g) of real signal g(x) (r = real) Fgx2 = np.fft.rfft(gx2) print(f'Size of Fgx1 (N={N1}): {len(Fgx1)}') print(f'Size of Fgx2 (N={N2}): {len(Fgx2)}') # e) print(f'c_2={Fgx1[2]:.1f}') #c_2=0.0-150.0j, c_2*N print(f'c_5={Fgx1[5]:.1f}') #c_5=100.0+0.0j, c_5*N plt.plot(np.real(Fgx1),'o', color='g', label=f'N={N1}') # Plot real part of Fgx vs looping index plt.plot(np.imag(Fgx1),'o', color='r') # Plot imaginary part of Fgx vs looping index plt.plot(np.real(Fgx2),'x', color='g', label=f'N={N2}') plt.plot(np.imag(Fgx2),'x', color='r') plt.title('Complex Fourier (green-real, red-imag)') plt.legend() plt.show() plt.plot([2*z/N1 for z in np.real(Fgx1)],'o', color='g', label='a') # Plot real part of Fgx vs looping index plt.plot([-2*z/N1 for z in np.imag(Fgx1)],'o', color='r', label='b') # Plot imaginary part of Fgx vs looping index plt.title(f'Real Fourier (N={N1})') plt.legend() plt.show()
56580b82fb7ecef03712dfecdb2f1e72d0442cff
KraProgrammer/AdventOfCode2020
/src/day23.py
3,892
3.515625
4
from aocd.models import Puzzle class Node: def __init__(self, data, prev_node, next_node): self.data = data self.prev_node = prev_node self.next_node = next_node class LinkedList: def __init__(self): self.index = {} def append(self, prev, data) -> Node: if prev is None: node = Node(data, None, None) node.next_node = node node.prev_node = node self.index[data] = node return node else: node = Node(data, prev, prev.next_node) prev.next_node = node node.next_node.prev_node = node self.index[data] = node return node def get(self, data) -> Node: return self.index[data] def len(self): return len(self.index) def to_list(self, start): node = self.get(start) array = [node.data] node = node.next_node while node.data != start: array.append(node.data) node = node.next_node return array def solve_puzzle_one(input): print(input) llist = LinkedList() prev = None for num in input: prev = llist.append(prev, num) current = llist.get(input[0]) move = 0 while move < 100: move += 1 pickup_start = current.next_node pickup_end = pickup_start.next_node.next_node skips = [] c = pickup_start for _ in range(3): skips.append(c.data) c = c.next_node pickup_end.next_node.prev_node = current current.next_node = pickup_end.next_node num = current.data destination = llist.len() if num == 1 else num - 1 while destination in skips: destination = llist.len() if destination == 1 else destination - 1 destination_node = llist.get(destination) pickup_end.next_node = destination_node.next_node destination_node.next_node.prev_node = pickup_end destination_node.next_node = pickup_start pickup_start.prev_node = destination_node current = current.next_node print(''.join([str(x) for x in llist.to_list(1)[1:]])) def solve_puzzle_two(input): print(input) llist = LinkedList() prev = None for num in input: prev = llist.append(prev, num) v = llist.len() + 1 while llist.len() < 1000000: prev = llist.append(prev, v) v += 1 current = llist.get(input[0]) move = 0 while move < 10000000: move += 1 pickup_start = current.next_node pickup_end = pickup_start.next_node.next_node skips = [] c = pickup_start for _ in range(3): skips.append(c.data) c = c.next_node pickup_end.next_node.prev_node = current current.next_node = pickup_end.next_node num = current.data destination = llist.len() if num == 1 else num - 1 while destination in skips: destination = llist.len() if destination == 1 else destination - 1 destination_node = llist.get(destination) pickup_end.next_node = destination_node.next_node destination_node.next_node.prev_node = pickup_end destination_node.next_node = pickup_start pickup_start.prev_node = destination_node current = current.next_node print(llist.get(1).next_node.data) print(llist.get(1).next_node.next_node.data) print(llist.get(1).next_node.next_node.data * llist.get(1).next_node.data) def parse_input(data): return [int(num) for num in data] test_input = """389125467""" if __name__ == '__main__': puzzle = Puzzle(year=2020, day=23) input = puzzle.input_data if False: input = test_input solve_puzzle_one(parse_input(input.strip())) solve_puzzle_two(parse_input(input.strip()))
529a0ae383f5e1650a35935e51e289f13dd8d1e5
KraProgrammer/AdventOfCode2020
/src/day21.py
2,197
3.5
4
from collections import defaultdict from aocd.models import Puzzle def solve_puzzle_one(input_array): counter, ingredients, allergens, possible_allergens = get_data(input_array) c = 0 for i in ingredients: if not possible_allergens[i]: c += counter[i] print(c) def get_data(input_array): ingredients = set() allergens = set() for i, a in input_array: ingredients = ingredients.union(i) allergens = allergens.union(a) possible_allergens = {i: allergens.copy() for i in ingredients} counter = defaultdict(int) for i_of_food, a_of_food in input_array: for a in a_of_food: for i in ingredients: if i not in i_of_food: possible_allergens[i].discard(a) for i in i_of_food: counter[i] += 1 return counter, ingredients, allergens, possible_allergens def solve_puzzle_two(input_array): counter, ingredients, allergens, possible_allergens = get_data(input_array) mapping = {} used = set() while len(mapping) < len(allergens): for i in ingredients: possible = [a for a in possible_allergens[i] if a not in used] if len(possible) == 1: mapping[i] = possible[0] used.add(possible[0]) s = "" # https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value array = [k for k, v in sorted(mapping.items(), key=lambda item: item[1])] print(','.join(array)) def parse_input(data): array = [] for line in data.splitlines(): i, rest = line.split('(contains ') ingredients = set(i.split()) allergens = set(rest[:-1].split(", ")) array.append((ingredients, allergens)) return array test_input = """mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish)""" if __name__ == '__main__': puzzle = Puzzle(year=2020, day=21) input = puzzle.input_data if False: input = test_input solve_puzzle_one(parse_input(input.strip())) solve_puzzle_two(parse_input(input.strip()))
7f2f690fa1b67d1c43566771e783c08d2eb57588
jamathis77/Python-fundamentals
/conditionals.py
2,444
4.28125
4
# A conditional resolves to a boolean statement ( True or False) left = True right = False # Equality Operators left != right # left and right are not equivalent left == right # left and right are equivalent left is right # left and right are same identity left is not right # Left and right are not same identity age_1 = 23 age_2 = 45 # Comparison Operators age_1 > age_2 # left is greater than right age_1 < age_2 age_1 >= age_2 age_1 <= age_2 # Logical Operators age_1 == 4 and age_2 < 22 # and operator (True) and (True) age_1 == 4 or age_2 < 22 # or operator not age_1 == 23 # a b a and b #------------------------------- # True True True # True False False # False True False # False False False # a b a or b # ----------------------------- # True True True # True False True # False True True # False False False # a not a # --------------- # True False # False True # x = 3 # name = "Ryan" # if x > 3 and name == "Ryan": # if True: # print("I'm inside of an if if statment") # print("X is pretty big, and that person's name is ryan") # elif x <= 3: # print("Maybe x is big, idunno") # else: # print("Otherwise, no") # Challenge # Take a name and age, and if the person is under 18, say "NAME, you are not an adult", # if the person is 18 but not 21, say "You are an adult, but not quite yet" # if the person is 21 and older, say ' You are fully an adult ' # cases ( 12, 18, 20, 21, 89 ) # extra spicy # If their name starts with an A, say "Cool name" # name = input("What is your name? > ") # age = int(input("What is your age? > ")) # if age in range(18): # print(f"{ name }, you are not an adult") # elif age in range(18, 21): # print("You are an adult, ish") # elif age >= 21: # print("You are a big person now") # if name[0].lower() == "a": # print("Cool name") # Declare a number # If the number is divisible by 3, print "Fizz" # If the number is divisible by 5, print "Buzz" # If the number is divisible by both 3 AND 5, print ONLY "FizzBuzz" # Otherwise, just print the number # Test cases: 1, 3, 5, 10, 15, 98 number = 98 if number % 3 == 0 and number % 5 == 0: # Or number % 15 == 0 print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number)
ce124a17f9b0f62b3a8f2f457f28a0fdf6c0babb
evargas1/Algorthims
/Non_repeat_elements.py
1,653
3.609375
4
""" Linear time solution Non repeat element Take a string and return characters that never repeats if mutiple unique then only return only the first unique character This algo is really helpful in cyber sercuity! """ def non_repeating(s): s = s.replace(' ', '').lower() char_count = {} # answer = set() # could make this a set and use # the add varaible or you could # make it an empty list and # append the letter # but i think set works better # to catch erros for c in s: if c in char_count: char_count[c] += 1 else: char_count[c] = 1 # for c in s: # if char_count[c] == 1: # answer.add(c) answer = [ c for c in s if char_count[c]==1] return answer print(non_repeating('I apple Love eating')) def non(s): char_count = {} s = s.replace(' ', '').lower() for c in s: if c in char_count: char_count[c] += 1 else: char_count[c] = 1 unique = [] y = sorted( char_count.items(), key=lambda x: x[1] # will sort by second # tuple posistion in this # case the value ) print(y[0]) print(y) for item in y: # checking the index # posistion of 1 now a tuple # which use to be the value # or number print(item) if item[1] == y[0][1]: # [0] first value # [1] the value in the first key value # index posistion? unique.append(item) return unique print(non('uuu iiiiiikkkkkklllll'))
edf5f02ad075fcac802302e8f71bc62746d6d051
jacob-brown/programming-notes-book
/programming_notes/_build/jupyter_execute/python_basic.py
4,747
4.46875
4
# Python: Basics ## Lists Methods: * `append()` * `clear()` * `copy()` * `count()` * `extend()` * `index()` * `insert()` * `pop()` * `remove()` * `reverse()` * `sort()` demoList = ["apple", "banana", "orange", "kiwi"] print(demoList) Adding/Removing items demoList.append('cherry') print(demoList) demoList.insert(1, 'grape') print(demoList) join 2 lists thislist = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical) print(thislist) or... thislist = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] thislist + tropical Removing items demoList = ["apple", "banana", "orange", "kiwi"] demoList.remove('apple') print(demoList) demoList.pop(1) print(demoList) del demoList[0] print(demoList) demoList.clear() # removes all items print(demoList) ## Copying a list make sure the lists aren't linked, with a deep copy thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist) del thislist[1] print(thislist) print(mylist) ## Tuples unchangeable `count()` and `index()` tupExample = (1, 2, 3) tupExample ## Sets unordered and unindexed, adding/removing is possible but not changing thisset = {"apple", "banana", "cherry"} thisset.add("orange") print(thisset) ## Dictionaries fruitDict = { "type" : "apple", "colour" : ["red", "green"], "weight" : 200 } print(fruitDict) print(fruitDict["type"]) fruitDict.get("weight") fruitDict.keys() fruitDict.values() fruitDict.items() Changing, adding, and removing items in a dictionary fruitDict = { "type" : "apple", "colour" : ["red", "green"], "weight" : 200 } fruitDict["weight"] = 500 print(fruitDict) fruitDict.update({"smell" : "appley"}) print(fruitDict) fruitDict["season"] = "summer" print(fruitDict["season"]) del fruitDict["colour"] print(fruitDict) ## Loops for i in range(0,5): print(i) x = 0 while x < 6: print(x) x = x + 1 breaks within loops x = 0 while x < 6: print(x) if x == 4: break x = x + 1 continue jumps back to the start of the loop x = 0 while x < 6: x += 1 if x == 4: continue print(x) i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6") ## Conditions (If..Else) a = 2 b = 20 if a > b: print("a is larger") elif a == b: print("they are equal") else: print("b is larger") a = 200 b = 33 c = 500 if a > b or a > c: print("At least one of the conditions is True") use `pass` to avoid an error. if 1 > 10: pass ## List Comprehension newList = ["apple", "banana", "cherry"] [x for x in newList] [x for x in newList if x != 'apple'] [x for x in newList if x != 'apple'] [x.upper() for x in newList] ## Functions and lambda lambda can have only one expression def printHello(): print("Hello") printHello() addTen = lambda x : x + 10 addTen(2) x = lambda a, b : a * b print(x(5, 6)) ## Key Concepts of Functions **Parameter** - varriable listed *when defining* the function **Argument** (args)- value that is sent to the function. Passes into a list **Keyword Argument** (kwargs) - arguments wth a *key = value* syntax. Passes into a dict ```{python} def add(a, b): # a and b are parameters return a+ b add(1, 2) # 1 and 2 are arguments add(a = 1, b = 2) # both are keyword arguments ``` N.B. positional arguments are those not defined with a keyword If we do not know how many positional arguments to pass use `*` def tupleOfNumbers(*numbers): return numbers tupleOfNumbers(1, 2, 3, 4, 5, 6) If we do not know how many keyword arguments to pass use `**` def makePerson(**infoOnPerson): for key, value in infoOnPerson.items(): print("{} is {}".format(key,value)) jacob = makePerson(first = "jacob", last = "brown", Age = 26) ## Modules Code library or a local `.py` file import numpy as np np.array([1, 2, 3]) from pandas import DataFrame as df df([1,2,3]) ## RegEx `import re` `re.` methods: * `findall` - Returns a list containing all matches * `search` - Returns a Match object if there is a match anywhere in the string * `.span()` - returns a tuple containing the start and end positions of the match. * `.string` - returns the string passed into the function * `.group()` - returns the part of the string where there was a match * `split` - Returns a list where the string has been split at each match * `sub` - Replaces one or many matches with a string *from w3* ## File Handling `open(filename, mode)` Mode types: `"r"` - read `"a"` - append `"w"` - write `"x"` - create open, readlines,and close ```python f = open("demofile.txt", "r") print(f.readline()) f.close() ```
6726f3ca4feff9c2fcf5d368be13470b2cc8d73f
makowiecka/Hangman
/door.py
1,332
3.65625
4
class DoorError(RuntimeError): #nowy błąd na podstawie istniejącego, doorerror dziedziczy po Runtimeerror i przyjmuje wszystkie jego własciwości pass class Door: # w klasach tworzymy w liczbach pojedyńczych def __init__(self, name: str): self.__name = name # ja wstawimy __ - nie mamy dostępu z zewnątrz, jest prywatna z punktu widzenia obiektu self.__locked = False self.__closed = False def open(self): if self.__locked: raise DoorError('Unlock the door to open them. ') self.__closed = False def close(self): self.__closed = True def lock(self): if not self.__closed: raise DoorError('Close the door to lock them. ') self.__locked = True def unlock(self): self.__locked = False def is_locked(self): return self.__locked def is_closed(self): return self.__closed # print(f'door nazywa się: {__name__}') if __name__ == '__main__': # name zmienna która przechowuje inf o nazwi modułu. Jeśli uruchamiamy ten moduł bezpośrenia to pod name jest main. Dołączam plik to nazwa pliku door = Door('front left') try: door.close() door.lock() except DoorError as error_message: print(error_message) print('qqq', door.is_locked())
b2a57d3dfb42d63aaeda6039e0b957661872528c
makowiecka/Hangman
/words_from_file/words.py
2,434
3.65625
4
import os from random import randint from abstract_word import AbstractWord class WordsFromFile(AbstractWord): @staticmethod #nie będzie działała na żadnych własnosciach danego obiektu def get_path(): #ścieżka return os.path.abspath(os.path.dirname(__file__)) #biblioteka os, moduł - path, funkcja dirname pierwsza część os.path.abspath - nie musiałoby być kiedyś był bład w programie i lepiej wpisywać def get_random_word(self): #zwróci wylosowane słowo tzn wylosuje linie ze zbioru words_in_file = self.get_words_count() # odwołujemy się do funkcji poniżej word_number = randint(1, words_in_file) #numer losujemy od 1 do całego zbioru return self.get_word_from_file(word_number).strip('\n') #zwróci słowo / linie z wylosowanej lini, usówając białe zanki przed i po słowie def get_word_from_file (self, word_number): #pobierze konkretne słowo z lini with open(f'{self.get_path()}/words.txt', 'r') as file: #otwiera plik for i in range(1, word_number + 1): word = file.readline() return word def get_words_count(self): #pobiera informacje o ilości lini czyli słów #normlnie pliki zaczytujemy do pamięci i nie martwimy się o nic więcej bo plik nie jest specjalnie wielki words_in_file = 0 with open(f'{self.get_path()}/words.txt', 'r') as file: while file.readline(): words_in_file += 1 return words_in_file # def get_random_word(self) -> str: #dopisujemy self - self mówi szukaj w środku w mojej klasie, w moim obiekcie, dopisuje parametr do funkcji # word_index = randint(0, len(self.words) - 1) # return self.words[word_index] # if __name__ == '__main__': # file = open('words.txt') #poczytać o open # while True: # line = file.readline() # # if line == '': # break # print(line.strip()) #funkcja strip usuwa białe znaki z lewej i praej stronie # # file.close() #musimy zamknąc #nie musimy pamiętać o zmaykaniu jeśli # if __name__ == '__main__': # with open('words.txt') as file: # poczytać o open # # python 3.8 # #while line := file.readline() # # print(line.strip()) # while True: # line = file.readline() # if line == '': # break # print(line.strip())
6d031a90814976c539f22823bffd72222b4625c9
JianfengYao/C-practice
/algorithm/algorithm-python/src/number_theory/gcd.py
274
3.78125
4
#!/usr/bin/env python # -*- coding:UTF-8 def gcd(a, b): divisor = a dividend = b while dividend is not 0: divisor, dividend = dividend, divisor % dividend return divisor def main(): print(gcd(12, 18)) if __name__ == "__main__": main()
bb6a42640770f39615f60d5b368ace2836d2e545
JianfengYao/C-practice
/algorithm/algorithm-python/src/lib/stack.py
828
4
4
#!/usr/bin/env python # -*- coding:UTF-8 import copy class Stack(object): """ 使用Python快速实现一个栈 """ def __init__(self, *arg): super(Stack, self).__init__() self.__stack = list(copy.copy(arg)) self.__size = len(self.__stack) def push(self, value): self.__stack.append(value) self.__size += 1 def pop(self): if self.__size <= 0: return None else: value = self.__stack[-1] self.__size -= 1 del self.__stack[-1] return value def __len__(self): return self.__size def empty(self): return self.__size <= 0 def __str__(self): return "".join(["Stack(list=", str(map(lambda s: str(s), self.__stack)), ",size=", str(self.__size), ')'])
7c2fde5d7a2da2544cf8ee68fe6ed77177fbacfc
sjogleka/Intelligent_Systems
/IS_Project2/code.py
15,712
3.8125
4
from random import randrange from copy import deepcopy from random import choice # A class to create queenstate and identify the best possible children based on number of queens attacking class QueensState: instance_counter = 0 def __init__(self, queen_positions=None, parent=None,f_cost=0,): self.side_length = int(n) if queen_positions == None: self.queen_num = self.side_length self.queen_positions = frozenset(self.random_queen_position()) else: self.queen_positions = frozenset(queen_positions) self.queen_num = len(self.queen_positions) self.path_cost = 0 self.f_cost = f_cost self.parent = parent self.id = QueensState.instance_counter QueensState.instance_counter += 1 # A function to generate queen positions randomly def random_queen_position(self): ''' Each queen is placed in a random row in a separate column ''' open_columns = list(range(self.side_length)) queen_positions = [(open_columns.pop(randrange(len(open_columns))), randrange(self.side_length)) for _ in range(self.queen_num)] return queen_positions # get the possible children from parent node def get_children(self): children = [] parent_queen_positions = list(self.queen_positions) for queen_index, queen in enumerate(parent_queen_positions): new_positions = [(queen[0], row) for row in range(self.side_length) if row != queen[1]] for new_position in new_positions: queen_positions = deepcopy(parent_queen_positions) queen_positions[queen_index] = new_position children.append(QueensState(queen_positions)) return children # A function to identify attacking queens def queen_attacks(self): def range_between(a, b): if a > b: return range(a-1, b, -1) elif a < b: return range(a+1, b) else: return [a] def zip_repeat(a, b): if len(a) == 1: a = a*len(b) elif len(b) == 1: b = b*len(a) return zip(a, b) def points_between(a, b): return zip_repeat(list(range_between(a[0], b[0])), list(range_between(a[1], b[1]))) def is_attacking(queens, a, b): if (a[0] == b[0]) or (a[1] == b[1]) or (abs(a[0]-b[0]) == abs(a[1] - b[1])): for between in points_between(a, b): if between in queens: return False return True else: return False attacking_pairs = [] queen_positions = list(self.queen_positions) left_to_check = deepcopy(queen_positions) while left_to_check: a = left_to_check.pop() for b in left_to_check: if is_attacking(queen_positions, a, b): attacking_pairs.append([a, b]) return attacking_pairs def num_queen_attacks(self): return len(self.queen_attacks()) def __str__(self): return '\n'.join([' '.join(['0' if (col, row) not in self.queen_positions else 'Q' for col in range( self.side_length)]) for row in range(self.side_length)]) def __hash__(self): return hash(self.queen_positions) def __eq__(self, other): return self.queen_positions == other.queen_positions def __lt__(self, other): return self.f_cost < other.f_cost or (self.f_cost == other.f_cost and self.id > other.id) print("Please select the algorithm to be executed :\n 1. Steepest Ascent \n 2. Hill Climbing with Sideway Moves\n 3. Random Restart") x=input()#Taking Input from User def steepest_ascent_hill_climb_false(queens_state,counter,allow_sideways=False, max_sideways=100): # This function will get call when steepest Ascent Hill Climb without side moves is selected node = queens_state path = [] sideways_moves = 0 while True: path.append(node) children = node.get_children() children_num_queen_attacks = [child.num_queen_attacks() for child in children] min_queen_attacks = min(children_num_queen_attacks) # If best child is not chosen randomly from the set of children that have the lowest number of attacks, # algorithm will go into infinite loop best_child = choice([child for child_index, child in enumerate(children) if children_num_queen_attacks[ child_index] == min_queen_attacks])# 'for' loop will check the best heuristic by iterating through the num of attacking moves related to particular child node. if (best_child.num_queen_attacks() > node.num_queen_attacks()):# If we found better heuristic then break break elif best_child.num_queen_attacks() == node.num_queen_attacks(): if not allow_sideways or sideways_moves == max_sideways:# Check if allowed side moves reched to the limit or not. break else: sideways_moves += 1 else: sideways_moves = 0 node = best_child if counter <4: print('Search Sequence :',counter,'\n', best_child, '\n')# Print first three sequences found while finding the solution return {'outcome': 'success' if node.num_queen_attacks()==0 else 'failure', 'solution': path} def steepest_ascent_hill_climb_true(queens_state,counter,allow_sideways=True, max_sideways=100): # This function will get call when steepest Ascent Hill Climb with side moves is selected node = queens_state path = [] sideways_moves = 0 while True: path.append(node) children = node.get_children() children_num_queen_attacks = [child.num_queen_attacks() for child in children] min_queen_attacks = min(children_num_queen_attacks) # If best child is not chosen randomly from the set of children that have the lowest number of attacks, # algorithm will go into infinite loop best_child = choice([child for child_index, child in enumerate(children) if children_num_queen_attacks[ child_index] == min_queen_attacks]) if (best_child.num_queen_attacks() > node.num_queen_attacks()): break elif best_child.num_queen_attacks() == node.num_queen_attacks(): if not allow_sideways or sideways_moves == max_sideways: break else: sideways_moves += 1 else: sideways_moves = 0 node = best_child if counter <4: print('Search Sequence :', counter, '\n', best_child, '\n') #print(best_child) return {'outcome': 'success' if node.num_queen_attacks()==0 else 'failure', 'solution': path} def steepest_ascent_hill_climb(queens_state,allow_sideways, max_sideways=100): node = queens_state path = [] sideways_moves = 0 while True: path.append(node) children = node.get_children() children_num_queen_attacks = [child.num_queen_attacks() for child in children] min_queen_attacks = min(children_num_queen_attacks) # If best child is not chosen randomly from the set of children that have the lowest number of attacks, # then algorithm will get stuck flip-flopping between two non-random best children when sideways moves are # allowed best_child = choice([child for child_index, child in enumerate(children) if children_num_queen_attacks[ child_index] == min_queen_attacks]) if (best_child.num_queen_attacks() > node.num_queen_attacks()): break elif best_child.num_queen_attacks() == node.num_queen_attacks(): if not allow_sideways or sideways_moves == max_sideways: break else: sideways_moves += 1 else: sideways_moves = 0 node = best_child return {'outcome': 'success' if node.num_queen_attacks()==0 else 'failure', 'solution': path} def random_restart_hill_climb(random_state_generator,allow_sideways,num_restarts=100, max_sideways=100): path = [] global total # Global Variable Declaration for _ in range(num_restarts): # Repeatedly do the steepest ascent hill climbing algorithm with or without side way moves for n number of iterations. result = steepest_ascent_hill_climb(random_state_generator(),allow_sideways=allow_sideways, max_sideways=max_sideways) path += result['solution'] num_restarts -= 1 temp =0 if result['outcome'] == 'success': temp = 100-num_restarts #check the num of restarts required for particular iteration break result['solution'] = path array.append(temp)#Appending num of restarts required in an array. total = 0 for i in array: total += i # Find the total, summation of restarts found in an arrray for particular iteration return result class QueensProblem: global n,num_iter # Global Variable Declaration print("Enter the number of queens") n = input()#Taking number of queens required in NxN board, as a input from user print("Enter the number of interations") num_iter = input()#Number of iterations to be performed num_iter = int(num_iter) # print(n) def __init__(self, start_state=QueensState()): self.start_state = start_state def stats(search_function,counter=1, num_iterations=num_iter): results = [] for iter_num in range(num_iterations): result = search_function(QueensState(),counter)#Create the object of QueenState and call the function passed e.g steepest_ascent_hill_climb/steepest_ascent_hill_climb_false counter += 1 result['path_length'] = len(result['solution'])-1#Storing the path length of each iteration in result results.append(result) arr = [[result for result in results if result['outcome'] == 'success'], #array arr will have all the result of SUCCESS and FAILURE [result for result in results if result['outcome'] == 'failure']] success = [] failure = [] for i in arr[0]: success.append(i['path_length'])#0th index of array is corresponding to Success. Append all elements in success array for i in arr[1]: failure.append(i['path_length'])#1st index of array is corresponding to Failure. Append all elements in failure array if len(success) != 0: #Print the average number of steps for success print('Average number of steps when it succeeds: ', int(round(sum(success) / float(len(success))))) if len(failure) != 0: # Print the average number of steps for failure print('Average number of steps when it fails: ', int(round(sum(failure) / float(len(failure))))) results = [results, [result for result in results if result['outcome'] == 'success'], [result for result in results if result['outcome'] == 'failure']] title_col_width = 30 data_col_width = 15 def print_data_row(row_title, data_string, data_func, results): #Print function to print in row column format nonlocal title_col_width, data_col_width row = (row_title + '\t').rjust(title_col_width) for result_group in results: row += data_string.format(**data_func(result_group)).ljust(data_col_width) print(row) print('\t'.rjust(title_col_width) + 'All Problems'.ljust(data_col_width) + 'Successes'.ljust(data_col_width) + 'Failures'.ljust(data_col_width)) #Call to print_data_flow function with total number of and percent print_data_row('Number of Problems:', '{count:.0f} ({percent:.1%})', lambda x: {'count':len(x), 'percent': len(x)/num_iterations}, results) section_break = '\n' + '_'*100 + '\n' def stats_random(search_function, num_iterations=num_iter): results = [] global array # Global Variable Declaration array = [] for iter_num in range(num_iterations): result = search_function(QueensState())#Create the object of QueenState and call the function passed e.g steepest_ascent_hill_climb/steepest_ascent_hill_climb_false result['path_length'] = len(result['solution'])-1#Storing the path length of each iteration in result results.append(result) arr = [[result for result in results if result['outcome'] == 'success'],#array arr will have all the result of SUCCESS and FAILURE [result for result in results if result['outcome'] == 'failure']] success = [] failure = [] for i in arr[0]: success.append(i['path_length'])#0th index of array is corresponding to Success. Append all elements in success array for i in arr[1]: failure.append(i['path_length'])#1st index of array is corresponding to Failure. Append all elements in failure array if len(success) != 0: # Print the average number of steps for success print('Average number of steps when it succeeds: ', int(round(sum(success) / float(len(success))))) if len(failure) != 0: # Print the average number of steps for failure print('Average number of steps when it fails: ', int(round(sum(failure) / float(len(failure))))) print(' '*50 + '\r', end='', flush=True) results = [results, [result for result in results if result['outcome'] == 'success'], [result for result in results if result['outcome'] == 'failure']] #print(results[0]) title_col_width = 30 data_col_width = 15 def print_data_row(row_title, data_string, data_func, results): nonlocal title_col_width, data_col_width row = (row_title + '\t').rjust(title_col_width) for result_group in results: row += data_string.format(**data_func(result_group)).ljust(data_col_width) print(row) print('Avg No. of Restarts Required: ', int((total / num_iterations))) print('\t'.rjust(title_col_width) + 'All Problems'.ljust(data_col_width) + 'Successes'.ljust(data_col_width) + 'Failures'.ljust(data_col_width)) print_data_row('Number of Problems:', '{count:.0f} ({percent:.1%})', lambda x: {'count':len(x), 'percent': len(x)/num_iterations}, results) if x=='1': print('Steepest ascent hill climb:\n') stats(steepest_ascent_hill_climb_false) print(section_break) elif x=='2': print('Hill Climbing with Sideway Moves (up to 100 consecutive sideways moves allowed):\n') stats(steepest_ascent_hill_climb_true) print(section_break) else: print("******************* Random Restart without Sideway Moves ******************") print('Random_restart_hill_climb):\n') stats_random(lambda x: random_restart_hill_climb(QueensState, allow_sideways=False)) print(section_break) print("******************* Random Restart with Sideway Moves ******************") print('Random_restart_hill_climb):\n') stats_random(lambda x: random_restart_hill_climb(QueensState, allow_sideways=True)) print(section_break)
4e5d2fddbb38e7f243c2302203c692e238740ee5
xudaniel11/interview_preparation
/robot_unique_paths.py
1,808
4.21875
4
""" A robot is located at the top-left corner of an M X N grid. The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid. How many possible unique paths are there? Input: M, N representing the number of rows and cols, respectively Output: an integer bottom-up DP solution from http://articles.leetcode.com/unique-paths/ tldr; the total unique paths at grid (i,j) is equal to the sum of total unique paths from grid to the right (i,j+1) and the grid below (i+1,j). """ import numpy as np import unittest def get_num_unique_paths(M, N): mat = np.zeros((M, N)) mat[M - 1] = np.ones((1, N)) mat[:, N - 1] = np.ones(M) for i in reversed(xrange(M - 1)): for j in reversed(xrange(N - 1)): right = mat[i, j + 1] down = mat[i + 1, j] mat[i, j] = right + down return int(mat[0, 0]) """ Follow up: Imagine certain spots are "off limits," such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right. Solution: make blocks 0. """ def robot(grid): m, n = grid.shape for i in reversed(range(m - 1)): for j in reversed(range(n - 1)): if grid[i, j] == 0: continue else: grid[i, j] = grid[i, j + 1] + grid[i + 1, j] return grid[0, 0] class TestUniquePaths(unittest.TestCase): def test_1(self): result = get_num_unique_paths(3, 7) expected = 28 self.assertEqual(result, expected) def test_blocks(self): mat = np.ones((3, 4)) mat[1, 0] = 0 result = robot(mat) expected = 6 self.assertEqual(result, expected) if __name__ == "__main__": unittest.main()
b72c2595f1863a8a3a681657428dd4d6caceefb2
xudaniel11/interview_preparation
/calculate_BT_height.py
1,621
4.15625
4
""" Calculate height of a binary tree. """ import unittest def calculate_height(node): if node == None: return 0 left, right = 1, 1 if node.left: left = 1 + calculate_height(node.left) if node.right: right = 1 + calculate_height(node.right) return max(left, right) class BinaryTreeNode(): def __init__(self, val): self.val = val self.left = None self.right = None class TestFirstCommonAncestor(unittest.TestCase): def test_1(self): root = BinaryTreeNode('A') root.left = BinaryTreeNode('B') root.right = BinaryTreeNode('C') root.right.left = BinaryTreeNode('F') root.right.right = BinaryTreeNode('G') root.left.left = BinaryTreeNode('D') root.left.right = BinaryTreeNode('E') result = calculate_height(root) expected = 3 self.assertEqual(result, expected) def test_2(self): root = BinaryTreeNode('A') root.left = BinaryTreeNode('B') root.right = BinaryTreeNode('C') root.left.left = BinaryTreeNode('D') root.left.right = BinaryTreeNode('E') root.left.left.left = BinaryTreeNode('F') root.left.left.right = BinaryTreeNode('G') root.left.left.left.left = BinaryTreeNode('H') result = calculate_height(root) expected = 5 self.assertEqual(result, expected) def test_3(self): root = BinaryTreeNode('A') result = calculate_height(root) expected = 1 self.assertEqual(result, expected) if __name__ == '__main__': unittest.main()
3c419ab15020a8827a24044dfa180da9a7a5c47f
xudaniel11/interview_preparation
/array_of_array_products.py
1,044
4.15625
4
""" Given an array of integers arr, write a function that returns another array at the same length where the value at each index i is the product of all array values except arr[i]. Solve without using division and analyze the runtime and space complexity Example: given the array [2, 7, 3, 4] your function would return: [84, 24, 56, 42] (by calculating: [7*3*4, 2*3*4, 2*7*4, 2*7*3]) Algorithm should run in O(N) time. Solution: create two arrays representing the direction we iterate in. Each element in each array represents the product so far from a particular direction up to that index. """ def get_array_of_array_products(arr): going_right = [1] for i in range(1, len(arr)): going_right.append(going_right[i - 1] * arr[i - 1]) going_left = [1] for i in range(1, len(arr)): going_left.append(going_left[i - 1] * arr[len(arr) - i]) going_left.reverse() return [x * y for x, y in zip(going_left, going_right)] print get_array_of_array_products([2, 4, 6, 7]) # should be [168, 84, 56, 48]
481fb0533a3f52fb1a2093472bbf07bcf8f1da0e
xudaniel11/interview_preparation
/city_destinations.py
2,047
4.09375
4
""" Given an input city, return the cities that can be reached. Algorithm: iterate through the initial list in order to create the adjacency matrix. Then, use DFS to figure out what cities can be connected to from the input one. """ import unittest def city_destinations(cities, original_city): # build adjacency list ad_list = adjacencyList() for i, (source, destination) in enumerate(cities): if ad_list.has_city(source): ad_list.add_destination(source, destination) elif not ad_list.has_city(source): ad_list.add_source(source) ad_list.add_destination(source, destination) # DFS visited = set() stack = [] stack.append(original_city) stack.extend(ad_list.get_destinations(original_city)) while stack: city = stack.pop() print city if city not in visited: visited.add(city) destinations = ad_list.get_destinations(city) if destinations: stack.extend(destinations) return visited class adjacencyList(): def __init__(self): self.ad_list = {} def add_source(self, city): self.ad_list[city] = [] def add_destination(self, source, destination): self.ad_list[source].append(destination) def has_city(self, city): return self.ad_list.has_key(city) def get_destinations(self, source): return self.ad_list.get(source) class TestCityDestinations(unittest.TestCase): """ SFO : [NYC, SAC, LAX, DC] NYC : [SFO, OAK] SAC : [LAX] DEL : [AUX] """ def test_usual_case(self): ex = [("SFO","NYC"),("NYC", "SFO"), ("NYC", "OAK"), ("SFO", "SAC"), ("SAC", "LAX"), ("SFO", "LAX"), ("DEL", "AUX"), ("SFO", "DC")] result = city_destinations(ex, "SFO") self.assertItemsEqual(result, ["NYC", "SAC", "LAX", "DC", "SFO", "OAK"]) def test_cycle(self): ex = [("SFO", "NYC"), ("NYC", "SFO")] result = city_destinations(ex, "SFO") self.assertItemsEqual(result, ["SFO", "NYC"]) def test_no_destinations(self): ex = [("SFO", "NYC"), ("DEL", "LAX")] result = city_destinations(ex, "SFO") self.assertItemsEqual(result, ["SFO", "NYC"]) if __name__ == '__main__': unittest.main()
be3e45acb992ac1db59427d3b411bdc2c8a3d84a
xudaniel11/interview_preparation
/Queue.py
337
3.71875
4
""" Queue DS """ class Queue(): def __init__(self): self.q = [] def enqueue(self, item): self.q.append(item) def dequeue(self): return self.q.pop(0) def is_empty(self): return len(self.q) == 0 def size(self): return len(self.q) def front(eslf): return A[0]
f26285e201db5aca5cf026b2e3377539ee23d1ab
xudaniel11/interview_preparation
/remove_duplicates_LL.py
1,403
3.875
4
""" Remove duplicates from an unsorted linked list in O(1) space. """ import Singly_LL as LL import unittest def remove_duplicates(ll): if ll.get_size() == 0 or ll.get_size == 1: return ll prev = ll.head curr = ll.head.next while curr: runner = ll.head while runner != curr: if runner.val == curr.val: # keep the first duplicate and remove curr, which is the # later one temp = curr.next prev.next = temp curr = temp break runner = runner.next if runner == curr: # only move on to the next curr if we've finished removing all # the dupes prev = curr curr = curr.next return ll class TestRemoveDupes(unittest.TestCase): def test_1(self): example = LL.Singly_LL() example.add(3) example.add(1) example.add(2) example.add(2) example.add(4) result = remove_duplicates(example) result.print_LL() # should 3 1 2 4 print "\n" def test_2(self): example = LL.Singly_LL() example.add(2) example.add(1) example.add(2) example.add(2) result = remove_duplicates(example) result.print_LL() # should be 2 if __name__ == "__main__": unittest.main()
8268e7d5e29f7ccb1616fa17c022ad060256c569
xudaniel11/interview_preparation
/check_balanced_tree.py
1,516
4.4375
4
""" Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one. Solution taken from CTCI: recursive algorithms calculate the maximum and minimum length paths in the tree. Compare the two at the end. """ import unittest def max_depth(node): if node == None: return 0 else: return 1 + max(max_depth(node.left), max_depth(node.right)) def min_depth(node): if node == None: return 0 else: return 1 + min(min_depth(node.left), min_depth(node.right)) def check_balanced_tree(node): return max_depth(node) - min_depth(node) <= 1 class BinaryTreeNode(): def __init__(self, val): self.val = val self.left = None self.right = None class Test_Balanced_Tree(unittest.TestCase): def test_case_1(self): root = BinaryTreeNode('A') root.left = BinaryTreeNode('B') root.right = BinaryTreeNode('C') root.right.left = BinaryTreeNode('F') root.right.right = BinaryTreeNode('G') root.left.left = BinaryTreeNode('D') root.left.right = BinaryTreeNode('E') result = check_balanced_tree(root) self.assertEqual(result, True) def test_case_2(self): root = BinaryTreeNode('A') root.left = BinaryTreeNode('B') root.right = BinaryTreeNode('C') root.right.left = BinaryTreeNode('F') root.right.left.left = BinaryTreeNode('G') result = check_balanced_tree(root) self.assertEqual(result, False) if __name__ == "__main__": unittest.main()
5b460faff9b8266878e666793101b3ac11e9cc87
xudaniel11/interview_preparation
/all_possible_subsets.py
1,072
4.03125
4
""" Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. Also, the subsets should be sorted in ascending ( lexicographic ) order. The list is not necessarily sorted. Example : If S = [1,2,3], a solution is: [ [], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3], ] """ def subsets_wrong(arr): result = [[]] for i, num in enumerate(arr): new_results = [] for j, subset in enumerate(result): # wrong bc im assigning a reference to the original object, # not copying it tmp = subset tmp.append(num) new_results.append(tmp) result.extend(new_results) return result def subsets(arr): result = [[]] for i, num in enumerate(arr): new_results = [] for j, subset in enumerate(result): new_results.append(subset + [num]) result.extend(new_results) return result print subsets([1, 2, 3])
6bfa59c214fd9b3794027905132da251f3775af6
xudaniel11/interview_preparation
/stairs.py
448
3.9375
4
""" There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1, 2, or 3 stairs at a time. Count the number of ways, the person can reach the top. Base cases handle illegal cases. """ def stairs(n): if n == 0: return 1 elif n < 0: return 0 else: return stairs(n - 1) + stairs(n - 2) + stairs(n - 3) print stairs(4) # should be 7 print stairs(5) # should be 13
0b95a6a31595b540c25dbb81cad8b99acd3af537
xudaniel11/interview_preparation
/binaryMatrixCloseness_INCORRECT.py
2,902
3.578125
4
""" @author - Daniel Xu Given a matrix M of number 1 and 0, for each cell in the matrix determine how far the closest 1 is to the current cell. If the 1 is the current cell, then the distance is 0 because there is no "distance". If the 1 is next to the cell, the distance is 1. Only consider cardinal directions (up, down, left, right) to consider the distances WARNING - THIS APPROACH IS WRONG a) DO NOT WANT TO USE DFS, WANT BFS b) DANGER OF CYCLES == INCORRECT METHODOLOGY c) USE binaryMatrixCloseness_v2.py !!!!! Want to do iterative / successive expansion from the starting 1 points """ import numpy as np import sys class BinaryMatrix: def __init__(self, inputMatrix): self.inputMatrix = inputMatrix self.height = inputMatrix.shape[0] self.width = inputMatrix.shape[1] self.memoMatrix = np.empty(inputMatrix.shape) self.memoMatrix[:] = sys.maxint self.visitMatrix = np.empty(inputMatrix.shape) self.visitMatrix[:] = np.NAN def resetVisitMatrix(self): self.visitMatrix = np.empty(self.inputMatrix.shape) self.visitMatrix[:] = np.NAN def setClosestOne(self, i, j): if i < 0 or i >= self.height or j < 0 or j >= self.width: return sys.maxint if self.memoMatrix[i,j] != sys.maxint: return self.memoMatrix[i,j] if self.inputMatrix[i,j] == 1: self.memoMatrix[i,j] = 0 return 0 if self.visitMatrix[i,j] == True: return sys.maxint self.visitMatrix[i,j] = True #print i,j uDist = self.setClosestOne(i+1,j) lDist = self.setClosestOne(i,j+1) dDist = self.setClosestOne(i-1,j) rDist = self.setClosestOne(i,j-1) # if i == 2 and j == 3: # print [uDist, lDist, dDist, rDist] self.memoMatrix[i,j] = 1 + min(uDist, lDist, dDist, rDist) return self.memoMatrix[i,j] def calculateMatrixCloseness(self): for i in range(self.height): for j in range(self.width): self.resetVisitMatrix() self.setClosestOne(i,j) self.printMemoMatrix() def printMemoMatrix(self): np.set_printoptions(precision=0) np.set_printoptions(suppress=True) print np.around(self.memoMatrix) testMatrix_1 = np.matrix([[0,0,1,0,0],[1,1,1,0,1],[1,0,1,0,0],[0,0,0,0,1],[1,0,0,0,0]]) testMatrix_2 = np.matrix([[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]) testMatrix_3 = np.matrix([[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]]) testMatrix_4 = np.matrix([[1,1,1,1,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[1,1,1,1,1]]) t1 = BinaryMatrix(testMatrix_1) t2 = BinaryMatrix(testMatrix_2) t3 = BinaryMatrix(testMatrix_3) t4 = BinaryMatrix(testMatrix_4) print "Testing\n %s" % testMatrix_1 t1.calculateMatrixCloseness() print "\n\nTesting\n %s" % testMatrix_2 t2.calculateMatrixCloseness() print "\n\nTesting\n %s" % testMatrix_3 t3.calculateMatrixCloseness() print "\n\nTesting\n %s" % testMatrix_4 t4.calculateMatrixCloseness()
f35842ab5a7e78d864e28944a262c49f06bfde31
BeatrizVasconcelos/Trabalho-Banco-de-Dados
/aux.py
14,799
3.609375
4
from getpass import getpass from cripto import crip # função que realiza login def login(db): while(True): # lê email do usuário print('Digite seu e-mail:') email = input() # executa query para buscar email digitado q = "SELECT * FROM usuario WHERE email='{}';".format(email) tuplas = db.select(q) # lista de tuplas # caso o email não esteja cadastrado, retorna ao inicio if(len(tuplas) < 1): print('Email não cadastrado.') continue # caso o usuario seja um autor, busca pela tupla correspondente if(tuplas[0][5] == 'Autor'): # executa query para buscar email digitado q = "SELECT * FROM autor WHERE email='{}';".format(email) tuplas = db.select(q) # lista de tuplas # usuario usuario = tuplas[0] # lê a senha do usuário senha = getpass('Digite sua senha:\n') senha = crip(senha) # checa se a senha foi digitada corretamente # caso sim, retorna uma lista com as funções do usuario if(senha == usuario[4]): print('Logado com sucesso.') return usuario # caso não, retorna ao começo else: print('Senha incorreta.') continue # função que realiza cadastro de usuários def cadastro(db): # lê nome e sobrenome do usuário print('Digite seu nome:') nome = input() print('Digite seu sobrenome:') sobrenome = input() # lê o email do usuário até que ele digite um email não cadastrado while(True): print('Digite seu e-mail:') email = input() q = "SELECT email FROM usuario WHERE email='{}';".format(email) tuplas = db.select(q) if(len(tuplas) == 0): break else: print('Email já cadastrado.') # lê a senha até que o usuario digite a mesma senha duas vezes while(True): senha = getpass('Digite uma senha:\n') senha2 = getpass('Digite novamente:\n') if(senha == senha2): senha = crip(senha) break else: print('Senhas não correspondem.') # lê o tipo de autor até que o usuário selecione uma opção válida while(True): print('Digite qual sua qualificação na cozinha! :)') print('1 - Amador') print('2 - Estudante') print('3 - Profissional') tipo = int(input()) if(tipo in (1, 2, 3)): if(tipo == 1): tipo = 'Amador' elif(tipo == 2): tipo = 'Estudante' else: tipo = 'Profissional' break else: print('Digite uma opção válida.') # query que insere um novo usuario q = "INSERT INTO autor" \ " (nome, sobrenome, email, senha, permissao, tipo_autor)" \ " VALUES ('{}', '{}', '{}', '{}', 'Autor', '{}');" q = q.format(nome, sobrenome, email, senha, tipo) # executa a query db.execute_query(q) # query para buscar o usuario inserido q = "SELECT * FROM autor WHERE email='{}';".format(email) tuplas = db.select(q) # retorna o usuario cadastrado return tuplas[0] # busca as receitas def get_receitas(db, *argv): # query basica para buscar receitas q = "SELECT * FROM Receita" # caso seja passado um argumento adicional, # adiciona na query if(len(argv) > 0): q += argv[0] # adicionada condição para ordenar por avaliacao_media # do maior para o menor q += " ORDER BY avaliacao_media DESC;" return db.select(q) # função para inserir uma receita def insere_receita(db, id_autor): meds = ('kg', 'g', 'colher de chá', 'colher de sopa', 'l', 'ml', 'unidade') cats = ('Lanche', 'Acompanhamento', 'Prato Principal', 'Sobremesa', 'Entrada') # lê o nome da receita print('Digite o nome da receita:') nome = input() # lê a categoria da receita print('Digite a categoria:') print(cats) while(True): categoria = input() if(categoria in cats): break print('Digite uma categoria válida') # lê os ingredientes print('Digite os ingredientes:') ingredientes = [] qtdes = [] while(True): # lê o nome do ingrediente print('Qual ingrediente você deseja adicionar?') ingrediente = input() # busca pelo ingrediente q = "SELECT * FROM ingrediente WHERE nome='{}';".format(ingrediente) tuplas = db.select(q) # caso encontre o ingrediente if(len(tuplas) > 0): # adiciona o id do ingrediente na lista ingredientes.append(tuplas[0][0]) # caso não encontre o ingrediente else: # insere o ingrediente na tabela q = "INSERT INTO ingrediente (nome)" \ " VALUES ('{}');".format(ingrediente) db.execute_query(q) # busca pelo ingrediente inserido q = "SELECT * FROM ingrediente" \ " WHERE nome='{}';".format(ingrediente) tuplas = db.select(q) # adiciona o id do ingrediente na lista ingredientes.append(tuplas[0][0]) # lê a quantidade de cada ingrediente print('Digite a quantidade:') while(True): try: resp1 = float(input()) except ValueError: resp1 = None finally: if(resp1): break print('Valor inválido') # lê a medida de cada ingrediente print('Digite a unidade de medida:') print(meds) while(True): try: resp2 = input() except ValueError: resp2 = None finally: if(resp2 in meds): break print('Valor inválido') # adiciona na lista de quantidades qtdes.append((resp1, resp2)) # lê do usuario se ele deseja inserir ou não outro ingrediente print('Deseja adicionar outro ingrediente?') resposta = sim_ou_nao() # sai do while caso a resposta seja 2 if(resposta == 2): break # query para inserir na tabela receita q1 = "INSERT INTO receita (nome, id_autor, categoria)" \ " VALUES ('{}', {}, '{}');".format(nome, id_autor, categoria) # insere na tabela receita db.execute_query(q1) # recupera o id da receita inserida q = "SELECT id FROM receita WHERE id_autor='{}' ORDER BY id DESC;" q = q.format(id_autor) id_rec = (db.select(q))[0][0] # insere na tabela Utilizado_em for i in range(len(ingredientes)): q2 = "INSERT INTO utilizado_em (id_receita, id_ingrediente, " \ "quantidade, medida) VALUES ({}, {}, {}, '{}');" q2 = q2.format(id_rec, ingredientes[i], qtdes[i][0], qtdes[i][1]) db.execute_query(q2) # modo de preparo print('Digite o modo de preparo:') num_passo = 0 while(True): num_passo += 1 print('Digite o {}º passo:'.format(num_passo)) passo = input() q3 = "INSERT INTO preparo VALUES ({}, {}, '{}');" q3 = q3.format(id_rec, num_passo, passo) db.execute_query(q3) # continua ou não print('Deseja adicionar mais um passo?') resposta = sim_ou_nao() # sai do while if(resposta == 2): break # print fim print('Receita cadastrada!') # lê do usuario uma resposta entre sim e não def sim_ou_nao(): print('(1) - Sim') print('(2) - Não') while(True): try: resposta = int(input()) except ValueError: resposta = -1 finally: if(resposta in (1, 2)): return resposta print('Resposta inválida') # altera os dados do usuario def alterar_cadastro(db, user, cond): # altera o usuario q = "UPDATE {} WHERE id={};".format(cond, user) db.execute_query(q) # altera receitas def editar_receita(db, tbs, opc, rec): q1 = "UPDATE " q2 = "INSERT INTO " q3 = "DELETE FROM " # alterar dados da receita if(len(tbs) == 1): q = q1 + "{} SET {} = '{}' WHERE id={};" # alterar nome if(opc == 1): print('Digite o novo nome da receita:') campo = 'nome' novo = input() # alterar categoria else: campo = 'categoria' cats = ('Lanche', 'Acompanhamento', 'Prato Principal', 'Sobremesa', 'Entrada') print('Digite a nova categoria da receita:') print(cats) while(True): try: novo = input() except ValueError: novo = '' finally: if(novo in cats): break print('Digite uma opção válida') # possui todas as informações para completar a query q = q.format(tbs[0], campo, novo, rec) # alterar modo de preparo elif(len(tbs) == 2): # adicionar passo if(opc == 1): q = q2 + "{} (id_receita, num_passo, passo) " \ "VALUES ({}, {}, '{}');" print('Informe o novo passo:') novo = input() # query para buscar o numero de passos temp = "SELECT COUNT(num_passo) FROM preparo WHERE id_receita={};" temp = temp.format(rec) # numero do novo passo num = (db.select(temp))[0][0] + 1 q = q.format(tbs[0], rec, num, novo) # remover o ultimo passo elif(opc == 2): q = q3 + "{} WHERE id_receita={} AND num_passo IN " \ "(SELECT MAX(num_passo) FROM {} WHERE id_receita={});" q = q.format(rec, tbs[0], rec) # editar passo else: # recupera a lista de passos da receita temp = "SELECT * FROM preparo WHERE id_receita={}".format(rec) passos = db.select(temp) # percorre a lista de passos for passo in passos: print(passo[2]) print('Deseja alterar este passo?') resp = sim_ou_nao() # caso o usuario deseje alterar if(resp == 1): print('Digite o novo passo:') novo = input() q = q1 + "{} SET passo='{}' WHERE id_receita={}" \ "AND num_passo={};".format(tbs[0], novo, rec, passo[1]) db.execute_query(q) return True # alterar ingredientes elif(len(tbs) == 3): # add ingrediente if(opc == 1): meds = ('kg', 'g', 'colher de chá', 'colher de sopa', 'l', 'ml', 'unidade') # lê o nome do ingrediente print('Qual ingrediente você deseja adicionar?') novo = input() # busca pelo ingrediente q = "SELECT * FROM utilizado_em WHERE nome='{}';".format(novo) ingredientes = db.select(q) # caso encontre o ingrediente if(len(ingredientes) > 0): i = ingredientes[0][0] # caso não encontre else: # insere o ingrediente temp = q2 + "{} (nome) VALUES ('{}')".format(tbs[2], novo) db.execute_query(temp) # busca pelo ingrediente inserido i = (db.select(q))[0][0] # lê a quantidade de cada ingrediente print('Digite a quantidade:') while(True): try: qtd = float(input()) except ValueError: qtd = None finally: if(qtd): break print('Valor inválido') # lê a medida de cada ingrediente print('Digite a unidade de medida:') print(meds) while(True): try: med = input() except ValueError: med = None finally: if(med in meds): break print('Valor inválido') # query para inserir em utilizado_em q = q2 + " (id_receita, id_ingrediente, quantidade, medida) " \ "VALUES ({}, {}, {}, '{}');" q = q.format(rec, i, qtd, med) # remover ingrediente elif(opc == 2): print('Qual ingrediente você deseja remover?') while(True): ing = input() # busca pelo ingrediente q = "SELECT id_ingrediente FROM ingrediente INNER JOIN " \ "utilizado_em ON id_ingrediente=id WHERE nome='{} " \ "AND id_receita={}';".format(ing, rec) ingredientes = db.select(q) # caso encontre o ingrediente if(len(ingredientes) > 0): i = ingredientes[0][0] break else: print('Ingrediente não utilizado') q = q3 + "{} WHERE id_receita={} AND id_ingrediente={};" q = q.format(tbs[1], rec, i) # alterar medida else: q = "SELECT nome, quantidade, medida, id FROM ingrediente " \ "INNER JOIN utilizado_em ON id=id_ingrediente WHERE " \ "id_receita={} ORDER BY nome;".format(rec) utilizados = db.select(q) for ing in utilizados: print('{} - {} {}'.format(ing[0], ing[1], ing[2])) print('Deseja alterar a medida desse ingrediente?') resp = sim_ou_nao() # caso sim, lê a nova quantidade if(resp == 1): print('Digite um novo valor:') while(True): try: qtd = float(input()) except ValueError: qtd = None finally: if(qtd): break print('Valor inválido') # query para alterar quantidade q = q1 + "{} SET quantidade={} WHERE id_receita={} AND " \ "id_ingrediente={};".format(tbs[1], qtd, rec, ing[3]) db.execute_query(q) return True else: return None db.execute_query(q) return True
6c26473dd26a547e51266f8b0d54f6c9df060b36
MatthewDobsonOnGitHub/Miscellaneous
/python_scripts/test_python_script.py
1,962
3.5
4
#!/usr/bin/env python # # # Load in the necessary libraries; importing them as smaller strings for brevity. import numpy as np import matplotlib.pyplot as plt import math import pylab # Now, we load in the transient data. # Enter data file name inside brackets. # This will store the data from the file as an array called 'data'. data = np.loadtxt('textfile.txt') # If needs be, we can set the size fo the output graph, but this is optional. # dpi = 'Dots Per Inches'. fig = plt.figure(figsize=(12,6), dpi = 100) # DATA PLOTTING # Firstly, we store the desired data to be plotted in arrays, one for each axis. # To do this, we select a given column, denoted by a number, and select all rows in the column (:). # Note: the 1st row/column is denoted '0', the 2nd row/column denoted '1', etc. x = data[:,0] y = data[:,1] y_error = data[:,2] # Now, we plot the data on the graph. # Note, we have errors associated with the y-values of the data, and so must be plotted also. To do this, we use the errorbar() function. # 'fmt' determines the style (1st letter) and colour (2nd letter) of the datapoints; 'o' makes circular points, 'b' makes blue points. #capsize determines the size fo the error bar caps. # linestyle determies the style of the line that joins the data points; here, we leave it blank, so no line is formed. plt.errorbar(x, y, yerr = y_error, fmt = 'ob', capsize = 5, linestyle = '') # Setting the titles for the x- and y-axes. # x-axis is time in units if Modified Julian Days. # y-axis is flux of light. plt.xlabel('MJD') plt.ylabel('Transient Flux') # Setting the numerical limits of the x- and y-axes plt.xlim([0,11]) plt.ylim([-20,120]) # We can also set gridlines and tick marks on the graph. plt.minorticks_on() plt.grid(which='major', linestyle=':') plt.grid(which='minor', linestyle=':') # Before plotting the figure, we save it plt.savefig('test_plot.pdf') # Now we display the figure itself! plt.show()
c6852a0f14a112645380329be291055f21736919
MatthewDobsonOnGitHub/Miscellaneous
/python_scripts/clipping_function.py
2,388
3.65625
4
def clipping_function(input_dictionary, output_dictionary): output_dictionary = {} # We loop through all the days of measurements, and loop through all the measurements taken on each day (nested loops). for key, value in input_dictionary.items(): # Define the number of points per day in the initial, unclipped data. list_length = len(value) # Define the number of points per day in the clipped data - this will be subject to change of value with each iteration list_length_new = len(value) # Create an array of list lengths, starting with original list length length_array = [list_length] # Finding the standard deviation and median values for each day; the function returns two variables, and assigns the values in a specific order, so be careful! sigma, med = median_and_stdev(value) # Performs the clipping an initial first time, calling the function 'remove_row' to remove an outlying data point (if one exists). new_list = remove_row(value, sigma, med) # Appends the length of the new, clipped list to the array. length_array.append(len(new_list)) print(length_array) while(True): # Infinite loop, until the last two elements in the array are of equal length # calculate new s.d. and median for every clipping iteration sigma, med = median_and_stdev(new_list) # If no more points have been clipped (i.e. the number of unclipped points in a day after passing the data through the clipping function is the same), we want the algorithm to stop for a given day. if length_array[-1] == length_array[-2]: # The newest list is appended to the empty dictionary for clipped data, with the same key as the original, unclipped data. output_dictionary[key] = new_list print("Break Out") print(length_array) return new_list break # If clipping has been performed (i.e. if the new clipped list is shorter than before), we want this to continue. else: # perform clipping again new_list = remove_row(value, sigma, med) # newest list added to the clipped data dictionary (it seemingly overwrites the original array) # number of remaining data points calculated, and appended to the appropriate array length_array.append(len(new_list)) print(length_array) sigma, med = median_and_stdev(new_list) output_dictionary[key] new_list return output_dictionary
30ca063384563a9b904f680295e18ed3061593b5
rodrigoctoledo/UnipPandemia
/Pademia1.py
10,035
3.9375
4
''' Rodrigo de Camargo Toledo D26EB3-6 CCP13 Algoritmo Pandemia Desenvolvedor: Rodrigo Toledo Baseado no Enunciado do Professor Dirceu, As Vezes é necessario interagir com o programa, apertando Enter para obter resultados ou inserindo informações Após apertar, o enter, pode demorar um pouco, pois coloquei o elemento temporal Durante o codigo Tem os meus Codigos e referencias as questoes do Professor e com as questões as respostas ''' import random from random import randint import os import time print("Bem Vindo ao Fim do Mundo de Pandemia") doenca = input('Entre com o nome da Doença: ') #Referencia da Probalidade: https://www.the-hospitalist.org/hospitalist/article/218769/coronavirus-updates/covid-19-update-transmission-5-or-less-among-close probalidade = int(randint(1,5)) # Parte do Codigo para Limpeza de Tela, mas como funciona apenas no CMD do Windows, Resolvi deixar comentado ''' matriz[l][c] = int(randint(0,200)) textoNaTela = "\ncomo limpar a tela do terminal cmd" print(10 * textoNaTela) print("\nLimparei a tela em 5 segundos!") os.system("cls") ''' ''' a) Implemente um software que contenha uma área (uma matriz quadrada, escolha o tamanho), que pode ser ocupada por pontos (escolha a quantidade), chamado de elementos (pessoas) ''' elementos = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]] elementos1 = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]] elementos2 = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]] for l in range(0,3): for c in range(0,6): elementos[l][c] = 'Saudavel' elementos1[l][c] = 'Saudavel' elementos2[l][c] = 'Saudavel' print('-='*30) for l in range(0,3): for c in range(0,6): if l == 0 and c == 0: elementos[l][c] ='Contaminado' '''A.1) Cada pessoa se movimentará dentro desta área''' print('Essa é o Esquema simples que representa o primeiro contaminado') for l in range(0, 3): # l1 += 1 # print("L1:"+str(l1)) for c in range(0, 6): # l2 += 1 # print("L2:" + str(l2)) print(f'[{elementos[l][c]:^5}]', end='') print() input("Pressione ENTER para continuar:") '''A.2) A cada ciclo (unidade temporal), cada pessoa se movimentará dentro desta área.''' print('-='*60) contflag = 0 contpassa =0 conttempo1 =0 flag = False # A.3) Em uma velocidade aleatória while(contflag < 17): time.sleep(randint(1, 1)) conttempo1 += 1 for l in range(0,3): for c in range(0,6): if elementos[l][c] =='Saudavel': # ao entrar em contato com outros elementos. # Ao final de cada ciclo, se uma pessoa estiver próxima de outra pessoa, # ela pode transmitir a doença para os elementos que estão em volta de si # (considere o posicionamento dentro da matriz, mais a probabilidade de transmissão da doença para este cálculo). #No caso, utilizei um Random, para possibilidade, e a Matriz se a pessoa está saudavel, no if acima prabalidade = randint(0, probalidade) # print(prabalidade) contpassa += 1 if prabalidade <=30: contflag += 1 #print("ContFlag:"+str(contflag)) elementos[l][c] ='Contaminado' for l in range(0, 3): # l1 += 1 # print("L1:"+str(l1)) for c in range(0, 6): # l2 += 1 # print("L2:" + str(l2)) print(f'[{elementos[l][c]:^5}]', end='') print() #b) Calcule quantos ciclos são necessários para se contaminar todos os elementos do grupo. print("Quantidade de ciclos para infectar todos:" + str(contpassa)) print("Tempo de passagem: "+str(conttempo1)+" Segundos") input("Pressione ENTER para continuar:") #c) Qual é a influencia da quantidade de pessoas que estão circulando pelas ruas, # na velocidade de contaminação das pessoas? # R: Quanto Mais pessoas nas Ruas, menos tempo ou ciclos acontece a infeccção de todos #Não consegui achar um numero para probalidade # https://saude.abril.com.br/medicina/coronavirus-novos-dados-sobre-grupos-de-risco/ # Peguei desse Site a Idade, para estipular o grupo de Risco #https://g1.globo.com/ciencia-e-saude/noticia/2019/09/16/estudo-confirma-recorde-de-longevidade-da-francesa-jeanne-calment-que-morreu-aos-122-anos.ghtml print('-='*60) contflag = 0 contpassa =0 i =int(0) flag = False conttempo2 =0 # C.1) e calcule, quanto isso influencia na velocidade de contaminação dos elementos. while(contflag <= 17): time.sleep(randint(1, 1)) conttempo2 += 1 idade = int(randint(0, 122)) i+=1 # C.1) Faça exercícios de limitando a movimentação dos elementos na matriz, # Pessoas Com mais de 60 ou com alguma outra doença que entre no grupo, representado, por resto da divisão 1, não se movimentam if idade >=60 and idade % 2 == 0: print("Pessoa no Grupo de Risco, não pode sair") else: for l in range(0,3): for c in range(0,6): if elementos1[l][c] =='Saudavel': # ao entrar em contato com outros elementos. # Ao final de cada ciclo, se uma pessoa estiver próxima de outra pessoa, # ela pode transmitir a doença para os elementos que estão em volta de si # (considere o posicionamento dentro da matriz, mais a probabilidade de transmissão da doença para este cálculo). #No caso, utilizei um Random, para possibilidade, e a Matriz se a pessoa está saudavel, no if acima prabalidade = randint(0, probalidade) # print(prabalidade) contpassa += 1 if prabalidade <=30: contflag += 1 # print("ContFlag:"+str(contflag)) elementos1[l][c] ='Contaminado' for l in range(0, 3): # l1 += 1 # print("L1:"+str(l1)) for c in range(0, 6): # l2 += 1 # print("L2:" + str(l2)) print(f'[{elementos1[l][c]:^5}]', end='') print() print("Quantidade de ciclos para infectar todos:" + str(contpassa)) print("Tempo de passagem: "+str(conttempo2)+" Segundos") #C.3) Qual é a diferença entre o tempo que demora para contaminar todos os elementos no b, e com a limitação da movimentação. print("Dirença de Tempo para o ciclo com e sem limitação: "+str(conttempo1-conttempo2)+" Segundos") input("Pressione ENTER para continuar:") #d) No protocolo de epidemia, estudado em classe, nem todos os elementos do sistema podem receber as informações mais atualizadas, isto acontece neste caso? Demonstre. #Vou mandar Via Email #e) Adicione o componente temporal, print('-='*60) contflag = 0 contpassa =0 mortes=0 curados=0 while(contflag <= 17): time.sleep(randint(1, 1)) conttempo2 += 1 for l in range(0,3): for c in range(0,6): if elementos2[l][c] =='Saudavel': # ao entrar em contato com outros elementos. # Ao final de cada ciclo, se uma pessoa estiver próxima de outra pessoa, # ela pode transmitir a doença para os elementos que estão em volta de si # (considere o posicionamento dentro da matriz, mais a probabilidade de transmissão da doença para este cálculo). #No caso, utilizei um Random, para possibilidade, e a Matriz se a pessoa está saudavel, no if acima prabalidade = randint(0, probalidade) # print(prabalidade) contpassa += 1 if prabalidade <=30: contflag += 1 # print("ContFlag:"+str(contflag)) elementos2[l][c] ='Contaminado' # As Mortes São bem Variaveis, segundo esse site: #Coloque de 1 a 30% possibilidade #https://www.abrasco.org.br/site/outras-noticias/saude-da-populacao/estimativas-do-impacto-da-covid-19-na-mortalidade-no-brasil/46151/ Morte = int(randint(1, 100)) Vivos = int(randint(1, 100)) #E.1) e comece a considerar que as pessoas se curam, depois de algum tempo, if Vivos >=90: elementos2[l][c] = 'Saudavel' # E.2)e que algumas morrem. O que muda neste cenário? # Quantos ciclos demora pras pessoas serem contaminadas, if Morte <= 5: elementos2[l][c] = 'Morto' mortes +=1 for l in range(0, 3): # l1 += 1 # print("L1:"+str(l1)) for c in range(0, 6): # l2 += 1 # print("L2:" + str(l2)) print(f'[{elementos2[l][c]:^5}]', end='') print() print("Quantidade de ciclos para infectar todos:" + str(contpassa)) #E.3) quantas pessoas morrem? print("Quantidade de Mortos:" + str(mortes)) print(doenca+" Ferrou o Mundo :( ") #f) Como comparar o espalhamento de um vírus, com a consistência de um banco de dados? #R: Em questão de Replicação de Dados ou Pessoas contamidas que replicam os virus para outros pelo contato, a Consistência eventual, #como apresenta alguns problemas de Replicação, assosio com as pessoas evitando contando e assim quebrando a replica do Virus #e) Como você compara cada indivíduo deste exercício, com processos e threads em um sistema distribuído? #R: Um Local fechado, seria o processador, e as pessoas são Theads e processos, o virus é o Recurso, se as Theads(Pessoas) #no Processador(Local), pararem de compartilhar recursos(Virus), vai ocorrer o Deadlock e as pessoas vão parar de compartilhar o virus #
6d1b7c713ca3d76f905109aa6770b67d3b2da4a3
Roooommmmelllll/Python-Codes
/randomNumList.py
1,029
3.984375
4
import random def makeList(): numList = [] for i in range(50): numList.append(random.randint(0,100)) return numList def stats(numList): total = 0 minimum = 100 maximum = 0 for i in range(50): total+=numList[i] if (numList[i] < minimum): minimum = numList[i] if (numList[i] > maximum): maximum = numList[i] average = total/50 print("Average is:", average) print("Minimum is:", minimum) print("Maximum is:", maximum) def bubbleSort(numList): swapped = True while(swapped == True): swapped = False for i in range(0,50): for j in range(i+1,50): if(numList[i] > numList[j]): temp = numList[i] numList[i] = numList[j] numList[j] = temp swapped = True return numList def printList(numList): print(numList) def main(): numList = makeList() printList(numList) stats(numList) sortedList = bubbleSort(numList) printList(sortedList) main()
d9aeb4ebe92db4d93fabc3c2362a1889605f1c35
Roooommmmelllll/Python-Codes
/string_slicing.py
176
3.78125
4
#string slicing def strSlice(): name = "Abraham Lincoln" print (name) #print (name[0]) #print (name[6:11]) #print (name[2::2]) print (name[-1::-1]) strSlice()
67f02f80af5d677d4752503c9947c994be1ad901
Roooommmmelllll/Python-Codes
/conversion_table.py
453
4.1875
4
#print a conversion table from kilograms to pounds #print every odd number from 1 - 199 in kilograms #and convert. Kilograms to the left and pounds to the right def conversionTable(): print("Kilograms Pounds") #2.2 pound = 1kilograms kilograms = 1 kilograms = float(kilograms) while kilograms <= 199: pounds = kilograms*2.2 print(str("%4.2f"%kilograms) + str("%20.2f"%pounds)) kilograms += 2 conversionTable()
648905f5d1d15cccd1a9356204ad69db0f30ce31
Roooommmmelllll/Python-Codes
/rightTriangleTest.py
970
4.21875
4
def getSides(): print("Please enter the three sides for a triagnle.\n" + "Program will determine if it is a right triangle.") sideA = int(input("Side A: ")) sideB = int(input("Side B: ")) sideC = int(input("Side C: ")) return sideA, sideB, sideC def checkRight(sideA, sideB, sideC): if sideA >= sideB and sideA >= sideC: if sideA**2 == (sideB**2+sideC**2): return True elif sideB >= sideA and sideB >= sideC: if sideB**2 == (sideA**2+sideC**2): return True elif sideC >= sideA and sideC >= sideB: if sideC**2 == (sideA**2+sideB**2): return True return False def printMe(right): if right == True: print("Those values create a right triangle!") else: print("Those values DO NOT create a right triangle!") def main(): sideA, sideB, sideC = getSides() #checkTriangle right = checkRight(sideA, sideB, sideC) printMe(right) main()
996e8730e24a1d8f763ea3f2f2fd1b7eebcfcd03
Roooommmmelllll/Python-Codes
/Brute_Force.py
1,814
3.625
4
import itertools import hashlib def main(): #Original Data name = "Jane Doe Smith" bd = "02/13/1981" ssn = "567-33-2013" pn = "831.228.5671" petName = "Kujo Friendly" win7Pass = "ae2e1fa899105c28184c0d0d11be8241" print("The Original Data") print(name,"\n",bd,"\n",ssn,"\n",pn,"\n",petName,"\n") #Splits Data into Lists nameStr = name.split(" ") bdStr = bd.split("/") ssnStr = ssn.split("-") pnStr = pn.split(".") petNameStr = petName.split(" ") print("The String Form Data") print(nameStr,"\n",bdStr,"\n",ssnStr,"\n",pnStr,"\n",petNameStr,"\n") #Combines all the lists into one big list bigList = nameStr + bdStr + ssnStr + pnStr + petNameStr print("The Combined Data List") print(bigList) #Permutates the pieces of the list into single strings and puts them in a list perms = itertools.permutations(bigList, r=3) permsList = list(perms) print("The list pieces have been separated into sets of 3.") #Finds the password! print("\n\nNow looking for password.") correctPass = "" #Holds password if found. correctHash = "" #Holds the password hash if found. tries = 0 for i in range(len(permsList)): #turns the generated password into MD5 hex joinedItem = ''.join((permsList[i])) joinItemByte = joinedItem.encode('utf-8') joinItemMD5 = hashlib.md5(joinItemByte) joinItemDigest = joinItemMD5.hexdigest() #keeps check of the tries tries += 1 #checks against the taken password if win7Pass == joinItemDigest: correctPass = joinedItem correctHash = joinItemDigest print("Password found!") break print("\nThe Hashed MD5:", correctHash) print("\nThe password is:", correctPass) print("\nIt only took", tries, "tries!") main()
cc19bcc1c8da5e3ab76d70a2c460820ddbc7e1ea
Roooommmmelllll/Python-Codes
/4 Points Distance CHecker.py
1,225
4
4
def woot(): print("Program will determine the " + "fastest route between four " + "points of travel.") print("Assume that point A is already plotted") pointsNum = 0 while pointsNum < 6: pointsNum+=1 if pointsNum == 1: pointAB = int(input("Please input the distance" + "from point A to B") elif pointsNum == 2: pointAC = int(input("Please input the distance" + "from point A to C") elif pointsNum == 3: pointAD = int(input("Please input the distance" + "from point A to D") elif pointsNum == 4: pointBC = int(input("Please input the distance" + "from point B to C") elif pointsNum == 5: pointBD = int(input("Please input the distance" + "from point B to D") elif pointsNum == 6: pointCD = int(input("Please input the distance" + "from point C to D") check1 = pointAB + pointBC + pointCD shortest = check1 check2 = pointAB + pointBD + pointCD if check1 > check2: shortest = check2 else:
3d12d105de0090fc2711f13e08ad7172732402b9
Roooommmmelllll/Python-Codes
/class_ifs.py
2,183
3.953125
4
def divide(): topnum = int(input("Please input a number for the numerator: ")) botnum = int(input("Please input a number for the denominator: ")) if(botnum == 0): print("You cannot divide with zero!!") answer = "undefined" return answer = topnum/botnum print("The answer is " + str(answer) + ".") def wages(): hours = int(input("Please input the amount of hours that you worked: ")) wage = float(input("Please input your hourly wage: ")) if(hours < 0 or wage < 0): print("You cannot enter a negative number!!") return earnings = hours*wage print("You earned " + str(("%.2f")%earnings) + " dollars in " + str(hours) + " hours.") def showMessage(): message = "Hello, world!" answer = input("Do you want to see the message? (Y / N): ") answer = answer.lower() if (answer == "yes" or answer == "y"): print(message) def channel(): print("This program will tell you what kind\nof programming is on the channel you enter.") channelNum = int(input("Please enter a favorite t.v. channel: ")) if (channelNum == 25): print("You must like sports.") if (channelNum == 72): print("You must like cartoons.") if (channelNum == 9): print("You must like public tv.") if (channelNum != 25 and channelNum != 72 and channelNum != 9): print("I do not know that channel.. :(") def drive(): print("This program will find out if you can drive a car in CA") age = int(input("How old are you?: ")) if (age >= 16): hasCar = input("Do you have a car? (Y/N): ") hasCar = hasCar.lower() if (hasCar == 'y' or hasCar == 'yes'): hasLicense = input("Do you have a driver's license? (Y/N): ") hasLicense = hasLicense.lower() if (hasLicense == 'y' or hasLicense == 'yes'): print("You can drive a car!") else: print("You need to have a car in order to drive..") else: print("You must have a license in order to drive a car.") else: print("You are not old enough to drive.") drive()
273d7533f1f2de41e71eb77e9d291101f461bb5f
Roooommmmelllll/Python-Codes
/bus_seats.py
247
3.96875
4
def rentbus(): people = int(input("How many people are going?: ")) extra = people - 34 if extra >= 0: print(extra, "people need to drive.") else: extra *= -1 print("There are", extra, "spaces empty on the bus.")
d28babacc9ada1b6bd9b74f941fe6b6b6d0131cc
Roooommmmelllll/Python-Codes
/highscores.py
774
4
4
def highscore(): loop = True while loop == True: students = input("How many students are in the class?: ") if students.isdigit() == True: break chr(2) ord(a) highscore1 = 0 highscore2 = 0 for i in range(0, students): while loop == True: newScore = input("Input a student's score: ") if newScore.isdigit() == True: break newScore = float(newScore) if newScore > highscore1 or newScore == highscore1: highscore2 = highscore1 highscore1 = newScore elif newScore > highscore2 and newScore < highscore1: highscore2 = newScore print("The highest score is:", highscore1) print("The second heighest score is:", highscore2) highscore()
fb44a10c97370bd7f1c1214260c1469b1c2f91b9
Roooommmmelllll/Python-Codes
/MathCAI.py
7,608
4.28125
4
# Computer Assisted Instruction. Practice Arithmetic. # At least 6 functions. # Use echo printing where apporpriate (printing with variables) # Extensions # F) Extend your program so that it has differnt grade levels. # For example, the program will only give problems with numbers at the level. # Grade 1 - Numbers 1 > 5 # Grade 2 - Numbers 1 > 10 # Grade 3 - Numbers 1 > 20 # Using the score of how the student is doing overall, you can promote # the student to the next grade level automatically if they are getting # 90% or more right at their grade level. import random # A) Extend your program so that when the user gets the right answer, # your program uses the random number generator to print out 1 out of # 4 different possible responses. # Do the same thing for their incorrect answers. def randOutput(isCorrect): randNum = random.randint(1,4) if (isCorrect == True): if(randNum == 1): print("That is Correct!") elif(randNum == 2): print("Awesome, right answer!") elif(randNum == 3): print("Good Job! That was correct!") elif(randNum == 4): print("Amazing! That's right!") else: if(randNum == 1): print("I'm sorry, but that is incorrect.") elif(randNum == 2): print("Good try! But that is wrong :(") elif(randNum == 3): print("Sorry, that's the wrong answer.") elif(randNum == 4): print("That answer's a little off. Sorry.") # C) Extend the program so that it evaluates the user by their scores. # This will take place at the end of each math type. # 100% right out of 10 problems, Amazing! # 90% right out of 10 problems, Excellent! # 80% is pretty good. # 70 - 80% is average, but needs more practice. # Below 70%, need a lot of review and practice. # If they get below 70% the program will display a review of that operation. # For example, multiplication should show a multiplication table def evaluateScore(percentCorrect): print("You got", percentCorrect, "% questions correct out of 10.") if(percentCorrect >= 90): print("Amazing job, you really have a knack for this!") elif(percentCorrect >= 80 and percentCorrect < 90): print("You should be proud of yourself!") elif(percentCorrect >= 70 and percentCorrect < 80): print("Almost there, a little more effort!") elif(percentCorrect < 70): print("You need some review and practice, here's some help.") def extraHelp(operand): if(operand == "+"): print("\n\nRemember that addition is like adding two bags of things together.") print("If you have one bag of marbles, with 3 marbles in it.") print("And you have another bag of marbles, with 2 marbles in it.") print("Then you put all the marbles from one bag and put it into the other,") print("you can count the marbles one by one, from the other bag.") print("Right now, the second bag has 2 marbles, so take one out.") print("The first bag has 4 marbles in it now, and the second bag has only 1.") print("Then you can take the last marble out of the second bag.") print("The first bag now has 5 marbles in it, and the second bag is empty!") print("This idea works for anything, and in normal math looks like 3 + 2 = ?") print("Which is 5!\n\n") elif(operand == "-"): print("\n\nRemember that you can think of subtraction as taking marbles out of a bag.") print("If you have a bag of 3 marbles, and you wish to take 2 out.") print("You remove one marble, so the bag now has 2 marbles in it.") print("Then you remove another marble, so that the bag now has 1 marble in it.") print("You can think of this problem in normal math as, 3 - 2 = ?") print("Which equals 1!\n\n") elif(operand == "*"): print("/n/n") colLine = ""+str("%5.0f"%()) for cols in range(1,13): colLine+= str("%5.0f"%(cols)) print(colLine) for vert in range(1,13): line = ""+str(vert) for horiz in range(1,13): line += str("%5.0f"%(vert*horiz)) print(line) print("/n/n") elif(operand == "/"): print("/n/nDivision is hard, but you cank think of it like this:") print("10 / 2 = ?") print("You subtract 2 from 10, until it reaches 0.") print("Then you add up how many times you had to subtract.") print("In this case, 10-2 = 8. 8-2 = 6. 6-2 = 4. 4-2 = 2. 2-2 = 0.") print("So, I had to subtract the 2 a total of five ( 5 ) times.") print("That means that 10 / 2 = 5!/n/n") # Give the student 10 problems, using random numbers from 1 to 12. # Questions should be in format, "What is 6 x 5?" or "What is 2 + 12?" def mathAdd(): counter = 0 correct = 0 while(counter < 10): tries = 0 num1 = random.randint(1,12) num2 = random.randint(1,12) answer = num1+num2 # D) Extend the program so that if the student gets it wrong, they can # try again and again until they get it right, and but is not counted # in their total for correct answers, it will only count by getting # it right on the first try. while(tries >= 0): print() print("What is", num1, "+", str(num2)+"?") user = input() # After giving an answer, check if the answer is correct, print out something like "Excellent!" if(int(user) == int(answer)): randOutput(True) if(tries == 0): correct += 1 break else: break else: randOutput(False) tries+=1 # If the answer is wrong, print out "Sorry, that is wrong. The correct answer is ##" counter += 1 # Your program should keep a count of how many questions the # student gets right. And should let them know at the end what # percentage of the ten programs they got right. This should # display at the end of each practice session operation. percentCorrect = correct*10 evaluateScore(percentCorrect) if(correct < 7): extraHelp("+") return correct #def mathSub(): #def mathMult(): #def mathDiv(): # B) Extend the program by adding a Mixture option. # Where they are given 10 questions using different Mathematics options. #def mathMix(): # Present students with a menu, where they can repeatedly choose to practice. # - Addition, Subtraction, Multiplication, and Division problems or to exit the program. # User chooses math operation to practice ( +, -, *, / ) def main(): totalCorrect = 0 totalQuestions = 0 while (totalQuestions >= 0): print("Please choose an operation to practice ( +, -, *, / )") print("You can enter M for a mix, or enter 0 (zero) to exit the program.") choice = input() if(choice == "0"): print("Thank you for using the Math Computer Assisted Instruction Program.") return elif(choice == "+"): numCorrect = mathAdd() # Keep track of a running score of the questions they got right in the whole program. # At the end of each 10 questions, the program should tell them their overall progress. # And then return to the menu. totalCorrect += numCorrect totalQuestions += 10 print("You currently have gotten", totalCorrect, "questions correct out of", totalQuestions) elif(choice == "-"): mathSub() elif(choice == "*"): mathMult() elif(choice == "/"): mathDiv() elif(choice == "M"): mathMix() #else: main()
722687225a39c563b955c4a56c8270b3aaea647c
Roooommmmelllll/Python-Codes
/printSlow.py
322
3.828125
4
import time def printSlow(): print("Please input a speed to print at") print("0.5 is pretty fast, while 5 is very very slow.") printSpeed = float(input()) newString = input("Input a long string: ") for i in range(len(newString)): print(newString[i], end="") time.sleep(printSpeed) printSlow()
5ba3a2d27ec8f58f97c54cc837c81f210362508a
Roooommmmelllll/Python-Codes
/largerNumber.py
241
4.125
4
def largeNumbers(): value = 0 for i in range(7): user = int(input("Please input seven numbers: ")) if user > value: value = user print("The largest number you entered was: " + str(value) + ".") largeNumbers()
109899d74d6d0c48afe0052224a64a258ea793e3
nishhub/EasyLevelPythonPrograms
/Sorting/Bubble Sort.py
346
3.890625
4
def bubble_sort(a_list): swap = True for i in range(len(a_list)-1, 0, -1): for j in range(0, i): if a_list[j] > a_list[j+1]: a_list[j], a_list[j+1] = a_list[j+1], a_list[j] swap = False if swap: return a_list = [4, 2, 38, 10, 5] bubble_sort(a_list) print(a_list)
8af20acbd18a8e179396fff27dedfa4cddda7d3c
mayer-qian/Python_Crash_Course
/chapter4/numbers.py
1,092
4.34375
4
#使用函数range生成数字,从1开始到5结束,不包含5 for value in range(1, 5): print(value) print("=======================================") #用range创建数字列表 numbers = list(range(1, 6)) print(numbers) print("=======================================") #定义步长 even_numbers = list(range(2, 11, 2)) print(even_numbers) print("=======================================") #将1-10的平方添加到列表 squares = [] for value in range(1, 11): squares.append(value**2) print(squares) print("=======================================") #列表解析 squares = [value**2 for value in range(1, 11)] print(squares) print("=======================================") #求大,求小,求和 digits = list(range(1, 11)) print("max digit is " + str(max(digits))) print("min digit is " + str(min(digits))) print("sum of digit is " + str(sum(digits))) print(sum(list(range(1, 1000000)))) #打印3到30内3的倍数 digis = list(range(3, 31, 3)) for digi in digis: print(digi) #1-10的立方 lifang = [value**3 for value in range(1, 11)] print(lifang)
c8d52dbd74315b07d658790c57a73802414fdba2
badre-Idrissi/tpPython
/application2.py
244
3.6875
4
nom = input("sasissez le nom : \n") genre_val=input("saisir le genre :\n") #genre= ("Monsieur" if genre_val=="1" else "Madame") genre=("Monsieur", "Madame")[genre_val=="0"] msg= "Bonjour {} {}" print("Bonjour {} {}".format(genre,nom))
0c3b01eeef287780b3c0cc135e5a4fe06f640778
christinalow/compsci-class
/projects/semester 1/#2-11-16-2017.py
376
3.5
4
import math #a = p(1+(r/n))**nt p = float(input("What is the amount you saved up?")) r = (int(input("What is your current savings rate in percent?"))/100) n = int(input("How often does your investment compound per year?")) a = 2*p x = (1 + (r/n)) y = a/p #y will always be 2 t = ((math.log10(y))/ (n*(math.log10(x)))) print("Your amount will double in " + str(t) + " years")
da90287810410dc0e41db8a5b93f63f99214496e
christinalow/compsci-class
/practice/2017-12-18.py
499
3.921875
4
sum=0 for i in range(1000): if i%4==0 or i%7==0: sum= sum + i print("The sum of all the multiples of 4 and 7 below 1000 is " + str(sum) +".") #checks to if user input is a prime number: import math num = int(input("Enter an integer: ")) mid = int(math.sqrt(num))+1 count=0 for x in range(2,mid): if num%x==0: count+=1 if count>0: print(str(num)+" is not a prime number.") elif count==0: print(str(num)+" is a prime number.") #future steps/challenge: see which is the highest factor
7d4ef9a2f61bbab56b14b9c3b26cc300e2fa6f1f
lxndrvn/python-lightweight-erp-3rd-tw-overload
/common.py
917
3.8125
4
# implement commonly used functions here import random # generate and return a unique and random string # other expectation: # - at least 2 special char()expect: ';'), 2 number, 2 l and 2 u case letter # - it must be unique in the list # # @table: list of list # @generated: string - generated random string (unique in the @table) def generate_random(table): l = "abcdefghijklmnopqrstuvwxyz" c = "[!@#$%^&*()?]" id = [i[0] for i in table] while True: num = [random.randint(0, 9) for i in range(2)] lo = [l[random.randint(0, len(l) - 1)] for i in range(2)] up = [l[random.randint(0, len(l) - 1)].upper() for i in range(2)] spec = [c[random.randint(0, len(c) - 1)] for i in range(2)] app = num + lo + up + spec generated = "".join(str(i) for i in app) if generated not in id: return False else: return generated
27a145eb25b3a446ef753448253916a71a4c44a9
WarriorsWCH/python-lesson
/字典/dict.py
699
4
4
info = {'name':'li', 'id':100, 'sex':'f', 'address':'english'} # 修改元素 info['id'] = 50 print(info) # 添加新的元素 info['age'] = 23 print(info) # del删除指定的元素 del info['sex'] print(info) # clear清空整个字典 info.clear() print(info) info = {'name':'li', 'id':100, 'sex':'f', 'address':'english'} # 键值对的个数 print(len(info)) # 返回一个包含字典所有KEY的列表 print(info.keys()) # 返回一个包含字典所有value的列表 print(info.values()) # 返回一个包含所有(键,值)元组的列表 print(info.items()) for key,value in info.items(): print(key,value) print('name' in info) print('li' in info) print('li' not in info)
5ffbd62fd3238c5c2bdddf9b3f24ffdc7262bf01
dmyerscough/demo
/test_main.py
407
3.53125
4
#!/usr/bin/env python import unittest from main import fib class TestFib(unittest.TestCase): def test_fib(self): """ Test fibonacci """ fibonacci = [] s = fib() for _ in range(0, 11): fibonacci.append(next(s)) self.assertEqual(fibonacci, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) if __name__ == '__main__': unittest.main()
9acef6fa13ba60dd674dfea65c1674d4dd939c94
thammaneni/Python
/Practice/TimedeltaExcercise.py
324
3.84375
4
from datetime import date from datetime import time from datetime import datetime from datetime import timedelta now = datetime.now() print ("Today is "+ str(now)) print ("Time after 365 days :"+str(now + timedelta(days=365))) print ("Date after 6 weeks, 4 days,20hours : ", str(now + timedelta(weeks=6,days=4,hours=20)))
79a6d94edab18821979a117ba4c226544aef0882
thammaneni/Python
/Practice/DateTimeFormat.py
443
4.0625
4
from datetime import datetime t = datetime.now() print (t.strftime("The current year is : %Y")) print (t.strftime("The current date is : %d")) print (t.strftime("The current month is : %B")) print (t.strftime("The current weekday is : %A")) print (t.strftime("The Local Date and Time is : %c")) print (t.strftime("The Local date is : %x")) print (t.strftime("The Local time is : %X")) print (t.strftime("The current time is : %I:%M:%S %p"))
b81b5ccc53216e4485737df5a37121c85939eb33
thammaneni/Python
/PythonPracticeEx/EvenListCreationSingleSTMT.py
450
3.859375
4
# import random # randomNumber = random.randint(0,5) # print (randomNumber) #========================================================= list1 = [30,32,46,12,13,14,15,16,17,18,19,20] subList = [ i for i in list1 if i % 2 == 0] subList.sort() print (subList) #======================================================== # a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # def only_even(): # onlyeven = a[0:len(a)-1:2] # print(onlyeven) # only_even()
c424feca5aea8d199dfc86454391ab6266123ea0
KinPeter/Udemy-and-other-courses
/Python-mega-course-by-Ardit-Sulce/bokeh_visualization/basic_graph.py
796
3.78125
4
# making a basic bokeh line graph from bokeh.plotting import figure from bokeh.io import output_file, show import pandas # ---- from python lists # prepare some data x = [1,2,3,4,5] y = [6,7,8,9,10] # need to be the same length # prepare the output file output_file('line.html') # create a figure object f1 = figure() # create line plot f1.line(x, y) # show the figure object show(f1) # ---- from local csv file df = pandas.read_csv('data.csv') x = df['x'] # index is the column name y = df['y'] output_file('line_from_csv.html') f2 = figure() f2.line(x, y) show(f2) # ---- from local online csv file df2 = pandas.read_csv('http://pythonhow.com/data/bachelors.csv') x = df2['Year'] y = df2['Engineering'] output_file('line_from_web_csv.html') f3 = figure() f3.line(x, y) show(f3)
a6a16620fe79273b2d803874fdfca403a58cac4a
KinPeter/Udemy-and-other-courses
/Python-mega-course-by-Ardit-Sulce/pandas_jupyter/supermarkets/import_read_and_slice_dataframes.py
1,874
3.84375
4
import os os.listdir() import pandas # import csv file df1 = pandas.read_csv("supermarkets.csv") # header = None : will not treat first row as header print(df1.set_index("ID")) # will treat ID column as index but only for output, not saving it print(df1.shape) # how many rows and colums we have? # import json file df2 = pandas.read_json("supermarkets.json") print(df2) # import excel file df3 = pandas.read_excel("supermarkets.xlsx", sheet_name=0) # sheet's index, so 0, 1, 2, etc print(df3) # import txt file, data separated by commas df4 = pandas.read_csv("supermarkets-commas.txt") # for txt with separated by commas just simply use read_csv print(df4) # import txt file, data separated by other character df5 = pandas.read_csv("supermarkets-semi-colons.txt", sep=";") # for txt with other separator use read_csv and add sep="" print(df5) # import online files df6 = pandas.read_csv("http://pythonhow.com/supermarkets.csv") # to open online file print(df6) # changing the layout with index, and save: df7 = df6.set_index("Address") # save table with index "address" to a new variable print(df7) # label based indexing: print( df7.loc["735 Dolores St" : "3995 23rd St", "City" : "Country"] # slice of table with range of rows and range of columns ) # getting a single cell: print( df7.loc["332 Hill St", "Name"] ) # getting 1 row to a list: print( list(df7.loc["551 Alvarado St", : ]) # excludes the index cell! ) # position based indexing: print( df7.iloc[1:4, 1:4] # range here is upperbound exclusive! ) # getting a single cell: print( df7.iloc[2, 4] # range excludes the index cell! ) # getting 1 row to a list: print( list(df7.iloc[5, : ]) # excludes the index cell! ) # combined indexing (Deprecated): print( df7.ix[2, "Name"] # can combine position and label, also can use range similarily as .loc and .iloc )
9700cb032358926683c69bfd64b0f904d2f0f757
KinPeter/Udemy-and-other-courses
/Python-by-in28minutes/02-OOP-project/book-reviews.py
709
3.59375
4
class Book: def __init__(self, id, name, author): self.id = id self.name = name self.author = author self.review = [] def __repr__(self): return repr((self.id, self.name, self.author, self.review)) def add_review(self, review): self.review.append(review) class Review: def __init__(self, id, review, rating): self.id = id self.review = review self.rating = rating def __repr__(self): return repr((self.id, self.review, self.rating)) book = Book(101, 'Object Oriented Programming with Python', 'Ranga') book.add_review(Review(10, "Great Book", 5)) book.add_review(Review(11, "Awesome", 5)) print(book)
6ddcb742d401c9179a8d0c36be4c9729950f51bd
KinPeter/Udemy-and-other-courses
/Python-mega-course-by-Ardit-Sulce/bokeh_visualization/weather_data.py
610
3.625
4
import pandas from bokeh.plotting import figure from bokeh.io import output_file, show p = figure(plot_width=800, plot_height=600, tools='pan') df = pandas.read_excel('http://pythonhow.com/data/verlegenhuken.xlsx') x = df['Temperature'] / 10 y = df['Pressure'] / 10 p.title.text='Temperature and Air Pressure' p.title.text_color='Gray' p.title.text_font='Arial' p.title.text_font_style='bold' p.xaxis.minor_tick_line_color=None p.yaxis.minor_tick_line_color=None p.xaxis.axis_label='Temperature (C)' p.yaxis.axis_label='Pressure (hPa)' p.circle(x, y, size=0.5) output_file('temp_and_press.html') show(p)
d8d913f624f5afef56252ae6a768bc688241708d
anti401/python1
/python1-lesson1/easy-3.py
535
3.96875
4
# coding : utf-8 # Задача-3: Запросите у пользователя его возраст. # Если ему есть 18 лет, выведите: "Доступ разрешен", # иначе "Извините, пользование данным ресурсом только с 18 лет" age = int(input('Сколько вам лет? - ')) if age >= 18: print('Доступ разрешен') else: print('Извините, пользование данным ресурсом только с 18 лет')
d9657338aa5ce5c4be2b5f189f5d6ea7b3bae1a6
anti401/python1
/python1-lesson1/easy-2.py
555
4.21875
4
# coding : utf-8 # Задача-2: Исходные значения двух переменных запросить у пользователя. # Поменять значения переменных местами. Вывести новые значения на экран. a = input('A = ') b = input('B = ') print('Вы ввели A = ' + str(a) + ' и B = ' + str(b)) # перестановка значений через временную переменную t = a a = b b = t print('А теперь A = ' + str(a) + ' и B = ' + str(b))
eb18ec7075c744764ea2d06be8bb29785f76f8da
anti401/python1
/python1-lesson3/normal-4.py
1,003
4.09375
4
# coding : utf-8 # Задача-4: # Даны четыре точки А1(х1, у1), А2(x2 ,у2), А3(x3 , у3), А4(х4, у4). # Определить, будут ли они вершинами параллелограмма. def middle(A, B): # середина отрезка return (A[0] + B[0]) / 2, (A[1] + B[1]) / 2 def equals(A, B): # совпадение точек return A[0] == B[0] and A[1] == B[1] points = [1, 1], [2, 4], [4, 1], [5, 4] # если совпадают середины диагоналей - параллелограмм if equals(middle(points[0], points[1]), middle(points[2], points[3])): print('Это параллелограмм!') elif equals(middle(points[0], points[2]), middle(points[1], points[3])): print('Это параллелограмм!') elif equals(middle(points[0], points[3]), middle(points[2], points[1])): print('Это параллелограмм!') else: print('Это не параллелограмм.')
84766bbb2176c3375eb0717a0566c46bdcbfff42
anti401/python1
/python1-lesson2/normal-1.py
865
3.640625
4
# coding : utf-8 # Дан список, заполненный произвольными целыми числами, получите новый список, # элементами которого будут квадратные корни элементов исходного списка, # но только если результаты извлечения корня не имеют десятичной части и # если такой корень вообще можно извлечь # Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2] import math list_orig = [2, -5, 8, 9, -25, 25, 4] list_new = [] for el in list_orig: if el >= 0 and math.sqrt(el).is_integer(): list_new.append(int(math.sqrt(el))) print('Исходный список: ', list_orig) print('Новый список: ', list_new)
9ec5a1b69aeddeef690353a6b10b1f7e8604fe23
miseop25/CS_Basic
/Algorithm/Sorting/QuickSort.py
1,014
3.96875
4
class Sort : def __init__(self, array): self.array = array def quickSort(self, st, ed) : if st >= ed : return pivot = st small = st + 1 big = ed temp = 0 while small <= big : while small <= ed and self.array[small] <= self.array[pivot] : small += 1 while big > st and self.array[big] >= self.array[pivot] : big -= 1 if small > big : temp = self.array[big] self.array[big] = self.array[pivot] self.array[pivot] = temp else : temp = self.array[small] self.array[small] = self.array[big] self.array[big] = temp self.quickSort(st, big-1) self.quickSort(big+1 , ed) if __name__ == "__main__": test = [3,7,8,1,5,9,6,10,2,4] s = Sort(test) s.quickSort(0, len(test)-1) print(s.array)
4ef007bae17e06e2f2f81f160d2d07e8e029375f
kahnadam/learningOOP
/Lesson_2_rename.py
688
4.3125
4
# rename files with Python import os def rename_files(): #(1) get file names from a folder file_list = os.listdir(r"C:\Users\adamkahn\learningOOP\lesson_2_prank") #find the current working directory saved_path = os.getcwd() print("Current Working Directory is "+saved_path) #change directory to the one with the files os.chdir(r"C:\Users\adamkahn\learningOOP\lesson_2_prank") #(2) for each file, rename file for file_name in file_list: print("Old Name - "+file_name) print("New Name - "+file_name.translate(None, "0123456789")) os.rename(file_name,file_name.translate(None, "0123456789")) #return to original working directory os.chdir(saved_path) rename_files()
43a152688669d42bbfe9472235b37505bd315265
jlopez0591/python-automate
/strings/table_printer.py
814
4
4
#table_printer.py #prints a table of lists with the same amount of elements #Function to print the table def printTable(tableData): rowLength = 0 colWidths = [0] * len(tableData) for i, column in enumerate(tableData): if(rowLength<len(column)): rowLength = len(column) for word in column: if(colWidths[i] < len(word)): colWidths[i] = len(word) for i in range(rowLength): tableRow='' for j, row in enumerate(tableData): tableRow+=row[i].rjust(colWidths[j])+' ' print(tableRow) #Main part of the program tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] printTable(tableData)
ce4909318398deed3194ca364684bbb07305892f
MarcusVinix/Cursos
/curso-de-python/exemplos/enumerate.py
411
4
4
numeros = [30, 28, 43, 54, -1, -4, -6, -7, 8, 7, 9,] print(numeros) i = 0 for num in numeros: print("FOR sem enumerate: [%d] --> %d" % (i, num)) #print("FOR sem enumerate: [", i, "] --> ", num) i += 1 i = 0 while i < len(numeros): print("While sem enumerate: [%d] --> [%d]" % (i, numeros[i])) i += 1 for i, num in enumerate(numeros): print("FOR com enumerate: [%d] --> %d" % (i, num))
291a113d8bcc954b18d084b0d6a64340d5c88958
MarcusVinix/Cursos
/curso-de-python/modulos/modulo_type.py
738
3.65625
4
import types def mostraTipo(dado): tipo = type(dado) if tipo == str: return ("String") elif tipo == int: return ("inteiro") elif tipo == list: return ("Lista") elif tipo == dict: return ("Dicionario") elif tipo == float: return ("Numero decimal") elif tipo == bool: return ("Booleano") elif tipo == types.BuiltinFunctionType: return ("Função interna") elif tipo == types.FunctionType: return ("Função") else: return (str(tipo)) print(mostraTipo("Marcus")) print(mostraTipo(28)) print(mostraTipo(78.8)) print(mostraTipo([5,7,8])) print(mostraTipo({"Python":120, "Go":130})) print(mostraTipo(print)) print(mostraTipo(None))
35b4f63c77d843ae5f23d2e1455fcc8cf2a184f6
MarcusVinix/Cursos
/curso-de-python/exercicios/contagem_cedulas.py
761
3.75
4
valor = float(input("Digite o valor: ")) cedulas = 0 valorCedulaAtual = 100 valorASerEntregue = valor while True: if valorCedulaAtual <= valorASerEntregue: cedulas += 1 valorASerEntregue -=valorCedulaAtual else: if cedulas > 0: print("%d cedula(s) de R$ %5.2f" % (cedulas, valorCedulaAtual)) if valorASerEntregue == 0: break if valorCedulaAtual == 100: valorCedulaAtual = 50 elif valorCedulaAtual == 50: valorCedulaAtual = 20 elif valorCedulaAtual == 20: valorCedulaAtual = 10 elif valorCedulaAtual == 10: valorCedulaAtual = 5 elif valorCedulaAtual == 5: valorCedulaAtual = 2 cedulas = 0
727df69164898002020bade490e3ac13d9b4c4b0
MarcusVinix/Cursos
/curso-de-python/funcoes_def/criando_funcoes_fatorial.py
485
4.0625
4
#fatorial de 3: 3 * 2 * 1 = 6 #fatorial de 4: 4 * 3 * 2 * 1 = 24 #fatorial de 5: 5 * 4 * 3 * 2 * 1 = 120 def fatorial(numero): f = 1 while numero > 1: f *= numero numero -= 1 return f print(fatorial(3)) print(fatorial(4)) print(fatorial(5)) print(fatorial(6)) def fatorial1(numero): f = 1 i = 1 while i <= numero: f *= i i += 1 return f print(fatorial1(3)) print(fatorial1(4)) print(fatorial1(5)) print(fatorial1(6))
073248546d1afb1cd215ae07e8c69a3f5c5c9373
MarcusVinix/Cursos
/curso-de-python/exemplos/string_len.py
130
3.59375
4
nome = "Marcus Vinicius" print("Nome: ", nome) print("Tamanho: ", len(nome)) tamanho = len(nome) print("Tamanho: ", tamanho) print(nome[5])
596f04b0adf35ebf8679d29bcab401868eb5eecb
MarcusVinix/Cursos
/curso-de-python/funcoes_def/criando_funcoes_pesquisa.py
829
3.6875
4
def pesquisar(lista, codigo): for i, codigos in enumerate(lista): if codigos == codigo: return ("Codigo %d encontrado no indice %d" % (codigo, i)) return ("O codigo %d não foi localizado" % codigo) listaProdutos = [4, 8, 2, 67, 5, 12] print(pesquisar(listaProdutos, 8)) print(pesquisar(listaProdutos, 5)) print(pesquisar(listaProdutos, 11)) print(pesquisar(listaProdutos, 2)) dicionarioCursos = {"pyhton": 130, "java": 110, "arduino": 90} def pesquisarDicionario(dicionarioPesquisar, cursoPesquisar): if cursoPesquisar in dicionarioPesquisar: print("Esse curso foi localizado, o seu preço é R$ %5.2f" % dicionarioPesquisar[cursoPesquisar]) else: print("Esse curso não foi localizado") pesquisarDicionario(dicionarioCursos, "java")
966c55fb0d234a61e5b66999b41be525a979d8c9
MarcusVinix/Cursos
/curso-de-python/funcoes_def/criando_as_proprias_funcoes.py
1,062
4.34375
4
print("Sem usar funções, a soma é: ", (5+6)) def soma(num1, num2): print("Usando funções (DEF), a soma é: ", (num1+num2)) def subtracao(num1, num2): print("Usando funções (DEF), a subtração é: ", (num1 - num2)) def divisao(num1, num2): print("Usando funções (DEF), a divisão é: ", (num1 / num2)) def multiplicacao(num1, num2): print("Usando funções (DEF), a multiplicação é: ", (num1 * num2)) soma(23, 45) subtracao(89, 56) divisao(87, 54) multiplicacao(34, 3) #usando comando return def soma1(num1, num2): return(num1+num2) valor1 = 70 valor2 = 80 print("Usando funções (DEF) com return, a soma é ", soma(8,7)) print("Usando funções (DEF) com return, a soma é ", soma(valor1,valor2)) def numeroPar(numero): return(numero % 2 == 0) print("O numero 4 é par? ", numeroPar(4)) print("O numero 5 é par? ", numeroPar(5)) def parOuImpar(numero1): if numeroPar(numero1): return "par" else: return "impar" print("O numero 7 é ", parOuImpar(7)) print("O numero 8 é ", parOuImpar(8))
22472b8911a31661edf487d34bcee15711c747de
MarcusVinix/Cursos
/curso-de-python/classes/classes_conta_banco.py
700
3.703125
4
class ContaBanco: def __init__(self, cliente, numeroConta, saldo=0): self.saldo = saldo self.cliente = cliente self.numeroConta = numeroConta def deposito(self, valor): self.saldo += valor print("Foi depositado R$%d em sua conta" % valor) def saque(self, valor): self.saldo -= valor print("Foi sacado R$%d de sua conta" % valor) def relatorio(self): print("Cliente: %s, conta numero: %s, saldo: %8.2f" % (self.cliente, self.numeroConta, self.saldo)) contaBanco = ContaBanco("Marcus Vinicius", "9999-99", 500) contaBanco.relatorio() contaBanco.deposito(500) contaBanco.relatorio() contaBanco.saque(300) contaBanco.relatorio()
ff7f7dcb405a313dedf08409f2714e36079b889c
MarcusVinix/Cursos
/curso-de-python/exemplos/tipo_de_dados.py
397
3.5625
4
#int inteiro = 8 print(type(inteiro)) #float numero = 9.7 print(type(numero)) #bolean ativo = True print(type(ativo)) #string nome = "Marcus Vinicius" print(type(nome)) #list lista = ["Marcus", "Goku", "Naruto", "Natsu"] print(type(lista)) #dict familia = {} familia[0, 0] = "Marcus" familia[0, 1] = "Goku" familia[1, 0] = "Naruto" familia[1, 1] = "Gustavo" print(type(familia)) print(familia[1, 0])
abe978d9498b3edcb311552d4c797e615dbdbc79
yqstar/MachineLearning
/TangYudi_MachineLearningCourse/MachineLearning/SVM/SVM_Facial_Recognition.py
2,685
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : svm_face_recognition.py # @Author: Shulin Liu # @Date : 2019/3/8 # @Desc : """ As an example of support vector machines in action, let's take a look at the facial recognition problem. We will use the Labeled Faces in the Wild dataset, which consists of several thousand collated photos of various public figures. A fetcher for the dataset is built into Scikit-Learn: """ from sklearn.datasets import fetch_lfw_people from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.pipeline import make_pipeline from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.metrics import classification_report, confusion_matrix import seaborn as sns faces = fetch_lfw_people(min_faces_per_person=60) print(faces.target_names) print(faces.images.shape) # Let's plot a few of these faces to see what we're working with: fig, ax = plt.subplots(3, 5) for i, axi in enumerate(ax.flat): axi.imshow(faces.images[i], cmap='bone') axi.set(xticks=[], yticks=[], xlabel=faces.target_names[faces.target[i]]) plt.show() # 每个图的大小是 [62×47] # 在这里把每一个像素点当成了一个特征,但是这样特征太多了,用PCA降维一下吧! pca = PCA(n_components=150, whiten=True, random_state=0) svc = SVC(kernel='rbf', class_weight='balanced') model = make_pipeline(pca, svc) x_train, x_test, y_train, y_test = train_test_split(faces.data, faces.target, random_state=0) # 使用grid search cross_validation 来选择参数 param = {'svc__C': [1, 5, 10], 'svc__gamma': [0.0001, 0.0005, 0.001]} grid = GridSearchCV(model, param) grid.fit(x_train, y_train) print(grid.best_params_) print(grid.best_score_) model = grid.best_estimator_ y_fit = model.predict(x_test) # 画出结果 fig, ax = plt.subplots(4, 6) for i, axi in enumerate(ax.flat): axi.imshow(x_test[i].reshape(62, 47), cmap='bone') axi.set(xticks=[], yticks=[]) axi.set_ylabel(faces.target_names[y_fit[i]].split()[-1], color='black' if y_fit[i] == y_test[i] else 'red') fig.suptitle('Predicted Names; Incorrect Labels in Red', size=14) plt.show() print(classification_report(y_test, y_fit, target_names=faces.target_names)) """ 精度(precision) = 正确预测的个数(TP)/被预测正确的个数(TP+FP) 召回率(recall)=正确预测的个数(TP)/预测个数(TP+FN) F1 = 2精度召回率/(精度+召回率) """ mat = confusion_matrix(y_test, y_fit) sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False, xticklabels=faces.target_names, yticklabels=faces.target_names) plt.xlabel('true label') plt.ylabel('predicted label') plt.show()
1103177ad273c3f1ac526fd1ad555b6cffe52279
pseandersson/lsystem
/tests/test_lmath.py
6,402
3.5625
4
""" Tests for expressions and calculate """ import unittest from random import choice, uniform from lsystem.lmath import calculate, Expression, Operator class TestExpression(unittest.TestCase): def test_add(self): """Test a simple expression""" expr = Expression('a+1') self.assertEqual(expr(a=1.), 2) def test_subtract(self): """Test a simple expression""" expr = Expression('t-1') self.assertEqual(expr(t=3.), 2) def test_mul(self): """Test a simple linear expression""" expr = Expression('5*a+2') self.assertEqual(expr(a=2.), 12) def test_pow(self): """Test a simple linear expression""" expr = Expression('a^2') self.assertEqual(expr(a=3.), 9) def test_passing_vars(self): expr = Expression('a^2') def fn(in_expr, **kwargs): return in_expr(**kwargs) self.assertEqual(fn(expr, a=3), 9) def test_constant_expression(self): """Test a constant expression e.g 5*3 + 1""" expr = Expression('5*3+1') self.assertTrue(expr.is_constant()) self.assertEqual(expr(), 16) class TestOperations(unittest.TestCase): """Class to test a faster calculator""" def test_operators_only_numbers(self): """Iterate over each operatore and do the math""" N = 10 for i in range(N): # ops = [OpAdd, OpDivide, OpMin, OpMultiply, OpPower, OpSubtract] ref_ops = [float.__add__, float.__truediv__, min, float.__mul__, pow, float.__sub__] a = [uniform(-10, 10) for x in ref_ops] b = [choice((-1, 1)) * uniform(0.00001, 10) for x in ref_ops] ops = [Operator(x, y, op) for x, y, op in zip(a, b, ref_ops)] ops[:] = [ops[i]() for i, x in enumerate(b)] ref_ops[:] = [ref_ops[i](x, y) for i, (x, y) in enumerate(zip(a, b))] self.assertListEqual(ops, ref_ops) def test_operators_with_numbers_and_args(self): """Iterate over each operatore and do the math with custom arguments""" N = 10 for i in range(N): # ops = [OpAdd, OpDivide, OpMin, OpMultiply, OpPower, OpSubtract] ref_ops = [float.__add__, float.__truediv__, min, float.__mul__, pow, float.__sub__] a = [uniform(-10, 10) for x in ref_ops] b = [choice((-1, 1)) * uniform(0.00001, 10) for x in ref_ops] ops = [Operator(x, 'x', op) for x, op in zip(a, ref_ops)] ops[:] = [ops[i](**{'x': x}) for i, x in enumerate(b)] ref_ops[:] = [ref_ops[i](x, y) for i, (x, y) in enumerate(zip(a, b))] self.assertListEqual(ops, ref_ops) def test_operators_with_only_args(self): """Iterate over each operatore and do the math with custom arguments""" N = 10 for i in range(N): # ops = [OpAdd, OpDivide, OpMin, OpMultiply, OpPower, OpSubtract] ref_ops = [float.__add__, float.__truediv__, min, float.__mul__, pow, float.__sub__] a = [uniform(-10, 10) for x in ref_ops] b = [choice((-1, 1)) * uniform(0.00001, 10) for x in ref_ops] ops = [Operator('a','b', op) for x, op in zip(a, ref_ops)] ops[:] = [ops[i](**{'a': x, 'b': y}) for i, (x, y) in enumerate(zip(a, b))] ref_ops[:] = [ref_ops[i](x, y) for i, (x, y) in enumerate(zip(a, b))] self.assertListEqual(ops, ref_ops) def test_operator_multiply(self): """test expressions like 1+2*3""" opr2 = Operator(2., 3., float.__mul__) opr1 = Operator(1., opr2, float.__add__) self.assertEqual(opr1(), 7) def test_operator_multiply_dual(self): """test expressions like 1+2*3+4""" opr2 = Operator(2., 3., float.__mul__) opr1 = Operator(1., opr2, float.__add__) opr3 = Operator(opr1, 4., float.__add__) self.assertEqual(opr3(), 11) def test_operator_multiply_args(self): """test expressions like x+2*3""" opr2 = Operator(2., 3., float.__mul__) opr1 = Operator('x', opr2, float.__add__) args = {'x': 1.} self.assertEqual(opr1(**args), 7) class TestCalculateMethod(unittest.TestCase): """Class which tests the calculate part of lsystem""" def test_e_behaivour(self): """Test expressions like 4e-1""" self.assertAlmostEqual(calculate('4e-1'), 0.4) def test_mul_par_e_div_min_min(self): """Test a complex expression""" self.assertAlmostEqual(calculate('2((3*5e-1)/4-2)-3'), -6.25) def test_par_add(self): """Test add with parentheries""" self.assertEqual(calculate('(5)+3'), 8) def test_par_mul(self): """Test multiplication with parentheries""" self.assertEqual(calculate('(5)*3'), 15) def test_div(self): """Test divsion with parentheries""" self.assertEqual(calculate('(5)/3'), 5 / 3) def test_scope_exp(self): """Test power of""" self.assertEqual(calculate('(4-2)^2'), 4) def test_min_to_pow_of_two(self): self.assertEqual(calculate('-2^2'), -4) def test_subtract(self): """Test of subtraction""" self.assertEqual(calculate('4-3'), 1) def test_subtract_neg_val(self): """Test subtraction if negation twice""" self.assertEqual(calculate('4--3'), 7) def test_neg_val_to_pow_of_two(self): self.assertEqual(calculate('(-2)^2'), 4) def test_neg_val_to_pow_mul_min(self): self.assertEqual(calculate('(-3)^2*2-3'), 15) def test_mul_neg_val_to_pow(self): self.assertEqual(calculate('5*(-2)^2'), 20) def test_val_min_neg_val_to_pow(self): self.assertEqual(calculate('5-(-2)^2'), 1) def test_val_min_val_to_decimal_pos(self): self.assertEqual(calculate('2-4^.5'), 0) def test_dec_add_val_mul_scope_div_scope_add(self): self.assertAlmostEqual(calculate('-4.3+3*(2-5)/(2.3-0.3)+4'), -4.8) def test_val_mininum_scope(self): """v denotes the min operator""" self.assertEqual(calculate('2*(2v(3/2))'), 3) self.assertEqual(calculate('2*((3/2)v2)'), 3) if __name__ == "__main__": unittest.main()
822ea9a3fb40c7e580cb25cb7b04f7418897ef28
fessupboy/python_bootcamp_3
/Tuples/Tuples.py
219
3.765625
4
t = (1,2,3) mylist = [1,2,3] print(type(t)) t = ('one',2) print(t[0]) print(t[-1]) t = ('a','a','b') print(t.count('a')) print(t.index('a')) print(t.index('b')) mylist[0] ='NEW' print(mylist) t[0] = 'NEW' print(t)
7118bf76fbb295f78247342b3b341f25d2d0a5c0
adikadu/DSA
/implementStack(LL).py
1,181
4.21875
4
class Stack: def __init__(self): self.top = None self.bottom = None self.length = 0 def node(self, value): return { "value": value, "next": None } def peek(self): if not self.length: return "Stack is empty!!!" return self.top["value"] def push(self, value): node = self.node(value) node["next"] = self.top self.top = node if not self.length: self.bottom = node self.length+=1 def pop(self): if not self.length: print("Stack is empty!!!") return node = self.top if self.length==1: self.top = None self.bottom = None else: self.top = self.top["next"] self.length -= 1 node["next"] = None return node def isEmpty(self): return not bool(self.length) def traverse(self): if not self.length: print("Stack is empty!!!") return x = self.top for i in range(self.length): print(x["value"]) x = x["next"] stack = Stack() print("Empty:",end=" ") stack.traverse() stack.push(1) stack.push(2) stack.push(3) print("Three values:", end=" ") stack.traverse() print("peek=", end=" ") print(stack.peek()) stack.pop() print("Two values:", end=" ") stack.traverse() print("peek=", end=" ") print(stack.peek())
4aaa2473dfc612231522c02ccd11dd26dbfceb0c
adikadu/DSA
/reverseString.py
437
3.859375
4
import re # def reverseString(a): # i=0 # j=len(a)-1 # a=list(a) # while(True): # if i>=j : return "".join(map(str, a)) # Converts list to string. # k=a[i] # a[i]=a[j] # a[j]=k # i+=1 # j-=1 # print(reverseString(input())) def reverseString(a): if len(re.findall(r"\S+", a)) == 0: #check if string contains only space. return "Type some input bro!!!" return a[::-1] # reverse a string print(reverseString(input()))
2def6eec36986f0266030ced224a42ef3b127396
adikadu/DSA
/factorial.py
197
3.75
4
def Rfact(n): if n == 0 or n==1 : return 1 return n*Rfact(n-1) def Ifact(n): if n==0: return 1 x = 1 for i in range(2, n+1): x *= i return x n=int(input()) print(Rfact(n)) print(Ifact(n))
1c9b8627cbcd812574bb52edbbfbc1bf9af86455
Juand0145/AirBnB_clone
/models/engine/file_storage.py
2,826
3.859375
4
#!/usr/Bin/python3 '''Is a class FileStorage that serializes instances to a JSON file and deserializes JSON file to instances:''' import json class FileStorage: '''Is a class FileStorage that serializes instances to a JSON file and deserializes JSON file to instances:''' __file_path = "file.json" __objects = {} def all(self): '''Instance Method that returns the dictionary __objects ''' return FileStorage.__objects def new(self, obj): '''Is apublic instance that sets in __objects the obj with key <obj class name>.id''' if obj is not None: key = "{}.{}".format(obj.__class__.__name__, obj.id) FileStorage.__objects[key] = obj def save(self): '''Is a public instance that serializes __objects to the JSON file (path: __file_path)''' json_obj_dict = {} for key, value in FileStorage.__objects.items(): json_obj_dict[key] = value.to_dict() with open(FileStorage.__file_path, 'w', encoding='utf-8') as my_file: json.dump(json_obj_dict, my_file) def reload(self): '''Is a instance method deserializes the JSON file to __objects (only if the JSON file (__file_path) exists ; otherwise, do nothing. If the file doesn’t exist, no exception should be raised)''' from models.base_model import BaseModel from models.user import User from models.state import State from models.city import City from models.amenity import Amenity from models.place import Place from models.review import Review ''' ''' try: with open(FileStorage.__file_path, 'r') as my_file: for key, value in json.load(my_file).items(): if key not in FileStorage.__objects: class_create = value['__class__'] if class_create == 'BaseModel': FileStorage.__objects[key] = BaseModel(**value) elif class_create == 'User': FileStorage.__objects[key] = User(**value) elif class_create == 'State': FileStorage.__objects[key] = State(**value) elif class_create == 'City': FileStorage.__objects[key] = City(**value) elif class_create == 'Amenity': FileStorage.__objects[key] = Amenity(**value) elif class_create == 'Place': FileStorage.__objects[key] = Place(**value) elif class_create == 'Review': FileStorage.__objects[key] = Review(**value) except: pass
95a649309ce0c95b56618400bce8eedb1bc7593d
Alex-Dumitru/python
/APPS/web_scraping/scrape_app.py
2,852
3.59375
4
""" scrape a website, gather data, and export it to csv target page: century21.com cached page, for practice: pythonhow.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/ """ import requests from bs4 import BeautifulSoup as BS web_page = requests.get('http://pythonhow.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/') web_page_content = web_page.content soup = BS(web_page_content, 'html.parser') allPropertyRow = soup.find_all("div", {"class": "propertyRow"}) # --> bs4.element.ResultSet # Because this is a list of bs4 elements, we can apply again find or find_all methods to each elem # extract property price from the 1st element # we need to use find, to apply the text property. Otherwise, we need to apply it to each element in the list # returned by find_all propertyPrice1 = allPropertyRow[0].find("h4", {"class": "propPrice"}).text # we have some rogue spaces and \n chars, so let's strip them propertyPrice1 = propertyPrice1.replace("\n","").replace(" ","") # iterate through all items # at this stage, we need to 'inspect' each element in the website, and find where it is stored, then extract it for item in allPropertyRow: price = item.find("h4", {"class": "propPrice"}).text.replace("\n","").replace(" ", "") address = item.find_all("span", {"class": "propAddressCollapse"})[0].text city = item.find_all("span", {"class": "propAddressCollapse"})[1].text # some items don't have the bed number listed, so we need to take into account that it will return None # and NoneType doesn't have a text attribute try: # this attribute returns the text from the <span> tag, and also the text from the <b> tag beds = item.find("span", {"class": "infoBed"}).text # if we want to get only the number of beds, we can apply the find() method again beds = item.find("span", {"class": "infoBed"}).find("b").text except: beds = "" try: sqft = item.find("span", {"class": "infoSqFt"}).find("b").text except: sqft = "" try: baths = item.find("span", {"class": "infoValueFullBath"}).find("b").text except: baths = "" try: half_bath = item.find("span", {"class": "infoValueHalfBath"}).find("b").text except: half_bath = "" for columnGroup in item.find_all("div", {"class": "columnGroup"}): # print(columnGroup) for featureGroup, featureName in zip(columnGroup.find_all("span", {"class": "featureGroup"}), columnGroup.find_all("span", {"class": "featureName"})): # print(featureGroup.text, featureName.text) if "Lot Size" in featureGroup.text: lotSize = featureName.text print(lotSize) print(price, beds, baths, half_bath, sqft) print() # print(soup.prettify()) # print(allPropertyRow) # print(">",propertyPrice1,"<")
c99ca779476eac58b05e117c1825ba4189922f96
Alex-Dumitru/python
/APPS/webmap_app/map1.py
4,458
4.0625
4
'''' ibrary needed folium pip install folium the base layer of the map comes from openstreetmaps ''' import folium import pandas def color_prod(elev): if elev < 1500: return 'green' elif 1500 <= elev < 3000: return 'orange' else: return 'red' map = folium.Map(location=[80,-100]) # create a Map object. Pass lat and long to the location # if you want specific coordinates, copy them from maps.google.com - Select a location, right click, and choose "What's here" map = folium.Map(location=[80,-100], zoom_start=6) # you can play with the initial zoom as well map = folium.Map(location=[80,-100], zoom_start=6, tiles="Mapbox Bright") # you can change the default layer # add a marker to the map map.add_child(folium.Marker(location=[80,-100], popup="Hi I am a marker", icon=folium.Icon(color='green'))) # recommended way is to create a feature group to add a marker to your map fg = folium.FeatureGroup(name="My Map") # the marker is a feature, so instead of adding it directly to the map, you add it to the group fg.add_child(folium.Marker(location=[80,-100], popup="Hi I am a marker", icon=folium.Icon(color='green', prefix='fa'))) #1 # and then you pass the FeatureGroup group as a child to the map map.add_child(fg) # one way to add multiple markers to the mas is to repeat #1 and change the parameters (loc, text, color etc) # second way is to use a for loop: for coordinates in [[81,-100],[81,-101]]: fg.add_child(folium.Marker(location=coordinates, popup="Hi I am a marker", icon=folium.Icon(color='green'))) #1 # 3rd way is from a file data = pandas.read_csv("Volcanoes_USA.txt") # generate a data frame with pandas lat = list(data["LAT"]) # create separate lists for LAT and LON lon = list(data["LON"]) # for lt, ln in zip(lat, lon): # fg.add_child(folium.Marker(location=[lt,ln], popup="Hi I am a marker", icon=folium.Icon(color='green'))) # focus on popup to make info dynamic elev = list(data["ELEV"]) for lt, ln, el in zip(lat, lon, elev): #fg.add_child(folium.Marker(location=[lt,ln], popup=str(el), icon=folium.Icon(color='green'))) # fg.add_child(folium.Marker(location=[lt,ln], popup="Elevation: "+str(el)+" m", icon=folium.Icon(color='green'))) # or we can add even more text # in case there are quotes (') in the popup string, we might get a blank webpage. To change this we need to use another parameter for popup # popup = folium.Popup(str(el), parse_html=True) # fg.add_child(folium.Marker(location=[lt,ln], popup=popup, icon=folium.Icon(color='green'))) # focus on icons # change their color to signify the elevation range (green = 0-2000m, orange = 2000-3000 m, red = +3000 m) # we can create a function to do this for us !!! see the function definition up #fg.add_child(folium.Marker(location=[lt,ln], popup=str(el), icon=folium.Icon(color=color_prod(el)))) # change the marker to a circle fg.add_child(folium.CircleMarker(location=[lt,ln], popup=str(el),radius=6, fill=True, fill_color=color_prod(el), color='grey', fill_opacity=0.7)) # add another layer to the map - a polygon layer (1st is the map, 2nd is the markers (point layer), and we can have also line layers to signal roads or rivers for example) fg.add_child(folium.GeoJson(data=open('world.json', 'r', encoding='utf-8-sig').read())) # add color-based polygon featuers # we will show the population of each country by different color (in ranges) fg.add_child(folium.GeoJson(data=open('world.json', 'r', encoding='utf-8-sig').read(), style_function=lambda x: {'fillColor':'yellow'})) #this will make all polygons filled with yellow fg.add_child(folium.GeoJson(data=open('world.json', 'r', encoding='utf-8-sig').read(), style_function=lambda x: {'fillColor':'green' if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red'})) # x is mapped to features inside the json file by GeoJson, and actually the method will loop through all of them to find the properties-pop2005 values # adding a layer control panel (turn on and off the layers (except the base map)) map.add_child(folium.LayerControl()) #basic control (controls all layers at once because we added just one child to the map - the feature group, but the group contains 2 layers) # solution would be to create feature groups for each layer or group of layers that you want to have separate map.save("Map1.html") # save the map to html
cb0847a0abcf8a256c51c110ce61ea8eb6743f56
Alex-Dumitru/python
/APPS/gui_and_db/kg_conv.py
1,052
4.0625
4
import tkinter as tk # create the window object window = tk.Tk() # define the function def kg_conv(): grams = float(e1_value.get()) * 1000 # convert kg to grams pounds = float(e1_value.get()) * 2.20462 # convert kg to pounds ounces = float(e1_value.get()) * 35.274 # convert kg to ounces # insert the values in respective fields t1.insert(tk.END,grams) t2.insert(tk.END,pounds) t3.insert(tk.END,ounces) # Create the button b1 = tk.Button(window, text='Convert', command=kg_conv) b1.grid(row=0, column=3) # Create the entry text field e1_value = tk.StringVar() e1 = tk.Entry(window, textvariable=e1_value) e1.grid(row=0, column=2) # Create the text widgets to display the results t1 = tk.Text(window, height=1, width=20) t1.grid(row=1,column=1) t2 = tk.Text(window, height=1, width=20) t2.grid(row=1,column=2) t3 = tk.Text(window, height=1, width=20) t3.grid(row=1,column=3) # Create a label to display input data type l1 = tk.Label(window, justify='center', text='KG') l1.grid(row=0, column=0) window.mainloop()
8d576d97f8aa4c97e8552e974bcedab81f504f3b
indigowhale33/COMS-4995
/task3/task3.py
842
3.578125
4
from __future__ import print_function, division import numpy as np def MSD(nparr, ax=0): """ Calculate mean and standard deviation of numpy array by axis Parameters ---------- - **Parameters**:: nparr : array_like Array containing numbers ax : int, optional (default=0) Axis along which means and standard deviations are computed. Returns ------- - **Returns**:: m,std : tuple tuple of mean and standard deviation of the input array in terms of the axis. Raises ------ - **Raises**:: ValueError if the given axis is not None or not 0 or 1. """ if(ax != None): try: val = int(ax) except ValueError: print("axis should be integer") if( ax < 0 or ax > 1): raise ValueError("axis should be between 0 to 1") return np.mean(nparr,axis=ax), np.std(nparr,axis=ax) MSD(np.array([[1,2],[3,4]]))
09fe6ea10b609f2ee63a8f089f44f404b57be93b
mkumar-gt/t1
/t4i.py
464
3.859375
4
Num_of_Numbers = 5 num_list = [] def main(): for i in range(Num_of_Numbers): userInput = int(input("please enter number: ")) num_list.append(userInput) info() def find_lowest(anything): lowestNumber = min(anything) return lowestNumber def totalN(anything): total = 0 for i in anything: total += i return total def info(): print("The lowest number is: ", str(find_lowest(num_list))) print("The total is: ", str(totalN(num_list))) main()
70ce7118d3b24c724eb22a295dc82dae9770e511
Dinesh-Sivanandam/HackerRank-Solutions
/sWAP_cASE.py
459
4.03125
4
def swap_case(S): import string lower = string.ascii_lowercase upper = string.ascii_uppercase T = [] for i in range(len(S)): if S[i] in lower: T.append(S[i].upper()) elif S[i] in upper: T.append(S[i].lower()) else: T.append(S[i]) return (''.join(T)) if __name__ == '__main__': s = input() result = swap_case(s) print (result)
e32e0bfa71eb66314bf38711126c8d5bf6662360
phyllis-jia/note-for-python
/generator.py
341
3.546875
4
##normal def squares(N): res=[] for i in range(N): res.append(i*i) return res for item in squares(9): print(item) ##generator def gensquares(N): for i in range(N): yield i**2 for item in gensquares(9): print(item) ##generator has less code than normal way. Lazy evaluation makes computer run better.
31b8704fbe6fef8de2c1d07e0d963ff053de66d4
chapman-cs510-2017f/cw-05-seongandkynan
/cplane.py
5,555
3.84375
4
#!/usr/bin/env python3 import abscplane """ The module includes a new class ListComplexPlane that subclasses the abstract base class AbsComplexPlane which is imported from the abscplane.py module. """ class ListComplexPlane(abscplane.AbsComplexPlane): """ This class implements the complex plane with given attributes. It uses a list comprehension to represent the 2D grid needed to store the complex plane. The complex plane is a 2D grid of complex numbers, having the form (x + y*1j), where 1j is the unit imaginary number in Python, and one can think of x and y as the coordinates for the horizontal axis and the vertical axis of the plane respectively. All attributes will be set during the __init__ constructor, and initialize the plane immediately upon class instantiation. Methods: __create_plane : a private method that creates or refreshs plane refresh : regenerate plane apply : apply a given function f zoom : transform planes going through all functions lists """ def __init__(self, xmin=-4,xmax=4,xlen=8,ymin=-4,ymax=4,ylen=8): """all attributes will be automatically set when the class becomes instantiated. Attributes: xmax (float) : maximum horizontal axis value xmin (float) : minimum horizontal axis value xlen (int) : number of horizontal points ymax (float) : maximum vertical axis value ymin (float) : minimum vertical axis value xunit (int) : grid unit value of x axis yunit (int) : grid unit value of y axis ylen (int) : number of vertical points plane : a list of stored complex plane fs (list[function]) : function sequence to transform plane """ self.xmin = xmin self.xmax = xmax self.xlen = xlen self.ymin = ymin self.ymax = ymax self.ylen = ylen self.xunit = (self.xmax - self.xmin) / self.xlen self.yunit = (self.ymax - self.ymin) / self.ylen # See the implementation details of creating a complex plane below # in _create_plane function. self.plane = [] self._create_plane() # store a list of functions that are being applied # in order to each point of the complex plane, initially empty self.fs = [] def _create_plane(self): """This ia a private method to create a list of complex plane at the time of class initiation with the default attributes (xmax, xmin, xlen, ymax, ymin,ylen). The method self.refresh also uses this private method to refresh each point in comlext planes using the stored attributes. Returns: a list of complex plane """ self.plane = [[(self.xmin + x*self.xunit) + (self.ymin + y*self.yunit)*1j for x in range(self.xlen+1)] for y in range(self.ylen+1)] def refresh(self): """Regenerate complex plane. Populate self.plane with new points (x + y*1j), using the stored attributes of xmax, xmin, xlen, ymax, ymin, and ylen to set plane dimensions and resolution. Reset the attribute fs to an empty list so that no functions are transforming the fresh plane. """ self._create_plane() self.fs = [] def apply(self, f): """Add the function f as the last element of self.fs. Apply f to every point of the plane, so that the resulting value of self.plane is the final output of the sequence of transformations collected in the list self.fs. """ self.fs.append(f) self.plane = [[f(self.plane[x][y]) for x in range(self.xlen+1)] for y in range(self.ylen+1)] def zoom(self,xmin,xmax,xlen,ymin,ymax,ylen): """Reset self.xmin, self.xmax, and self.xlen. Also reset self.ymin, self.ymax, and self.ylen. Regenerate the plane with the new range of the x- and y-axes, then apply all transformations in fs in the correct order to the new points so that the resulting value of self.plane is the final output of the sequence of transformations collected in the list self.fs. Attributes: xmax (float) : maximum horizontal axis value xmin (float) : minimum horizontal axis value xlen (int) : number of horizontal points ymax (float) : maximum vertical axis value ymin (float) : minimum vertical axis value xunit (int) : grid unit value of x axis yunit (int) : grid unit value of y axis ylen (int) : number of vertical points plane : a list of stored complex plane fs (list[function]) : function sequence to transform plane """ self.xmin = xmin self.xmax = xmax self.xlen = xlen self.ymin = ymin self.ymax = ymax self.ylen = ylen self.xunit = (self.xmax - self.xmin) / self.xlen self.yunit = (self.ymax - self.ymin) / self.ylen self._create_plane() for i, f in enumerate(self.fs): print("running the function "+str(i+1)) self.plane = [[f(self.plane[x][y]) for x in range(self.xlen+1)] for y in range(self.ylen+1)] def main(): cplane = ListComplexPlane() print(cplane.plane) if __name__ == "__main__": main()