blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d5003983716fb6640b9b34eed0f8ad1fee260967
q13245632/CodeWars
/Booleanlogic.py
918
3.59375
4
# -*-coding:utf8-*- # 自己的解法 def func_or(a,b): if a: return True else: if b: return True return False def func_xor(a,b): if a: if not b: return True else: if b: return True return False # Test.describe("Basic tests") # Test.assert_equals(func_or(True, True), True) # Test.assert_equals(func_or(True, False), True) # Test.assert_equals(func_or(False, False), False) # Test.assert_equals(func_or(0, 11), True) # Test.assert_equals(func_or(None, []), False) # Test.assert_equals(func_xor(True, True), False) # Test.assert_equals(func_xor(True, False), True) # Test.assert_equals(func_xor(False, False), False) # Test.assert_equals(func_xor(0, 11), True) # Test.assert_equals(func_xor(None, []), False) # 思路不同 def func_or(a,b): return not (not a and not b) def func_xor(a,b): return (not a) != (not b)
35276bd8d0bde54d510607b3bddc516175edabdd
q13245632/CodeWars
/Characterwithlongestrepetition.py
1,002
3.859375
4
# -*-coding:utf8 -*- # 自己的解法 def longest_repetition(chars): if chars is None or len(chars) == 0: return ("",0) pattern = chars[0] char = "" c_max = 0 count = 1 for s in xrange(1,len(chars)): print chars[s] if chars[s] == pattern: count += 1 else: if c_max < count: c_max = count char = chars[s-1] pattern = chars[s] count = 1 if c_max < count: c_max = count char = chars[len(chars) - 1] return (char,c_max) # 其他解法 def longest_repetition(chars): from itertools import groupby return max(((char, len(list(group))) for char, group in groupby(chars)), key=lambda char_group: char_group[1], default=("", 0)) import re def longest_repetition(chars): if not chars: return ("", 0) longest = max(re.findall(r"((.)\2*)", chars), key=lambda x: len(x[0])) return (longest[1], len(longest[0]))
e8f3a4b8488bc263cf35d953261b0faf8fb4669a
q13245632/CodeWars
/Directions Reduction.py
1,709
3.796875
4
# -*- coding:utf-8 -*- # author: yushan # date: 2017-03-14 def dirReduc(arr): lst = [] for i in arr: if len(lst) <= 0: lst.append(i) continue if i == 'NORTH': if lst[-1:][0] == 'SOUTH': lst.pop() else: lst.append(i) continue if i == 'SOUTH': if lst[-1:][0] == 'NORTH': lst.pop() else: lst.append(i) continue if i == 'EAST': if lst[-1:][0] == 'WEST': lst.pop() else: lst.append(i) continue if i == 'WEST': if lst[-1:][0] == 'EAST': lst.pop() else: lst.append(i) continue return lst opposite = {'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'} def dirReduc(plan): new_plan = [] for d in plan: if new_plan and new_plan[-1] == opposite[d]: new_plan.pop() else: new_plan.append(d) return new_plan def dirReduc(arr): dir = " ".join(arr) dir2 = dir.replace("NORTH SOUTH", '').replace("SOUTH NORTH", '').replace("EAST WEST", '').replace("WEST EAST", '') dir3 = dir2.split() return dirReduc(dir3) if len(dir3) < len(arr) else dir3 # a = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"] # test.assert_equals(dirReduc(a), ['WEST']) # u=["NORTH", "WEST", "SOUTH", "EAST"] # print dirReduc(u) # test.assert_equals(dirReduc(u), ["NORTH", "WEST", "SOUTH", "EAST"])
cec3d32d73c63985e62eb3bd2a7f32a38f074037
q13245632/CodeWars
/First non-repeating letter.py
1,548
3.84375
4
# -*- coding:utf-8 -*- # author: yushan # date: 2017-03-27 from collections import Counter def first_non_repeating_letter(string): string_copy = string.lower() counter = Counter(string_copy) index = len(string) ch = "" for k,v in counter.items(): if v == 1 and string_copy.index(k) < index: index = string_copy.index(k) ch = k return ch if ch in string else ch.upper() def first_non_repeating_letter(string): string_lower = string.lower() for i, letter in enumerate(string_lower): if string_lower.count(letter) == 1: return string[i] return "" # Test.describe('Basic Tests') # Test.it('should handle simple tests') # Test.assert_equals(first_non_repeating_letter('a'), 'a') # Test.assert_equals(first_non_repeating_letter('stress'), 't') # Test.assert_equals(first_non_repeating_letter('moonmen'), 'e') # # Test.it('should handle empty strings') # Test.assert_equals(first_non_repeating_letter(''), '') # # Test.it('should handle all repeating strings') # Test.assert_equals(first_non_repeating_letter('abba'), '') # Test.assert_equals(first_non_repeating_letter('aa'), '') # # Test.it('should handle odd characters') # Test.assert_equals(first_non_repeating_letter('~><#~><'), '#') # Test.assert_equals(first_non_repeating_letter('hello world, eh?'), 'w') # # Test.it('should handle letter cases') # Test.assert_equals(first_non_repeating_letter('sTreSS'), 'T') # Test.assert_equals(first_non_repeating_letter('Go hang a salami, I\'m a lasagna hog!'), ',')
29f08f68b75f30dc980f8529d1ab5ee555787747
q13245632/CodeWars
/Formattothe2nd.py
723
3.90625
4
# -*-coding:utf8-*- # 自己的解法 def print_nums(*args): max_len = 0 if len(args) <= 0: return '' else: for i in args: if max_len < len(str(i)): max_len = len(str(i)) string = '{:0>' + str(max_len) + '}' return "\n".join([string.format(str(i)) for i in args]) # test.describe('Basic Tests') # test.assert_equals(print_nums(), '') # test.assert_equals(print_nums(2), '2') # test.assert_equals(print_nums(1, 12, 34), '01\n12\n34') # test.assert_equals(print_nums(1009, 2), '1009\n0002') # 其他解法 def print_nums(*args): width = max((len(str(num)) for num in args), default=0) return '\n'.join('{:0{}d}'.format(num, width) for num in args)
b9b8c049ca9962375210716f57ecfdd7b9af6472
q13245632/CodeWars
/WhatTheBiggestSearchKeys.py
1,909
3.765625
4
# -*-coding:utf8 -*- # author: yushan # date: 2017-02-26 # 自己的解法 def the_biggest_search_keys(*args): if len(args) == 0: return "''" lst = [] maxlen = 0 for i in args: if len(i) == maxlen: lst.append("'"+i+"'") elif len(i) > maxlen: maxlen = len(i) lst = [] lst.append("'"+i+"'") lst.sort() return ", ".join(lst) def the_biggest_search_keys(*args): by_len = {} fmt = "'{}'".format for a in args: by_len.setdefault(len(a), []).append(a) try: return ', '.join(fmt(b) for b in sorted(by_len[max(by_len)])) except ValueError: return "''" def the_biggest_search_keys(*args): maxLen = max(map(len, args), default=None) return "''" if not args else ", ".join(sorted(filter(lambda s: len(s)-2 == maxLen, map(lambda s: "'{}'".format(s), args)))) def the_biggest_search_keys(*keys): m = max(map(len, keys)) if keys else "''" return str( sorted( filter(lambda x: len(x) == m, keys) ) )[1:-1] if keys else m def the_biggest_search_keys(*keys): return ', '.join(sorted("'" + key + "'" for key in keys if len(key) == max(map(len, keys)))) if len(keys) else "''" print the_biggest_search_keys("key1", "key222222", "key333") print the_biggest_search_keys("coding", "tryruby", "sorting") print the_biggest_search_keys() # Test.describe("Basic tests") # Test.assert_equals(the_biggest_search_keys("key1", "key22", "key333"), "'key333'") # Test.assert_equals(the_biggest_search_keys("coding", "sorting", "tryruby"), "'sorting', 'tryruby'") # Test.assert_equals(the_biggest_search_keys("small keyword", "how to coding?", "very nice kata", "a lot of keys", "I like Ruby!!!"), "'I like Ruby!!!', 'how to coding?', 'very nice kata'") # Test.assert_equals(the_biggest_search_keys("pippi"), "'pippi'") # Test.assert_equals(the_biggest_search_keys(), "''")
c2db75efb101720de872fbd9d22b16b7fa4e0af4
q13245632/CodeWars
/Permutations.py
326
3.984375
4
# -*- coding:utf-8 -*- # author: yushan # date: 2017-03-23 import itertools def permutations(string): lst = itertools.permutations(string) lst = list(set(["".join(i) for i in lst])) return lst import itertools def permutations(string): return list("".join(p) for p in set(itertools.permutations(string)))
b382a3fab0bf42f3309b54065556330e3054b3d7
huajh/python_start
/image_denoising/anisotropic_diff.py
3,178
3.515625
4
import numpy as np import warnings from matplotlib import pyplot as plt def anisodiff(img, niter=1, kappa=50, gamma=0.1, step=(1., 1.), option=1): """ Anisotropic diffusion. Usage: imgout = anisodiff(im, niter, kappa, gamma, option) Arguments: img - input image niter - number of iterations kappa - conduction coefficient 20-100 ? gamma - max value of .25 for stability step - tuple, the distance between adjacent pixels in (y,x) option - 1 Perona Malik diffusion equation No 1 2 Perona Malik diffusion equation No 2 Returns: imgout - diffused image. kappa controls conduction as a function of gradient. If kappa is low small intensity gradients are able to block conduction and hence diffusion across step edges. A large value reduces the influence of intensity gradients on conduction. gamma controls speed of diffusion (you usually want it at a maximum of 0.25) step is used to scale the gradients in case the spacing between adjacent pixels differs in the x and y axes Diffusion equation 1 favours high contrast edges over low contrast ones. Diffusion equation 2 favours wide regions over smaller ones. """ # ...you could always diffuse each color channel independently if you # really want if img.ndim == 3: warnings.warn("Only grayscale images allowed, converting to 2D matrix") img = img.mean(2) # initialize output array img = img.astype('float32') imgout = img.copy() # initialize some internal variables deltaS = np.zeros_like(imgout) deltaE = deltaS.copy() NS = deltaS.copy() EW = deltaS.copy() gS = np.ones_like(imgout) gE = gS.copy() for ii in xrange(niter): # calculate the diffs deltaS[:-1, :] = np.diff(imgout, axis=0) deltaE[:, :-1] = np.diff(imgout, axis=1) # conduction gradients (only need to compute one per dim!) if option == 1: gS = np.exp(-(deltaS/kappa)**2.)/step[0] gE = np.exp(-(deltaE/kappa)**2.)/step[1] elif option == 2: gS = 1./(1.+(deltaS/kappa)**2.)/step[0] gE = 1./(1.+(deltaE/kappa)**2.)/step[1] # update matrices E = gE*deltaE S = gS*deltaS # subtract a copy that has been shifted 'North/West' by one # pixel. don't as questions. just do it. trust me. NS[:] = S EW[:] = E NS[1:, :] -= S[:-1, :] EW[:, 1:] -= E[:, :-1] # update the image imgout += gamma*(NS+EW) return imgout if __name__ == '__main__': fname = 'lenaNoise.jpg' # your code here, you should get this image shape when done: im = plt.imread(fname).astype(float) #imgout = anisodiff(im, niter, kappa, gamma, option) im_new = anisodiff(im, 50) fig, ax = plt.subplots(1, 2, figsize=(10, 7)) ax[0].set_title('Original image') ax[0].imshow(im, plt.cm.gray) ax[1].set_title('Reconstructed Image') ax[1].imshow(im_new, plt.cm.gray) fig.savefig("anisodiff_denoising_1.pdf")
a02d06dd30aef52d2d19d7d3f6c1dbbf20b112fa
ogsf/Python-Exercises
/Python Exercises/src/Ch3_Examples.py
1,243
4.03125
4
''' Created on May 25, 2013 @author: Kevin ''' filler = ("String", "filled", "by", "a tuple") print "A %s %s %s %s" % filler a = ("first", "second", "third") print "The first element of the tuple is %s" % (a[0]) print "The second element of the tuple is %s" % (a[1]) print "The third element of the tuple is %s" % (a[2]) print "Use 'len' to return the number of elements in a tuple" print "So I type 'print %d' %% len(a)' and I see:" print "%d" % len(a) breakfast = ["pot of coffee", "pot of tea", "slice of toast", "egg"] count = 0 a = "a" for count in range(len(breakfast)): if breakfast[count][0] == "e": a = "an" print "Today's breakfast includes %s %s" % (a, breakfast[count]) a = "a" breakfast.append("waffle") print "Today's breakfast also includes %s %s" % (a, breakfast[4]) + "." # print "Breakfast includes a", # for element in breakfast: # print element + ", ", # #print element + ", ".join(map(str,breakfast)) + ".", punctuation = ", " count = 0 #print len(breakfast) print "Breakfast includes a", for item in breakfast: count = count + 1 # print count if count == len(breakfast): punctuation = "." print item + punctuation,
3e93376c30710a336310de2da0d89be71e1f782b
freerangehen/AoC2019
/day4.py
668
3.859375
4
def is_valid(number): number = str(number) prev_digit = None have_double = False for each_digit in number: if prev_digit: if each_digit == prev_digit: have_double = True if each_digit < prev_digit: return False else: prev_digit = each_digit else: prev_digit = each_digit return have_double if __name__ == "__main__": assert(is_valid(111111)) assert(not is_valid(223450)) assert(not is_valid(123789)) count = 0 for n_ in range(272091,815432): if is_valid(n_): count += 1 print(count)
dd60ca87e05fa1755e80fd0a1711a97bb84c0767
Guilherme-Artigas/Python-intermediario
/Aula 15.5 - Exercício 70 - Estatísticas em produtos/ex070_.py
1,132
3.625
4
from time import sleep controle = True total = Produto = menor_preco = 0 print('*-' * 13) print(' * LOJA SUPER BARATEZA * ') print('*-' * 13) print() while controle == True: nome = str(input('Nome do Produto: ')) preco = float(input('Preço: R$ ')) total += preco if preco > 1000: Produto += 1 if menor_preco == 0 or preco < menor_preco: # Produto_B = Produto mais barato! menor_preco = preco Produto_B = nome controle2 = True while controle2 == True: resposta = str(input('Continuar [S/N]: ')).strip().upper()[0] if resposta == 'S': controle = True controle2 = False elif resposta == 'N': controle = False controle2 = False else: print(f'Você digitou uma opção invalida! Aguarde... ') sleep(3) controle2 = True print() print('{:-^40}'.format(' FIM DO PROGRAMA ')) print(f'Total da compra: R$ {total:.2f} ') print(f'Foram {Produto} produtos custando mais de R$ 1.000') print(f'Item mais barato foi {Produto_B} custando R$ {menor_preco:.2f}')
a720bebe341646da8e5d7c76f21a25bb617a5a22
Guilherme-Artigas/Python-intermediario
/Aula 14.1 - Exercício 57 - Validação de Dados/ex057_.py
675
3.859375
4
""" Minha solução... r = 's' while r == 's': sexo = str(input('Sexo [M/F]: ')).strip().upper()[0] if (sexo == 'M'): r = 'n' print('Dado registrado com sucesso, SEXO: M (Masculino)') elif (sexo == 'F'): r = 'n' print('Dado registrado com sucesso, SEXO: F (Feminino)') else: print('Você digitou um valor invalido, por favor tente de novo!') r = 's' """ sexo = str(input('Sexo [M/F]: ')).strip().upper()[0] while sexo not in 'MmFf': print('Dados digitados invalidos, digite novamente!') sexo = str(input('Sexo [M/F]: ')).strip().upper()[0] print('Dados registrados com sucesso. Sexo: {}'.format(sexo))
aef6e912e8e89b1edaeb56492c51ca1a2d52dda7
Guilherme-Artigas/Python-intermediario
/Aula 13.9 - Exercício 54 - Grupo da Maioridade/ex054_.py
237
3.640625
4
q = 0 for c in range(1, 8): anoN = int(input('Digite o ano de nascicmento da {}º pessoa: '.format(c))) idade = 2020 - anoN if (idade < 21): q += 1 print('Quantidade de pessoas menores de idade:{} pessoas'.format(q))
ac9ed5d3670dc1612bd3f0bf6a8e7e28146739c1
Guilherme-Artigas/Python-intermediario
/Aula 12.4 - Exercício 39 - Alistamento Militar/ex039_.py
1,589
4.09375
4
from datetime import date ano_atual = date.today().year sexo = str(input('Digite seu Sexo [Homem / mulher]: ')) if (sexo == 'Homem') or (sexo == 'homem') or (sexo == 'H') or (sexo == 'h'): ano_N = int(input('Digite o ano do seu nascimento: ')) idade = ano_atual - ano_N print() print('Quem nasceu em {} tem {} anos em {}'.format(ano_N, idade, ano_atual)) print() if idade < 18: print('Você ainda não tem a idade suficiente para o alistamento militar obrigatório!') print('Sua idade: {} anos... faltam {} anos para o seu alistamento! que sera em {}'.format(idade, 18 - idade, (18 - idade) + ano_atual)) elif idade > 18: print('Você ja passou da idade do alistamento militar obrigatório!') print('Sua idade: {} anos... ja se passaram {} anos do seu alistamento! que foi em {}'.format(idade, idade - 18, ano_atual - (idade - 18))) else: print('Sua idade: {} anos... você deve se alistar imediatamente!'.format(idade)) else: print('O alistamento militar é obrigatorio para homens! obrigado por responder tenha um bom dia...') # Minha solução ''' ano = int(input('Digite o ano do seu nascimento: ')) ano_a = int(input('Digite o ano atual: ')) idade = ano_a - ano if idade < 18: print('Você ainda não tem idade paras se alistar!') print('Faltam {} anos para você ter a idade necessaria...'.format(18 - idade)) elif idade == 18: print('Você esta na idade de se apresentar para o alistamento!') else: print('Você ja passou {} anos, da fase de alistamento!'.format(idade - 18)) '''
cc7a4308797597975dcf0029e34c707aabdfda38
Guilherme-Artigas/Python-intermediario
/Aula 13.5 - Exercício 50 - Soma dos pares/ex050_.py
173
3.875
4
somaP = 0 for c in range(1, 6): n = int(input('Digite um valor: ')) if (n % 2 == 0): somaP += n print('Soma dos valores pares digitados = {}'.format(somaP))
5d499ce12bdb550033ce907c61bbd5c44debbbb7
gmastorg/CTI110
/M2T1_SalesPrediction_Canjura.py
217
3.6875
4
#CTI 110 #M2T1 - Sales Prediction #Gabriela Canjura #08/30/2017 #calculate profit margin totalSales= int(input('Enter total sales: ')) annualProfit = float(totalSales*.23) print ('Annual sales = ',annualProfit,'.')
2044a3f44b9af55830532e836ddd2505dd5346b3
gmastorg/CTI110
/M6T2_FeetToInchesConverter_Canjura.py
500
4.25
4
#Gabriela Canjura #CTI110 #10/30/2017 #M6T2: feet to inches converter def main(): #calls a funtions that converts feet to inches and prints answer feet = float(0) inches = float(0) feet = float(input("Enter a distance in feet: ")) print('\t') inches = feet_to_inches(feet) print("That is",inches,"inches.") def feet_to_inches(feet): #calculates inches inches = feet * 12 return inches main()
1098b2cb56836f9ef77cb4a563a62b5bc02d432e
hypatiad/codefigthtstests
/checkPalindrome.py
494
4.09375
4
# -*- coding: utf-8 -*- """ Given the string, check if it is a palindrome. For inputString = "ana", the output should be checkPalindrome(inputString) = true; For inputString = "tata", the output should be checkPalindrome(inputString) = false; For inputString = "a", the output should be checkPalindrome(inputString) = true. @author: hypatiad """ def checkPalindrome(inputString): if 1<=len(inputString)<=1E5: revString=inputString[::-1] return(revString==inputString)
7d2b7c33e756b60003d97b54bb495aebb2c8cf31
bitf14m513/schedulingalgo
/Preorityscheduling.py
4,349
4
4
print("------------------------Priority Scheduling Non Preempting-------------------") t_count = int(input("Enter Total Number of Process : -> ")) jobs = [] def take_input(): for process in range(0, t_count): at = 0 bt = 0 job_attr = {"process_name": "None", "AT": 0, "BT": 0, "ST": 0, "FT": 0, "PT": 0} job_attr["process_name"] = process + 1 job_attr["AT"] = int(input("Enter Arrival Time of Process %d : ->" % (process + 1))) job_attr["BT"] = int(input("Enter Burst Time of Process %d : ->" % (process + 1))) job_attr["PT"] = int(input("Enter Priority of Process %d : ->" % (process + 1))) jobs.append(job_attr) # _________________function to sort array _________________________________________________________ def smallest(array_to_sort): smallest = array_to_sort[0] for process in range(0, len(array_to_sort)): if smallest["AT"] > array_to_sort[process]["AT"]: smallest = array_to_sort[process] return smallest def sort_jobs(array_to_sort): sorted_array = [] count = len(array_to_sort) for count in range(count): small = smallest(array_to_sort) sorted_array.append(small) array_to_sort.remove(small) return sorted_array # __________________________________________________________________________________________________ def count_arrived_jobs(current_time, jobs_array): count = 0 for job in jobs_array: if current_time >= job["AT"]: count = count + 1 return count def check_end(jobs_array): flag = False for job in jobs_array: if job["FT"] == 0: flag = True return flag else: flag = False return flag def find_prioritized_job(jobs_array, arrived_job_count): prioritized = "None" if arrived_job_count == 1: if jobs_array[0]["FT"] == 0: prioritized = jobs_array[0] return prioritized for job in range(0, arrived_job_count-1): if job+1 < len(jobs_array): if jobs_array[job+1]["PT"] > jobs_array[job]["PT"]: if jobs_array[job]["FT"] == 0: prioritized = jobs_array[job] else: if jobs_array[job+1]["FT"] == 0: prioritized = jobs_array[job+1] else: if jobs_array[job+1]["FT"] == 0: prioritized = jobs_array[job+1] else: if jobs_array[job]["FT"] == 0: prioritized = jobs_array[job] return prioritized def p_r_scheduling(jobs_array): current_time = 0 while check_end(jobs_array): arrived_job_count = count_arrived_jobs(current_time, jobs_array) running_job = find_prioritized_job(jobs_array, arrived_job_count) running_job["ST"] = current_time current_time += running_job["BT"] running_job["FT"] = current_time if check_end(jobs_array) == False: return jobs_array def display_result(jobs_array): print("\n\n\n-----------------------------------------------------------------------------------------") print("\t\t\t\t=process#=== A T ===== B T ===== S T ====== F T ====== W T ===== ") for job in jobs_array: print("\t\t\t\t==== ", job["process_name"], " ===== ", job["AT"], "=======", job["BT"], "=======", job["ST"], "=======", job["FT"], "========", job["ST"]-job["AT"]) print("-----------------------------------------------------------------------------------------") return 0 def main(): take_input() jobs_sorted = sort_jobs(jobs) copy_jobs_sorted = [] # copying to preserve it for i in range(0, len(jobs)): job_attr = {"process_name": "None", "AT": 0, "BT": 0, "ST": 0, "FT": 0, "PT": 0} job_attr["process_name"] = jobs[i]["process_name"] job_attr["AT"] = jobs[i]["AT"] job_attr["BT"] = jobs[i]["BT"] job_attr["ST"] = jobs[i]["ST"] job_attr["FT"] = jobs[i]["FT"] job_attr["PT"] = jobs[i]["PT"] copy_jobs_sorted.append(job_attr) # copied and preserved as records display_result(p_r_scheduling(jobs_sorted)) main()
7b549d7fad13846b90a4f439379c9dbfa7017207
alimovAN19/1-3-9Test
/1-3-9NameGame.py
1,493
3.890625
4
# -*- coding: utf-8 -*- from __future__ import print_function '''Alter the code to produce a different output if your name is entered. As always, start a log file test your code. When it works, upload the code without changing the file name. Upload the log file to the classroom alonf with your code''' def who_is_this(): name=raw_input('Please enter the name of someone in this class:') if name=='Abbos': print(name,""" favorite phrase is : "First according to the height of a Minion (which is 3.5 feet on average)" "Gru is 4 minions tall, which means he is a godly size of 14 feet tall. Furthermore if any of you remember" "the original Despicable Me," "you know there is a scene when Vector kidnaps the three girls and shoots a series of heat-seeking misses" "at Gru, he then dodges them all. According to the speed of an average ballistic missile (1900 mph) and " "the size of the missile according to his ankle size, " "Gru can perceive and move at such a speed that the missiles only move 9.5 miles per hour, 0.5% of their" "original speed. After this Gru punches a shark and it is paralyzed meaning its spine is probably shattered," "to remind you it would require a force greater than 3,000 newtons to fracture the spine." "That’s equal to the impact created by a 500-pound car crashing into a wall at 30 miles per hour. I rest my case.""") return
ff96730fd2863c392f87d93e3dbd842ad063e88d
jhd/nntest
/sigmoid.py
981
3.609375
4
import itertools import math class Sigmoid(): weights = [] bias = [] weighedInput = None activation = None activationPrime = None error = None def __init__(self, startWeights=None, startBias=None): self.weights = startWeights self.bias = startBias def sig(self, x): return 1 / (1 + math.exp(-1 * x )) def eval(self, inputs): if len(inputs) != len(self.weights): return float("inf") total = self.bias #1 / (1 + math.exp(-x)) Sigmoid function for (weight, input) in itertools.izip(self.weights, inputs): total += weight * input output = self.sig(total) #print self, " ", inputs, " : ", output self.weighedInput = total self.activation = output self.activationPrime = output*(1-output) return output def printS(self): print self, " ", self.weights, self.bias
8fbfdaca1191359762e5b2cb142b19de0ceb7a9a
noobcoderr/python_spider
/alien_invasion/bullet.py
1,057
3.984375
4
import pygame from pygame.sprite import Sprite class Bullet(Sprite): """a class that manage how a ship fire""" def __init__(self,ai_settings,screen,ship): """create a bullet where ship at""" super(Bullet,self).__init__() self.screen = screen #creat a bullet rectangle at (0,0) then set right location self.rect = pygame.Rect(0,0,ai_settings.bullet_width,ai_settings.bullet_height) self.rect.centerx = ship.rect.centerx self.rect.top = ship.rect.top #store location of bullet that expression with float self.y = float(self.rect.y) self.color = ai_settings.bullet_color self.speed_factor = ai_settings.bullet_speed_factor def update(self): """move up the bullet""" #update the value of the bullet location self.y -= self.speed_factor #update the vale of bullet rect self.rect.y = self.y def draw_bullet(self): """draw bullet on the screen""" pygame.draw.rect(self.screen,self.color,self.rect)
5b7ddd980eef5d63cc7cda3da0a9504a4a969a76
MateusdeOliveira15/IFCE-PYTHON
/Lista/q9.py
421
3.96875
4
#Faça um programa que receba do usuário uma string e imprima a string sem suas vogais. string = input('Digite uma string: ') lista = list(string) string_nova = [] for i in range(len(lista)): if lista[i] != 'a' and lista[i] != 'e' and lista[i] != 'i' and lista[i] != 'o' and lista[i] != 'u': string_nova.append(lista[i]) string_nova = ''.join(string_nova) print('String sem as vogais: {}'.format(string_nova))
034d4f75912f5e1a3e85ea3d83c28938d5fdaa2d
MateusdeOliveira15/IFCE-PYTHON
/Lista/q10.py
451
4
4
#Faça um programa em que troque todas as ocorrências de uma letra L1 pela letra L2 em #uma string. A string e as letras L1 e L2 devem ser fornecidas pelo usuário. string = input('Digite uma string: ') letra1 = input('Digite uma letra: ') letra2 = input('Digite outra letra: ') string = list(string) for i in range(len(string)): if letra1 in string: cod = string.index(letra1) string[cod] = letra2 string = ''.join(string) print(string)
98cf462c49a5227c9af6638e2589de8202bd961a
ajorve/pdxcodeguild
/objects/valet/valet.py
857
3.875
4
""" Create a car for color, plate # and doors. Create a parking lot that will only fit to its capacity the cars created. """ class Vehicle: def __init__(self, color, plate, doors): self.color = color self.plate = plate self.doors = doors def __str__(self): return "{0.color} , #{0.plate}, {0.doors} ".format(self) @staticmethod def honk(): return "HONK!" class ParkingLot: def __init__(self, capacity, rate): self._capacity = capacity self.hourly_rate = rate self.available_spaces = capacity self.spaces = list() def park(self, vehicle): if len(self.spaces) <= self._capacity: self.spaces.append(vehicle) self.available_spaces -= 1 else: return "Lot is Full"
28192ec1a2ff45eab9f27fe8b1227a910adaba93
ajorve/pdxcodeguild
/warm-ups/string_masking.py
1,364
3.953125
4
""" # String Masking Write a function, than given an input string, 'mask' all of the characters with a '#' except for the last four characters. ``` In: '1234' => Out: '1234' In: '123456789' => Out: '#####6789' """ # def string_masking(nums_list): # """ # >>> string_masking([1, 2, 3, 4, 5, 6, 7, 8, 9]) # '#####6789' # """ # nums_list = list(nums_list) # # if len(nums_list) <= 4: # return nums_list # # else: # masked_list = list() # for num in nums_list[-4:]: # masked_list.append(str(num)) # # for _ in nums_list[:-5]: # masked_list.append('#') # # result = "".join(masked_list[::-1]) # # return result # # nums_masked = [str(num) if num in nums_list[-4:] else '#' for num in nums_list] # # return nums_masked # def string_masking(nums_list): """ >>> string_masking([1, 2, 3, 4, 5, 6, 7, 8, 9]) '#####6789' """ nums_list.reverse() # Reversing result = list() for index, number in enumerate(nums_list): if index not in (0, 1, 2, 3): result.append('#') else: result.append(str(number)) # Putinem back result.reverse() final_result = "".join(result) return final_result
f81cd655babcadec3b45696091a852a56b8ccd92
ajorve/pdxcodeguild
/warm-ups/wall-painting.py
564
4
4
""" This is a Multiline Comment. THis is the first thing in the file. AKA 'Module' Docstring. """ def wall_painting(): wall_width = int(input("What is the width of the wall?")) wall_height = int(input("What is the height of the wall?")) gallon_cost = int(input("What is the cost of the gallon")) gallon_covers= 400 sq_footage = wall_width * wall_height gallon_total = sq_footage // gallon_covers cost = gallon_total * gallon_cost print("If will cost you ${} to paint this wall..".format(cost)) wall_painting()
dfd38f505944aeb4fee6fa57bda110fa84952084
ajorve/pdxcodeguild
/json-reader/main.py
1,131
4.5
4
""" Objective Write a simple program that reads in a file containing some JSON and prints out some of the data. 1. Create a new directory called json-reader 2. In your new directory, create a new file called main.py The output to the screen when the program is run should be the following: The Latitude/Longitude of Portland is 45.523452/-122.676207. '/Users/Anders/Desktop/PDX_Code/practice/json-reader/json_text.txt', {'Portand' : {'Latitude' : '45.523452/-122.676207', 'Longitude' : '-122.676207 '}} """ import json def save(filename, data): """ Take a dict as input, serializes it, then the serialized version of the dict saves to the specified filename. """ data = input('Enter in the information you would like to write to this file.') with open(filename, 'w') as file: serialized = json.dumps(data) file.write(serialized) save(filename, data) def load(filename): """ Takes a filename """ with open(filename, 'r') as file: raw_data = file.read() data = json.loads(raw_data) return data load(filename)
dbfe81b01a012a936086b78b5344682238e88ea5
ajorve/pdxcodeguild
/puzzles/fizzbuzz.py
1,145
4.375
4
""" Here are the rules for the FizzBuzz problem: Given the length of the output of numbers from 1 - n: If a number is divisible by 3, append "Fizz" to a list. If a number is divisible by 5, append "Buzz" to that same list. If a number is divisible by both 3 and 5, append "FizzBuzz" to the list. If a number meets none of theese rules, just append the string of the number. >>> fizz_buzz(15) ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz'] REMEMBER: Use Encapsulation! D.R.Y. >>> joined_buzz(15) '1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz' """ def fizz_buzz(stop_num): number_list = list() for each_number in range(1, stop_num + 1): if each_number % 3 == 0 and each_number % 5 == 0: #if each_number % 15 == 0: number_list.append("FizzBuzz") elif each_number % 3 == 0: number_list.append("Fizz") elif each_number % 5 == 0: number_list.append("Buzz") else: number_list.append(each_number) return number_list def joined_buzz(number): return " ".join(fizz_buzz(number))
cbb5dfcd92d734e476075cc01b063ce611826b92
ajorve/pdxcodeguild
/warm-ups/sum_times.py
1,245
3.890625
4
""" Weekly warmup Given a list of 3 int values, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. If 13 is the first number, return 0. In: 1, 2, 3 => Out: 6 In: 5, 13, 6 => Out: 5 In: 1, 13, 9 => Out: 1 """ import time def sum_times(user_nums): """ >>> sum_times([1, 3, 5]) 9 >>> sum_times([13, 8, 9]) 0 """ nums = list() for num in user_nums: if num == 13: break else: nums.append(num) return sum(nums) def collect_nums(): """ Collects user input, build a list of ints, and calls the sum_times function """ nums = list() while True: answer = input("Please enter some numbers to find their SUM or type done: ") if answer in ('q', 'quit', 'exit', 'done'): sum_times(nums) else: try: num = int(answer) nums.append(num) except ValueError: print("Invalid, please enter a number instead...") time.sleep(2) raise TypeError("Invalid, please enter a number instead.")
5733f941bb23cec0470a41d4bb6ab1f78d86bd73
ajorve/pdxcodeguild
/warm-ups/pop_sim.py
2,021
4.375
4
""" Population Sim In a small town the population is 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to 1200 inhabitants? Write a function to determine the the answer given input of the starting population, the number of additional inhabitants coming each year, the anual percent of increase, and the target population. solve(start_pop, additional, delta, target) In: solve(1000, 50, 2, 1200) Out: 3 Years. """ def pop_sim(start_pop, growth, births, target): """ Write a function to determine the the answer given input of the starting population, the number of additional inhabitants coming each year, the annual percent of increase, and the target population. >>> pop_sim(1000, 50, 2, 1200) It took approximately 3 years to get to 1200 people :param start_pop: int :param growth: int :param births: int :param target: int :return: str """ population = start_pop new_inhabs = births pop_change = growth target_pop = target years_past = 0 while population < target_pop: result = ((population * (pop_change * .01)) + new_inhabs) population += result years_past += 1 message = f"It took approximately {years_past} years to get to {target_pop} people" print(message) return message def pop_collection(): print("Welcome to the Global Population Simulator!") start_pop = int(input("What is the current population?: ")) growth = int(input("What is the average annual growth rate % (use whole number) ?: ")) births = int(input("How many annual births?: ")) target = int(input("What is the desired target population?: ")) data = (start_pop, growth, births, target) pop_sim(*data) if __name__ == "__main__": pop_collection()
df1f704b954ec8d3d0680b2776a7afaf3ba4357f
redashu/augmenu2018
/day2.py
351
4
4
import time print "Hello world " x=10 y=20 time.sleep(2) print x+y # taking input from user in python 2 n1=raw_input("type any number1 : ") n2=raw_input("type any number2 : ") z=int(n1)+int(n2) time.sleep(2) print "sum of given two numbers is : ",z ''' take 5 input from user and make a tuple with only uniq elements '''
a8ae1110868b0bd4845ac1ee59fc4b3c27ccbc1e
Lite-Java/KNN
/KNN.py
789
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 22 21:46:15 2018 @author: 刘欢 """ import numpy as np class NearestNeighbor: def _init_(self): pass def train(self,X,y): """X is N X D where each row is an example.y is 1-dimension of size N""" self.Xtr=X self.ytr=y def predict(self,X): num_test=X.shape[0]#obtain the 0 dimension length of the X Ypred=np.zeros(num_test,dtype=self.ytr.dtype) for i in xrange(num_test): #using the L1 distance distances=np.sum(np.abs(self.Xtr-X[i,:],axis=1)) min_index=np.argmin(distances) #predict the label of the nearest example Ypred[i]=self.ytr[min_index] return Ypred
d13b5bdd1b380482a8ee433c8b513a830a01bb4d
tangmingsheng/Python_Learn
/20190611_语言元素.py
435
3.859375
4
# f=float(input("请输入华氏温度")) # c=(f-32)/1.8 # print("%.1f华氏温度 = %.1f摄氏度"% (f,c)) # import math # radius = float(input("请输入圆周半径:")) # perimeter = 2 * math.pi * radius # area = math.pi * radius * radius # print("周长:%.2f" % perimeter) # print("面积:%.2f" % area) year = int(input("请输入年份:")) is_leap = (year % 4 == 0 and year % 100 !=0 or year % 400 == 0) print(is_leap)
fd2a8b080bd4435fc8229279b5bbce26f782c677
lahwaacz/Scripts
/pythonscripts/misc.py
2,184
3.71875
4
#! /usr/bin/env python """ Human-readable file size. Algorithm does not use a for-loop. It has constant complexity, O(1), and is in theory more efficient than algorithms using a for-loop. Original source code from: http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size """ from math import log unit_list = { "long": list(zip(['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'], [0, 0, 1, 2, 2, 2])), "short": list(zip(['B', 'K', 'M', 'G', 'T', 'P'], [0, 0, 1, 2, 2, 2])), } def format_sizeof(num, unit_format="long"): if num > 1: exponent = min(int(log(num, 1024)), len(unit_list[unit_format]) - 1) quotient = float(num) / 1024**exponent unit, num_decimals = unit_list[unit_format][exponent] format_string = '{:.%sf} {}' % (num_decimals) return format_string.format(quotient, unit) else: return str(int(num)) + " B" """ Nice time format, useful for ETA etc. Output is never longer than 6 characters. """ def format_time(seconds): w, s = divmod(seconds, 3600*24*7) d, s = divmod(s, 3600*24) h, s = divmod(s, 3600) m, s = divmod(s, 60) if w > 0: return "%dw" % w if d > 0: return "%dd%02dh" % (d, h) if h > 0: return "%02dh%02dm" % (h, m) if m > 0: return "%02dm%02ds" % (m, s) return str(s) """ Get content of any readable text file. """ def cat(fname): try: f = open(fname, "r") s = f.read() f.close() return s.strip() except: return None """ Returns a string of at most `max_length` characters, cutting only at word-boundaries. If the string was truncated, `suffix` will be appended. """ import re def smart_truncate(text, max_length=100, suffix='...'): if len(text) > max_length: pattern = r'^(.{0,%d}\S)\s.*' % (max_length-len(suffix)-1) return re.sub(pattern, r'\1' + suffix, text) else: return text """ Recursive directory creation function (like 'mkdir -p' in linux). """ import os def mkdir(path): try: os.makedirs(path) except OSError as e: if e.errno != 17: raise e
1058223566e7c3af49e5df00ff6d6754b4d9088c
onwayWalk/aaa
/day02/xiaoyouxi.py
294
3.796875
4
import random print("请输入一个数") a=int(input()) b=random.randint(0,10) while a!=b: if a>b: print("猜大了噢,再猜一次吧") a=int(input()) else: print ("猜小了哦,再猜一次吧") a=int(input()) print ("太棒了,猜对了!")
5ec0e7fec324bb65eeb8484c83c50180db82d595
onwayWalk/aaa
/day02/test06.py
473
3.796875
4
# 实现登陆系统的三次密码输入错误锁定功能(用户名:root,密码:admin) print("qing shu ru zhang hao mi ma") a,b=input().split() i=1 username="root" password="admin" while 1: if username==a and password==b: print("deng lu cheng gong ") break elif i==3: print("yong hu suo ding !") break else: print("deng lu shi bai : qing chong xin shu ru :") a, b = input().split() i += 1
b5f8bc0b3e61470c6bc6d779e470244f5a52a508
onwayWalk/aaa
/day10_thread/test03.py
1,459
3.6875
4
from threading import Thread import time box=500 boxN=0 cus=6 class cook(Thread): name='' def run(self) -> None: while True: global box,boxN,cus if boxN<box: boxN+=1 print("%s做了一个蛋挞!,现在有%s个"%(self.name,boxN)) else: if cus>0: time.sleep(0.01) print("%s休息了三分钟"%self.name) else: break class customer(Thread): name='' money=2000 def run(self) -> None: while True: global box,boxN,cus if boxN>0 : if self.money>0: self.money-=2 boxN-=1 print("%s买了一个蛋挞!,还剩%s¥"%(self.name,self.money)) else: cus-=1 print("%s没钱了要走了"%self.name) break else: time.sleep(0.01) print("%s休息了两分钟,还想吃!"%self.name) c1=cook() c2=cook() c3=cook() c1.name="张三" c2.name="李四" c3.name="wa" cu1=customer() cu2=customer() cu3=customer() cu4=customer() cu5=customer() cu6=customer() cu1.name="1号" cu2.name="2号" cu3.name="3号" cu4.name="4号" cu5.name="5号" cu6.name="6号" c1.start() c2.start() c3.start() cu1.start() cu2.start() cu3.start() cu4.start() cu5.start() cu6.start()
4d6ce6a41f6ba8d94f67fc4e63a0d2b09cfd6eb7
AyngaranKrishnamurthy/Python-Simple-Programs
/Single swap.py
668
4.0625
4
def swapstr(str1, str2): len1 = len(str1) len2 = len(str2) if (len1 != len2): #Checks for if both the strings are of same length return False prev = -1 curr = -1 count = 0 i = 0 while i<len1: #Compares string for resemblence of elements if (str1[i] != str2[i]): #Counts number of swaps needed count = count + 1 if (count > 2): return False prev = curr curr = i i = i+1 return(count==2 and str1[prev] == str2[curr] and str1[curr] == str2[prev]) str1 = input("Enter string 1: ") str2 = input("Enter string 2: ") if (swapstr(str1,str2)): print ('True') else: print ('False')
8b4fcea87d0a7ac318a2f9c0b0ae019175d7e291
juan6630/MTIC-Practice
/Python/clase11.py
1,273
4.15625
4
def dos_numeros(): num1 = float(input('Ingrese el primer número')) num2 = float(input('Ingrese el segundo número')) if num1 == num2: print(num1 * num2) elif num1 > num2: print(num1 - num2) else: print(num1 + num2) def tres_numeros(): num1 = float(input('Ingrese el primer número')) num2 = float(input('Ingrese el segundo número')) num3 = float(input('Ingrese el tercer número')) if num1 > num2 and num1 > num3: print(num1) elif num2 > num3: print(num2) else: print(num3) def utilidad(): antiguedad = float(input('Ingrese su antigüedad en años')) if antiguedad < 1: print('Utilidad del 5%') elif 1 <= antiguedad < 2: print('Utilidad 7%') elif 2 <= antiguedad < 5: print('Utilidad 10%') elif 5 <= antiguedad < 10: print('Utilidad 15%') else: print('Utilidad 20%') def horas_extra(): horas = float(input('Ingrese el número de horas trabajadas')) if horas > 40: extras = horas - 40 if extras <= 8: print('Se pagan ' + str(extras * 2) + ' horas extra') elif extras > 8: print('Se pagan' + str(8 * 2 + (extras - 8) * 3) + 'horas extra') horas_extra()
b46ee7847c7fc4045af1a79fd52efc0616f8a616
YoungWoongJoo/Learning-Python
/list/list1.py
666
3.875
4
""" 리스트 rainbow의 첫번째 값을 이용해서 무지개의 첫번째 색을 출력하는 코드입니다. 3번째줄이 first_color에 무지개의 첫번째 값을 저장하도록 수정해 보세요. rainbow=['빨강','주황','노랑','초록','파랑','남색','보라'] #rainbow를 이용해서 first_color에 값을 저장하세요 first_color = print('무지개의 첫번째 색은 {}이다'.format(first_color) ) """ rainbow=['빨강','주황','노랑','초록','파랑','남색','보라'] #rainbow를 이용해서 first_color에 값을 저장하세요 first_color = rainbow[0] print('무지개의 첫번째 색은 {}이다'.format(first_color) )
24442d594ecf27a0df3058aff922011d6953e8dc
YoungWoongJoo/Learning-Python
/bool/bool2.py
733
4.46875
4
""" or연산의 결과는 앞의 값이 True이면 앞의 값을, 앞의 값이 False이면 뒤의 값을 따릅니다. 다음 코드를 실행해서 각각 a와 b에 어떤 값이 들어가는지 확인해 보세요. a = 1 or 10 # 1의 bool 값은 True입니다. b = 0 or 10 # 0의 bool 값은 False입니다. print("a:{}, b:{}".format(a, b)) """ a = 1 or 10 # 1의 bool 값은 True입니다. b = 0 or 10 # 0의 bool 값은 False입니다. print("a:{}, b:{}".format(a, b)) #a=1, b=10 #or 앞이 true이면 앞, false이면 뒤 a = 1 or 10 # 1의 bool 값은 True입니다. b = 0 or 10 # 0의 bool 값은 False입니다. print("a:{}, b:{}".format(a, b)) #a=1, b=10 #or 앞이 true이면 앞, false이면 뒤
55757b84c56e85cee15ca08b313294a7919b8564
YoungWoongJoo/Learning-Python
/random/random1.py
474
4
4
""" https://docs.python.org/3.5/library/random.html#random.choice 에서 random.choice의 활용법을 확인하고, 3번째 줄에 코드를 추가해서 random_element가 list의 element중 하나를 가지도록 만들어 보세요. import random list = ["빨","주","노","초","파","남","보"] random_element = print(random_element) """ import random list = ["빨","주","노","초","파","남","보"] random_element = random.choice(list) print(random_element)
f7b72f1287d5a2b3c61390235c41b2fd81681a5b
YoungWoongJoo/Learning-Python
/function/function2.py
705
4.3125
4
""" 함수 add는 매개변수로 a와 b를 받고 있습니다. 코드의 3번째 줄을 수정해서 result에 a와 b를 더한 값을 저장하고 출력되도록 만들어 보세요. def add(a,b): #함수 add에서 a와 b를 입력받아서 두 값을 더한 값을 result에 저장하고 출력하도록 만들어 보세요. result = print( "{} + {} = {}".format(a,b,result) )#print문은 수정하지 마세요. add(10,5) """ def add(a,b): #함수 add에서 a와 b를 입력받아서 두 값을 더한 값을 result에 저장하고 출력하도록 만들어 보세요. result = a+b print( "{} + {} = {}".format(a,b,result) )#print문은 수정하지 마세요. add(10,5)
cc2af962b0a91dfe357a9cee79571bff2e7449a6
YoungWoongJoo/Learning-Python
/bool/bool1.py
716
3.984375
4
""" 다음 코드를 실행해서 어느 경우 if문 안의 코드가 실행되는지 확인해 보세요. if []: print("[]은 True입니다.") if [1, 2, 3]: print("[1,2,3]은/는 True입니다.") if {}: print("{}은 True입니다.") if {'abc': 1}: print("{'abc':1}은 True입니다.") if 0: print("0은/는 True입니다.") if 1: print("1은 True입니다.") """ if []: #false print("[]은 True입니다.") if [1, 2, 3]: #true print("[1,2,3]은/는 True입니다.") if {}: #false print("{}은 True입니다.") if {'abc': 1}: #true print("{'abc':1}은 True입니다.") if 0: #false print("0은/는 True입니다.") if 1: #true print("1은 True입니다.")
b4f5e679116a4a68c30846b2128890f0bc53d8f5
leeonlee/misc
/euler/5.py
152
3.953125
4
def isDivisible(number): for i in range(20,1,-1): if number % i != 0: return False return True i = 2 while not isDivisible(i): i += 2 print i
b5a4db5c966000f3b3126d5a75e4e33eba5793b8
leeonlee/misc
/euler/4.py
299
3.765625
4
def palindrome(number): return str(number)[::-1] == str(number) def largest(): i = 999 * 999 j = 999 while i >= 100000: if palindrome(i): while j >= 100: if i % j == 0 and len(str(j)) == 3 and len(str(int(i/j))) == 3: print i return j -= 1 j = 999 i -= 1 largest()
7dfacf5c92af0747086f799b21abe106acd9b185
0x464e/comp-cs-100
/8/pistekirjanpito_a.py
988
3.765625
4
""" COMP.CS.100 pistekirjanpito_a. Tekijä: Otto Opiskelijanumero: """ def main(): counted_scores = {} try: file = open(input("Enter the name of the score file: "), "r") except OSError: print("There was an error in reading the file.") return scores = [] for line in file: parts = line.split() if len(parts) != 2: print("There was an erroneous line in the file:\n" + line) return scores.append(parts) for score in scores: try: if score[0] in counted_scores: counted_scores[score[0]] += int(score[1]) else: counted_scores[score[0]] = int(score[1]) except ValueError: print("There was an erroneous score in the file:\n" + score[1]) return print("Contestant score:") print("\n".join([f"{x} {y}" for x, y in sorted(counted_scores.items())])) if __name__ == "__main__": main()
2036aac98dd7e9ff312100e3625ce12d35b44bb6
0x464e/comp-cs-100
/3/tulitikkupeli.py
1,129
3.59375
4
""" COMP.CS.100 tulitikkupeli. Tekijä: Otto Opiskelijanumero: """ def main(): total_sticks = 21 player = 0 # oli vissii ok olettaa et sielt # tulee inputtina aina intti sticks = int(input("Game of sticks\n" "Player 1 enter how many sticks to remove: ")) while True: if sticks not in range(1, 4): sticks = int(input("Must remove between 1-3 sticks!\n" f"Player {player+1} enter how many " "sticks to remove: ")) else: total_sticks -= sticks if total_sticks <= 0: print(f"Player {player+1} lost the game!") break # togglaan xorilla player ^= 1 # ei vissii pitäny välittää siit et monikko "are ... sticks" ei # toimi jos on vaa 1 tikku jäljel sticks = int(input(f"There are {total_sticks} sticks left\n" f"Player {player+1} enter how many " "sticks to remove: ")) if __name__ == "__main__": main()
281d096877dfa31bad260fab583c547d4c70ca68
0x464e/comp-cs-100
/3/yogi_bear.py
702
3.90625
4
""" COMP.CS.100 Old MacDonald Had a Farm -laulu. Tekijä: Otto Opiskelijanumero: """ # en usko et tätä joku manuaalisesti kattoo, mut # jos kattoo, nii meni moti variablejen nimeämisen # kaa, ne nyt on mitä sattuu :'_D def repeat_name(name, count): for _ in range(1, count+1): print(f"{name}, {name} Bear") def verse(words, name): print(words) print(f"{name}, {name}") print(words) repeat_name(name, 3) print(words) repeat_name(name, 1) print() def main(): verse("I know someone you don't know", "Yogi") verse("Yogi has a best friend too", "Boo Boo") verse("Yogi has a sweet girlfriend", "Cindy") if __name__ == "__main__": main()
1e07d223937d4701534d7e5d0ead745167344c62
0x464e/comp-cs-100
/6/tekstintasaus.py
3,798
3.875
4
""" COMP.CS.100 tekstintasaus. Tekijä: Otto Opiskelijanumero: """ def main(): print("Enter text rows. Quit by entering an empty row.") inp = read_message() # "moro mitä kuuluu :D:D :'_D :-D" max_length = int(input("Enter the number of characters per line: ")) # 12 # "list comprehension" # luo listan kaikist sanoist poistaen tyhjät. # tyhjii tulee string.split(" ") kans jos on monta # välilöyntii peräkkäi words = [x for x in inp.split(" ") if x] words = [] for word in inp.split(" "): if word: # jos epätyhjä words.append(word) # words = ["moro", "mitä", "kuuluu" ":D:D" ":'_D", ":-D"] rows = [] current_row = [] current_row_len = 0 # ensi tehää alalistoi, "rivei" sillee et # nii monta sanaa per rivi ku mahtuu siihe # maksimi pituutee for word in words: # jos atm rivii mahtuu viel lisää yhen sanan if current_row_len + len(word) <= max_length: current_row.append(word) current_row_len += len(word) + 1 else: # jos atm rivi tyhjä (voi vaa tapahtuu ekan rivin ekal sanal jos # se sana on liia pitkä), nii ei lisää sitä tyhjää rivii tonne if current_row: rows.append(current_row) current_row = [word] current_row_len = len(word) + 1 # sit viel lopuks se keskenjääny rivi perään mukaan rows.append(current_row) # rows = [['moro', 'mitä'], ['kuuluu', ':D:D'], [":'_D", ':-D']] # tallennan tän ettei tarvii turhaan laskee tota joka loopin kierros last_row_index = len(rows) - 1 # enumeraten kaa saa molemmat sekä loopin indexin ja ite elementin for i, row in enumerate(rows): # jos ollaa vikas rivis nii printtaa sen vaa ja lähtee loopist vittuu # vikaan rivii ei pitäny pistää extra välilyöntei if i == last_row_index: print(" ".join(row)) break # tallennan taas tän pituuden koska sitä tullaa käyttää kaks kertaa row_len = len(row) if row_len == 1: print(*row) # jos rivis on vaa yks sana nii sit vaa printtaa continue # sen ja rupee työstää seuraavaa rivii # kui paljo välilyöntei pitää täyttää siihe rivii et täynnä to_fill = max_length - len("".join(row)) - row_len + 1 # poistan vikan sanan siit listast, koska vikan sanan perää # ei mitää välilöyntei lisätä last_word = row.pop() # taas tallennan sen pituuden ettei tarvii turhaa laskee # sitä joka loopin kierroksel row_len = len(row) for j in range(to_fill): # täs on ehkä vähän taikaa, mut siis kätevästi ku ottaa indexist # modulon elementtien määräl, nii se vastaus menee hienosti läpi # jokasen arrayn elementin ja sen jälkee alottaa taas alust jos # looppaamist riittää niinki pitkäl # ja sit täs vaa lisää aina yhe välilöynni kerral sen elementi perää row[j % row_len] += " " # sit onki valmis printtaamaa ekan rivin ja muistan lisätä sen # aijjemin poistetun vikan sanan siihe perään # ja sit seuraavan rivin kimppuu vaa print(" ".join(row), last_word) def read_message(): """ vastaanottaa syötettä kunnes tyhjä rivi :return: string, syöte """ ret = "" inp = input() # ei kine jos käyttäjä pistää rivin vaihtoi # kaikki teksti vaa pötköön ja välilöynti väliin while inp != "": ret += " " + inp inp = input() # poistetaa se extra välilöynti tost alust return ret[1:] if __name__ == "__main__": main()
80318b9873859647862039df26e805d293d16d18
0x464e/comp-cs-100
/11/murtolukulista.py
4,737
3.96875
4
""" COMP.CS.100 murtolukulista. Tekijä: Otto Opiskelijanumero: """ class Fraction: """ This class represents one single fraction that consists of numerator (osoittaja) and denominator (nimittäjä). """ def __init__(self, numerator, denominator): """ Constructor. Checks that the numerator and denominator are of correct type and initializes them. :param numerator: int, fraction's numerator :param denominator: int, fraction's denominator """ # isinstance is a standard function which can be used to check if # a value is an object of a certain class. Remember, in Python # all the data types are implemented as classes. # ``isinstance(a, b´´) means more or less the same as ``type(a) is b´´ # So, the following test checks that both parameters are ints as # they should be in a valid fraction. if not isinstance(numerator, int) or not isinstance(denominator, int): raise TypeError # Denominator can't be zero, not in mathematics, and not here either. elif denominator == 0: raise ValueError self.__numerator = numerator self.__denominator = denominator def __lt__(self, other): return self.__numerator/self.__denominator < \ other.__numerator / other.__denominator def __gt__(self, other): return self.__numerator/self.__denominator > \ other.__numerator / other.__denominator def __str__(self): return self.return_string() def simplify(self): """ fake docstrging :return: """ gcd = greatest_common_divisor(self.__numerator, self.__denominator) self.__numerator //= gcd self.__denominator //= gcd def complement(self): """ fake docstring :return: """ return Fraction(-1*self.__numerator, self.__denominator) def reciprocal(self): """ fake docstring :return: """ return Fraction(self.__denominator, self.__numerator) def multiply(self, frac_obj): """ fake docstring :return: """ return Fraction(self.__numerator * frac_obj.__numerator, self.__denominator * frac_obj.__denominator) def divide(self, frac_obj): """ fake docstring :return: """ return Fraction(self.__numerator * frac_obj.__denominator, self.__denominator * frac_obj.__numerator) def add(self, frac_obj): """ fake docstring :return: """ return Fraction(frac_obj.__denominator * self.__numerator + self.__denominator * frac_obj.__numerator, self.__denominator * frac_obj.__denominator) def deduct(self, frac_obj): """ fake docstring :return: """ return Fraction(frac_obj.__denominator * self.__numerator - self.__denominator * frac_obj.__numerator, self.__denominator * frac_obj.__denominator) def return_string(self): """ :returns: str, a string-presentation of the fraction in the format numerator/denominator. """ if self.__numerator * self.__denominator < 0: sign = "-" else: sign = "" return f"{sign}{abs(self.__numerator)}/{abs(self.__denominator)}" def greatest_common_divisor(a, b): """ Euclidean algorithm. Returns the greatest common divisor (suurin yhteinen tekijä). When both the numerator and the denominator is divided by their greatest common divisor, the result will be the most reduced version of the fraction in question. """ while b != 0: a, b = b, a % b return a def read_message(): """ vastaanottaa syötettä kunnes tyhjä rivi :return: array, syötteet """ ret = [] inp = input() while inp != "": ret.append(inp) inp = input() return ret def main(): print("Enter fractions in the format integer/integer.\n" "One fraction per line. Stop by entering an empty line.") print_out = "The given fractions in their simplified form:\n" while True: inp = input() if inp == "": break split = [int(x) for x in inp.split("/")] frac = Fraction(split[0], split[1]) og = frac.return_string() frac.simplify() print_out += f"{og} = {frac.return_string()}\n" print(print_out.rstrip()) if __name__ == "__main__": main()
d749af202a4ee42fa4f5f79548febcab1b46e95e
vvvaish/Book-My-Movie
/mod1.py
4,234
3.8125
4
class operations: def __init__(self,row,col): self.row = row self.col = col self.cinema = [] for i in range(self.row + 1): x = [] for j in range(self.col + 1): if i == 0: if j == 0 and j == 0: x.append(' ') else: x.append(j) elif j == 0: x.append(i) else: x.append('S') self.cinema.append(x) if self.row*self.col > 60: self.price_list = [] y1 = self.row // 2 for i in range(self.row): x1 = [] for j in range(self.col): if i + 1 <= y1: x1.append(10) else: x1.append(8) self.price_list.append(x1) self.dict = {} self.ticket = 0 self.curr_income = 0 def show(self): for i in range(self.row + 1): for j in range(self.col + 1): print(self.cinema[i][j],end = ' ') print('') print('\n') def buy_ticket(self): x = int(input('Row Number :')) y = int(input('column Number :')) if self.cinema[x][y] == 'B': print('\n') print('Already Booked!!!') print('\n') return if (self.row*self.col<= 60): print('PRICE: ',10) price = 10 else: print('PRICE: ',self.price_list[x-1][y-1]) price = self.price_list[x-1][y-1] i1 = input('Do You Want To Buy It? (yes/no) ?') if i1 == 'yes': l = {} print('\n') print('Kindly Fill Details\n') a = input('Enter Name: ') b = input('Enter Gender: ') c = input('Enter Age: ') print('Ticket Price: ',str(price)) e = input('Enter Contact no: ') l['name'+str(len(self.dict)+1)] = a l['gen' + str(len(self.dict) + 1)] = b l['age' + str(len(self.dict) + 1)] = c l['price' + str(len(self.dict) + 1)] = price l['no' + str(len(self.dict) + 1)] = e self.dict[str(x)+str(y)] = l self.cinema[x][y] = 'B' self.ticket += 1 if self.row * self.col >60: self.curr_income += self.price_list[x - 1][y - 1] print('\n') print('Ticket Booked Successfully') print('\n') else: print('\n') print("ohh!!!! You Missed Such A Nice Movie") print('\n') def statistics(self): if self.row * self.col <= 60: ans = ((self.ticket*10) / (self.row * self.col * 10))*100 print('Number Of Purchased Tickets: ',self.ticket) print('Percentage: ',str(round(ans,2))+'%') print('Current Income: ','$'+str(self.ticket*10)) print('Total Income: ','$'+str(self.row*self.col*10)) print('\n') else: x = 0 for i in self.price_list: x = x + sum(i) ans = (self.curr_income/x)*100 print('Number Of Purchased Tickets: ',self.ticket) print('Percentage: ', str(round(ans, 2)) + '%') print('Current Income: ', '$' + str(self.curr_income)) print('Total Income: ', '$' + str(x)) print('\n') def show_BookedTicketUser_info(self): a = int(input('Enter Row Number: ')) b = int(input('Enter Column Number: ')) print('\n') l = ['Name:','Gender:','Age:','Ticket Price:','Phone Number:'] if str(a)+str(b) not in self.dict: print("This Sit Not Booked Yet!!!") for i in self.dict: count = 0 if i == str(a)+str(b): for j in self.dict[str(a)+str(b)]: print(l[count], self.dict[str(a)+str(b)][j]) count += 1 print('\n')
41ffebc58f2c3f35520955e2bdec311c4f103bf0
NazguaL/UFOs
/game_functions/create_fleet.py
1,744
3.734375
4
from alien import Alien def get_number_rows(ai_settings, ship_height, alien_height): """Определяет количество рядов, помещающихся на экране.""" available_space_y = (ai_settings.screen_height - (5 * alien_height) - ship_height) number_rows = int(available_space_y / (2 * alien_height)) return number_rows def get_number_aliens_x(ai_settings, alien_width): # Вычисляет количество пришельцев в ряду. available_space_x = ai_settings.screen_width - 2 * alien_width number_aliens_x = int(available_space_x / (2 * alien_width)) return number_aliens_x def create_alien(ai_settings, screen, aliens, alien_number, row_number): """Создает пришельца и размещает его в ряду.""" alien = Alien(ai_settings, screen) alien_width = alien.rect.width alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number aliens.add(alien) def create_fleet(ai_settings, screen, ship, aliens): """Создает флот пришельцев.""" # Создание пришельца и вычисление количества пришельцев в ряду. alien = Alien(ai_settings, screen) number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width) number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height) # Создание первого ряда пришельцев. for row_number in range(number_rows): for alien_number in range(number_aliens_x): create_alien(ai_settings, screen, aliens, alien_number, row_number)
902271740940425156907021aecdd1d4c8b05d9e
visajkapadia/huffman-coding-python
/huffman.py
2,951
3.671875
4
start = None class Node: def __init__(self, letter, probability): self.letter = letter self.probability = probability self.next = None class LinkedList: LENGTH = 0 def insertAtEnd(self, letter, probability): node = Node(letter, probability) global start self.LENGTH = self.LENGTH + 1 ptr = start if ptr is None: start = node return else: while ptr.next is not None: ptr = ptr.next ptr.next = node def removeAtStart(self): global start self.LENGTH = self.LENGTH - 1 if start is None: return ptr = start start = start.next return ptr def sortLinkedList(self): global start if start is None: return ptr = start while ptr.next is not None: nxt = ptr.next while nxt is not None: if ptr.probability > nxt.probability: ptr.probability, nxt.probability = nxt.probability, ptr.probability ptr.letter, nxt.letter = nxt.letter, ptr.letter nxt = nxt.next ptr = ptr.next def insertSorted(self, letter, probability): global start self.LENGTH = self.LENGTH + 1 node = Node(letter, probability) if start is None: start = node return prev = start curr = prev.next if curr is None: prev.next = node return while curr.probability <= probability: curr = curr.next prev = prev.next if curr is None: break node.next = curr prev.next = node def printLinkedList(self): global start ptr = start while ptr is not None: print(ptr.letter, ptr.probability) ptr = ptr.next print() linkedlist = LinkedList() linkedlist.insertAtEnd('a', 0.20) linkedlist.insertAtEnd('b', 0.20) linkedlist.insertAtEnd('c', 0.15) linkedlist.insertAtEnd('d', 0.15) linkedlist.insertAtEnd('e', 0.15) linkedlist.insertAtEnd('f', 0.10) linkedlist.insertAtEnd('g', 0.05) mydict = {"a" : "", "b" : "", "c" : "", "d" : "", "e" : "", "f" : "", "g" : ""} linkedlist.sortLinkedList() for i in range(1, linkedlist.LENGTH): x = linkedlist.removeAtStart() for character in x.letter: mydict[character] = "0" + mydict[character] y = linkedlist.removeAtStart() for character in y.letter: mydict[character] = "1" + mydict[character] linkedlist.insertSorted(x.letter + y.letter, x.probability + y.probability) print("a :", mydict['a']) print("b :", mydict['b']) print("c :", mydict['c']) print("d: ", mydict['d']) print("e: ", mydict['e']) print("f: ", mydict['f']) print("g: ", mydict['g'])
8523f0d7a6dd5773e2b947e5302906f1f385187d
kevinwei666/python-projects
/hw1/solution1/Q4.py
634
4.625
5
""" Asks the user to input an integer. The program checks if the user entered an integer, then checks to see if the integer is within 10 (10 is included) of 100 or 200. If that is the case, prints ‘Yes’, else prints ‘No’. Examples: 90 should print 'Yes' 209 should also print 'Yes' 189 should print 'No' """ #Get user input num = input("Enter an integer: ") try: num = int(num) #Checks to see if int is within 10 of 100 or 200 if ((90 <= x <= 110) or (190 <= x <= 210)): print('Yes') else: print('No') except ValueError as e: print(num + " is not an integer") print(e)
ec555598b456c810f86a0948aff0073e49bb2077
kevinwei666/python-projects
/hw1/Q10-3.py
387
3.84375
4
#Given the following coefficients: 1, 3, 1 #Solve the quadratic equation: ax^2 + bx + c #Here's a reminder of the quadratic equation formula #https://en.wikipedia.org/wiki/Quadratic_formula d = b^2 - 4ac if d < 0: print('no solution') elif d = 0: print(-b/2*a) else: solution1 = -b + d^0.5 / 2*a solution2 = -b - d^0.5 / 2*a print('solutiuon1') print(solution2)
768be2ffc01f8e2e3dc1fd9e6971f63258d4e17d
ZombiMigz/Adventure-Rooms-
/startup.py
1,273
3.78125
4
#player framework class player: def __init__(self): pass player = player() player.maxhealth = 100 player.health = 100 #startup def startup(): import framework import main framework.printunknown("Hello, what's your name?") framework.guide('Type your name, then hit ENTER') player.name = input('') framework.printunknown("Hi " + player.name + ".") framework.console('Player name set to ' + player.name) #class selection def classSelection(): framework.printunknown("Please pick a class") while True: print('<<MAGE>> <<BESERKER>> <<KNIGHT>> <<ARCHER>>') player.playerClass = input('') if player.playerClass == ("MAGE" or "BESERKER" or "KNIGHT" or "ARCHER"): print("Are you sure you want to be a " + player.playerClass + "?") if input('') == 'y': framework.console("class set to " + player.playerClass) framework.printunknown("Ok! You are now a " + player.playerClass) break if input('') == 'n': framework.printclear('') continue else: print("I'm sorry, I didn't understand.") framework.guide('Type the character y or n, then hit enter.')
146b320e4fd906f1e9a40f63512007ccb6cbd836
jemtca/Python-Development
/Scripting/email_sender/email_sender_static.py
595
3.515625
4
import smtplib # to create a SMTP server from email.message import EmailMessage email = EmailMessage() email['from'] = '' # email (from) email['to'] = [''] # email/emails (to) email['subject'] = '' # email subject email.set_content('') # email message with smtplib.SMTP(host = '', port = 587) as smtp: # param1: SMTP server, param2: port smtp.ehlo() smtp.starttls() smtp.login('', '') # param1: 'email', param2: 'password' smtp.send_message(email) print('All done!') # SMTP server (google): host = 'smtp.gmail.com' # SMTP server (outlook): host = 'smtp-mail.outlook.com'
cd4362ab4eb9b4521ffcd45b4355837d80ff6683
HaaaToka/HUPROG19
/final/Jenga/solveOkan.py
1,090
3.5625
4
""" 1 <= Q <= 10 1< N <= 10^7 """ q=int(input().strip()) # if not 1 <= q <= 10: # print("1Constraints") for _ in range(q): n=int(input().strip()) # if not 1 < n <= 10**7: # print("2Constraints") txt=[] tam,yarim=0,0 """ yarim -> *-- , --* tam -> -*- """ for __ in range(n): txt.append(input().strip()) # for chr in txt[-1]: # if not (chr=="*" or chr=="-"): # print("3Constraints") if txt[-1][1]=="*": continue else: if txt[-1][0]=="-" and txt[-1][2]=="-": # --- tam += 1 elif txt[-1][0]=="-" and txt[-1][2]=="*": # --* yarim += 1 elif txt[-1][0] == "*" and txt[-1][2] == "-":# *-- yarim += 1 if yarim%2==0 and tam%2==0: print("Fatih") else: print("Onur") """ ONUR basliyor ve ilk hamlesinden sonra yarim kalan sayisini cift yapabiliyorsa sonraki hamlelerde Fatih ne yaparsa aynisini yaptigi durumda ONUR kazanir 2 3 --- --* --- 3 --- -*- --- """
56b8dad133fe4f9c472136e6a35dbd903625710c
creator-123/Sorting-Algorithm
/sort.py
13,125
4.28125
4
# -*- encoding: UTF-8 -*- # 冒泡排序 def bubbleSort(nums): """ 冒泡排序:每次与相邻的元素组成二元组进行大小对比,将较大的元素排到右边,小的元素排到左边,直至迭代完数组。 备注:将排好序的元素,放到最后面 """ for i in range(len(nums) - 1): # 遍历 len(nums)-1 次 for j in range(len(nums) - i - 1): # 已排好序的部分不用再次遍历 if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] # Python 交换两个数不用中间变量,将大的数排到后面 return nums # 选择排序 def selectionSort(nums): """ 选择排序:每次在后面的元素中,选取最小的元素,并插入到前面已经排好序的列表最右方。 备注:将排好序的元素,放到最前面 """ for i in range(len(nums) - 1): # 遍历 len(nums)-1 次 minIndex = i # 记录最小的元素index for j in range(i + 1, len(nums)): # 排好序的元素,放到最前面 if nums[j] < nums[minIndex]: # 更新最小值索引 minIndex = j # 修改最小值元素的index nums[i], nums[minIndex] = nums[minIndex], nums[i] # 把最小数交换到前面 return nums # 插入排序 def insertionSort(nums): """ 插入排序:每次将后面的元素,插到前面已经排好序的元素中; 备注:将排好序的元素,放到最前面 优化:后面的插入算法,可以使用二分查找法进行计算次数的优化。 """ for i in range(len(nums) - 1): # 遍历 len(nums)-1 次 curNum, preIndex = nums[i+1], i # curNum 保存当前待插入的数,i为当前元素的index while preIndex >= 0 and curNum < nums[preIndex]: # 将比 curNum 大的元素向后移动 nums[preIndex + 1] = nums[preIndex] # 将当前位置的值,赋值给下一个位置 preIndex -= 1 # 索引往左退一位 nums[preIndex + 1] = curNum # 待插入的数的正确位置 return nums # 希尔排序 def shellSort(nums): """ 希尔排序:是插入排序的一种更高效率的实现。不同之处,在于它优先比较距离较远的元素 备注:核心在于间隔序列的设定,可提前设定,也可动态设定 """ lens = len(nums) gap = 1 while gap < lens // 3: gap = gap * 3 + 1 # 动态定义间隔序列 while gap > 0: for i in range(gap, lens): curNum, preIndex = nums[i], i - gap # curNum 保存当前待插入的数 while preIndex >= 0 and curNum < nums[preIndex]: nums[preIndex + gap] = nums[preIndex] # 将比 curNum 大的元素向后移动 preIndex -= gap nums[preIndex + gap] = curNum # 待插入的数的正确位置 gap //= 3 # 下一个动态间隔 return nums # 归并排序 def mergeSort(nums): """ 归并排序:一种分而治之的思想应用,有两种实现方法:自上而下的递归、自下而上的迭代 """ # 归并过程 def merge(left, right): result = [] # 保存归并后的结果 i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: # 比较左右元素的大小 result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result = result + left[i:] + right[j:] # 剩余的元素直接添加到末尾 return result # 递归过程 if len(nums) <= 1: return nums mid = len(nums) // 2 # 取中位数 left = mergeSort(nums[:mid]) right = mergeSort(nums[mid:]) return merge(left, right) # 快速排序 def quickSort(nums): """ 思路: 基准:从数列中挑出一个元素,称为 “基准”(pivot); 分区: 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边); 在这个分区退出之后,该基准就处于数列的中间位置; 递归:递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列,按照上述步骤排序; 备注:这种写法的平均空间复杂度为 O(nlogn) @param nums: 待排序数组 @param left: 数组上界 @param right: 数组下界 """ if len(nums) <= 1: return nums pivot = nums[0] # 基准值 left = [nums[i] for i in range(1, len(nums)) if nums[i] < pivot] right = [nums[i] for i in range(1, len(nums)) if nums[i] >= pivot] return quickSort(left) + [pivot] + quickSort(right) def quickSort2(nums, left, right): """ 这种写法的平均空间复杂度为 O(logn) @param nums: 待排序数组 @param left: 数组上界 @param right: 数组下界 """ # 分区操作 def partition(nums, left, right): pivot = nums[left] # 基准值 while left < right: while left < right and nums[right] >= pivot: right -= 1 nums[left] = nums[right] # 比基准小的交换到前面 while left < right and nums[left] <= pivot: left += 1 nums[right] = nums[left] # 比基准大交换到后面 nums[left] = pivot # 基准值的正确位置,也可以为 nums[right] = pivot return left # 返回基准值的索引,也可以为 return right # 递归操作 if left < right: pivotIndex = partition(nums, left, right) quickSort2(nums, left, pivotIndex - 1) # 左序列 quickSort2(nums, pivotIndex + 1, right) # 右序列 return nums # 堆排序 # 大根堆(从小打大排列) def heapSort(nums): """ 堆排序: 大根堆:每个节点的值都大于或等于其子节点的值,用于升序排列; 小根堆:每个节点的值都小于或等于其子节点的值,用于降序排列。 思路: 此代码采用大根堆的思想 1.创建一个堆 H[0……n-1]; 2.把堆首(最大值)和堆尾互换; 3.把堆的尺寸缩小 1,并把新的数组顶端元素 调整到相应位置; 4.重复步骤2,直到堆的尺寸为1。 备注:python中,基本数据类型,不能在内部函数中赋值,而非基本类型,如list、dict等,可以在内部函数中,修改某个索引值 """ # 调整堆 def adjustHeap(nums, i, size): # 非叶子结点的左右两个孩子 lchild = 2 * i + 1 rchild = 2 * i + 2 # 在当前结点、左孩子、右孩子中找到最大元素的索引 largest = i if lchild < size and nums[lchild] > nums[largest]: # 左子节点 > 父节点 largest = lchild if rchild < size and nums[rchild] > nums[largest]: # 右子节点 > 父节点 largest = rchild # 如果最大元素的索引不是当前结点,把大的结点交换到上面,继续调整堆 if largest != i: nums[largest], nums[i] = nums[i], nums[largest] # 第 2 个参数传入 largest 的索引是交换前大数字对应的索引 # 交换后该索引对应的是小数字,应该把该小数字向下调整 adjustHeap(nums, largest, size) # 建立堆 def builtHeap(nums, size): for i in range(len(nums)//2)[::-1]: # 从倒数第一个非叶子结点开始建立大根堆 adjustHeap(nums, i, size) # 对所有非叶子结点进行堆的调整 # print(nums) # 第一次建立好的大根堆 # 堆排序 size = len(nums) builtHeap(nums, size) for i in range(len(nums))[::-1]: # [::-1]将数组倒序 # 每次根结点都是最大的数,最大数放到后面 nums[0], nums[i] = nums[i], nums[0] # 交换完后还需要继续调整堆,只需调整根节点,此时数组的 size 不包括已经排序好的数 adjustHeap(nums, 0, i) return nums # 由于每次大的都会放到后面,因此最后的 nums 是从小到大排列 # 计数排序 def countingSort(nums): """ 计数排序:计数排序要求输入数据的范围在 [0,N-1] 之间,则可以开辟一个大小为 N 的数组空间,将输入的数据值转化为键存储在该数组空间中,数组中的元素为该元素出现的个数。 思路: 1. 花O(n)的时间扫描一下整个序列 A,获取最小值 min 和最大值 max 2. 开辟一块新的空间创建新的数组 B,长度为 ( max - min + 1) 3. 数组 B 中 index 的元素记录的值是 A 中某元素出现的次数 4. 最后输出目标整数序列,具体的逻辑是遍历数组 B,输出相应元素以及对应的个数 """ bucket = [0] * (max(nums) + 1) # 桶的个数 for num in nums: # 将元素值作为键值存储在桶中,记录其出现的次数 bucket[num] += 1 i = 0 # nums 的索引 for j in range(len(bucket)): while bucket[j] > 0: # 当bucket的元素值,大于0,那么继续从里面取数 nums[i] = j bucket[j] -= 1 i += 1 return nums # 桶排序 def bucketSort(nums, defaultBucketSize = 5): """ 桶排序:计数排序的升级版,利用函数的映射关系,将数组中的元素映射到对应的桶中,再使用排序算法对每个桶进行排序。 思路: 1. 设置固定数量的空桶。 2. 把数据放到对应的桶中。 3. 对每个不为空的桶中数据进行排序。 4. 拼接不为空的桶中数据,得到结果 """ maxVal, minVal = max(nums), min(nums) bucketSize = defaultBucketSize # 如果没有指定桶的大小,则默认为5 bucketCount = (maxVal - minVal) // bucketSize + 1 # 数据分为 bucketCount 组 buckets = [] # 创建空的二维桶 for i in range(bucketCount): buckets.append([]) # 利用函数映射将各个数据放入对应的桶中 for num in nums: buckets[(num - minVal) // bucketSize].append(num) # 放进对应的桶里 nums.clear() # 清空 nums # 对每一个二维桶中的元素进行排序 for bucket in buckets: insertionSort(bucket) # 假设使用插入排序 nums.extend(bucket) # 将排序好的桶依次放入到 nums 中 return nums # 基数排序 def radixSort(nums): """ 基数排序:桶排序的一种推广,考虑待排序记录的多个关键维度。 1. MSD(主位优先法):从高位开始进行排序 2. LSD(次位优先法):从低位开始进行排序 思路: (LSD法) 1. 将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零 2. 从最低位开始,依次进行一次排序 3. 从最低位排序一直到最高位排序完成以后, 数列就变成一个有序序列 """ mod = 10 div = 1 mostBit = len(str(max(nums))) # 最大数的位数决定了外循环多少次 buckets = [[] for row in range(mod)] # 构造 mod 个空桶 while mostBit: for num in nums: # 将数据放入对应的桶中 buckets[num // div % mod].append(num) i = 0 # nums 的索引 for bucket in buckets: # 将数据收集起来 while bucket: nums[i] = bucket.pop(0) # 依次取出 i += 1 div *= 10 mostBit -= 1 return nums a = [2,4,6,1,3,9,10,33,2,60,8,20] result = radixSort(a) print(result)
dd6c1d03c8a15228d5892ef94e20636941f989f8
cjd1884/pyLectureMultiModalAnalysis
/classification/preprocessing.py
1,674
3.578125
4
from sklearn import preprocessing as pp import pandas as pd def do_preprocessing(df, categorical_columns=None): df = standardize(df) if categorical_columns is not None: df = categorical_2_numeric(df, categorical_columns) return df def standardize(df): ''' Standardizes the provided dataframe. :param df: the input dataframe :return: the standardized dataframe ''' # Get only float columns (containing data) float_columns = df.select_dtypes(include=['float64']).columns.to_list() string_columns = df.select_dtypes(exclude=['float64']).columns.to_list() # Create the Scaler object scaler = pp.StandardScaler() # Fit your data on the scaler object scaled_df = scaler.fit_transform(df[float_columns]) scaled_df = pd.DataFrame(scaled_df, columns=float_columns) # Concat with non float columns (removed before standardization) scaled_df = pd.concat([df[string_columns], scaled_df], axis=1, join='inner') return scaled_df def categorical_2_numeric(df, columns): ''' Converts dataframe category columns to numeric. Currently used only for label column. :param df: the input dataframe :param columns: the columns to be changed to numeric :return: the dataframe with numeric columns (previous were objects) ''' # Update column data types to categorical (previous was object) df[columns] = df[columns].astype('category') # Select categorical columns cat_columns = df.select_dtypes(['category']).columns # Convert them to numeric df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes) return df
276a75d07f610dfad18575d23dcc26ba843be9aa
cjd1884/pyLectureMultiModalAnalysis
/old/av_merge.py
1,958
3.59375
4
''' Short description: Script for merging associated video and audio files into a single medium using FFMPEG. It expects that audio files are stored as `in_dir/audio/audio_k.mp4` (and similarly for video) and stores the newly created file as `out_dir/media/medium_k.mp4` ''' import ffmpy import os def main(in_dir='./data', out_dir='./data'): ''' Merges a video file with its associated audio file creating a single medium, which it is stored in a directory `out_dir/media/` Input: in_dir: the directory containing the `audio` and `video` folders out_dir: the directory containing the `media` folder where the merged media will be stored Output: None ''' # [1] match associated audio and video # e.g. audio_k is matched with video_k audio_path = os.path.join(in_dir, 'audio', '') video_path = os.path.join(in_dir, 'video', '') audio_files = os.listdir(audio_path) video_files = os.listdir(video_path) matched_pairs = [(video_name, audio_name) for video_name in video_files for audio_name in audio_files if video_name.split('.')[0].split('_')[-1] == audio_name.split('.')[0].split('_')[-1]] print(matched_pairs) # [2] preparing the output folder and merging audio and video into a single medium path_name = os.path.join(out_dir, 'media', '') os.makedirs(path_name, mode=0o777, exist_ok=True) for idx in range(len(matched_pairs)): video = os.path.join(in_dir, 'video', matched_pairs[idx][0]) audio = os.path.join(in_dir, 'audio', matched_pairs[idx][1]) output_name = 'medium_' + str(idx) + '.mp4' output = os.path.join(path_name, output_name) inp = {audio: None, video: None} oup = {output: ['-c', 'copy']} ff = ffmpy.FFmpeg(inputs=inp, outputs=oup) # print(ff.cmd) ff.run() if __name__=='__main__': main()
e61e9a0dd1533eca20ca131949e683b0d87aba71
krisgrav/IN1000
/3. oblig/lister.py
2,125
3.9375
4
#1 '''Programmet lager en liste med tre verdier. Deretter blir en fjerde verdi lagt til i programmet. Til slutt printes den første og tredje verdien i listen.''' liste1 = [1, 5, 9] liste1.append(11) print(liste1[0], liste1[2]) #2 '''Programmet lager en tom liste. Deretter brukes .append og en input-funksjon til å samle inn 4 input fra brukeren. Til slutt printes den ferdige listen. Her har jeg gjort oppgaven to ganger, en gang med bruk av prosedyre, og en uten. Var usikker på hva som var best, så jeg lot begge stå.(Jeg bruker liste3 videre i oppgavene)''' liste2 = [] liste2.append(input("Skriv inn et navn(1/4): ")) liste2.append(input("Skriv inn et navn(2/4): ")) liste2.append(input("Skriv inn et navn(3/4): ")) liste2.append(input("Skriv inn et navn(4/4): ")) print(liste2) liste3 = [] def navn(): liste3.append(input("Skriv inn et navn(1/4): ")) liste3.append(input("Skriv inn et navn(2/4): ")) liste3.append(input("Skriv inn et navn(3/4): ")) liste3.append(input("Skriv inn et navn(4/4): ")) navn() print(liste3) #3 '''For å forsikre at det ikke er tull med store og små bokstaver har jeg lagt inn en funkjson som endrer alle verdiee i listen til små bokstaver. Deretter sjekker programmet om navnet mitt finnes i lista ved bruk av if og else, og printer to forskjellige output om det stemmer eller ikke.''' liste3 = [navn.lower() for navn in liste3] if 'kristian' in liste3: print("Du husket meg!") else: print("Glemte du meg?") #4 '''Programmet lager en ny liste der tallene fra liste1 førs adderes, så multipliseres, og lagres sammen. Deretter printer programmet den nye listen med navn sum_prod. Den opprinnelige liste1 og sum_prod legges sammen og danner kombi_liste, for å så printes. Til slutt bruker programmet en .pop() funkjson til å fjerne den siste indexen i listen to ganger, og printer sluttresultatet.''' sum_prod = [liste1[0] + liste1[1] + liste1[2] + liste1[3] , liste1[0] * liste1[1] * liste1[2] * liste1[3]] print(sum_prod) kombi_liste = liste1 + sum_prod #, eller + ??? print(kombi_liste) kombi_liste.pop(-1) kombi_liste.pop(-1) print(kombi_liste)
cc94647d2b34d67d0feea3bc0dca72a928b2fd61
tsg-ut/esolang-battle-archive
/komabasai2018-day1/python3.py
79
3.65625
4
y=int(input())-2 x=int(input()) print("*"*x+("\n*"+" "*(x-2)+"*")*y+"\n"+"*"*x)
21d842412724f3144975448a20ce0dc91e92d2fa
LuckyQingke/myrepository
/pythontest/test.py
418
3.71875
4
#dict d={'cc':22,'bb':11,'mm':'00'} if('cc' in d): print(d['cc']) print(d) d['dd'] = 90 print(d) d.pop('mm') print(d) def appendL(d): d['ee']=99 appendL(d) print(d) #python迭代对象 for x in 'asdfg': print(x) for value in enumerate([1,2,3]): print(value) for i,value in enumerate([1,2,3]): print(i,value) L1 = ['Hello','World',18,'Apple',None] L2 = [s.lower() for s in L1 if isinstance(s,str) ] print(L2)
cfa8167b3df46123ee695b344e9025d91dad2673
kaido89/General
/tools_API/ldap/ldap_api.py
1,186
3.515625
4
#!/usr/bin/env python3 from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES def main(): ldap_server = input('LDAP SERVER url (eg. example.com): ') # it should be the ldap_server server = Server(ldap_server, get_info=ALL) # it should have the login user ldap_user = input('LDAP USER (eg. KAIDO89): ') # it should have the user password ldap_pass = input('LDAP PASSWORD (eg. KAIDO89_PASSWORD): ') # it should have the company forest forest = input('LDAP FOREST (eg. COMPANY_NAME): ') conn = Connection(server, user=forest+"\\"+ldap_user, password=ldap_pass, auto_bind=True) search_user = input('SEARCH USER in LDAP (eg. KAIDO89_FRIEND): ') search_user_result = conn.search('dc='+str(forest).lower()+',dc=com', '(&(objectclass=person)(mailNickname=' + search_user + '))', attributes=[ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES]) # confirmed search run correctly if search_user_result: print(conn.entries) # if did not found anything else: print('Did not found this user') conn.unbind() main()
9cc7bbd72c1e4a79e101815dd46b4964c2d7306d
wflosin/Code-Portfolio
/Python/combatgame.py
18,018
3.953125
4
import time import random def main(): #[a,b,c, d] #[0] is the monster's health, #[1] is its speed, #[2] is its damage, #[3] is its armour class goblin = [8, 2, 4, 2] spider = [12, 5, 6, 4] dragon = [30, 7, 10, 7] smiley = [21, 6 , 8, 1] weapon = None print("This is a combat simulator") time.sleep(1) print("") """ new weapon template elif weaponch in []: print("") time.sleep(0.5) print("") weapon = [, ] """ while weapon == None: weaponch = str.lower(input("Choose your weapon! \n")) if weaponch in ['dagger', 'knife', 'pointy stick', 'throwing knife', 'throwing knives', 'knives','shank']: print("You chose to use a pointy dagger!") time.sleep(0.5) print("Daggers are very fast, but very weak") #[a,b] a[0:10], speed. b[0:10], damage weapon = [4, 1] elif weaponch in ['short sword','machete']: print("You chose to use a short sword!") time.sleep(0.5) print("Short swords are fast, but weak") weapon = [3, 2] elif weaponch in ['long sword', 'sword']: print("You chose to use a long sword!") time.sleep(0.5) print("Long swords are average in speed and damage") weapon = [3, 3] elif weaponch in ['battle ax', 'wits']: print("You chose to use a battle ax!") time.sleep(0.5) print("Battle axes are strong, but slow") weapon = [2, 4] elif weaponch == 'great sword': print("You chose to use a great sword!") time.sleep(0.5) print("Great swords are very strong, but very slow") weapon = [1, 5] elif weaponch == 'stick': print("You saw the rack of weapons but you don't confide to society's standards,") time.sleep(0.5) print("so you pick up a stick on the ground") time.sleep(0.5) print("Sticks are very fast, but extremely weak") weapon = [4, 1] elif weaponch in ['laser sword', 'light saber', 'lightsaber']: print("You chose to use the mythical laser sword!") time.sleep(0.5) print("Laser swords are deadly, and extremely fast") weapon = [5, 10] elif weaponch in ['charisma', 'my looks', 'my good looks', 'sexiness', 'my face', 'my beautiful face', 'charm']: print("You chose to use you charm!") time.sleep(0.5) print("You're pretty gorgeous, you've got this battle in the bag") weapon = [10, 1] elif weaponch in ['mace', 'morning star', 'club']: print("You chose to use a mace!") time.sleep(0.5) print("Maces are slow but deadly!") weapon = [2, 5] elif weaponch in ['magic', 'dark magic', 'spells', 'will', 'will power', 'spookiness', 'magic missile', 'fireball']: print("You chose to use deadly magic!") time.sleep(0.5) print("Magic is literally the best way to go!") weapon = [10, 10] elif weaponch in ['nap', 'sleep', 'rest', 'take a nap']: print("You chose to go to sleep!") time.sleep(0.5) print("Sleep well!") weapon = [0, 0] elif weaponch in ['bomb', 'nuke', 'atomic bomb', 'hydrogen bomb', 'grenade','explosives', 'bazooka', 'grenade launcher', 'rocket launcher']: print("You chose to use deadly explosives!") time.sleep(0.5) print("Bombs are far past slow, but incinerates anything in its path!") weapon = [0.3, 100] elif weaponch in ['test']: print("test weapon") time.sleep(0.5) weapon = [100, 100] elif weaponch in ['gun', 'pistol', 'rifle', 'sniper rifle', 'assault rifle']: print("You chose to use a gun!") time.sleep(0.5) print("Guns are fast and powerful!") weapon = [5, 7] elif weaponch in ['spear', 'pike', '11-foot pole', 'staff', 'rod']: print("You chose to use a spear!") time.sleep(0.5) print("spears are fast and average in damage") weapon = [5, 3] elif weaponch in ['potato', 'potahto', 'carrot', 'peas', 'potato gun', 'tomato', 'radishes', 'cilantro', 'waffles', 'spam', 'ghost pepper','potato launcher']: print("You chose to try and start a food fight!") time.sleep(0.5) print("Food is delicious, but not practical in a real fight") weapon = [6, 1] elif weaponch in ['peace', 'talk', 'words', 'my words', 'compromise', 'diplomacy', 'hugs', 'justice', 'law', 'order', 'law and order', 'the united nations','friendship', 'community']: print("You chose to not fight!") time.sleep(0.5) print("Just because you won't attack, doesn't mean they won't") weapon = [0, 100] elif weaponch in ['deception', 'lies', 'trickery', 'evil']: print("You decide to deceive you foe!") time.sleep(0.5) print("trickery is slow but deadly") weapon = [1, 6] elif weaponch in ['staring contest', 'looking', 'my eyes', 'eyes', 'stare']: print("You decided to have a staring contest with your foe!") time.sleep(0.5) print("First to break loses!") weapon = [3, 3] elif weaponch in ['fists', 'fisticuffs', 'bare hands', 'bare handed', 'hand to hand', 'hand', 'fist']: print("You decided to fight with your bare hands!") time.sleep(0.5) print("Your fists are extremely fast, and extremely weak") weapon = [8, 1] elif weaponch in ['rock', 'rocks', 'stone', 'stones', 'tomahawk', 'rotten tomato', 'rotten tomaotes', 'throwing weapon', 'sling', 'pebbles']: print("You decided to go with a throwing weapon!") time.sleep(0.5) print("They're slow but pack a punch!") weapon = [1, 5] elif weaponch in ['whip', 'sock whip', 'rope']: print("You decided to use a whip!") time.sleep(0.5) print("whips are fast and pretty deadly") weapon = [5, 6] elif weaponch in ['stapler', 'staple gun', 'nail gun']: print("You decided to use a staple gun!") time.sleep(0.5) print("Fast, but the stples don't do much") weapon = [3, 2] elif weaponch in ['wooden spoon','fork','ladle','spoon','spatula','soup spoon','whisk','plastic spoon','spork','butter knife']: print("You decided to use kitchen utensils") time.sleep(0.5) print("Fast, but don't do much") weapon = [6, 1] elif weaponch in ['frying pan','pot','sauce pan','wok']: print("You chose to use A FRIGGEN FRYING PAN") time.sleep(0.5) print("You are now a certified badass") weapon = [5, 6] elif weaponch in ['memes','meme','dank memes','dat boi','yeet']: print("You chose to use memes as a weapon") time.sleep(0.5) print("Memes are the best thing to arise on this planet") weapon = [3, 20] elif weaponch in ['fast test']: print("Fast weapon test") time.sleep(0.5) weapon = [100, 0] elif weaponch in ['taser', 'stun stick', 'shock stick', 'electric fence', 'electric chair', 'static electricity', 'tesla coil']: print("You chose the power of electricity!") time.sleep(0.5) print("BZZZZZZT ZAP ZAP") weapon = [11, 7] else: print("That's not a valid option.\n") #[a,b,c] a, player health. b, player speed. c, player damage. player = [20, weapon[0], weapon[1]] time.sleep(2) print("") for wtf in ['goblin', 'spider', 'dragon', 'smiley']: wtf = str.lower(input("Do you want to fight a goblin, a spider or a dragon? \n")) if wtf in ['goblin', 'spider', 'dragon', 'smiley']: print("You chose to fight a " + wtf) print("") time.sleep(1) break else: print("You can't see that monster") time.sleep(1) continue if wtf == 'goblin': print("A nasty looking goblin approaches!") time.sleep(0.5) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("░░░░░░░░░THE GOBLIN ATTACKS YOU░░░░░░░░") print("░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░██████") print("███░░░░░░░░░░░░░░███████████░░████████░░") print("████████░░░░██████▒█▒▒█▒▒▒▒███▒▒▒███░░░░") print("░░░████▒█████▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒██░░░░░░░") print("░░░░░░████▒▒▒▒▒▒███▒▒▒▒███▒▒▒█████░░░░░░") print("░░░░░░██▒▒▒▒▒▒▒▒█o█▒▒▒▒█o█▒▒▒▒▒▒▒██░░░░░") print("░░░░░██▒▒▒▒▒▒▒▒▒▒▒▒███▒▒▒▒▒▒▒▒▒▒▒██░░░░░") print("░░░░░█▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒███▒▒▒▒▒▒▒███░░░░░░") print("░░░░░████▒▒▒▒▒▒▒█_█_█_█_█▒▒▒████░░░░░░░░") print("░░░░░░░░█████▒▒█_█_█_█_█▒█████░░░░░░░░░░") print("░░░░░░░░░░░░█████▒▒▒▒▒▒▒████░A░░░░░░░░░░") print("░░░░░░░░░░░░░░░░░████████░░░░█░░░░░░░░░░") print("░░░░░░░░░░░░░░░░░█▒▒░█░░░░░░_█_░░░░░░░░░") print("░░░░░░░░░░░░░░████▒▒▒██░░░░░░█░░░░░░░░░░") print("░░░░░░░░░░░░██░▒▒▒▒▒▒▒████████░░░░░░░░░░") print("░░░░░░░░░░░██░▒▒▒▒▒▒▒▒▒████░░░░░░░░░░░░░") print("░░░░░░░░░░░█░██░▒▒▒▒░███░░░░░░░░░░░░░░░░") print("░░░░░░░░░░██░██░▒▒▒▒██░░░░░░░░░░░░░░░░░░") print("░░░░░░░░░░░█████▒▒▒▒█░░░░░░░░░░░░░░░░░░░") print("░░░░░░░░░░░░░░░█▒▒▒▒█░░░░░░░░░░░░░░░░░░░") print("░░░░░░░░░░░░░░███████░░░░░░░░░░░░░░░░░░░") print("░░░░░░░░░░░░░░█░░░░░██░░░░░░░░░░░░░░░░░░") print("░░░░░░░░░░░░░██░░░░░░██░░░░░░░░░░░░░░░░░") print("░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("") time.sleep(2) monster = goblin monstername = 'goblin' #goblin stats [8, 2, 2, 12] #spider elif wtf == 'spider': print("A massive spider approaches!") time.sleep(0.5) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("░░░░░░░░░░░░THE SPIDER ATTACKS YOU░░░░░░░░░░░░") print("░░░░░░░░░░░░░░░░░░░██████████░░████░░░░░░░░░░░░") print("░░░░░░███████░█████▒▒█████▒░█████░██░░░░░░░░░░░") print("░░░░░███░░░███░▒▒░▒▒█░░░░░█░▒░░░████░░░░░░░░░░░") print("░░░░░░██████░░▒▒▒▒░█░██░██░█▒▒▒▒░░███████░░░░░░") print("░░░███████░▒▒▒▒▒▒▒▒░█░░▒░░█░▒▒▒▒░░██░░████░░░░░") print("░████░░░█▒▒▒▒▒▒▒▒▒▒▒░█░█░█░▒▒▒▒▒░░███░░░░███░░░") print("░█░░░░░░█▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░██▒███░░░█░░░") print("░░░██▒▒████░░░▒▒▒███████████▒▒░░███░░░████░░░░░") print("░░█▒▒██░░█████████▒█▒█▒▒█▒█░█░░██████░░░███░░░░") print("░████░░░██░██░░█▒▒█▒█▒▒█▒█▒▒█████▒▒▒░█░░░░█░░░░") print("░██░░░░░█░▒█░░░█▒▒▒▒▒▒▒▒▒▒▒▒█░░░░██▒▒░█░░░░░░░░") print("░░░░░░░░█▒▒█░░░░██░░████░░██░░░░░░░░███░░░░░░░░") print("░░░░░░░░█▒██░░░░░██░░░░░░██░░░░░░░░░░██░░░░░░░░") print("░░░░░░░░███░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░") print("░░░░░░░░██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n") monster = spider time.sleep(2) monstername = 'spider' #spider stats [12, 5, 1, 8] #dragon elif wtf == 'dragon': print("A collosal dragon approaches! \n") time.sleep(0.5) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print(" THE DRAGON ATTACKS YOU ") print(" __ __ ") print(" ( _) ( _) ") print(" / / \ / /\_\_ ") print(" / / \ / / | \ \ ") print(" / / \ / / |\ \ \ ") print(" / / , \ , / / /| \ \ ") print(" / / |\_ /| / / / \ \_\ ") print(" / / |\/ _ '_|\ / / / \ \ ") print(" | / |/ O \O\ \ / | | \ \ ") print(" | |\| \_\_ / / | \ \ ") print(" | | |/ \.\ o\o) / \ | \ ") print(" \ | /\,`v-v / | | \ ") print(" | \/ /_| \,_| / | | \ \ ") print(" | | /__/_ / _____ | | \ \ ") print(" \| [__] \_/ |_________ \ | \ ()") print(" / [___] ( \ \ |\ | | // ") print(" | [___] |\| \| / |/ ") print(" /| [____] \ |/\ / / || ") print(" ( \ [____ / ) _\ \ \ \| | || ") print(" \ \ [_____| / / __/ \ / / // ") print(" | \ [_____/ / / \ | \/ // ") print(" | / '----| /=\____ _/ | / // ") print(" __ / / | / ___/ _/\ \ | || ") print(" (/-(/-\) / \ (/\/\)/ | / | / ") print(" (/\/\) / / // ") print(" _________/ / / ") print(" \____________/ ( ") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n") monster = dragon time.sleep(2) monstername = 'dragon' elif wtf == 'smiley': print("") time.sleep(0.5) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print(" ;) ") print(" ") print(" ,----------. ") print(" / __ __ \ ") print(" | | | | | | ") print(" @| |__| |__| |@ ") print(" | \ .\ / | ") print(" \ \______/ / ") print(" \ _ / ") print(" '--------' ") print(" | __ ") print(" /|\_[.']^^^^^\ ") print(" / | '--'vvvvv/ ") print(" / \ ") print(" _/ \_ ") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n") monster = smiley time.sleep(2) monstername = 'smiley' combat(player, monster, monstername) again = str.lower(input("Do you want to play again? [y/n] ")) if again in ['yes', 'y', 'yas', 'sure', 'okay', 'why not', 'yolo']: main() else: pass def combat(player, monster, monstername): pspeed = player[1] espeed = monster[1] palive = True ealive = True critical = 1 while (palive or ealive) == True: if pspeed >= espeed: espeed += monster[1] input("It's your turn! Press [enter] to attack!") ptohit = random.randrange(1, 21) if ptohit > monster[3]: if ptohit == 20: print("Critical hit!") critical = 2 tedamage = (random.randrange(1, player[2]+2)) * critical print("You hit for %2s damage!" % tedamage) monster[0] -= tedamage critical = 1 time.sleep(1) else: print("You missed!") time.sleep(1) else: pspeed += player[1] print("The %6s attacks!" % monstername) time.sleep(1) etohit = random.randrange(1, 21) if etohit > 10: if etohit == 20: print("Critical hit!") critical = 2 tpdamage = (random.randrange(1, monster[2]+2)) * critical print("You get hit for %2i damage!" % tpdamage) player[0] -= tpdamage critical = 1 time.sleep(1) else: print("the %6s missed!" % monstername) time.sleep(1) #death calculations [0] if player[0] < 0: palive = False else: palive = True print("You are at %2i health" % player[0]) print("") if monster[0] < 0: ealive = False else: ealive = True if (palive and not ealive) == True: print("You killed the %6s! \n" % monstername) return elif (ealive and not palive) == True: print("The %6s killed you! \n" % monstername) return elif (ealive and palive) == False: print("You both died!\n") return else: continue if __name__ == '__main__': main()
291afaa5eb6a3a5e8a87f945826cf9b93d872d7e
jgjefersonluis/python-pbp
/secao02-basico/aula27-lacorepeticao/main.py
188
3.84375
4
# Faça um laço de repetição usando o comando while começando com o valor 50 # até 100 a = 50 # variavel while a <= 100: # condição print(a) # instrução a = a + 1
7a4ce4b010222efd9670600554c384f40fc040fc
jgjefersonluis/python-pbp
/secao01-introducao/variaveis/main15-time.py
387
3.640625
4
import time #declarando as variaveis num = 2 num1 = 3 data_hota_atual = time.asctime() num2num = 5 #Usando os valores das variaveis para produzir texto print("variavel com apenas letras %i" %num) print("variavel com letras e numero no final %i" %num1) print("variavel com caractere especial uderline ", data_hota_atual) print("variavel com letras e numero no entre as letras %i" %num1)
ace87f462bb896fa3a87a0a89c71569ef676e01f
jgjefersonluis/python-pbp
/secao02-basico/aula02-variaveis-comandos/float.py
82
3.53125
4
# Float # Ponto Flutuante a = float(input('Digite um valor decimal: ')) print(a)
d37b7a9f7bbfbc9b2a247ccb2988c220d802bf95
jgjefersonluis/python-pbp
/secao01-introducao/operadoreslogicobooleanos/main.py
222
3.828125
4
# AND = Dois valores verdades # OR = Um valor verdade // Dois falsos # NOT = Inverte o valor a = 10 b = 5 sub = a - b print(a != b and sub == b) print(a == b and sub == b) print(a == b or sub == b) print(not sub == a)
5dfecf790c2ed3a9623301cdf7c1d112e76cbc25
jgjefersonluis/python-pbp
/secao02-basico/aula23-aumentosalarial/main.py
444
3.78125
4
# Escreva um programa para calcular aumento salarial, se o valor do salario for maior que R$ 1200,00 # o percentual de aumento será de 10% senao sera de 15%. salario = float(input('Digite o seu salario: ')) # condições if salario > 1200: pc_aumento = 0.10 aumento = salario * pc_aumento if salario <= 1200: pc_aumento = 0.15 aumento = salario * pc_aumento print('O seu aumento salarial é de R$ %7.2f reais. ' %aumento)
6002c33a5aa29c39155830b6b9f066f5d21c0a1b
AbhilashMathews/gp_extras
/examples/plot_gpr_manifold.py
4,013
3.75
4
# Authors: Jan Hendrik Metzen <[email protected]> # # License: BSD 3 clause """ ============================================================================== Illustration how ManifoldKernel can exploit data on lower-dimensional manifold ============================================================================== This example illustrates how the ManifoldKernel allows exploiting when the function to be learned has a lower effective input dimensionality (2d in the example) than the actual observed data (5d in the example). For this, a non-linear mapping (represented using an MLP) from data space onto manifold is learned. A stationary GP is used to learn the function on this manifold. In the example, the ManifoldKernel is able to nearly perfectly recover the original square 2d structure of the function input space and correspondingly learns to model the target function better than a stationary, anisotropic GP in the 5d data space. """ print __doc__ import numpy as np import matplotlib.pyplot as plt from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels \ import RBF, WhiteKernel, ConstantKernel as C from sklearn.metrics import mean_squared_error from sklearn.model_selection import learning_curve from gp_extras.kernels import ManifoldKernel np.random.seed(0) n_samples = 100 n_features = 5 n_dim_manifold = 2 n_hidden = 3 # Generate data def f(X_nn): # target function return np.sqrt(np.abs(X_nn[:, 0] * X_nn[:, 1])) X_ = np.random.uniform(-5, 5, (n_samples, n_dim_manifold)) # data on manifold A = np.random.random((n_dim_manifold, n_features)) # mapping from manifold to data space X = X_.dot(A) # X are the observed values y = f(X_) # Generate target values by applying function to manifold # Gaussian Process with anisotropic RBF kernel kernel = C(1.0, (1e-10, 100)) * RBF([1] * n_features, [(0.1, 100.0)] * n_features) \ + WhiteKernel(1e-3, (1e-10, 1e-1)) gp = GaussianProcessRegressor(kernel=kernel, alpha=0, n_restarts_optimizer=3) # Gaussian Process with Manifold kernel (using an isotropic RBF kernel on # manifold for learning the target function) # Use an MLP with one hidden-layer for the mapping from data space to manifold architecture=((n_features, n_hidden, n_dim_manifold),) kernel_nn = C(1.0, (1e-10, 100)) \ * ManifoldKernel.construct(base_kernel=RBF(0.1, (1.0, 100.0)), architecture=architecture, transfer_fct="tanh", max_nn_weight=1.0) \ + WhiteKernel(1e-3, (1e-10, 1e-1)) gp_nn = GaussianProcessRegressor(kernel=kernel_nn, alpha=0, n_restarts_optimizer=3) # Fit GPs and create scatter plot on test data gp.fit(X, y) gp_nn.fit(X, y) print "Initial kernel: %s" % gp_nn.kernel print "Log-marginal-likelihood: %s" \ % gp_nn.log_marginal_likelihood(gp_nn.kernel.theta) print "Learned kernel: %s" % gp_nn.kernel_ print "Log-marginal-likelihood: %s" \ % gp_nn.log_marginal_likelihood(gp_nn.kernel_.theta) X_test_ = np.random.uniform(-5, 5, (1000, n_dim_manifold)) X_nn_test = X_test_.dot(A) y_test = f(X_test_) plt.figure(figsize=(8, 6)) plt.subplot(1, 2, 1) plt.scatter(y_test, gp.predict(X_nn_test), c='b', label="GP RBF") plt.scatter(y_test, gp_nn.predict(X_nn_test), c='r', label="GP NN") plt.xlabel("True") plt.ylabel("Predicted") plt.legend(loc=0) plt.title("Scatter plot on test data") print "RMSE of stationary anisotropic kernel: %s" \ % mean_squared_error(y_test, gp.predict(X_nn_test)) print "RMSE of stationary anisotropic kernel: %s" \ % mean_squared_error(y_test, gp_nn.predict(X_nn_test)) plt.subplot(1, 2, 2) X_gp_nn_test = gp_nn.kernel_.k1.k2._project_manifold(X_nn_test) plt.scatter(X_gp_nn_test[:, 0], X_gp_nn_test[:, 1], c=y_test) cbar = plt.colorbar() cbar.ax.set_ylabel('Function value', rotation=270) plt.xlabel("Manifold dimension 1") plt.ylabel("Manifold dimension 2") plt.title("Learned 2D Manifold") plt.show()
572a81171d108cd73f3ea478253c06b442eeef51
kyhuudong/Learn-Algorithm
/MatrixKeanuReeves/MatrixCheckTriangleTopAndBot.py
478
3.53125
4
M1 = [ [2,3,4], [0,5,7], [0,0,7]] M2 = [[7,0,0], [7,5,0], [4,3,2]] def TriangleTopMatrix(M): for i in range(1,len(M)): for j in range(i): if(M[i][j] != 0): return False return True def TriangleBotMatrix(M): for i in range(len(M)): for j in range(i+1,len(M)): if(M[i][j] != 0): return False return True print(TriangleTopMatrix(M1)) print(TriangleBotMatrix(M2))
c4003359c66806d171bc8d22855e75c40bb854a1
isotomurillo/Programacion
/Python/Pila/forma lista parcial.py
304
3.75
4
def formarList(num): if isinstance (num,int) and (num>0): return pares(num) else: return "Número Incorrecto" def pares(num): if num==0: return[] elif (num%10)%2==0: return Lista[num%10]+pares(num//10) else: return pares(num//10)
e19fc7953dc495fef5987d49d2a6febb41042ef5
igorsobreira/playground
/problems/notifications.py
1,151
4.1875
4
''' Eu tenho um objeto da classe A que muda muito de estado e objetos das classes B e C que devem ser notificados quando o objeto da classe A muda de estado. Como devo projetar essas classes? ''' class Publisher(object): def __init__(self): self.status = "FOO" self._subscribers = [] def register(self, subscriber): if subscriber not in self._subscribers: self._subscribers.append(subscriber) def notify_all(self): for subscriber in self._subscribers: subscriber.notify(self) def something_happenned(self): print ("I'm on Publisher, modifying my state") self.notify_all() class Subscriber(object): def notify(self, publisher): print ("Hi, I'm {0} being notified".format(str(self))) class SubscriberB(Subscriber): def __str__(self): return "A" class SubscriberC(object): def __str__(self): return "B" def main(): publisher = Publisher() publisher.register(SubscriberB()) publisher.register(SubscriberC()) publisher.something_happenned() if __name__ == '__main__': main()
474203b4cfbb1ebb634431a2eed392f539a98f6e
igorsobreira/playground
/problems/project_euler/20.py
258
3.90625
4
#-*- coding: utf-8 -*- ''' n! means n × (n − 1) × ... × 3 × 2 × 1 Find the sum of the digits in the number 100! ''' def factorial(n): if n == 0: return 1 return n * factorial(n-1) print sum( [ int(n) for n in str(factorial(100)) ] )
d4f45f0640ce0cd0e066ce92db1c3be386570eed
jmorton89/Portfolio
/Code Golf- Fizzbuzz.py
111
3.71875
4
for i in range(1,101): if i%3==0 and i%5==0:i='FizzBuzz' elif i%3==0:i='Fizz' elif i%5==0:i='Buzz' print(i)
e095d54de54855fbf5c006b6fe47ee93e51fd5ba
DinakarBijili/Data-structures-and-Algorithms
/BINARY TREE/11.Top View of Binary Tree .py
1,394
4.28125
4
""" Top View of Binary Tree Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. For the given below tree 1 / \ 2 3 / \ / \ 4 5 6 7 Top view will be: 4 2 1 3 7 Note: Return nodes from leftmost node to rightmost node. Example 1: Input: 1 / \ 2 3 Output: 2 1 3 Example 2: Input: 10 / \ 20 30 / \ / \ 40 60 90 100 Output: 40 20 10 30 100 """ class TreeNode: def __init__(self,data): self.data = data self.left = None self.right = None def getData(self): return self.data def getLeft(self): return self.left def getRight(self): return self.right def TopView(Tree): if not Tree: return [] if Tree: TopView(Tree.getLeft()) TopView(Tree.getRight) print(Tree.data) if __name__ == "__main__": """ 1 / \ 2 3 / \ / \ 4 5 6 7 Top view will be: 4 2 1 3 7 """ root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.left = TreeNode(6) root.right.right = TreeNode(7) print("Top View: ") TopView(root)
feedbf88435af6b186da9dcd85041587edcee515
DinakarBijili/Data-structures-and-Algorithms
/BINARY TREE/6.Inorder Tree Traversal – Iterative and Recursive.py
1,406
3.921875
4
""" Inorder Tree Traversal – Iterative and Recursive Construct the following tree 1 / \ / \ 2 3 / / \ / / \ 4 5 6 / \ / \ 7 8 output = 4 2 1 7 5 8 3 6 """ #Recursive method class TreeNode: def __init__(self,data ): self.data = data self.left = None self.right = None def getData(self): return self.data def getLeft(self): return self.left def getRight(self): return self.right def Inorder_traversal(Tree): if not Tree: return if Tree: Inorder_traversal(Tree.getLeft()) print(Tree.getData(), end=" ") Inorder_traversal(Tree.getRight()) return if __name__ == "__main__": """ Construct the following tree 1 / \ / \ 2 3 / / \ / / \ 4 5 6 / \ / \ 7 8 """ root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.right.left = TreeNode(5) root.right.right = TreeNode(6) root.right.left.left = TreeNode(7) root.right.left.right = TreeNode(8) Inorder_traversal(root)
7629f38b20e5dd43ceda19cceb9e68a7386adee0
DinakarBijili/Data-structures-and-Algorithms
/SORTING AND SEARCHING/18.K-th element of two sorted Arrays.py
1,027
4.25
4
""" K-th element of two sorted Arrays Given two sorted arrays arr1 and arr2 of size M and N respectively and an element K. The task is to find the element that would be at the k’th position of the final sorted array. Example 1: Input: arr1[] = {2, 3, 6, 7, 9} arr2[] = {1, 4, 8, 10} k = 5 Output: 6 Explanation: The final sorted array would be - 1, 2, 3, 4, 6, 7, 8, 9, 10 The 5th element of this array is 6. Example 2: Input: arr1[] = {100, 112, 256, 349, 770} arr2[] = {72, 86, 113, 119, 265, 445, 892} k = 7 Output: 256 Explanation: Final sorted array is - 72, 86, 100, 112, 113, 119, 256, 265, 349, 445, 770, 892 7th element of this array is 256. """ def Kth_element_in_two_sortedarr(arr1,arr2,target): ans =arr1+arr2 ans.sort() for i, j in enumerate(ans): if i+1 == target: return j return [] if __name__ == "__main__": arr1 = [100, 112, 256, 349, 770] arr2 = [72, 86, 113, 119, 265, 445, 892] target = 7 print(Kth_element_in_two_sortedarr(arr1,arr2,target))
90c36140e441af6d4d68bc6b4199e42038ae31d2
DinakarBijili/Data-structures-and-Algorithms
/Algorithms/Sorting_Algorithms/5.Quick_sort.py
930
4.0625
4
# Quick Sort using Python # Best = Average = O(nlog(n)); Worst = O(n^2) #Quick sort is divide-and-conquer algorithm. it works by a selecting a pivot element from an array and partitionong the other elements into two sub-array. # according to wheather their are less that or greaterthan the pivot. the sub-arrays are then sorted recursively. #DIVIDE AND CONQUER METHOD def quick_sort(arr): if len(arr) <= 1: return arr less_than_pivot = [] greater_than_pivot = [] pivot = arr[0] #first index for value in arr[1:]: if value <= pivot: less_than_pivot.append(value) else: greater_than_pivot.append(value) print("%15s %1s %-15s"% (less_than_pivot,pivot,greater_than_pivot)) return quick_sort(less_than_pivot)+[pivot]+quick_sort(greater_than_pivot) if __name__ == "__main__": arr = [4,6,3,2,9,7,3,5] print(arr) result = quick_sort(arr) print(result)
6d66d78b7774086fa047257b28fd2d3d83c7d7ca
DinakarBijili/Data-structures-and-Algorithms
/ARRAY/10.min_no._of_jumps_to_reach_end_of_arr.py
1,639
4.1875
4
""" Minimum number of jumps Given an array of integers where each element represents the max number of steps that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element. Example 1: Input: N=11 arr=1 3 5 8 9 2 6 7 6 8 9 Output: 3 Explanation: First jump from 1st element to 2nd element with value 3. Now, from here we jump to 5th element with value 9, and from here we will jump to last. Example 2: Input : N= 6 arr= 1 4 3 2 6 7 Output: 2 Explanation: First we jump from the 1st to 2nd element and then jump to the last element. Your task: You don't need to read input or print anything. Your task is to complete function minJumps() which takes the array arr and it's size N as input parameters and returns the minimum number of jumps. Expected Time Complexity: O(N) Expected Space Complexity: O(1) """ def jump(arr): if len(arr) <= 1 : return 0 # Return -1 if not possible to jump if arr[0] <= 0 : return -1 jump_count = 0 curr_reachable = 0 for index , values in enumerate(arr): if index > curr_reachable: curr_reachable = reachable jump_count += 1 reachable = max(0,index + values) return jump_count if __name__ == "__main__": arr = [1,3, 5, 8, 9, 2, 6, 7, 6, 8, 9 ] # ndex =[0,1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = jump(arr) print("Max Jumps to reach End in",result,"Steps!")
ecc51e9f138f6e8d3cfeeb04fab9a9c45edc2ce8
DinakarBijili/Data-structures-and-Algorithms
/STACK AND QUEUE/2.Queue(FIFO).py
2,870
3.9375
4
""" Queue (First<-In First->Out ) Like Stack, Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of queue is any queue of consumers for a resource where the consumer that came first is served first. The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added. Operations on Queue: Mainly the following four basic operations are performed on queue: Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition. Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition. Front: Get the front item from queue. Rear: Get the last item from queue. (deleting and inserting) Enqueue(adds)-> | | | | | -> Dequeue(remove) / \ Rear Front """ class Queue(object): def __init__(self,limit=10): self.queue = [] self.limit = limit self.size = 0 def __str__(self) -> str: return " ".join([str(i) for i in self.queue]) def isEmpty(self): return self.size <= 0 def isFull(self): return self.size == self.limit # to add an element from the rear end of the queue def enqueue(self, data): if self.isFull(): print("queue overflow") return # queue overflow else: self.queue.append(data) self.size += 1 # to pop an element from the front end of the queue def dequeue(self): if self.isEmpty(): print("Queue is Empty") return # queue underflow else: self.queue.pop(0) self.size -= 1 def getSize(self): return self.size def getFront(self): if self.isEmpty(): print("Queue is Empty") return else: return self.queue[0] def getRear(self): if self.isEmpty(): print("Queue is Empty ") return else: return self.queue[-1] if __name__ == "__main__": #FIFO myQueue = Queue() myQueue.enqueue(1) myQueue.enqueue(2) myQueue.enqueue(3) myQueue.enqueue(4) myQueue.enqueue(5) print("Enqueue(INSERT):-", myQueue) print('Queue Size:',myQueue.getSize() ,'\n') myQueue.dequeue() # remove from 1st myQueue.dequeue() # remove from 2nd print("dequeue(DELETE):-", myQueue) print('Queue Size:',myQueue.getSize()) print("Front item is:",myQueue.getFront()) print("Rear item is:",myQueue.getRear())
4bd049da90d733d69710804afaa9b5352667caf3
DinakarBijili/Data-structures-and-Algorithms
/SORTING AND SEARCHING/7.Majority Element.py
900
4.40625
4
""" Majority Element Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array. Example 1: Input: N = 3 A[] = {1,2,3} Output: -1 Explanation: Since, each element in {1,2,3} appears only once so there is no majority element. Example 2: Input:A[] = {3,1,3,3,2} Output: 3 Explanation: Since, 3 is present more than N/2 times, so it is the majority element. """ def Majority_elements(arr): if not arr: return [] dict = {} for i in arr: if i not in dict: #[3:1, 4:1 , 2:1] dict[i] = 1 else: dict[i] += 1 #[3:2, 4:5 , 2:2] if dict[i] > len(arr)//2: return i return "No Majority Elements" if __name__ == "__main__": arr = [3,1,3,2] res = (Majority_elements(arr)) print(res)
07c39032e44ce00d6df3d3b1306ebb5e0fbb0ce5
DinakarBijili/Data-structures-and-Algorithms
/STRING/Edit Distance.py
1,182
4.0625
4
""" Edit Distance Given two strings s and t. Find the minimum number of operations that need to be performed on str1 to convert it to str2. The possible operations are: Insert Remove Replace Example 1: Input: s = "geek", t = "gesek" Output: 1 Explanation: One operation is required inserting 's' between two 'e's of str1. Example 2: Input : s = "gfg", t = "gfg" Output: 0 Explanation: Both strings are same. """ # def Edit_distance(s, t): # count = 0 # if s == t: # return 0 # if s not in t: # count += 1 # return count # if __name__ == "__main__": # s = "ecfbefdcfca" # t = "badfcbebbf" # print(Edit_distance(s, t)) # output 9 def edit_distance(s1, s2): m=len(s1)+1 n=len(s2)+1 tbl = {} for i in range(m): tbl[i,0]=i for j in range(n): tbl[0,j]=j print(tbl) for i in range(1, m): for j in range(1, n): cost = 0 if s1[i-1] == s2[j-1] else 1 tbl[i,j] = min(tbl[i, j-1]+1, tbl[i-1, j]+1, tbl[i-1, j-1]+cost) return tbl[i,j] if __name__ == "__main__": s = "geek" t = "gesek" print(edit_distance(s, t)) # output 9
a6b70b95e2abd954adf5c0ef7884792630fc1e5e
DinakarBijili/Data-structures-and-Algorithms
/LINKED_LIST/Rotate Doubly linked list by N nodes.py
2,692
4.1875
4
""" Rotate Doubly linked list by N nodes Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. N = 2 Rotated List: Examples: Input : a b c d e N = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d """ class Node: def __init__(self,data): self.data = data self.next = None self.prev = None def set_next(self): return self.next def makeList(data): head = Node(data[0]) for elements in data[1: ]: ptr = head while ptr.next: ptr = ptr.next ptr.next = Node(elements) return head def PrintList(head): nodes = [] ptr = head while ptr: if ptr is head: nodes.append("[Head %s]"%ptr.data) elif ptr.next is None: nodes.append("[Tail %s] ->[None]"%ptr.data) else: nodes.append("[%s]"%ptr.data) ptr = ptr.next print(" -> ".join(nodes)) class Linked_list: def __init__(self): self.head = None def Rotate_LinkedList_of_N_nodes(head, N = 2): if N == 0: return # list = a <-> b <-> c <-> d <-> e. curr = head # current will either point to Nth # or None after this loop. Current # will point to node 'b' count = 1 while count < N and curr != None: curr = curr.next count += 1 # If current is None, N is greater # than or equal to count of nodes # in linked list. Don't change the # list in this case if curr == None: return # current points to Nth node. Store # it in a variable. NthNode points to # node 'b' in the above example Nthnode = curr # current will point to last node # after this loop current will point # to node 'e' while curr.next != None: curr = curr.next curr.next = head # Change prev of Head node to current # Prev of 'a' is now changed to node 'e' head.prev = curr # head is now changed to node 'c' head = Nthnode.next # Change prev of New Head node to None # Because Prev of Head Node in Doubly # linked list is None head.prev = None # change next of Nth node to None # next of 'b' is now None Nthnode.next = None return head if __name__== "__main__": obj = Linked_list() head = makeList(['a','b','c','d','e']) print("Original Linked List: ") PrintList(head) print("\nPairs of Linked List of N=2: ") PrintList(Rotate_LinkedList_of_N_nodes(head))
6fc2e1d949f0bfaa8b60947c38faf8e435a41a73
DinakarBijili/Data-structures-and-Algorithms
/BINARY TREE/1.Level order traversal.py
1,352
4.125
4
""" Level order traversal Given a binary tree, find its level order traversal. Level order traversal of a tree is breadth-first traversal for the tree. Example 1: Input: 1 / \ 3 2 Output:1 3 2 Example 2: Input: 10 / \ 20 30 / \ 40 60 Output:10 20 30 40 60 N N """ class TreeNone: def __init__(self, data, left=None, right = None): self.data = data self.left = left self.right = right def __str__(self): return str(self.data) class Soluation: def Level_order_traversal(self,root): res = [] if root is None: return None queue = [] queue.append(root) while len(queue)>0: node = queue.pop(0) res.append(node.data) if node.left != None: queue.append(node.left) if node.right != None: queue.append(node.right) return res if __name__ == "__main__": obj = Soluation() # node = list(map(int, input().split())) root = TreeNone(10) root.left = TreeNone(20) root.right = TreeNone(30) root.left.left = TreeNone(40) root.left.right = TreeNone(50) ans = obj.Level_order_traversal(root) print(ans)
1c32e5e226de7d4f2d1e3711911554730b406f9a
DinakarBijili/Data-structures-and-Algorithms
/LINKED_LIST/Check if Linked List is Palindrome.py
2,064
4.21875
4
""" Check if Linked List is Palindrome Given a singly linked list of size N of integers. The task is to check if the given linked list is palindrome or not. Example 1: Input: N = 3 value[] = {1,2,1} Output: 1 Explanation: The given linked list is 1 2 1 , which is a palindrome and Hence, the output is 1. Example 2: Input: N = 4 value[] = {1,2,3,4} Output: 0 Explanation: The given linked list is 1 2 3 4 , which is not a palindrome and Hence, the output is 0. """ class Node: def __init__(self, data ): self.data = data self.next = None def makeList(data): head = Node(data[0]) for elements in data[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = Node(elements) return head def PrintList(head): nodes = [] ptr = head while ptr: if ptr is head: nodes.append("[Head %s]"%ptr.data) elif ptr is None: nodes.append("[Tail %s] -> [None]]"%ptr.data) else: nodes.append("[%s]"%ptr.data) ptr = ptr.next print (" -> ".join(nodes)) class Linked_list: def __init__(self): self.head = None def Check_Palindrome(list): ptr = list stack = [] isplaindrome = True while ptr != None: stack.append(ptr.data) # Storing Data ptr = ptr.next # move while list != None: i = stack.pop() # pop data from stack and add to i if list.data == i: #if first and last is equal stack values store in i then stack become empty isplaindrome = True else: isplaindrome = False # else if first and last is not same then the list.data is not equal then stop break list = list.next return isplaindrome if __name__ == "__main__": obj = Linked_list() list = makeList([5, 1, 1 ,5, 4, 3, 2, 3, 3, 3, 3 ,3, 2, 2, 1, 2, 2, 1, 5, 5, 5, 1, 5, 2, 3, 3, 2, 2, 1, 5, 3, 3, 2, 3, 4, 2, 1, 2, 4, 5]) result = Check_Palindrome(list) print(result)
af1eae902cacf9c3bbf7f609e763f01dc286edf0
DinakarBijili/Data-structures-and-Algorithms
/BINARY TREE/8.Postorder Tree Traversal – Iterative and Recursive.py
3,014
4.0625
4
""" Postorder Tree Traversal – Iterative and Recursive Construct the following tree 1 / \ / \ 2 3 / / \ / / \ 4 5 6 / \ / \ 7 8 output:4 2 7 8 5 6 3 1 """ class TreeNode: def __init__(self,data): self.data = data self.left = None self.right = None def getData(self): return self.data def getLeft(self): return self.left def getRight(self): return self.right def Postorder_Traversal(Tree): if not Tree: return if Tree: Postorder_Traversal(Tree.getLeft()) Postorder_Traversal(Tree.getRight()) print(Tree.getData(),end=" ") return if __name__ == "__main__": """ 1 / \ / \ 2 3 / / \ / / \ 4 5 6 / \ / \ 7 8 """ root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.right.left = TreeNode(5) root.right.right = TreeNode(6) root.right.left.left = TreeNode(7) root.right.left.right = TreeNode(8) print("Postorder Traversal: ") Postorder_Traversal(root) # #Iterative method # from collections import deque # # Data structure to store a binary tree node # class Node: # def __init__(self, data=None, left=None, right=None): # self.data = data # self.left = left # self.right = right # # Iterative function to perform postorder traversal on the tree # def postorderIterative(root): # # create an empty stack and push the root node # stack = deque() # stack.append(root) # # create another stack to store postorder traversal # out = deque() # # loop till stack is empty # while stack: # # pop a node from the stack and push the data into the output stack # curr = stack.pop() # out.append(curr.data) # # push the left and right child of the popped node into the stack # if curr.left: # stack.append(curr.left) # if curr.right: # stack.append(curr.right) # # print postorder traversal # while out: # print(out.pop(), end=' ') # if __name__ == '__main__': # """ Construct the following tree # 1 # / \ # / \ # 2 3 # / / \ # / / \ # 4 5 6 # / \ # / \ # 7 8 # """ # root = Node(1) # root.left = Node(2) # root.right = Node(3) # root.left.left = Node(4) # root.right.left = Node(5) # root.right.right = Node(6) # root.right.left.left = Node(7) # root.right.left.right = Node(8) # postorderIterative(root)
dcd5db7c301734d0b7406153043d6e89ece94997
DinakarBijili/Data-structures-and-Algorithms
/LINKED_LIST/Reverse a Linked List in groups of given size.py
2,665
4.3125
4
""" Reverse a Linked List in groups of given size Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list. Example 1: Input: LinkedList: 1->2->2->4->5->6->7->8 K = 4 Output: 4 2 2 1 8 7 6 5 Explanation: The first 4 elements 1,2,2,4 are reversed first and then the next 4 elements 5,6,7,8. Hence, the resultant linked list is 4->2->2->1->8->7->6->5. Example 2: Input: LinkedList: 1->2->3->4->5 K = 3 Output: 3 2 1 5 4 Explanation: The first 3 elements are 1,2,3 are reversed first and then elements 4,5 are reversed.Hence, the resultant linked list is 3->2->1->5->4. Your Task: You don't need to read input or print anything. Your task is to complete the function reverse() which should reverse the linked list in group of size k and return the head of the modified linked list. """ class Node: def __init__(self, data): self.data = data self.next = None def makelist(data): head = Node(data[0]) for elements in data[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = Node(elements) return head def printlist(head): nodes = [] ptr = head while ptr: if ptr is head: nodes.append("[Head: %s]"%ptr.data) elif ptr.next is None: nodes.append("[Tail: %s] -> [None]"%ptr.data) else: nodes.append("[%s]"%ptr.data) ptr = ptr.next print(" -> ".join(nodes)) class Linked_list: def __init__(self): self.head = None def reverse_of_size(self, head, k=4): new_stack = [] prev = None current = head while (current != None): val = 0 while (current != None and val < k): # if val is < 4 new_stack.append(current.data) # adding to new_stack current = current.next # current increase to next val+=1 # val also increase by 1 thround next # Now pop the elements of stack one by one while new_stack: # If final list has not been started yet. if prev is None: prev = Node(new_stack.pop()) head = prev else: prev.next = Node(new_stack.pop()) prev = prev.next prev.next = None return head if __name__ == "__main__": obj = Linked_list() list1 = makelist([1,2,2,4,5,6,7,8]) print("Original Linked_List: ") printlist(list1) print("\n Reverse Linked_List of Size K: ") printlist(obj.reverse_of_size(list1))
34da084f0c7ec038a9502cf05bfeb9d56baca684
DinakarBijili/Data-structures-and-Algorithms
/ARRAY/Palindromic Array.py
431
3.75
4
""" Example: Input: 2 5 111 222 333 444 555 3 121 131 20 Output: 1 0 """ def palindromic(arr, n): rev = (arr[::-1]) if rev == arr: return True else: return False if __name__ == "__main__": t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int,input().split())) if palindromic(arr, n): print(1) else: print(0)
da2f6f83dca1a4776eba5777e39cb41676e29f2a
DinakarBijili/Data-structures-and-Algorithms
/ARRAY/4.Sort_arr-of_0s,1s,and,2s.without_using_any_sortMethod.py
971
4.375
4
# Sort an array of 0s, 1s and 2s # Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order. # Example 1: # Input: # N = 5 # arr[]= {0 2 1 2 0} # Output: # 0 0 1 2 2 # Explanation: # 0s 1s and 2s are segregated # into ascending order. # Example 2: # Input: # N = 3 # arr[] = {0 1 0} # Output: # 0 0 1 # Explanation: # 0s 1s and 2s are segregated # into ascending order. def quick_sort(arr): if len(arr) <= 1: return arr less_than_pivot = [] greater_than_pivot = [] pivot = arr[0] #first index for value in arr[1:]: if value <= pivot: less_than_pivot.append(value) else: greater_than_pivot.append(value) print("%15s %1s %15s"% (less_than_pivot,pivot,greater_than_pivot)) return quick_sort(less_than_pivot)+[pivot]+quick_sort(greater_than_pivot) if __name__ == "__main__": arr = [4,6,3,2,9,7,3,5] print(arr) result = quick_sort(arr) print(result)
11960b0f8caeafeda8c4cffcfa4d90bf087ad4bd
DinakarBijili/Data-structures-and-Algorithms
/BINARY TREE/5.Create a mirror tree from the given binary tree.py
1,605
4.375
4
""" Create a mirror tree from the given binary tree Given a binary tree, the task is to create a new binary tree which is a mirror image of the given binary tree. Examples: Input: 5 / \ 3 6 / \ 2 4 Output: Inorder of original tree: 2 3 4 5 6 Inorder of mirror tree: 6 5 4 3 2 Mirror tree will be: 5 / \ 6 3 / \ 4 2 Input: 2 / \ 1 8 / \ 12 9 Output: Inorder of original tree: 12 1 2 8 9 Inorder of mirror tree: 9 8 2 1 12 """ class TreeNode: def __init__(self,data): self.data = data self.left = None self.right = None def getData(self): return self.data def getLeft(self): return self.left def getRight(self): return self.right def inorder(root): if not root: return if root: inorder(root.getLeft()) print(root.getData(),end=" ") inorder(root.getRight()) return def convertToMirror(root): if not root: return if root: convertToMirror(root.getRight()) print(root.getData(), end=" ") convertToMirror(root.getLeft()) return if __name__ == "__main__": ''' Construct the following tree 5 / \ 3 6 / \ 2 4 ''' root = TreeNode(5) root.left = TreeNode(3) root.right = TreeNode(6) root.left.left = TreeNode(2) root.left.right = TreeNode(4) print("Inorder Traversal: ") inorder(root) print("\nMirror of Inorder Traversal: ") convertToMirror(root)
1c01d4fdc49e7addb4a02b1e32959abfb4df5377
GBXXI/LucidProgramming
/Algorithms/Look_n_Say_Sequence.py
1,326
3.90625
4
# %% [markdown] # ## String Processing: Look and Say Sequence.<br> # The sequence starts with the number 1:<br> #                1<br> # We then say how many of each integer exists in the sequence to # generate the next term.<br> # For instance, there is "one 1". This gives the next term:<br> #                1<br> #                11<br> #                21<br> #                12 11<br> #                11 12 21<br> #                31 22 11<br> #                13 11 22 21<br> # More information on:<br> # <link>https://en.wikipedia.org/wiki/Look-and-say_sequence</link> # %% [codecell] def lns_seq(seq): occ_list = [] i = 0 while i < len(seq): count = 1 while i + 1 < len(seq) and seq[i] == seq[i+1]: i += 1 count += 1 occ_list.append(str(count)+seq[i]) i += 1 return "".join(occ_list) # %% [codecell] def first_elem_rept(first_element, repetition): s = first_element for _ in range(repetition-1): s = lns_seq(s) # print(f'{str(first_element)} + {s}') return print(s) # %% [codecell] if __name__ == "__main__": s = "1211" first_elem_rept("d", 5)
fc8c3b2a5970f408d17c0f2b89be8add746f63f4
pronyushkin/learn1
/l1l2/test2.py
2,328
3.90625
4
'''Еще набор тестовых заданий с интенсива.''' from math import sqrt def do_nothing(): '''Делаем ничего, возвращаем ничто.''' return None def test_info(): '''Тест работа со словарем.''' user_info = {'first_name':'fn', 'last_name':'ln'} print(user_info['first_name'], user_info['last_name']) print('словарь: ', user_info) user_info['first_name'] = input('введите имя: ') user_info['last_name'] = input('введите фамилию: ') print('имя: ', user_info['first_name']) print('фамилия: ', user_info['last_name']) print('словарь: ', user_info) def interact_sqrt(): '''Задание решение квадратного уравнения.''' print('решение квадратного уравнения') ratio_a = int(input('введите коэффициетн A:')) ratio_b = int(input('введите коэффициетн B:')) ratio_c = int(input('введите коэффициетн C:')) compute_sqrt(ratio_a, ratio_b, ratio_c) def compute_sqrt(ratio_a, ratio_b, ratio_c): '''Решение квадратного уравнения.''' if ratio_a == 0: print('x = ', -ratio_c/ratio_b) else: the_discriminant = ratio_b * ratio_b - 4 * ratio_a * ratio_c if the_discriminant < 0: print('нет действительных корней') elif the_discriminant == 0: print('x = ', -ratio_b/(2*ratio_a)) else: print('x1 = ', (-ratio_b + sqrt(the_discriminant)) /(2*ratio_a)) print('x1 = ', (-ratio_b - sqrt(the_discriminant)) /(2*ratio_a)) def get_ans(ans_dict, user_in, defans): '''Ответ по словарю.''' return ans_dict.get(user_in, defans) def interact_ans(): '''Консольный бот.''' rep_dict = {'привет':'И тебе привет!', 'как дела': 'лучше всех', 'пока':'увидимся'} user_in = '' while True: user_in = input(':') user_in = user_in.lower() print(get_ans(rep_dict, user_in, 'даже не знаю')) if user_in == 'пока': return if __name__ == '__main__': interact_ans()
1665a5752794a64a0de7e505e172a814c9b32e8f
andrewsanc/pythonFunctionalProgramming
/exerciseLambda.py
282
4.15625
4
''' Python Jupyter - Exercise: Lambda expressions. ''' # Using Lambda, return squared numbers. #%% nums = [5,4,3] print(list(map(lambda num: num**2, nums))) # List sorting. Sort by the second element. #%% a = [(0,2), (4,3), (9,9), (10,-1)] a.sort(key=lambda x: x[1]) print(a) #%%
3ee8c523fd80d72e388a4fe972ea834745909b28
andrewsanc/pythonFunctionalProgramming
/lambda.py
427
3.875
4
''' Python Jupyter - Lambda. Lambda expressions are one time anonymous functions. lambda param: action(param) ''' #%% myList = [1,2,3,4] print(list(map(lambda item: item*2, myList))) print(myList) #%% words = ['alcazar', 'luci', 'duncan', 'sam'] print(list(map(lambda name: name.title(), words))) #%% from functools import reduce myList = [1,2,3,4] print(reduce(lambda acc, item: acc+item, myList)) #%%
4717d68b14a296bc895da87ff083cb2db711e551
vik407/holbertonschool-interview
/0x10-rain/0-rain.py
538
3.625
4
#!/usr/bin/python3 """ 0_rain.py """ def rain(walls): """ Return rainwater trapped with array of wall heights. """ i, j = 0, len(walls) - 1 lmax = rmax = res = 0 while i < j: if walls[j] > walls[i]: if walls[i] > lmax: lmax = walls[i] else: res += lmax - walls[i] i += 1 else: if walls[j] > rmax: rmax = walls[j] else: res += rmax - walls[j] j -= 1 return res