blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
03cf74ca321ee100a1efcd1028cd59d0a7b56449
JoseCordobaEAN/ProgramacionEAN20191
/semana_17/Fruta.py
1,670
4.1875
4
class Fruta: sabor = '' cantidad = 0 pelada = False __TIPOS__ = {'banano': [5, 100], 'manzana': [6, 50], 'pera': [5, 70], 'piña': [60, 1500], 'papaya': [130, 2200] } def __init__(self, sabor, cantidad): """ Crea una nueva fruta :param sabor: cadena con el tipo de fruta :param cantidad: La cantidad de fruta en inventario """ self.sabor = sabor if sabor in self.__TIPOS__ else 'banano' self.cantidad = cantidad def pelar(self): """ Pela la fruta si no esta pelada :return: El estado de la fruta """ if not self.pelada: self.pelada = True return self.pelada raise ValueError('La fruta ya esta pelada') def cortar(self, cantidad_usar): ''' Corta la fruta si esta pelada, retorna la cantidad de fruta pelada :param cantidad_usar: la cantidad de fruta a usar :return: la cantidad obtenida para esa fruta ''' if self.pelada: return cantidad_usar * self.__TIPOS__[self.sabor][0] else: raise ValueError('La fruta no esta pelada') def licuar(self, cantidad_usar): """ licua la fruta si esta pelada, retorna la cantidad de fruta pelada :param cantidad_usar: la cantidad de fruta a usar :return: la cantidad de zumo obtenida para esa fruta """ if self.pelada: return cantidad_usar * self.__TIPOS__[self.sabor][1] else: raise ValueError('La fruta no esta pelada')
7c6de1a61795f5db82a9d779308299a49ec4296b
CodeThales/Blue_Ed_Tech_Python
/Aula 06 - Funções - Parte1/Ex04.py
670
3.96875
4
#Faça um programa que calcule o salário de um colaborador na empresa XYZ. #O salário é pago conforme a quantidade de horas trabalhadas. # Quando um funcionário trabalha mais de 40 horas ele recebe um adicional # de 1.5 nas horas extras trabalhadas. def salario(horas,valor_hora): if horas > 40: h_extra = (horas - 40) * 1.5 pgto = (horas *valor_hora) + h_extra else: pgto = horas * valor_hora return pgto horas = float(input(f'Quantas horas foram trabalhadas: ')) valor_hora = float(input(f'Digite o valor da hora trabalhada: ')) pgto = salario(horas,valor_hora) print(f'O pagamento será de R${pgto:.2f}')
1dfb293002adb33e9ab64aa04b2c13d147501cc2
hakank/hakank
/cpmpy/four_numbers.py
2,040
3.53125
4
""" Four number problem in cpmpy. From http://stackoverflow.com/questions/17720465/given-4-numbers-of-array-of-1-to-10-elements-find-3-numbers-whose-sum-can-gener 'Given 4 numbers of array of 1 to 10 elements. Find 3 numbers whose sum can generate all the four numbers?' ''' I am given an array containing a list of 4 random numbers (1 to 10 inclusive). I am supposed to generate a list of 3 numbers (1 to 10 inclusive) so that I can generate all the 4 numbers of the initial list by adding the 3 numbers of the generated list. Someone Please provide an algorithm for doing this. ''' For the problem instance mentioned in a comment [1,3,7,8], there are 5 solutions: r: [1, 3, 7, 8] x: [1, 3, 4] ---------- r: [1, 3, 7, 8] x: [1, 2, 5] ---------- r: [1, 3, 7, 8] x: [1, 2, 6] ---------- r: [1, 3, 7, 8] x: [1, 2, 7] ---------- r: [1, 3, 7, 8] x: [1, 3, 7] Model created by Hakan Kjellerstrand, hakank@hakank.com See also my cpmpy page: http://www.hakank.org/cpmpy/ """ import sys,math import numpy as np from cpmpy import * from cpmpy.solvers import * from cpmpy_hakank import * from itertools import combinations def rand_nums(max_n,max_val): """ returns a list of atmost n values in 1..max_val """ return np.unique(np.random.randint(1,max_val,max_n)) def four_numbers(nums,n,max_val=10,num_sols=0): print("nums:",nums) print("n:",n) m = len(nums) x = intvar(1,max_val,shape=n,name="x") # coefficient matrix tmp = boolvar(shape=(m,n),name="tmp") model = Model() for i in range(m): model += [sum([tmp[i,j]*x[j] for j in range(n)]) == nums[i]] model += [increasing(x)] ss = CPM_ortools(model) num_solutions = ss.solveAll(solution_limit=num_sols,display=x) print("number of solutions:", num_solutions) print() num_sols = 0 nums = [1,3,7,8] n = 3 four_numbers(nums,n,10,num_sols) print("\nSome random cases:") num_sols = 10 for i in range(10): nums = rand_nums(7,10) n = min([3,len(nums)-1]) four_numbers(nums,n,10,num_sols)
129c52f7ce8972ed3ce5a1a340c297956b9529af
Frankyyoung24/SequencingDataScientist
/Algrithms/week4/brute_force.py
553
3.828125
4
import itertools as it from overlap import overlap def scs(ss): # ss means the set of strings shortest_sup = None # the permutations function is very useful for ssperm in it.permutations(ss): sup = ssperm[0] for i in range(len(ss) - 1): olen = overlap(ssperm[i], ssperm[i + 1], min_length=1) # add the suffix from the overlap length to the end sup += ssperm[i + 1][olen:] if shortest_sup is None or len(sup) < len(shortest_sup): shortest_sup = sup return shortest_sup
e623a3ad436693c332544633e53eb2561daefa41
aepuripraveenkumar/Data-structures-and-algorithms-in-python-by-michael-goodrich
/R-1.6.py
238
4.3125
4
'''Python code to find sum of odd positive integers''' def sum_of_squares_of_odd_positive_integers(n): return sum((i*i) for i in range(1,n,2) if(n>=0)) if __name__=='__main__': print(sum_of_squares_of_odd_positive_integers(5))
674f03b064431907392afc619fba103c325294fa
biobeth/snake_club
/resources/5.functions_and_imports/is even.py
102
3.59375
4
def is_even(n): if n/2 == True: print True else: print False is_even(6)
4cff30390fb7234047e592f02cfbe0d9f7045f4f
OneGuyy/python-syntaxes
/LISTS.py
772
3.75
4
import random import sys import os grocery_list = ['Juice', 'Tomatoes', 'Apples', 'Eggs'] print('First Item is', grocery_list[0]) grocery_list[0] = "Soda" print('First Item is', grocery_list[0]) print(grocery_list[1:3]) other_events = ['Wash Car', 'Cash Check', 'City Tour'] to_do_list = [other_events, grocery_list] print(to_do_list) print((to_do_list[1][3])) grocery_list.append('Candy') print(to_do_list) grocery_list.insert(1, 'Video Games') print(to_do_list) grocery_list.remove("Video Games") grocery_list.sort() grocery_list.reverse() print(grocery_list) del grocery_list[4] print(grocery_list) to_do_list2 = other_events + grocery_list print(len(to_do_list2)) print(min(to_do_list2)) print(max(to_do_list2))
a50a50425a1c92f9105e9e0b4ffffee4053d1087
manjot-baj/My_Python_Django
/Python Programs/Decorators_5.py
500
3.703125
4
from functools import wraps def only_int_allow(Function): def wrapper(*args, **kwargs): Data_types = [] for arg in args: Data_types.append(type(arg) == int) if all(Data_types): return Function(*args, **kwargs) else: return "Invalid input" return wrapper @only_int_allow def add_all(*args): total = 0 for i in args: total += i return total list1 = [i for i in range(1, 11)] print(add_all(1, 2, 3))
41dcf1fc27367972330271aa33d0ac791457e69c
ErmantrautJoel/Python
/Buscar en lista.py
320
3.796875
4
def buscarenlista(): n = int(input("Digame la cantidad de palabras:")) lista = [] for nn in range(1,n+1): print ("Digame la palabra",nn,":",end=" ") n2 = input() lista += [n2] s = input("Digame la palabra a buscar:") n = lista.count(s) print ("La palabra",s,"aparece",n,"veces") buscarenlista()
ad45e9398df0da8ae425c9ebf788781893622399
xCrypt0r/Baekjoon
/src/9/9366.py
552
3.546875
4
""" 9366. 삼각형 분류 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 68 ms 해결 날짜: 2020년 9월 23일 """ import sys def main(): for i in range(1, int(input()) + 1): A, B, C = sorted(map(int, sys.stdin.readline().split())) if A + B <= C: print(f'Case #{i}: invalid!') else: res = 'equilateral' if A == B == C else ('isosceles' if A == B or B == C or C == A else 'scalene') print(f'Case #{i}: {res}') if __name__ == '__main__': main()
0ba28f868a736f6d4321a43a69f91a6f22cfe4aa
Shehaab/CodeSignal
/FindEmailDomain.py
252
3.65625
4
import re def findEmailDomain(address): """Return the legitimate domain part of an Email address""" # Find @ sign, then one or more alphanumeric character, then one or more dots. return re.search("@[\w].+",address).group()[1:]
f33d7c318e22be05e8b33b60613b9fb4356fe9a1
rudasi/euler
/euler15.py
630
3.765625
4
factorial_hash = {} def factorial(n): if (n in factorial_hash.keys()): return factorial_hash[n] elif (n == 0 or n == 1): factorial_hash[n] = 1 return 1 else: val = factorial(n-1) * n factorial_hash[n] = val return val def combinations(a,b): return (factorial_hash[a]/(factorial_hash[b] * factorial_hash[a-b])) if __name__ == "__main__": coefficients = [] answer = 0 for i in range(0,21): factorial(i) for i in range(0,21): coefficients.append(combinations(20,i)) for i in coefficients: answer += i*i print answer
c22d96e5287b81135c7e627afe67c0b82ae8ca0a
Lenferd/deep-learning-course
/Lab 1/tests.py
1,864
3.609375
4
import unittest import numpy as np class TestNumpy(unittest.TestCase): def test_generate_array(self): arr = np.array([2, 2], float) print("test_generate_array\n {}".format(arr)) def test_matrix_not_rec_creation(self): matrix = np.matrix([[1, 2], [3, 4]]) print("test_matrix_not_rec_creation\n {}".format(matrix)) def test_matrix_rec_creation(self): matrix = np.array([[1, 2], [3, 4]]) print("test_matrix_rec_creation\n {}".format(matrix)) def test_transpose(self): matrix = np.array([[1, 2], [3, 4]]) print("test_transpose\n {} \n {}".format(matrix, matrix.T)) def test_permutation(self): number = 10 # Permutation for numbers from 0 to 10 permutation = np.random.permutation(number) print("test_permutation\n {} \n {}".format(number, permutation)) def test_random_array_float(self): arr = np.random.rand(2) print("test_random_array_float\n {}".format(arr)) def test_random_array_int(self): max = 10 size = 2 arr = np.random.randint(max, size=size) print("test_random_array_int\n {}".format(arr)) def test_shuffle_array(self): size = 10 arr = np.random.randint(10, size=size) permutation = np.random.permutation(size) # This is for ndarray. # Because there we have 2 dimensional array, and we shuffle only second one (columns for example) # shuffled_arr = arr[:, permutation] shuffled_arr = arr[permutation] print("test_shuffle_array\n {} \n {}".format(arr, shuffled_arr)) def test_matmul(self): a = np.array([[1, 0], [0, 1]]) b = np.array([[4, 1], [2, 2]]) print("test_shuffle_array\n {} \n {}".format(np.matmul(a, b), np.matmul(b, a))) if __name__ == '__main__': unittest.main()
ff4071d28e245e705aece238b955e94c95dd502a
sakshirits/python-automation-scripts
/collatzSequence.py
352
4.0625
4
def collatz(n): if n%2==0: return n//2 else: return 3*n+1 def main(): try: n=int(input("Enter the number:")) d=n while True: val = collatz(d) print(val) d = val if val == 1: break except ValueError: print(" You must enter an integer.") main()
917f79b4b2b5c9b02e1b7e8831d0b4310828dd5c
suziW/KBQA
/porg.py
708
3.640625
4
import argparse parser = argparse.ArgumentParser(description='search related things(movie,music or book) you might wanna know') parser.add_argument('input', type = str, help = 'input what u wanna search') parser.add_argument('-s','--specify_search', type = str, choices=['movie', 'music', 'book'], help = 'specify a search type') args = parser.parse_args() search_result = args.input if args.specify_search == 'movie': print(search_result, args.specify_search) elif args.specify_search == 'music': print(search_result, args.specify_search) elif args.specify_search == 'book': print(search_result, args.specify_search) else: print(search_result, "all")
1020fb02ec9bd90e946e3d1d8ce4467a3bce273a
NavneetKourSidhu/Python
/basics/armstrong.py
218
4.125
4
number = int(input('number: ')) sum = 0 temp = number while temp > 0: cube = temp % 10 sum += cube**3 temp //= 10 if number == sum: print('armstrong number') else: print('not a armstrong number')
c8e0c3526115aec4ae205ac77db4de6750de6723
nedbat/blogtools
/PathGlob.py
1,468
3.5625
4
""" Filename globbing utility. """ import os import fnmatch import re __all__ = ["glob"] def glob(pathname, deep=0): """ Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. """ result = [] if not hasMagic(pathname): if os.path.exists(pathname): result = [pathname] else: dirname, basename = os.path.split(pathname) if not dirname: result = globInDir(os.curdir, basename) else: if hasMagic(dirname): dirs = glob(dirname, deep) else: dirs = [dirname] if not hasMagic(basename): for dirname in dirs: if basename or os.path.isdir(dirname): name = os.path.join(dirname, basename) if os.path.exists(name): result.append(name) else: for dirname in dirs: sublist = globInDir(dirname, basename) for name in sublist: result.append(os.path.join(dirname, name)) return result def globInDir(dirname, pattern): try: names = os.listdir(dirname or os.curdir) except os.error: return [] return fnmatch.filter(names,pattern) magicCheck = re.compile('[*?[]') def hasMagic(s): return magicCheck.search(s) is not None
b516a195c118762d2a8506588b92833857eb88a4
dsbatov/PythonHSE
/lesson1.py
192
3.90625
4
number = int(input()) print("Следующее за " + str(number) + " число: " + str(number + 1)) print("Предыдущее до " + str(number) + " число: " + str(number - 1))
88698e0b3841c45d1661dd69e99864b7b658d9c8
kiyohiro8/Lombardia
/control.py
18,301
3.609375
4
#ゲームの操作に関する関数をここに格納 #捨て札を山札に混ぜて切り直す関数 def reshuffle(library, graveyard): import random while len(graveyard) > 0: library.append(graveyard.pop()) random.shuffle(library) #一般ドロー関数の定義 def general_draw(player, opponent, library, graveyard): from AI import draw_priority #公開される3枚のカード open_card = [] if len(library) >= 3: for i in range(3): open_card.append(library.pop()) else: while len(library) > 0: open_card.append(library.pop()) reshuffle(library, graveyard) for i in range(3-len(open_card)): open_card.append(library.pop()) if player.ptype == "human": print(player.hand) print("%sの手札" %player.name) print(open_card) print("公開されたカード") check = 0 while check == 0: card = input("手札に加えるカードを選んでください\n") if card in open_card: check = 1 player.hand.append(card) open_card.remove(card) else: print("公開されたカードの中に%sはありません\n" %card) else: card = draw_priority(open_card, player, opponent, library, graveyard) player.hand.append(card) open_card.remove(card) if opponent.ptype == "human": print(opponent.hand) print("%sの手札" %opponent.name) print(open_card) print("公開されたカード") check = 0 while check == 0: card = input("手札に加えるカードを選んでください\n") if card in open_card: check = 1 opponent.hand.append(card) open_card.remove(card) graveyard.extend(open_card) else: print("公開されたカードの中に%sはありません\n" %card) else: card = draw_priority(open_card, opponent, player, library, graveyard) opponent.hand.append(card) open_card.remove(card) graveyard.extend(open_card) #王子3枚の公開 def three_prince(player, opponent, library, graveyard): print("%sは3枚の王子を公開しました(勝利)" %player.name) player.point += 10 #司教4枚の公開 def four_bishop(player, opponent, library, graveyard): print("%sは4枚の司教を公開しました(2点)" %player.name) player.point += 2 player.reveal = 1 #司教3枚の公開 def three_bishop(player, opponent, library, graveyard): print("%sは3枚の司教を公開しました(1点)" %player.name) player.point += 1 player.reveal = 1 #司教3枚と王子2枚の公開 def three_bishop_two_prince(player, opponent, library, graveyard): print("%sは3枚の司教と2枚の王子を公開しました(2点)" %player.name) player.point += 2 player.reveal = 1 #司教2枚と王子2枚の公開 def two_bishop_two_prince(player, opponent, library, graveyard): print("%sは2枚の司教と2枚の王子を公開しました(1点)" %player.name) player.point += 1 player.reveal = 1 #貴族n枚捨て def discard_noble(player, opponent, library, graveyard, number): print("%sは%i枚の貴族を捨てました(%i点)" %(player.name, number, number-1)) player.point += number - 1 for i in range(number): player.hand.remove("貴族") graveyard.append("貴族") #貴族n枚と王子2枚捨て def discard_noble_two_prince(player, opponent, library, graveyard, number): print("%sは%i枚の貴族と2枚の王子を捨てました(%i点)" %(player.name, number, number)) player.point += number - 1 for i in range(2): player.hand.remove("王子") graveyard.append("王子") for i in range(number): player.hand.remove("貴族") graveyard.append("貴族") #騎士3枚捨てて攻撃 def discard_three_knight(player, opponent, library, graveyard): from AI import block_tend print("%sは3枚の騎士を捨てて攻撃しました" %player.name) for i in range(3): player.hand.remove("騎士") graveyard.append("騎士") attack_success = True if opponent.ptype == "human": if opponent.hand.count("騎士") >= 2: if opponent.hand.count("王子") >= 2: block = input("防御しますか? 0.騎士2枚で防御 1.騎士1枚と王子2枚で防御 2.防御しない") if block == "0": for i in range(2): opponent.hand.remove("騎士") graveyard.append("騎士") attack_success = False print("%sは騎士2枚を捨てて防御しました" %opponent.name) elif block == "1": opponent.hand.remove("騎士") graveyard.append("騎士") for i in range(2): opponent.hand.remove("王子") graveyard.append("王子") attack_success = False print("%sは騎士1枚と王子2枚を捨てて防御しました" %opponent.name) else: pass else: block = input("防御しますか? 0.騎士2枚で防御 1.防御しない") if block == "0": for i in range(2): opponent.hand.remove("騎士") graveyard.append("騎士") attack_success = False print("%sは騎士2枚を捨てて防御しました" %opponent.name) else: pass elif opponent.hand.count("騎士") == 1 and opponent.hand.count("王子") >= 2: block = input("防御しますか? 0.騎士1枚と王子2枚で防御 1.防御しない") if block == "0": opponent.hand.remove("騎士") graveyard.append("騎士") for i in range(2): opponent.hand.remove("王子") graveyard.append("王子") attack_success = False print("%sは騎士1枚と王子2枚を捨てて防御しました" %opponent.name) else: pass else: pass else: if opponent.hand.count("騎士") >= 2: block = block_tend(opponent, player, library, graveyard) if block == 0: for i in range(2): opponent.hand.remove("騎士") graveyard.append("騎士") attack_success = False print("%sは騎士2枚を捨てて防御しました" %opponent.name) else: pass elif opponent.hand.count("騎士") == 1 and opponent.hand.count("王子") >= 2: block = block_tend(opponent, player, library, graveyard) if block == 0: opponent.hand.remove("騎士") graveyard.append("騎士") for i in range(2): opponent.hand.remove("王子") graveyard.append("王子") attack_success = False print("%sは騎士1枚と王子2枚を捨てて防御しました" %opponent.name) else: pass if attack_success == True: if player.ptype == "human": check = 0 while check == 0: print(opponent.hand) discard_type = input("どのカードを捨てさせますか?\n") if discard_type in opponent.hand: player.point += min(opponent.point, opponent.hand.count(discard_type)) opponent.point -= min(opponent.point, opponent.hand.count(discard_type)) for i in range(opponent.hand.count(discard_type)): opponent.hand.remove(discard_type) graveyard.append(discard_type) check = 1 else: print("手札にあるカードの中から選んでください。\n") else: discard_type = attack_priority(player, opponent, library, graveyard) player.point += min(opponent.point, opponent.hand.count(discard_type)) opponent.point -= min(opponent.point, opponent.hand.count(discard_type)) for i in range(opponent.hand.count(discard_type)): opponent.hand.remove(discard_type) graveyard.append(discard_type) else: pass #騎士2枚王子2枚捨てて攻撃 def discard_two_knight_two_prince(player, opponent, library, graveyard): from AI import block_tend print("%sは騎士2枚と王子2枚を捨てて攻撃しました" %player.name) for i in range(2): player.hand.remove("騎士") graveyard.append("騎士") player.hand.remove("王子") graveyard.append("王子") attack_success = True if opponent.ptype == "human": if opponent.hand.count("騎士") >= 2: block = input("防御しますか? 0.騎士2枚で防御 1.防御しない") if block == "0": for i in range(2): opponent.hand.remove("騎士") graveyard.append("騎士") attack_success = False print("%sは騎士2枚を捨てて防御しました" %opponent.name) else: pass else: pass else: if opponent.hand.count("騎士") >= 2: block = block_tend(opponent, player, library, graveyard) if block == "0": for i in range(2): opponent.hand.remove("騎士") graveyard.append("騎士") attack_success = False print("%sは騎士2枚を捨てて防御しました" %opponent.name) else: pass if attack_success == True: if player.ptype == "human": check = 0 while check == 0: print(opponent.hand) discard_type = input("どのカードを捨てさせますか?\n") if discard_type in opponent.hand: player.point += min(opponent.point, opponent.hand.count(discard_type)) opponent.point -= min(opponent.point, opponent.hand.count(discard_type)) for i in range(opponent.hand.count(discard_type)): opponent.hand.remove(discard_type) graveyard.append(discard_type) check = 1 else: print("手札にあるカードの中から選んでください。\n") else: discard_type = attack_priority(player, opponent, library, graveyard) player.point += min(opponent.point, opponent.hand.count(discard_type)) opponent.point -= min(opponent.point, opponent.hand.count(discard_type)) for i in range(opponent.hand.count(discard_type)): opponent.hand.remove(discard_type) graveyard.append(discard_type) else: pass #手札を見てできる行動を提示する関数 def action_preview(player,action_list): action_list.append("0. ターンを終了する。\n") if player.hand.count("王子") == 3: action_list.append("1. 王子3枚を公開して勝利する。\n") elif player.hand.count("王子") == 2: if player.hand.count("司教") >= 3 and player.reveal == 0: action_list.append("2. 司教3枚と王子2枚を公開して2点を得る。\n") action_list.append("3. 司教2枚と王子2枚を公開して1点を得る。\n") elif player.hand.count("司教") == 2: action_list.append("3. 司教2枚と王子2枚を公開して1点を得る。\n") else: pass if player.hand.count("騎士") >= 2: action_list.append("4. 騎士2枚と王子2枚を捨て、相手を攻撃する\n") else: pass if player.hand.count("貴族") >= 3: action_list.append("5. 貴族3枚と王子2枚を捨て、3点を得る。\n") action_list.append("6. 貴族2枚と王子2枚を捨て、2点を得る。\n") action_list.append("7. 貴族1枚と王子2枚を捨て、1点を得る。\n") elif player.hand.count("貴族") == 2: action_list.append("6. 貴族2枚と王子2枚を捨て、2点を得る。\n") action_list.append("7. 貴族1枚と王子2枚を捨て、1点を得る。\n") elif player.hand.count("貴族") == 1: action_list.append("7. 貴族1枚と王子2枚を捨て、1点を得る。\n") else: pass else: pass if player.hand.count("司教") >= 4 and player.reveal == 0: action_list.append("8. 司教4枚を公開して2点を得る。\n") action_list.append("9. 司教3枚を公開して1点を得る。\n") elif player.hand.count("司教") == 3: action_list.append("9. 司教3枚を公開して1点を得る。\n") else: pass if player.hand.count("騎士") >= 3: action_list.append("10. 騎士3枚を捨て、相手を攻撃する\n") else: pass if player.hand.count("貴族") >= 4: action_list.append("11. 貴族4枚を捨て、3点を得る。\n") action_list.append("12. 貴族3枚を捨て、2点を得る。\n") action_list.append("13. 貴族2枚を捨て、1点を得る。\n") elif player.hand.count("貴族") == 3: action_list.append("12. 貴族3枚を捨て、2点を得る。\n") action_list.append("13. 貴族2枚を捨て、1点を得る。\n") elif player.hand.count("貴族") == 2: action_list.append("13. 貴族2枚を捨て、1点を得る。\n") else: pass #入力されたactionkeyによって行動の関数を引っ張り出す関数 def action(player, opponent, library, graveyard, actionkey): if actionkey == "1": if player.hand.count("王子") == 3: three_prince(player, opponent, library, graveyard) else: print("無効なコマンドです") elif actionkey == "2": if player.hand.count("司教") >= 3 and player.hand.count("王子") >=2 and player.reveal == 0: three_bishop_two_prince(player, opponent, library, graveyard) else: print("無効なコマンドです") elif actionkey == "3": if player.hand.count("司教") >= 2 and player.hand.count("王子") >=2 and player.reveal == 0: three_bishop_two_prince(player, opponent, library, graveyard) else: print("無効なコマンドです") elif actionkey == "4": if player.hand.count("騎士") >= 2 and player.hand.count("王子") >= 2: discard_two_knight_two_prince(player, opponent, library, graveyard) else: print("無効なコマンドです") elif actionkey == "5": if player.hand.count("貴族") >= 3 and player.hand.count("王子") >= 2: discard_noble_two_prince(player, opponent, library, graveyard, 3) else: print("無効なコマンドです") elif actionkey == "6": if player.hand.count("貴族") >= 2 and player.hand.count("王子") >= 2: discard_noble_two_prince(player, opponent, library, graveyard, 2) else: print("無効なコマンドです") elif actionkey == "7": if player.hand.count("貴族") >= 1 and player.hand.count("王子") >= 2: discard_noble_two_prince(player, opponent, library, graveyard, 1) else: print("無効なコマンドです") elif actionkey == "8": if player.hand.count("司教") >= 4 and player.reveal == 0: four_bishop(player, opponent, library, graveyard) else: print("無効なコマンドです") elif actionkey == "9": if player.hand.count("司教") >= 3 and player.reveal == 0: three_bishop(player, opponent, library, graveyard) else: print("無効なコマンドです") elif actionkey == "10": if player.hand.count("騎士") >= 3: discard_three_knight(player, opponent, library, graveyard) else: print("無効なコマンドです") elif actionkey == "11": if player.hand.count("貴族") >= 4: discard_noble(player, opponent, library, graveyard, 4) else: print("無効なコマンドです") elif actionkey == "12": if player.hand.count("貴族") >= 3: discard_noble(player, opponent, library, graveyard, 3) else: print("無効なコマンドです") elif actionkey == "13": if player.hand.count("貴族") >= 2: discard_noble(player, opponent, library, graveyard, 2) else: print("無効なコマンドです") else: pass
452785019f14a79c1eacec65d85a61399daa8e91
vadsimus/Python
/HackerRank/Python Challenge/Piling Up!.py
425
3.59375
4
# https://www.hackerrank.com/challenges/piling-up/problem n = int(input()) for _ in range(n): answer = True input() line = list(map(int, input().split())) while len(line) > 1: if line[0] >= line[1]: del line[0] continue elif line[-1] >= line[-2]: del line[-1] continue answer = False break print("Yes" if answer else 'No')
9e85691042d8875534553d284090f9989a4baab0
elahea2020/6.00
/6.0001PSET/PSET4/part_a/test_ps4a.py
6,712
3.609375
4
# for running unit tests on 6.00/6.0001/6.0002 student code import unittest import ps4a as student # A class that inherits from unittest.TestCase, where each function # is a test you want to run on the student's code. For a full description # plus a list of all the possible assert methods you can use, see the # documentation: https://docs.python.org/3/library/unittest.html#unittest.TestCase class TestPS4A(unittest.TestCase): ### test representation def test_data_representation(self): student_t1 = student.tree1 student_t2 = student.tree2 student_t3 = student.tree3 # # check lengths tree_length_msg = "Your list for %s has length %s, but should be length %s." self.assertEqual(len(student_t1), 2, tree_length_msg % ('tree1', len(student.tree1), 2)) self.assertEqual(len(student_t2), 2, tree_length_msg % ('tree2', len(student.tree2), 2)) self.assertEqual(len(student_t3), 3, tree_length_msg % ('tree3', len(student.tree3), 3)) # check children self.assertEqual(student_t1[0], [1,10], "The left subtree of tree1 is incorrect.") self.assertEqual(student_t1[1], 2, "The right subtree of tree1 is incorrect.") self.assertEqual(student_t2[0], [15,9], "The left subtree of tree2 is incorrect.") self.assertEqual(student_t2[1], [[9,7],10], "The right subtree of tree2 is incorrect.") self.assertEqual(student_t3[0], [12], "The left subtree of tree3 is incorrect.") self.assertEqual(student_t3[1], [2,4,2], "The right subtree of tree3 is incorrect.") ### tests for add_tree def test_mul_example_trees(self): expected_1 = 20 expected_2 = 85050 expected_3 = 1152 actual_1 = student.mul_tree([[1,10],2]) actual_2 = student.mul_tree([[15,9],[[9,7],10]]) actual_3 = student.mul_tree([[12],[2,4,2],[6]]) self.assertEqual(actual_1, expected_1, "Expected add(tree1) to be 20, but got %s" % actual_1) self.assertEqual(actual_2, expected_2, "Expected add(tree2) to be 85050, but got %s" % actual_2) self.assertEqual(actual_3, expected_3, "Expected add(tree3) to be 1152, but got %s" % actual_3) ### tests for operate_tree def test_op_add_example_trees(self): def addem(a,b): """ Example operator function. Takes in two integers, returns their sum. """ return a + b expected_1 = 13 expected_2 = 50 expected_3 = 26 actual_1 = student.operate_tree([[1,10],2], addem, 0) actual_2 = student.operate_tree([[15,9],[[9,7],10]], addem, 0) actual_3 = student.operate_tree([[12],[2,4,2],[6]], addem, 0) self.assertEqual(actual_1, expected_1, "Expected operate_tree(tree1, addem, 0) to be 13, but got %s" % actual_1) self.assertEqual(actual_2, expected_2, "Expected operate_tree(tree2, addem, 0) to be 50, but got %s" % actual_2) self.assertEqual(actual_3, expected_3, "Expected operate_tree(tree3, addem, 0) to be 26, but got %s" % actual_3) def test_op_prod_example_trees(self): def prod(a,b): """ Example operator function. Takes in two integers, returns their product. """ return a * b expected_1 = 20 expected_2 = 85050 expected_3 = 1152 actual_1 = student.operate_tree([[1,10],2], prod, 1) actual_2 = student.operate_tree([[15,9],[[9,7],10]], prod, 1) actual_3 = student.operate_tree([[12],[2,4,2],[6]], prod, 1) self.assertEqual(actual_1, expected_1, "Expected operate_tree(tree1, prod, 1) to be 20, but got %s" % actual_1) self.assertEqual(actual_2, expected_2, "Expected operate_tree(tree2, prod, 1) to be 85050, but got %s" % actual_2) self.assertEqual(actual_3, expected_3, "Expected operate_tree(tree3, prod, 1) to be 1152, but got %s" % actual_3) def test_op_search_odd_example_trees(self): expected_1 = True expected_2 = True expected_3 = False actual_1 = student.operate_tree([[1,10],2], student.search_odd, False) actual_2 = student.operate_tree([[15,9],[[9,7],10]], student.search_odd, True) actual_3 = student.operate_tree([[12],[2,4,2],[6]], student.search_odd, False) self.assertEqual(actual_1, expected_1, "Expected operate_tree(tree1, search_odd, False) to be True, but got %s" % actual_1) self.assertEqual(actual_2, expected_2, "Expected operate_tree(tree2, search_odd, False) to be True, but got %s" % actual_2) self.assertEqual(actual_3, expected_3, "Expected operate_tree(tree3, search_odd, False) to be False, but got %s" % actual_3) # Dictionary mapping function names from the above TestCase class to # the point value each test is worth. point_values = { 'test_data_representation' : 0, 'test_mul_example_trees' : 0.5, 'test_op_add_example_trees' : 0.5, 'test_op_prod_example_trees' : 0.5, 'test_op_search_odd_example_trees': 0.5 } # Subclass to track a point score and appropriate # grade comment for a suit of unit tests class Results_600(unittest.TextTestResult): # We override the init method so that the Result object # can store the score and appropriate test output. def __init__(self, *args, **kwargs): super(Results_600, self).__init__(*args, **kwargs) self.output = [] self.points = 2 def addFailure(self, test, err): test_name = test._testMethodName msg = str(err[1]) self.handleDeduction(test_name, msg) super(Results_600, self).addFailure(test, err) def addError(self, test, err): test_name = test._testMethodName self.handleDeduction(test_name, None) super(Results_600, self).addError(test, err) def handleDeduction(self, test_name, message): point_value = point_values[test_name] if message is None: message = 'Your code produced an error on test %s.' % test_name self.output.append('[-%s]: %s' % (point_value, message)) self.points -= point_value def getOutput(self): if len(self.output) == 0: return "All correct!" return '\n'.join(self.output) def getPoints(self): return self.points if __name__ == '__main__': suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestPS4A)) result = unittest.TextTestRunner(verbosity=2, resultclass=Results_600).run(suite) output = result.getOutput() points = result.getPoints() # weird bug with rounding if points < .1: points = 0 print("\nProblem Set 4A Unit Test Results:") print(output) print("Points: %s/2\n" % points)
66bc35080051c02d611ab2fc1295eda2aaa8d747
ysei/project-euler
/pr026.py
1,712
4.0625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. """ MAX_NUM = 1000 # max number of problem input. def recurring_cycle(lst, dm): """ found recurring cycle in lst. if not exist, return None """ if not lst: return None else: # XXX: check only last of list because this function called each time. if lst[0] == dm: return str(reduce(lambda a, b: a * 10 + b, map(lambda t: t[0], lst))) else: return recurring_cycle(lst[1:], dm) def fraction(num): """ return reurring cycle of unit fraction of num; (1 / num) """ work = [(0, 1)] while True: val = work[-1][1] * 10 d, m = divmod(val, num) if m == 0: # fraction has no recurring cycle. return "" cycle = recurring_cycle(work, (d, m)) if cycle: return cycle else: work.append((d, m)) def compare_tuple(t1, t2): """ compare tuple with second element length. """ return len(t2[1]) - len(t1[1]) def main(num): """ main function. """ nums = range(2, num) fracs = [fraction(i) for i in nums] pairs = zip(nums, fracs) pairs.sort(compare_tuple) print pairs[0][0] # print first element of list head. if __name__ == "__main__": main(MAX_NUM)
d1ba360f29a7adde24062172272a7d27e50c1b16
ApurvaJogal/python_Assignments
/Assignment6/Assignment6_1.py
1,025
4.4375
4
#Write a program which contains one class named as Demo. #Demo class contains two instance variables as no1 ,no2. #That class contains one class variable as Value. #There are two instance methods of class as Fun and Gun which displays values of instance variables. #Initialise instance variable in init method by accepting the values from user. #After creating the class create the two objects of Demo class as #Obj1 = Demo(11,21) #Obj2 = Demo(51,101) # #Now call the instance methods as #Obj1.Fun() #Obj2.Fun() #Obj1.Gun() #Obj2.Gun() # Author: Apurva Anil Jogal # Date : 28th March 2019 class Demo: #class variable Value=None; def __init__(self, x, y): self.no1 = input("Enter first number: \n"); #instance variable self.no2 = input("Enter second number: \n"); #instance variable def Fun(self): #instance method print(self.no1,self.no2); def Gun(self): #instance method print(self.no1,self.no2); Obj1 = Demo(11,21); Obj2 = Demo(51,101); Obj1.Fun() Obj2.Fun() Obj1.Gun() Obj2.Gun()
d75f8ddd111330678d913425a33d662b270026fd
Kamil-Jan/LeetCode
/medium/ZigZagConversion.py
892
3.5625
4
def convert_border_row(s, i, numRows): convertion = "" step = 2 * (numRows - 1) for j in range(i, len(s), step): convertion += s[j] return convertion class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s convertion = convert_border_row(s, 0, numRows) big_step = 2 * (numRows - 1) - 2 small_step = 2 for i in range(1, numRows - 1): step = big_step j = i while j < len(s): convertion = convertion + s[j] j += step if step != small_step: step = small_step else: step = big_step big_step -= 2 small_step += 2 convertion = convertion + convert_border_row(s, numRows - 1, numRows) return convertion
ad66f5c67364e3b3a5355857e7f9ad3d4cf9293b
woochan-hwang/Algorithms-DS-Practice
/Linked Lists/loopdetect.py
1,577
3.921875
4
# Write a code to detect the beginning of a loop in a singly linked list # Standard Python implementation of Node object class Node: def __init__(self, x): self.val = x self.next = None class Solution: def __init__(self, dummy = 0): self.dummy_head = Node(dummy) # Loop back from end to the kth node def generate_linked_list(self, input_list, k): head = self.dummy_head tail = head c = 0 # Iterate through input list to create linked lists for item in input_list: curr = Node(item) tail.next = curr tail = curr if c == k: loop_head = curr c += 1 tail.next = loop_head return head.next, loop_head # Brute force method def loop_detect_brutef(self, head): memory = [] print('Running through linked list ...') while 1: print('Node val: ', head.val) memory.append(head) head = head.next if head in memory: print('Loop detected: ', head.val) break return head # Testing Solution test = Solution() test_list = [1,2,3,7,1,9,8,3,1,7] k = int(input('which node is loop head?: ')) head, true_loop_head = test.generate_linked_list(input_list = test_list, k = k) print('Original Linked List: ', test_list) loop_head = test.loop_detect_brutef(head) print('Calculated loop head is {} with value {}. This matches answer: {}'.format(loop_head, loop_head.val, loop_head == true_loop_head))
9f60ccd490cce516c3fb192b806bd02635d59a33
nyctigers007/interviewer
/datastructures/bst.py
1,717
3.71875
4
# jian li implemented July 5, 2019 class Node (): def __init__(self, val): self.data = val self.right = None self.left = None class binaryTree(): def __init__(self): self.root = None def insert(self, root, val): newnode = Node(val) if self.root == None: self.root = newnode if val< root.data: if root.left is None: root.left = newnode else: self.insert(root.left, val) else: if root.right is None: root.right = newnode else: self.insert(root.right, val) def find(self,root, target): if root == None: return False if root.data == target: return True if target < root.data: self.find(root.left, target) else: self.find(root.right, target) return False def printInorder(self, root): if root: self.printInorder(root.left) print 'printing in order data:', root.data self.printInorder(root.right) def printPostorder(self, root): if root: self.printPostorder(root.left) self.printPostorder(root.right) print 'printing post order data:', root.data def printPreorder(self,root): if root: print 'printing preorder data:', root.data self.printPreorder(root.left) self.printPreorder(root.right) bst = binaryTree(); root = Node(3) bst.insert(root, 7) bst.insert(root, 1) bst.insert(root, 5) bst.printInorder(root) bst.printPreorder(root) bst.printPostorder(root) print (bst.find(root, 7))
1d7dd2cba6277ba405e9e8d23d73b5d9897f293e
Parizval/CodeChefCodes
/Python/Beginner/FBMT.py
506
3.765625
4
for a in range(int(input())): n = int(input()) if n == 0 : print("Draw") else: TeamA = input() ScoreA= 1 ScoreB = 0 TeamB = "" for i in range(n-1): j = input() if j == TeamA: ScoreA += 1 else: TeamB = j ScoreB += 1 if ScoreA > ScoreB: print(TeamA) elif ScoreB > ScoreA: print(TeamB) else: print("Draw")
f9bf1622e964f5746de6f4f47fa0c1931c43e771
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/INTERVIEW-PREP-COMPLETE/Leetcode/56.py
501
3.53125
4
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if not intervals: return [] if len(intervals) < 2: return intervals intervals = sorted(intervals, key=lambda x: x[0]) stack = [] for interval in intervals: if stack and stack[-1][1] >= interval[0]: stack[-1][1] = max(stack[-1][1], interval[1]) continue stack.append(interval) return stack
5cbda72d1faef442e81fdef088160c86a66e6f32
ucandoitrohit/Python3
/Python_Basic_script/Python_Basic/12.set.py
170
3.53125
4
s = set() print(type(s)) xyz = set([1,2,3,4]) print(xyz) print(type(xyz)) num = set() num.add(1) num.add(2) s.union({3,4}) num1= s.union({3,4}) print(num) print(num1)
f80548226f3427819193c323cdcbc2047a29490c
maymashd/webdev2019
/week10/CodeingBat/logic-1/date-fashion.py
169
4.125
4
def f(a,b): if a>=8 or b>=8: return 2 elif a<=2 or b<=2: return 0 else: return 1 a=int(input()) b=int(input()) print(f(a,b))
b4ff9dcf5c6e5da9770ae6a6be6e36fd0fbd3d2c
Piachonkin-Alex/EarleyAlgo
/app/main.py
3,751
3.515625
4
# terminals - a-z # non-terminals A-Z # start - non-terminal S # empty symbol is an empty string class Rule: def __init__(self, left_side: str, right_side: str): self.lhs = left_side self.rhs = right_side class Situation: def __init__(self, left_side: str, right_side: str, point_cord: int, offset: int): self.left_side = left_side self.ride_side = right_side self.point_cord = point_cord self.offset = offset def __hash__(self): return hash((self.left_side, self.ride_side, self.point_cord, self.offset)) def __eq__(self, other): res = self.left_side == other.left_side and self.ride_side == other.ride_side return res and self.offset == other.offset and self.point_cord == other.point_cord class EarleyParser: def __init__(self, rules: list): self.rules = [] self.rules.append(Rule('#', 'S')) # help rule self.rules += rules self.lists_of_situations = [] self.word = "" def check(self, word: str): self.lists_of_situations = [] self.word = word for _ in range(len(word) + 1): # list of situation initialization self.lists_of_situations.append(set()) self.lists_of_situations[0].add(Situation('#', 'S', 0, 0)) # first add for iteration in range(0, len(word) + 1): self.scan(iteration) sz = len(self.lists_of_situations[iteration]) while True: self.complete(iteration) self.predict(iteration) if sz == len(self.lists_of_situations[iteration]): # check changing break else: sz = len(self.lists_of_situations[iteration]) if Situation('#', 'S', 1, 0) in self.lists_of_situations[-1]: # finding result return True else: return False def scan(self, step): # scan from j - 1 to j if step == 0: return for trans in self.lists_of_situations[step - 1]: if trans.point_cord < len(trans.ride_side) and trans.ride_side[trans.point_cord] == self.word[step - 1]: new_trans = Situation(trans.left_side, trans.ride_side, trans.point_cord + 1, trans.offset) self.lists_of_situations[step].add(new_trans) def predict(self, step): # predict new = set() for trans in self.lists_of_situations[step]: if trans.point_cord == len(trans.ride_side): continue waiting_lhs = trans.ride_side[trans.point_cord] for rule in self.rules: if rule.lhs == waiting_lhs: new_trans = Situation(rule.lhs, rule.rhs, 0, step) new.add(new_trans) self.lists_of_situations[step].update(new) def complete(self, j): new = set() for trans in self.lists_of_situations[j]: if trans.point_cord < len(trans.ride_side): continue for wait_trans in self.lists_of_situations[trans.offset]: if wait_trans.point_cord < len(wait_trans.ride_side) and \ wait_trans.ride_side[wait_trans.point_cord] == trans.left_side: new_trans = Situation(wait_trans.left_side, wait_trans.ride_side, wait_trans.point_cord + 1, wait_trans.offset) new.add(new_trans) self.lists_of_situations[j].update(new) if __name__ == '__main__': rules = [] num = int(input()) for _ in range(num): lhs = input() rhs = input() rules.append(Rule(lhs, rhs)) word = input() print(EarleyParser(rules).check(word))
092b060118b68c9d4460e4a1732e9fc4a05096b4
MannyIOI/Competitive-Programming
/Week-2/Day-1/intersection.py
244
3.890625
4
class Solution: def intersection(self, nums1, nums2): intersection = [] for i in nums1: if i in nums2 and i not in intersection: intersection.append(i) return intersection
0a0168a9c5d45ffde0572545efad7b9734a97c38
YahyaQandel/CodeforcesProblems
/Boy_or_Girl.py
114
3.71875
4
username = input() s = "".join(set(username)) if len(s)%2 == 0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
1d63cea4cfb0bfe50daad29c54d14aebcc12a960
FoxGriVer/PythonLabs
/lab4/list_utils.py
556
3.828125
4
def last(l): return l[-1] def middle(l): try: if(len(l) % 2 == 0): raise Exception("Number of elements in the list is not odd") middleIndex = int((len(l) - 1)/2) return l[middleIndex] except Exception as e: print(e) def product(l): result = 1 for element in l: result *= element return result def even_sum(l): result = 0 position = 0 for element in l: if(position % 2 == 0): result += element position += 1 return result
233b063498df464c7aa3f104966c021be31c4a3a
sonivaibhav27/Data-Structure
/BST/DrawBSTFromPreorder.py
1,369
3.84375
4
class Node: def __init__(self,data): self.data= data self.left =None self.right=None class BST: def __init__(self): self.root =None def insertElement(self,dataOfArr): self.root= Node(dataOfArr[0]) i = 1 while i < len(dataOfArr): if dataOfArr[i] < self.root.data: if self.root.left is None: self.root.left =Node(dataOfArr[i]) else: temp =self.root while temp.left: temp=temp.left if temp.data > dataOfArr[i]: temp.left = Node(dataOfArr[i]) else: temp.right = Node(dataOfArr[i]) else: if self.root.right is None: self.root.right = Node(dataOfArr[i]) else: temp =self.root while temp.right: temp=temp.right temp.right = Node(dataOfArr[i]) i+=1 def printTree(self): print(self.root.left.left.right.data) # def inorder(root): # if root: # inorder(root.left) # print(root.data) # inorder(root.right) b=BST() b.insertElement([8,5,1,7,10,12]) b.printTree()
c281b52abd61ddb9bd091ecabf4223ddbced2694
jasontwright/coursera
/pythonlearn/week08/split.py
100
3.984375
4
abc = 'With three words' stuff = abc.split() print stuff print stuff[0] for w in stuff : print w
355869fff1a459757a34e47e39fe1a4f276f2626
viethngn/Bloxorz-Game-AI
/searchBiDir.py
4,559
3.5625
4
from display import Displayable, visualize from searchProblem import Path, Arc from searchGeneric import Searcher class BidirectionalSeacher(Searcher): """returns a searcher for a problem. Paths can be found by repeatedly calling search(). This does depth-first search unless overridden """ def __init__(self, problem): """creates a searcher from a problem """ self.problem = problem self.initialize_Ffrontier() self.initialize_Bfrontier() self.num_expanded_forward = 0 self.num_expanded_backward = 0 self.num_expanded = 0 self.forward = {} self.backward = {} self.add_to_Ffrontier(Path(problem.start_node())) self.add_to_Bfrontier(Path(problem.goal_node())) super().__init__(problem) def initialize_Ffrontier(self): self.Ffrontier = [] def initialize_Bfrontier(self): self.Bfrontier = [] def empty_frontier(self): return self.Ffrontier == [] or self.Bfrontier == [] def add_to_Ffrontier(self,path): self.Ffrontier.append(path) def add_to_Bfrontier(self,path): self.Bfrontier.append(path) def result(self, path1, path2): current = path2 result = path1 while current.arc != None: result = Path(result, Arc(current.arc.to_node, current.arc.from_node, 1, current.arc.action)) current = current.initial #print(result) return result @visualize def search(self): """returns (next) path from the problem's start node to a goal node. Returns None if no path exists. """ while not self.empty_frontier(): #forward path = self.Ffrontier.pop(0) if (path.end() in self.forward): continue self.forward[path.end()] = path self.display(2, "Expanding:",path,"(cost:",path.cost,")") self.num_expanded_forward += 1 if self.problem.is_goal(path.end()): # solution found self.display(1, self.num_expanded_forward, "forward paths have been expanded and", len(self.Ffrontier), "paths remain in the Ffrontier") self.solution = path # store the solution found return path else: neighs = self.problem.neighbors(path.end()) self.display(3,"Neighbors are", neighs) for arc in reversed(neighs): #intersect, solution found if arc.to_node in self.backward: result = self.result(Path(path,arc), self.backward[arc.to_node]) self.num_expanded = self.num_expanded_forward + self.num_expanded_backward self.solution = result return result elif arc.to_node not in self.forward: self.add_to_Ffrontier(Path(path,arc)) self.display(3,"FFrontier:",self.Ffrontier) #backward path = self.Bfrontier.pop(0) if (path.end() in self.backward): continue self.backward[path.end()] = path self.display(2, "Expanding:",path,"(cost:",path.cost,")") self.num_expanded_backward += 1 if self.problem.is_start(path.end()): # solution found self.display(1, self.num_expanded_backward, "backward paths have been expanded and", len(self.Bfrontier), "paths remain in the Bfrontier") self.solution = path # store the solution found return path else: neighs = self.problem.neighbors(path.end(), True) self.display(3,"Neighbors are", neighs) for arc in reversed(neighs): #intersect, solution found if arc.to_node in self.forward: result = self.result(self.forward[arc.to_node], Path(path,arc)) self.num_expanded = self.num_expanded_forward + self.num_expanded_backward self.solution = result return result elif arc.to_node not in self.backward: self.add_to_Bfrontier(Path(path,arc)) self.display(3,"BFrontier:",self.Bfrontier) self.num_expanded = self.num_expanded_forward + self.num_expanded_backward self.display(1,"No (more) solutions. Total of", self.num_expanded,"paths expanded.")
be6e4323fff5bf526e0b08412ff9ced119bb066a
JonLevin25/coding-problems
/daily-coding-problems/problem001/solution/solution.py
398
3.5
4
from typing import List def solve(arr: List[int], k: int) -> bool: missing_nums = set() for n in arr: if n in missing_nums: return True # Calculate the number needed to sum with n (and get our target k) # add this to a hash set that we can compare later missing_difference = k - n missing_nums.add(missing_difference) return False
5bb29e31c340ee1983a8aaeecd28cfe10351680f
moonlimb/scheme_to_js_translator
/xml_to_js/helper/decorate.py
711
3.828125
4
# file containing decorator / helper functions # Q: Use decorators/wrapper function to add curly braces? def make_fcn(fn): def wrapper(): return fn() + "()" return wrapper def add_parens(fn): def wrapper(): return "(" + fn() + ")" return wrapper def add_curly_braces(content): def wrapper(): return "{" + content + "; }" return wrapper #keywords=['function', 'if', 'for'] """ content_test= "function content" @add_curly_braces def decorator_test(): return content_test loop_cond_test = "i=0; i<=10; i++" @add_parens def paren_test(): return loop_cond_test fcn_name='square' @make_fcn def call_function(): return fcn_name print decorator_test() print paren_test() print call_function() """
21ceb3902e962f4bcc4cdd1e8879e8b48f0048d0
Altynaila/homework-month1
/lesson3/lesson3.1.py
392
3.984375
4
age = int(input()) if age > 18: name = input() if name == "Daniiar": hobby == input() if hobby == "drawing": print("Вы не умеете петь") else: print("Вы умеете петь") print("Вас зовут Данияр") else: print("Вы не Данииияр") else: print("Вам нельзя!")
aeb30d508701c06925a062a9deb99eeb3c70c7f6
srajsonu/InterviewBit-Solution-Python
/Maths/Maths III/palindrome_integer.py
598
3.671875
4
class Solution: def Solve(self, A): divisor = 1 while A / divisor >= 10: divisor *= 10 while A: leading = A // divisor trailing = A % 10 if leading != trailing: return 0 # Removing the leading and # trailing digit from number A = (A % divisor) // 10 # Reducing divisor by a factor # of 2 as 2 digits are dropped divisor //= 100 return 1 if __name__ == '__main__': A = 12121 B = Solution() print(B.Solve(A))
21301ed824f9b48d0285cbe0e2d35889d391ff2a
gosch/Katas-in-python
/2018/august/codesignal/minesweeper.py
809
3.53125
4
def minesweeper(matrix): res = [] top = [False] * (len(matrix[0]) + 2) down = top[:] matrix_temp = [] matrix_temp.append(top) for i in matrix: matrix_temp.append([False] + i[:] + [False]) matrix_temp.append(down) for i in range(1, len(matrix_temp) - 1): row = [] for j in range(1, len(matrix_temp[i]) - 1): up = [1 for x in matrix_temp[i - 1][j - 1:j + 2] if x] mid = [1 if matrix_temp[i][j-1] else 0, 1 if matrix_temp[i][j+1] else 0] dow = [1 for x in matrix_temp[i + 1][j - 1:j + 2] if x] row.append(sum(up + mid + dow)) res.append(row) return res matrix = [[True, False, False], [False, True, False], [False, False, False]] print(minesweeper(matrix)) val = str('H')
f870d5f3ad6909cff78e009cbf572d5d3db53a36
sayalichakradeo/class-work
/8.4.py
202
3.890625
4
fhand = open("romeo.txt") my_list=list() for line in fhand: line = line.lower() words = line.split() for word in words: if word not in my_list: my_list.append(word) my_list.sort() print(my_list)
257f01af2442f2ffacc35d4fe2672eff27bb00b3
linvieson/json-navigator
/json_navigator.py
2,909
4.4375
4
''' This module gets the json file from the user. It asks a user, which part of the json object he or she wants to see and outputs its value. ''' import json def get_json() -> dict: ''' Make a get request on a server. Return json object as a python dictionary. ''' path = input('Enter a path to json file: ') files = open(path, 'r', encoding = 'utf-8') data = json.load(files) return data def check_list(dates: list, num: int) -> str: ''' Recursive function that gets the data requested by user. Return string value, list or json object if the user enters ALL. ''' num = int(num) if isinstance(dates[num], dict): print('It is an object. Enter one of the available values or enter\ ALL if you want to see the whole object: ') keys = list(iter(dates.keys())) for key in keys: if key != keys[-1]: print(key, end=', ') else: print(key) return check_input(dates[num]) if isinstance(dates[num], list): print(f'It is a list. Enter index from 0 to {len(dates[num])} or enter\ ALL if you want to see the whole list: ') return check_input(dates[num]) return dates[num] def check_input(data: dict) -> str: ''' Recursive function that gets the data requested by user. Return string value, list or json object if the user enters ALL. ''' user = input() if user == 'ALL': return json.dumps(data, indent = 4, ensure_ascii = False) if isinstance(data, dict) and user in data.keys(): if isinstance(data[user], dict): print('It is an object. Enter one of the available values or enter\ ALL if you want to see the whole object: ') keys = list(iter(data[user])) for key in keys: if key != keys[-1]: print(key, end=', ') else: print(key) return check_input(data[user]) if isinstance(data[user], list): dates = data[user] length = len(dates) print(f'It is a list. Enter index from 0 to {length} or enter\ ALL if you want to see the whole list: ') num = input() if num == 'ALL': return data[user] return check_list(dates, num) return str(user) + ': ' + str(data[user]) def main() -> str: ''' Main function that runs the whole program. ''' data = get_json() print('To navigate through the file, enter one of the available\ values.') print('Available keys: ') keys = list(iter(data.keys())) for key in keys: if key != keys[-1]: print(key, end=', ') else: print(key) try: result = check_input(data) return result except KeyError: return 'Incorrect value. Try again!' if __name__ == '__main__': print(main())
e583f00f298fb7e4cbe49cfb28526044c7b08f88
verde-green/NLP_100
/Chapter1/nlp_06.py
519
3.546875
4
# -*- coding: utf-8 -*- def n_gram(obj, n): return [obj[i:i+n:] for i in range(len(obj) - n + 1)] if __name__ == "__main__": text = ["paraparaparadise", "paragraph"] X = set(n_gram(text[0], 2)) Y = set(n_gram(text[1], 2)) se = ["True" if "se" in X else "False", "True" if "se" in Y else "False"] print(f"X: {X}") print(f"Y: {Y}") print(f"X | Y: {X | Y}") print(f"X & Y: {X & Y}") print(f"X - Y: {X - Y}") print(f'"se" in X: {se[0]}') print(f'"se" in Y: {se[1]}')
f35f74649e6a42d00cc03a4079cb9b9f0ba02047
akshaytiwari0203/python_3
/06_LoopingInPython/for_test.py
168
4.28125
4
limit=int(input("Enter upper bound: ")) for num in range(1,limit) : print(f" {num} \n") string=input("Enter a string: ") for char in string : print(char + "\n")
e1d52d6f91555c9a29cd8fa75d8b71e927fdac85
caolina1314/UI-test
/8_def.py
1,964
4.1875
4
# 在python中用def关键字来定义函数,后接函数标识符名称和圆括号() # return[表达式]结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回None ''' 语法: def function name(parameters): "函数_文档字符串" function_suite return [expression] 或 def my_abs(x): if x >= 0: return x else: return -x ''' ''' # 定义add()函数 def add (a,b): # print(a+b) # 调用add()函数 # add(3, 5) return a + b c = add(3,5) print(c) ''' """ def add(a=1,b=2): return a + b c1 =add() c2 = add(3, 5) print(c1) print(c2) """ # 传可变对象实例 ''' # coding:utf-8 def changeme(mylist): # 可写函数说明 "修改传入的列表" mylist.append([1,2,3,4,]) print('函数内取值:',mylist) return # 调用changeme函数 mylist = [10,20,30] changeme(mylist) print('函数外取值',mylist) ''' # 默认参数 """ # coding:utf-8 def printinfo(name, age=35): # 写函数说明 '打印任何传入的字符串' print('name',name) print('age',age) return # 调用printinfo函数 printinfo (age=50,name='miki') printinfo(name='miki') """ # 不定长参数 ''' # coding:utf-8 def printinfo(arg1,*vartuple): # 加了星号(*)的变量名会存放所有未命名的变量参数 '打印任何传入的参数' print('输出:') print(arg1) for var in vartuple: print(var) return # 调用printinfo函数 printinfo(10) printinfo(70,60,50) ''' # 全局变量和局部变量 # coding : utf - 8 total = 0 # 这是一个全局变量 def sum(arg1,arg2): # 返回两个参数的和 total = arg1 + arg2 # total在这里是局部变量 print('函数内是局部变量:',total) return total # 调用sum函数 sum(10,20) print('函数外是全局变量:',total)
396da1c0337b3b13ae7cbc1c2503c23c758135c5
nathanesau/AdventOfCode
/day2/problem2.py
1,149
3.53125
4
# https://adventofcode.com/2019/day/2#part2 OPCODE_ADD = 1 OPCODE_MULTIPLY = 2 OPCODE_FINISHED = 99 def get_output(arr, noun, verb): arr[1] = noun arr[2] = verb for op_index in range(0, len(arr), 4): opcode = arr[op_index] if opcode is OPCODE_ADD: arr[arr[op_index + 3]] = arr[arr[op_index + 1]] + arr[arr[op_index + 2]] elif opcode is OPCODE_MULTIPLY: arr[arr[op_index + 3]] = arr[arr[op_index + 1]] * arr[arr[op_index + 2]] elif opcode is OPCODE_FINISHED: return arr[0] # done return arr[0] # should not happen def solve(arr, target): computed = {} max_noun = min(99, len(arr) - 1) max_verb = min(99, len(arr) - 1) for noun in range(0, max_noun): for verb in range(0, max_verb): pair = (arr[noun], arr[verb]) if arr[noun] < arr[verb] else (arr[verb], arr[noun]) if pair not in computed: output = get_output(arr.copy(), noun, verb) computed[pair] = output if output == target: return 100 * noun + verb return -1 # no result found
56d157b267f13ab2f733da71e7aa2ec4ac4cc026
zischuros/Introduction-To-Computer-Science-JPGITHUB1519
/Lesson 1 - How to get Started/Selecting sub-sequencies/sub-sequencies.py
254
3.625
4
string = "programacion" # string [start : stop-1] print string[0:8] print string [5:] #from start to end print string [:6] #from begin to stop print string [5:5] # do not exist print string[:] # from begin to end input()
a405a3a5ee50ca4a31393390786eb3cc1b986925
fransHalason/IndonesiaAI
/Basic Python/Part 4 - Python Data Types/default.py
323
4.40625
4
''' PYTHON: FUNCTION DEFAULT PARAMETER Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value. The default value is assigned by using assignment(=) operator. ''' def my_function(name=""): print("Hello " + name) my_function("James")
3a7abc7dad839ee448a8f89b75fec61ac2baf4f8
bozhikovstanislav/Python-Fundamentals
/PythonIntroFunc_debug/06.RiseNumberOnNumber.py
212
3.875
4
def rise_number(base_number: float, number_to_rise: float) -> float: return base_number ** number_to_rise number_one = input() number_tow = input() print(rise_number(float(number_one), float(number_tow)))
1c8c97afb4977a500ba6914d0e819b20f37724b0
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_118/1015.py
1,021
3.71875
4
import math import sys def is_palindrome(s): s=str(s) for i in range(0, len(s)//2): if (s[i] != s[len(s)-i-1]): return False return True #source: http://stackoverflow.com/questions/2489435/how-could-i-check-if-a-number-is-a-perfect-square # - "Babylonian algorithm" def is_square(apositiveint): if( apositiveint == 1 or apositiveint == 4 or apositiveint == 9): return True x = apositiveint // 2 seen = set([x]) while x * x != apositiveint: x = (x + (apositiveint // x)) // 2 if x in seen: return False seen.add(x) return True def main(): numCases = int(sys.stdin.readline()) for i in range(1, numCases+1): counter = 0 line = sys.stdin.readline() #lo = int(line.split( )[0]) #hi = int(line.split( )[1]) for j in range(int(line.split( )[0]), int(line.split( )[1])+1): if ( is_palindrome(j) and is_square(j) ): if( is_palindrome(int(math.sqrt(j)))): counter = counter + 1 #print "found"+str(j) print "Case #"+str(i)+": "+str(counter) if __name__ == '__main__': main()
2c4fde429af0dbfdf9c32e52fcacc58eae71fc5e
dmehta504/DecisionTrees-RandomForests
/submission.py
26,219
3.53125
4
import numpy as np from collections import Counter import time class DecisionNode: """Class to represent a single node in a decision tree.""" def __init__(self, left, right, decision_function, class_label=None): """Create a decision function to select between left and right nodes. Note: In this representation 'True' values for a decision take us to the left. This is arbitrary but is important for this assignment. Args: left (DecisionNode): left child node. right (DecisionNode): right child node. decision_function (func): function to decide left or right node. class_label (int): label for leaf node. Default is None. """ self.left = left self.right = right self.decision_function = decision_function self.class_label = class_label def decide(self, feature): """Get a child node based on the decision function. Args: feature (list(int)): vector for feature. Return: Class label if a leaf node, otherwise a child node. """ if self.class_label is not None: return self.class_label elif self.decision_function(feature): return self.left.decide(feature) else: return self.right.decide(feature) def load_csv(data_file_path, class_index=-1): """Load csv data in a numpy array. Args: data_file_path (str): path to data file. class_index (int): slice output by index. Returns: features, classes as numpy arrays if class_index is specified, otherwise all as nump array. """ handle = open(data_file_path, 'r') contents = handle.read() handle.close() rows = contents.split('\n') out = np.array([[float(i) for i in r.split(',')] for r in rows if r]) if(class_index == -1): classes= out[:,class_index] features = out[:,:class_index] return features, classes elif(class_index == 0): classes= out[:, class_index] features = out[:, 1:] return features, classes else: return out def build_decision_tree(): """Create a decision tree capable of handling the sample data. Tree is built fully starting from the root. Returns: The root node of the decision tree. """ # Decision Tree # A1 == 0 # / \ # / \ # A4 == 0 1 # / \ # / \ # / \ # A3 == 0 A2 == 0 # / \ / \ # 1 0 1 0 decision_tree_root = DecisionNode(None, None, lambda a1: a1[0] == 0) node_a2 = DecisionNode(None, None, lambda a2: a2[1] == 0) node_a3 = DecisionNode(None, None, lambda a3: a3[2] == 0) node_a4 = DecisionNode(None, None, lambda a4: a4[3] == 0) # Build Root decision_tree_root.left = node_a4 decision_tree_root.right = DecisionNode(None, None, None, 1) # Build Left (A4) node_a4.left = node_a3 node_a4.right = node_a2 # Build Left of A4 (A3) node_a3.left = DecisionNode(None, None, None, 1) node_a3.right = DecisionNode(None, None, None, 0) # Build Right of A4 (A2) node_a2.left = DecisionNode(None, None, None, 1) node_a2.right = DecisionNode(None, None, None, 0) # TODO: finish this. # raise NotImplemented() return decision_tree_root def confusion_matrix(classifier_output, true_labels): """Create a confusion matrix to measure classifier performance. Output will in the format: [[true_positive, false_negative], [false_positive, true_negative]] Args: classifier_output (list(int)): output from classifier. true_labels: (list(int): correct classified labels. Returns: A two dimensional array representing the confusion matrix. """ # TODO: finish this. # Creates a 2x2 array # [0 , 0 # 0, 0] matrix = np.array([[0, 0], [0, 0]]) for i in range(len(classifier_output)): # If we classify correctly check for True Positive or True Negative if classifier_output[i] == true_labels[i]: if true_labels[i] == 1: matrix[0, 0] = matrix[0, 0] + 1 # True Positive else: matrix[1, 1] = matrix[1, 1] + 1 # True Negative # If we classify incorrectly check for False Positive or False Negative elif classifier_output[i] != true_labels[i]: if true_labels[i] == 0: matrix[1, 0] = matrix[1, 0] + 1 # False Positive else: matrix[0, 1] = matrix[0, 1] + 1 # False Negative return matrix # raise NotImplemented() def precision(classifier_output, true_labels): """Get the precision of a classifier compared to the correct values. Precision is measured as: true_positive/ (true_positive + false_positive) Args: classifier_output (list(int)): output from classifier. true_labels: (list(int): correct classified labels. Returns: The precision of the classifier output. """ # TODO: finish this. matrix = confusion_matrix(classifier_output, true_labels) true_positive = matrix[0, 0] false_positive = matrix[1, 0] return true_positive / (true_positive + false_positive) # raise NotImplemented() def recall(classifier_output, true_labels): """Get the recall of a classifier compared to the correct values. Recall is measured as: true_positive/ (true_positive + false_negative) Args: classifier_output (list(int)): output from classifier. true_labels: (list(int): correct classified labels. Returns: The recall of the classifier output. """ # TODO: finish this. matrix = confusion_matrix(classifier_output, true_labels) true_positive = matrix[0, 0] false_negative = matrix[0, 1] return true_positive / (true_positive + false_negative) # raise NotImplemented() def accuracy(classifier_output, true_labels): """Get the accuracy of a classifier compared to the correct values. Accuracy is measured as: correct_classifications / total_number_examples Args: classifier_output (list(int)): output from classifier. true_labels: (list(int): correct classified labels. Returns: The accuracy of the classifier output. """ matrix = confusion_matrix(classifier_output, true_labels) true_positive = matrix[0, 0] true_negative = matrix[1, 1] return (true_positive + true_negative)/len(true_labels) # TODO: finish this. # raise NotImplemented() def gini_impurity(class_vector): """Compute the gini impurity for a list of classes. This is a measure of how often a randomly chosen element drawn from the class_vector would be incorrectly labeled if it was randomly labeled according to the distribution of the labels in the class_vector. It reaches its minimum at zero when all elements of class_vector belong to the same class. Args: class_vector (list(int)): Vector of classes given as 0 or 1. Returns: Floating point number representing the gini impurity. """ number_unique_class, number_counts = np.unique(class_vector, return_counts=True) gini_impurity_for_class = [] if len(class_vector) == 0: return 0 for i in range(len(number_unique_class)): # Calculate gini impurity for each class as p_i * (1 - p_i) p_i = number_counts[i] / len(class_vector) gini_impurity_for_class.append(p_i * (1.0 - p_i)) g_impurity = np.sum(gini_impurity_for_class) # Total gini impurity is sum of gini impurity for each class return g_impurity # raise NotImplemented() def gini_gain(previous_classes, current_classes): """Compute the gini impurity gain between the previous and current classes. Args: previous_classes (list(int)): Vector of classes given as 0 or 1. current_classes (list(list(int): A list of lists where each list has 0 and 1 values). Returns: Floating point number representing the information gain. """ g_impurity_previous = gini_impurity(previous_classes) # Calculate the total size of future classes total = 0.0 for i in range(len(current_classes)): total = total + len(current_classes[i]) if total == 0: return 0 # Calculate gini impurity of each future class (split) gain = 0.0 for i in range(len(current_classes)): g_impurity = gini_impurity(current_classes[i]) gain += (len(current_classes[i])/total) * g_impurity return g_impurity_previous - gain # raise NotImplemented() class DecisionTree: """Class for automatic tree-building and classification.""" def __init__(self, depth_limit=float('inf')): """Create a decision tree with a set depth limit. Starts with an empty root. Args: depth_limit (float): The maximum depth to build the tree. """ self.root = None self.depth_limit = depth_limit def fit(self, features, classes): """Build the tree from root using __build_tree__(). Args: features (m x n): m examples with n features. classes (m x 1): Array of Classes. """ self.root = self.__build_tree__(features, classes) def __build_tree__(self, features, classes, depth=0): """Build tree that automatically finds the decision functions. Args: features (m x n): m examples with n features. classes (m x 1): Array of Classes. depth (int): depth to build tree to. Returns: Root node of decision tree. """ # TODO: finish this. # Check for termination # No more samples left i.e. no more X values remaining if features.shape[0] <= 1: return DecisionNode(None, None, None, int(np.median(classes))) # If all classes are the same, then return the class if np.unique(classes).shape[0] == 1: return DecisionNode(None, None, None, classes[0]) # If max depth reached, then return most frequent class if depth == self.depth_limit: class_values, class_count = np.unique(classes, return_counts=True) most_frequent_index = np.argmax(class_count) return DecisionNode(None, None, None, class_values[most_frequent_index]) else: # Find the feature with the highest normalized Gini Gain best_index = self.select_splitval(features, classes) # Choose the split value as the mean of the best feature found to split on alpha_best = np.mean(features[:, best_index]) max_feature = np.max(features[:, best_index]) if max_feature == alpha_best: return DecisionNode(None, None, None, int(np.median(classes))) # Recursively build the left and right subtree root = DecisionNode(None, None, lambda feature: feature[best_index] <= alpha_best) left_index = np.where(features[:, best_index] <= alpha_best) # Get the indices for left tree right_index = np.where(features[:, best_index] > alpha_best) # Get the indices for right tree root.left = self.__build_tree__(features[left_index], classes[left_index], depth + 1) root.right = self.__build_tree__(features[right_index], classes[right_index], depth + 1) return root # raise NotImplemented() def select_splitval(self, features, classes): gain = [] previous_classes = classes.tolist() # For each feature in features, calculate the Gini Gain obtained by splitting on that feature for i in range(features.shape[1]): feature = features[:, i] # Split on the median value for that particular feature, this ensures we split the data in half split = np.median(feature) left_split = np.where(feature[feature[:] <= split]) right_split = np.where(feature[feature[:] > split]) current_classes = [classes[left_split], classes[right_split]] # Calculate the gini gain obtained by splitting on the selected feature gain.append(gini_gain(previous_classes, current_classes)) best_index = np.argmax(gain) # Finds the index of the feature that has the highest Gini Gain return best_index def classify(self, features): """Use the fitted tree to classify a list of example features. Args: features (m x n): m examples with n features. Return: A list of class labels. """ class_labels = [self.root.decide(feature) for feature in features] # TODO: finish this. # raise NotImplemented() return class_labels def generate_k_folds(dataset, k): """Split dataset into folds. Randomly split data into k equal subsets. Fold is a tuple (training_set, test_set). Set is a tuple (features, classes). Args: dataset: dataset to be split. k (int): number of subsections to create. Returns: List of folds. => Each fold is a tuple of sets. => Each Set is a tuple of numpy arrays. """ # TODO: finish this. features = dataset[0] classes = dataset[1] num_of_bags = int(len(np.column_stack((features, classes))) / k) # n // k i.e. number of samples in each bag data = np.column_stack((features, classes)) folds = [] for i in range(k): copy = np.copy(data) np.random.shuffle(copy) # Shuffle the data # Create an index array index_array = np.arange(0, features.shape[0], dtype=int) # Create a slice to make a testing set with n // k data points index_slice = np.random.choice(index_array, num_of_bags, replace=False) test_data = copy[index_slice, :] train_data = np.delete(copy, index_slice, 0) # Delete the points used in testing set to get the training set # Get the features train_features = train_data[:, 0:-1] test_features = test_data[:, 0:-1] # Get the classes train_classes = train_data[:, -1] test_classes = test_data[:, -1] # Add the fold i.e. (training set, testing set) folds.append(((train_features, train_classes), (test_features, test_classes))) return folds # raise NotImplemented() class RandomForest: """Random forest classification.""" def __init__(self, num_trees, depth_limit, example_subsample_rate, attr_subsample_rate): """Create a random forest. Args: num_trees (int): fixed number of trees. depth_limit (int): max depth limit of tree. example_subsample_rate (float): percentage of example samples. attr_subsample_rate (float): percentage of attribute samples. """ self.trees = [] self.num_trees = num_trees self.depth_limit = depth_limit self.example_subsample_rate = example_subsample_rate self.attr_subsample_rate = attr_subsample_rate self.attributes_used = [] # Creating a list to track which attributes were used to train a specific tree def fit(self, features, classes): """Build a random forest of decision trees using Bootstrap Aggregation. features (m x n): m examples with n features. classes (m x 1): Array of Classes. """ # TODO: finish this. # Converting features and classes into numpy for slicing/indexing operations features = np.asarray(features) classes = np.asarray(classes) for i in range(self.num_trees): # Create an index array, then at random (w/ replacement) choose samples to create a training set # Size of sample is based on example_subsample_rate index_array = np.arange(0, features.shape[0], dtype=int) sample_slice = np.random.choice(index_array, size=int(self.example_subsample_rate * features.shape[0]), replace=True) # Get the training features and classes for our subsample train_classes = classes[sample_slice] train_features = features[sample_slice] # From above sample, choose attributes at random to learn on, size is based on attr_subsample_rate attribute_slice = np.random.randint(features.shape[1], size=int(self.attr_subsample_rate * features.shape[1])) train_features = train_features[:, attribute_slice] tree = DecisionTree(self.depth_limit) tree.fit(train_features, train_classes) self.trees.append(tree) self.attributes_used.append(attribute_slice) # raise NotImplemented() def classify(self, features): """Classify a list of features based on the trained random forest. Args: features (m x n): m examples with n features. """ # TODO: finish this. votes = [] features = np.asarray(features) # For each tree in the forest, get the classifications from each tree # based on the features used to build tree for i in range(self.num_trees): tree = self.trees[i] features_used = features[:, self.attributes_used[i]] votes.append(tree.classify(features_used)) votes = np.array(votes) classifications = [] # Based on the votes from each tree, return the class that most frequently appears for i in range(len(features)): classes = votes[:, i] class_val, class_count = np.unique(classes, return_counts=True) # Get the classification that appears most frequently and add it to the list classifications.append(class_val[np.argmax(class_count)]) return classifications # raise NotImplemented() class ChallengeClassifier: """Challenge Classifier used on Challenge Training Data.""" def __init__(self): """Create challenge classifier. Initialize whatever parameters you may need here. This method will be called without parameters, therefore provide defaults. """ # TODO: finish this. self.trees = [] self.depth_limit = 16 self.num_trees = 16 self.example_subsample_rate = 0.47 self.attr_subsample_rate = 0.73 self.attributes_used = [] # Creating a list to track which attributes were used to train a specific tree # raise NotImplemented() def fit(self, features, classes): """Build a random forest of decision trees using Bootstrap Aggregation. features (m x n): m examples with n features. classes (m x 1): Array of Classes. """ # TODO: finish this. # Converting features and classes into numpy for slicing/indexing operations features = np.asarray(features) classes = np.asarray(classes) for i in range(self.num_trees): # Create an index array, then at random (w/ replacement) choose samples to create a training set # Size of sample is based on example_subsample_rate index_array = np.arange(0, features.shape[0], dtype=int) sample_slice = np.random.choice(index_array, size=int(self.example_subsample_rate * features.shape[0]), replace=True) # Get the training features and classes for our subsample train_classes = classes[sample_slice] train_features = features[sample_slice] # From above sample, choose attributes at random to learn on, size is based on attr_subsample_rate attribute_slice = np.random.choice(range(0, features.shape[1]), size=int(self.attr_subsample_rate * features.shape[1]), replace=False) attribute_slice = np.sort(attribute_slice) train_features = train_features[:, attribute_slice] tree = DecisionTree(self.depth_limit) tree.fit(train_features, train_classes) self.trees.append(tree) self.attributes_used.append(attribute_slice) # raise NotImplemented() def classify(self, features): """Classify a list of features based on the trained random forest. Args: features (m x n): m examples with n features. """ # TODO: finish this. votes = [] features = np.asarray(features) # For each tree in the forest, get the classifications from each tree # based on the features used to build tree for i in range(self.num_trees): tree = self.trees[i] features_used = features[:, self.attributes_used[i]] votes.append(tree.classify(features_used)) votes = np.array(votes) classifications = [] # Based on the votes from each tree, return the class that most frequently appears for i in range(len(features)): classes = votes[:, i] class_val, class_count = np.unique(classes, return_counts=True) # Get the classification that appears most frequently and add it to the list classifications.append(class_val[np.argmax(class_count)]) return classifications # raise NotImplemented() class Vectorization: """Vectorization preparation for Assignment 5.""" def __init__(self): pass def non_vectorized_loops(self, data): """Element wise array arithmetic with loops. This function takes one matrix, multiplies by itself and then adds to itself. Args: data: data to be added to array. Returns: Numpy array of data. """ non_vectorized = np.zeros(data.shape) for row in range(data.shape[0]): for col in range(data.shape[1]): non_vectorized[row][col] = (data[row][col] * data[row][col] + data[row][col]) return non_vectorized def vectorized_loops(self, data): """Element wise array arithmetic using vectorization. This function takes one matrix, multiplies by itself and then adds to itself. Args: data: data to be sliced and summed. Returns: Numpy array of data. """ # TODO: finish this. data_np = np.array(data) data = (data_np * data_np) + data_np return data # raise NotImplemented() def non_vectorized_slice(self, data): """Find row with max sum using loops. This function searches through the first 100 rows, looking for the row with the max sum. (ie, add all the values in that row together). Args: data: data to be added to array. Returns: Tuple (Max row sum, index of row with max sum) """ max_sum = 0 max_sum_index = 0 for row in range(100): temp_sum = 0 for col in range(data.shape[1]): temp_sum += data[row][col] if temp_sum > max_sum: max_sum = temp_sum max_sum_index = row return max_sum, max_sum_index def vectorized_slice(self, data): """Find row with max sum using vectorization. This function searches through the first 100 rows, looking for the row with the max sum. (ie, add all the values in that row together). Args: data: data to be sliced and summed. Returns: Tuple (Max row sum, index of row with max sum) """ # TODO: finish this. data_np = np.array(data) data_np_slice = data_np[0:100, :] data_np_slice = np.sum(data_np_slice, axis=1) # Sum along all each row in the slice return (data_np_slice[np.argmax(data_np_slice)], np.argmax(data_np_slice)) # raise NotImplemented() def non_vectorized_flatten(self, data): """Display occurrences of positive numbers using loops. Flattens down data into a 1d array, then creates a dictionary of how often a positive number appears in the data and displays that value. ie, [(1203,3)] = integer 1203 appeared 3 times in data. Args: data: data to be added to array. Returns: List of occurrences [(integer, number of occurrences), ...] """ unique_dict = {} flattened = np.hstack(data) for item in range(len(flattened)): if flattened[item] > 0: if flattened[item] in unique_dict: unique_dict[flattened[item]] += 1 else: unique_dict[flattened[item]] = 1 return unique_dict.items() def vectorized_flatten(self, data): """Display occurrences of positive numbers using vectorization. Flattens down data into a 1d array, then creates a dictionary of how often a positive number appears in the data and displays that value. ie, [(1203,3)] = integer 1203 appeared 3 times in data. Args: data: data to be added to array. Returns: List of occurrences [(integer, number of occurrences), ...] """ # TODO: finish this. data_np_flat = np.array(data).flatten() data_positive = data_np_flat[data_np_flat > 0.0] values, number_of_occurrences = np.unique(data_positive, return_counts=True) list_of_occurrences = [] for i in range(len(values)): list_of_occurrences.append((values[i], number_of_occurrences[i])) return list_of_occurrences # raise NotImplemented() def return_your_name(): # return your name # TODO: finish this return "Dhruv Mehta" # raise NotImplemented()
65e225411c7a8f1fd5179b13d2aa825668e5d651
yusufazishty/Kaggle-WDI-Mining
/Energy/A_energy_fetching.py
9,147
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu May 26 11:19:05 2016 @author: yusufazishty """ #For converting the sqlite to the json files, the dataframe in spark need json inputs import sqlite3 as lite import sys import json import copy from pprint import pprint # fetch from sqlite data def fetch_db(query, data_path): con = None try: con = lite.connect(data_path) cur = con.cursor() cur.execute(query) data = cur.fetchall() return data except lite.Error as e: print("Error %s:" % e.args[0]) sys.exit(1) finally: if con: con.close() # save the fetched data from sql to csv def save_txt(dataToSave,fileName): #python 3 #csvfile = open(fileName, 'w', newline='') #python 2 #csvfile = open(fileName, 'wb') #Writer = csv.writer(csvfile, delimiter=';', quoting=csv.QUOTE_ALL) #Writer.writerow([ str("CountryName"), str("CountryCode"), str("Year"), str("Value") ]) with open(fileName, 'w') as txtfile: for i in range(len(dataToSave)): #print(locale.format('%.2f', float(dataToSave[i][3]), True)) #Writer.writerow([ str(dataToSave[i][0]), str(dataToSave[i][1]), int(dataToSave[i][2]), locale.format('%.2f', float(dataToSave[i][3]), True) ]) #Writer.writerow([ dataToSave[i][0], dataToSave[i][1], dataToSave[i][2], locale.format('%.2f', dataToSave[i][3], True) ]) try : line=str(dataToSave[i][0])+";"+str(dataToSave[i][1])+";"+str(dataToSave[i][2])+";"+str(dataToSave[i][3])+"\n" except IndexError as detail: print(detail) print(i) txtfile.write(line) txtfile.close() def get_dict(sql_data, Fields): sql_data_list=[] for i in range(len(sql_data)): dicti = {Fields[0]:sql_data[i][1], Fields[1]:sql_data[i][0], Fields[2]:sql_data[i][2], Fields[3]:sql_data[i][3] } sql_data_list.append(dicti) sql_data_dict = json.JSONEncoder().encode(sql_data_list) return sql_data_dict #Start fetching from the sqlite SQL_PATH = "database.sqlite" Fields=["CountryCode", "Country", "Year", "Value"] #1 Ambil data indikator %populasi terakses listrik query_1="SELECT CountryName,CountryCode,Year,Value FROM Indicators WHERE IndicatorCode = 'EG.ELC.ACCS.ZS' ORDER BY CountryName" akses_listrik = fetch_db(query_1,SQL_PATH) akses_listrik_dict = get_dict(akses_listrik, Fields) with open('fetched_data/akses_listrik.json', 'w') as fp: fp.write(akses_listrik_dict) fp.close() #2 Ambil data indikator %populasi terakses bbm non padat query_2="SELECT CountryName,CountryCode,Year,Value FROM Indicators WHERE IndicatorCode = 'EG.NSF.ACCS.ZS' ORDER BY CountryName" akses_bbm = fetch_db(query_2,SQL_PATH) akses_bbm_dict = get_dict(akses_bbm, Fields) #Edit the order with http://www.jsoneditoronline.org/ with open('fetched_data/akses_bbm.json', 'w') as fp: fp.write(akses_bbm_dict) fp.close() #3 Indikator energi terbarukan #a Ambil data indikator hydro electricity query_3a="SELECT CountryName,CountryCode,Year,Value FROM Indicators WHERE IndicatorCode = 'EG.ELC.HYRO.ZS' ORDER BY CountryName" hydro = fetch_db(query_3a,SQL_PATH) hydro_dict = get_dict(hydro, Fields) #Edit the order with http://www.jsoneditoronline.org/ with open('fetched_data/hydro.json', 'w') as fp: fp.write(hydro_dict) fp.close() #b Ambil data natural gas electricityquery_3a="SELECT CountryName,CountryCode,Year,Value FROM Indicators WHERE IndicatorCode = 'EG.ELC.HYRO.ZS' ORDER BY CountryName" query_3b="SELECT CountryName,CountryCode,Year,Value FROM Indicators WHERE IndicatorCode = 'EG.ELC.NGAS.ZS' ORDER BY CountryName" gas=fetch_db(query_3b,SQL_PATH) gas_dict = get_dict(gas, Fields) #Edit the order with http://www.jsoneditoronline.org/ with open('fetched_data/gas.json', 'w') as fp: fp.write(gas_dict) fp.close() # Cari persentase energi terbarukan tiap negara energi_terbarukan = copy.deepcopy(gas) for i in range(len(gas)): value=((energi_terbarukan[i][3]+hydro[i][3])/2) lst = list(energi_terbarukan[i]) lst[3]=value tup=tuple(lst) energi_terbarukan[i]=tup energi_terbarukan_dict = get_dict(energi_terbarukan, Fields) #Edit the order with http://www.jsoneditoronline.org/ with open('fetched_data/energi_terbarukan.json', 'w') as fp: fp.write(energi_terbarukan_dict) fp.close() #c Ambil data coal electricity query_3c="SELECT CountryName,CountryCode,Year,Value FROM Indicators WHERE IndicatorCode = 'EG.ELC.COAL.ZS' ORDER BY CountryName" coal=fetch_db(query_3c,SQL_PATH) coal_dict = get_dict(coal, Fields) #Edit the order with http://www.jsoneditoronline.org/ with open('fetched_data/coal.json', 'w') as fp: fp.write(coal_dict) fp.close() #d Ambil data oil electricity query_3d="SELECT CountryName,CountryCode,Year,Value FROM Indicators WHERE IndicatorCode = 'EG.ELC.PETR.ZS' ORDER BY CountryName" oil=fetch_db(query_3d,SQL_PATH) oil_dict = get_dict(oil, Fields) #Edit the order with http://www.jsoneditoronline.org/ with open('fetched_data/coal.json', 'w') as fp: fp.write(coal_dict) fp.close() energi_habis = copy.deepcopy(oil) for i in range(len(oil)): value=((energi_habis[i][3]+coal[i][3])/2) lst = list(energi_habis[i]) lst[3]=value tup=tuple(lst) energi_habis[i]=tup energi_habis_dict = get_dict(energi_habis, Fields) #Edit the order with http://www.jsoneditoronline.org/ with open('fetched_data/energi_habis.json', 'w') as fp: fp.write(energi_habis_dict) fp.close() #e Ambil data nuclear electricity query_3e="SELECT CountryName,CountryCode,Year,Value FROM Indicators WHERE IndicatorCode = 'EG.ELC.NUCL.ZS' ORDER BY CountryName" nuclear=fetch_db(query_3e,SQL_PATH) data=[] for i in range(len(nuclear)): for j in range(41): data.append(nuclear) nuclear_dict = get_dict(nuclear, Fields) #Edit the order with http://www.jsoneditoronline.org/ with open('fetched_data/nuclear.json', 'w') as fp: fp.write(nuclear_dict) fp.close() #Opening energi terbarukan, convert to dataset style, save to csv def train_test(source_file,train_name, test_name): with open(source_file) as json_data: data = json.load(json_data) #pprint(data) all_CountryCode=[] all_Country=[] all_Year=[] all_Value=[] for i in range(len(data)): all_CountryCode.append(data[i]["CountryCode"]) all_Country.append(data[i]["Country"]) all_Year.append(data[i]["Year"]) all_Value.append(data[i]["Value"]) dataset=[] for i in range(len(all_Country)): line=[] line.append(all_Value[i]);line.append(all_Year[i]); line.append(all_CountryCode[i]);line.append(all_Country[i]); dataset.append(line) #print(dataset) train=[] test=[] for i in range(len(dataset)): if dataset[i][1]==2012: test.append(dataset[i]) if dataset[i][1]!=2012: train.append(dataset[i]) #print(train) #print(test) distinct_code=[] code_count=0 distinct_country=[] country_count=0 for i in range(len(dataset)): if dataset[i][2] not in distinct_code: distinct_code.append(dataset[i][2]) code_count+=1 if dataset[i][2] not in distinct_country: distinct_country.append(dataset[i][2]) country_count+=1 #print(distinct_code) #for i in range(len(distinct_code)): # distinct_code[i]=(distinct_code[i],i) # distinct_country[i]=(distinct_country[i],i) #Transform data train ke numeric semua for i in range(len(train)): if train[i][0] in distinct_code: idx_dist_code = distinct_code.index(train[i][0]) train[i][0] = idx_dist_code train[i][1] = idx_dist_code print(train) #Transform data test ke numeric semua for i in range(len(test)): if test[i][0] in distinct_code: idx_dist_code = distinct_code.index(test[i][0]) test[i][0] = idx_dist_code test[i][1] = idx_dist_code print(test) save_txt(train, train_name) save_txt(test, test_name) source=["fetched_data/energi_terbarukan.json","fetched_data/energi_habis.json","fetched_data/nuclear.json"] train_name=["train_terbarukan.txt", "train_habis.txt", "train_nuclear.txt"] test_name=["test_terbarukan.txt", "test_habis.txt", "test_nuclear.txt"] for i in range(len(source)): train_test(source[i],train_name[i], test_name[i]) del akses_listrik, query_1, akses_bbm, query_2, hydro, query_3a, gas, query_3b, energi_terbarukan, coal, query_3c, oil, query_3d,energi_habis ,nuclear, query_3e
24f444f8c0bc2a8f6b7133a31e97fef2dad6e94f
Shruti280598/simple-chat-bot
/chat.py
1,265
3.796875
4
# simple-chat-bot import random import sys Questions = [ "How to use firefighting robot ?", "what care should ?", "for what purpose it can use" ] Answers = [ "First fill container of robot which will help to extinguise fire then switch on it's batttery to give power to the robot to work .", "keep it in room temperature" "clean it regularly", "when there is any type of fire accident " ] print("Hii i am firefighting robot cbatbot\n") def list_faq(): for i in range(len(Questions)): print(str(i)+" : "+Questions[i]) def check_for_FAQ_by_index(): list_faq() question_id = input("which question do you want to answer?\n") response = "" if "bye" in question_id: sys.exit() elif int(question_id) < len(Questions): response = Answers[int(question_id)] else: response = "I dont know the answer to that question " return response def check_for_FAQ(question): response =" " if qustion in Questions: index = Questions.index(question) response = Answers[index] else: response = "I dont know the answer to that" return response while True: response = check_for_FAQ_by_index() print("\n yourbot: " + response)
42426643e0b17b4e407d8ef4bff1301b7ce2034f
pdst-lccs/lccs-python
/Section 6 - Modular Programming/Breakout 6.4 Check Digits/extractDigit - 2 digits.py
344
3.734375
4
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Breakout 6.4 Check digits # Extract the digits from a 2 digit number n = int(input("Enter a 2 digit number: ")) d2 = n%10 # %10 extracts the final digit d1 = n//10 # //10 to remove the final digit print(d1, d2)
6aac8b7973cb7a70a86215d3bb18f730f1e7c595
neralwar/Python-Training
/Python Programming Basics/bubblesort.py
298
3.96875
4
#Bubble Sort def bubblesort(itmelist): for i in range(len(itmelist)): for i in range(0,len(itmelist)-i-1): if itmelist[i] > itmelist[i+1]: itmelist[i],itmelist[i+1] = itmelist[i+1],itmelist[i] print(itmelist) listitem = [1,4,3,6,15,18,19,0,17] bubblesort(listitem)
0ae8f744ccf3cd9cfbd88f6f010c2c2e506bf043
markhend/pe
/python/66.py
1,189
3.609375
4
from math import factorial, sqrt from time import time t = time() squares = {x*x for x in range(1,10**6)} sol = dict() for D in range(998,997,-1): if D in squares: continue print "D is", D, x = 1 while True: x += 1 y2 = divmod((x*x-1), D) print y2 input() if y2[0] in squares and y2[1] == 0: sol[D] = x break print "and min_x is", x print max(sol, key=sol.get) print 'time', time()-t ''' Consider quadratic Diophantine equations of the form: x^2 - Dy^2 = 1 For example, when D=13, the minimal solution in x is 649^2 - 13 x 180^2 = 1. It can be assumed that there are no solutions in positive integers when D is square. By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the following: 3^2 - 2 x 2^2 = 1 2^2 - 3 x 1^2 = 1 9^2 - 5 x 4^2 = 1 5^2 - 6 x 2^2 = 1 8^2 - 7 x 3^2 = 1 Hence, by considering minimal solutions in x for D<=7, the largest x is obtained when D=5. Find the value of D<=1000 in minimal solutions of x for which the largest value of x is obtained. Tough ones to calc are e.g. 61, 97, 106, 109, 139, 149, 151, 157 1000, 999, '''
a149133d2b3c56dd3c187f69fce5f5792ea58dd8
swdrich/python-challenge
/PyPoll/main.py
3,729
3.90625
4
#Import modules import os import csv #Don't panic, something is happening. print("Calculating...") #Establish file path csv_path = os.path.join("Resources","election_data.csv") #print(csv_path) #read CSV # Open the CSV with open(csv_path) as csv_file: election_data = csv.reader(csv_file, delimiter=",") #print(election_data) #Count the number of rows in the data set, minus the header header = next(election_data) #print(header) #define values #voter_ID = [] #county = [] candidate_name = [] #begin for loop for row in election_data: #add data to lists #voter_ID.append(str(row[0])) #county.append(str(row[1])) candidate_name.append(str(row[2])) #print(voter_ID) # Calcualte the total number of votes cast total_votes = len(candidate_name) #print(total_votes) #Get unique values from list and write to new list: #geeksforgeeks.org/python-get-unique-values-list/ # function to get unique values unique_candidates = [] candidate_votes = [] vote_total = 0 def unique(candidate_name): # traverse for all elements for name in candidate_name: # check if exists in unique_list or not if name not in unique_candidates: unique_candidates.append(name) # print list #for name in unique_candidates: #print (name) return unique_candidates unique(candidate_name) #print(unique_candidates) #count votes per candidate candidate_votes = [] def vote_count(unique_candidates): #set initial counter vote_total = 0 #traverse first list for name in unique_candidates: #compare to second list for vote in candidate_name: #add votes if name == vote: vote_total = int(vote_total) + 1 #add to list candidate_votes.append(vote_total) #print(candidate_votes) #reset counter vote_total = 0 return candidate_votes vote_count(unique_candidates) #print(candidate_votes) #find winner win_vote = max(candidate_votes) win_index = candidate_votes.index(win_vote) winner = unique_candidates[win_index] #print(winner) #calcualte vote percentage total candidate_vote_percent = [] for x in (candidate_votes): vote_percent = round((float(int(x) / int(total_votes)) * 100), 3) candidate_vote_percent.append(vote_percent) #print(candidate_vote_percent) #print(unique_candidates) #print(candidate_vote_percent) #print(candidate_votes) #zip lists to make tuple candidate_tuple = tuple(zip(unique_candidates, candidate_vote_percent, candidate_votes)) #candidate_1 = list(candidate_tuple[0]) #print(candidate_1) print(" ") print("Election Results") print("--------------------------") print(f"Total Votes: {total_votes}") print("--------------------------") for lst in candidate_tuple: print(f"{lst[0]}: {lst[1]}00% ({lst[2]})") print("--------------------------") print(f"Winner: {winner}") print("--------------------------") #Open export path for text file: #tip o' the pin to this exchange: # https://stackoverflow.com/questions/5214578/print-string-to-text-file output_path = os.path.join("Analysis", "PyPoll_Analysis.txt") with open(output_path, "w") as text_file: print("Election Results", file = text_file) print("--------------------------", file = text_file) print(f"Total Votes: {total_votes}", file = text_file) print("--------------------------", file = text_file) for lst in candidate_tuple: print(f"{lst[0]}: {lst[1]}00% ({lst[2]})", file=text_file) print("--------------------------", file = text_file) print(f"Winner: {winner}", file = text_file) print("--------------------------", file = text_file)
bda6756d7cff2f90513e717a7428b61842b041d8
vivver4/Python_Spider
/验证码的识别/普通图形验证码.py
748
3.578125
4
''' 安装tesserocr的时候用pip intall tesserocr pillow总是发生错误,用 conda install -c simonflueckiger tesserocr可以成功,-c直接从https://conda.anaconda.org搜索 simonflueckiger的tesserocr库安装 这个内容需要复制到C盘符下的scratch.py中运行,具体原因不清楚 ''' import tesserocr from PIL import Image image=Image.open('C:/Users/shangya/Desktop/a.jpg') ''' 转灰度处理 ''' image=image.convert('L') ''' 二值化处理 这里设置阈值为140效果较好,默认为127 ''' threshold=140 table=[] for i in range(256): if i < threshold: table.append(0) else: table.append(1) image=image.point(table, '1') image.show() result=tesserocr.image_to_text(image) print(result)
a67d89b8d8396f2ccfebac170e867427a557e471
SoloExitus/SANDPT
/Task2.py
418
3.734375
4
def is_numeric(x): if type(x) == int or type(x) == float: return True return False def coincidence(*args) -> list: res = [] if len(args) < 2: return res array = args[0] range = args[1] min = range[0] max = range[len(range) - 1] + 1 for x in array: if (is_numeric(x)): if (x >= min and x < max) : res.append(x) return res
ac1b06a6d15c6c16b49c6fbb6a7e0c87810d156f
jinhyun-so/CodedPrivateNN
/models/activ_func.py
5,005
4.03125
4
import torch from torch import nn import torch.nn.functional as F from torch.nn.parameter import Parameter # import Parameter to create custom activations with learnable parameters # simply define a silu function def silu(input): ''' Applies the Sigmoid Linear Unit (SiLU) function element-wise: SiLU(x) = x * sigmoid(x) ''' return input * torch.sigmoid(input) # use torch.sigmoid to make sure that we created the most efficient implemetation based on builtin PyTorch functions # create a class wrapper from PyTorch nn.Module, so # the function now can be easily used in models class SiLU(nn.Module): ''' Applies the Sigmoid Linear Unit (SiLU) function element-wise: SiLU(x) = x * sigmoid(x) Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input References: - Related paper: https://arxiv.org/pdf/1606.08415.pdf Examples: >>> m = silu() >>> input = torch.randn(2) >>> output = m(input) ''' def __init__(self): ''' Init method. ''' super().__init__() # init the base class def forward(self, input): ''' Forward pass of the function. ''' return silu(input) # simply apply already implemented SiLU class soft_exponential(nn.Module): ''' Implementation of soft exponential activation. Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input Parameters: - alpha - trainable parameter References: - See related paper: https://arxiv.org/pdf/1602.01321.pdf Examples: >>> a1 = soft_exponential(256) >>> x = torch.randn(256) >>> x = a1(x) ''' def __init__(self, in_features, alpha=None): ''' Initialization. INPUT: - in_features: shape of the input - aplha: trainable parameter aplha is initialized with zero value by default ''' super(soft_exponential, self).__init__() self.in_features = in_features # initialize alpha if alpha == None: self.alpha = Parameter(torch.tensor(0.0)) # create a tensor out of alpha else: self.alpha = Parameter(torch.tensor(alpha)) # create a tensor out of alpha self.alpha.requiresGrad = True # set requiresGrad to true! def forward(self, x): ''' Forward pass of the function. Applies the function to the input elementwise. ''' if (self.alpha == 0.0): return x if (self.alpha < 0.0): return - torch.log(1 - self.alpha * (x + self.alpha)) / self.alpha if (self.alpha > 0.0): return (torch.exp(self.alpha * x) - 1) / self.alpha + self.alpha class act_xsquare(nn.Module): def __init__(self): ''' Init method. ''' super().__init__() # init the base class def forward(self, input): ''' Forward pass of the function. ''' return input * input # simply apply already implemented SiLU class act_xsquare2(nn.Module): def __init__(self): ''' Init method. ''' super().__init__() # init the base class def forward(self, input): ''' Forward pass of the function. ''' return input * input + input # simply apply already implemented SiLU class act_poly(nn.Module): def __init__(self, degree): ''' Init method. ''' super().__init__() # init the base class self.degree = degree def forward(self, input): ''' Forward pass of the function. ''' if self.degree == 2: return 0.1992 + 0.5002*input + 0.1997 * input * input # simply apply already implemented SiLU if self.degree == 3: return 0.1995 + 0.5002 * input + 0.1994 * input * input + 0.0164 * input * input * input class act_poly_param(nn.Module): def __init__(self, in_features, c0 = None, c1 = None, c2 = None): ''' Initialization. INPUT: - in_features: shape of the input - aplha: trainable parameter aplha is initialized with zero value by default ''' super().__init__() # super(act_poly_param, self).__init__() self.in_features = in_features self.c0 = Parameter(torch.tensor(0.1992)) self.c1 = Parameter(torch.tensor(0.5002)) self.c2 = Parameter(torch.tensor(0.1997)) self.c0.requiresGrad = True self.c1.requiresGrad = True self.c2.requiresGrad = True def forward(self, input): ''' Forward pass of the function. Applies the function to the input elementwise. ''' return self.c0 + self.c1*input + self.c2 * input * input
d70165ce93014d5baaa9610b284daea03fa59fe2
Ummyers/ProbabilidadPython
/MemoProgramas/UsuarioProba.py
371
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 26 17:04:14 2020 Curso introductorio de Proba para python. @author: ummyers """ while True: try: entero = int(input("Ingresa un número: ")) except ValueError: print("Ingresaste un número inválido") else: print("Elegiste el número entero ", entero) break
1b8d8aa0f8caf88106d09b0248fa05453ece622e
GitSeob/programmers
/all/lv1/secret_map.py
468
3.65625
4
def solution(n, arr1, arr2): res = [] for a, b in zip(arr1, arr2): line = '' div = 2**(n-1) # print(a, b) for _ in range(n): if a // div > 0 or b // div > 0: line += '#' else: line += ' ' a = a%div b = b%div div = div//2 res.append(line) return res arr1 = [9, 20, 28, 18, 11] arr2 = [30, 1, 21, 17, 28] arr3 = [46, 33, 33, 22, 31, 50] arr4 = [27, 56, 19, 14, 14, 10] print(solution(5, arr1, arr2)) print(solution(6, arr3, arr4))
93e61f82256ef3cd620315b19d60ddc8b88716e5
dongupak/Basic-Python-Programming
/Ch20_Coding/coding_stype_bad.py
524
3.5625
4
# ( a * x^2 ) + ( b * x ) + c = 0 # a != 0 인 x에 관한 2차 방정식, 근의 공식으로 해 구하기 # 매개변수를 사용해서 해를 출력해 봅시다 def get_root( a, b, c) : r1 = (-b + (b ** 2 - 4 * a * c ) ** 0.5)/ (2 * a) r2 = (-b - (b ** 2 - 4 * a * c) ** 0.5)/( 2*a ) return r1 , r2 # 함수 호출시 인자를 상수값을 사용함 # result1, result2를 이용해서 결과값을 반환 받아온다 result1 , result2= get_root(1, 2, -8) print('해는', result1,'또는',result2)
a5e572307bac8170cdc13454131fb95fff5b1ee1
cpeixin/leetcode-bbbbrent
/linklist/LRUCache.py
3,308
3.828125
4
""" https://github.com/wangzheng0822/algo/blob/master/python/06_linkedlist/LRUCache.py """ class DbListNode(object): def __init__(self, x, y): """ 节点为哈希表+双向链表 :param x: :param y: """ self.key = x self.value = y self.next = None self.prev = None class LRUCache(object): def __init__(self, capacity): """ 初始化一个空双向链表 :type capacity: int """ self.cap = capacity self.catche = {} self.top = DbListNode(None, -1) self.tail = DbListNode(None, -1) self.top.next = self.tail self.tail.prev = self.top def get(self, key): """ :type key: int :rtype: int """ """判断节点是否存在""" if key in self.catche.keys(): cur = self.catche[key] """首先跳出原来的位置""" cur.prev.next = cur.next cur.next.prev = cur.prev """top,tail为哨兵节点""" top_node = self.top.next cur.next = top_node top_node.prev = cur self.top.next = cur cur.prev = self.top return cur.value return -1 def put(self, key, value): """ :type key: int :type value: int :rtype: None """ if key in self.catche.keys(): """如果插入节点存在,则将插入节点调换为位,插入到哨兵节点后的头节点。此时不存在增删节点,所以不用判断链表长度""" cur = self.catche[key] """首先跳出原来的位置""" cur.prev.next = cur.next cur.next.prev = cur.prev """top,tail为哨兵节点""" top_node = self.top.next cur.next = top_node top_node.prev = cur self.top.next = cur cur.prev = self.top else: # 增加新结点至首部 cur = DbListNode(key, value) self.catche[key] = cur # 最近用过的置于链表首部 top_node = self.top.next self.top.next = cur cur.prev = self.top cur.next = top_node top_node.prev = cur """判断长度删除尾节点""" if len(self.catche.keys()) > self.cap: self.catche.pop(self.tail.prev.key) # 去掉原尾结点 self.tail.prev.prev.next = self.tail self.tail.prev = self.tail.prev.prev def __repr__(self): vals = [] p = self.top.next while p.next: vals.append(str(p.value)) p = p.next return '->'.join(vals) if __name__ == '__main__': cache = LRUCache(2) cache.put(1, 1) cache.put(2, 2) print(cache) cache.get(1) # 返回 1 print(cache) cache.put(3, 3) # 该操作会使得密钥 2 作废 print(cache) cache.get(2) # 返回 -1 (未找到) print(cache) cache.put(4, 4) # 该操作会使得密钥 1 作废 print(cache) cache.get(1) # 返回 -1 (未找到) cache.get(3) # 返回 3 print(cache) cache.get(4) # 返回 4 print(cache)
ce3af49196e4413c9806f348444cef3b1477cdc7
vrushti-mody/Leetcode-Solutions
/Reverse_Bits.py
249
3.5625
4
# Reverse bits of a given 32 bits unsigned integer. n=str(bin(n)) a="" for i in range(0,len(n)-2): a = a + n[len(n)-i-1] for i in range(len(n)-2,32): a=a+"0" print(a) return int(a,2)
72cee0bbc26a869d04a25f40584f571f67e67f6f
MajkelT/Python_Bootcamp_ALX_03102018
/Collections/Zadanie #1.py
220
3.875
4
x=(1,2,3,4,5,6,7,8,9,10) print(x[1]) #drugi element print(x[-2]) #przedostatni element print(x[2:7]) #elementy od trzeciego do siódmego print(x[::3]) #co trzeci element print(x[::-2]) #co drugi element licząc od końca
d11da144abcdce75b0bf8803edc827f0f5740abc
GabeAboy/PythonScripts
/NewLine.py
226
3.640625
4
x = 'There is a dog and fox fighting in the park and there is an apple falling down.' x = x.split(' ')#insert veriable for i,word in enumerate(x): if i != 0 and i % 3 == 0: x[i] = word + '\n' print ' '.join(x)
54f3e7d61e6610ddaf8374f2a1841d0ea37817dd
ProgrammingMuffin/major
/filter.py
347
3.78125
4
from nltk.corpus import stopwords from nltk.tokenize import word_tokenize def removeStopWords(sentence): words = word_tokenize(sentence) stopWords = set(stopwords.words('english')) newWords = [word for word in words if not word in stopWords] return newWords def extractUselessWords(words): #handle removal of useless words
65a9de9c8f70b3bae2bfa0c58a720c2cad9380b3
bowmanjd/pycsvdemo
/simplereader.py
299
3.5625
4
import csv from pathlib import Path inpath = Path("sample.csv") with inpath.open("r", newline="", encoding="utf-8-sig") as infile: reader = csv.DictReader(infile) for row in reader: fullname = f"{row['First name']} {row['Middle name']} {row['Last name']}" print(fullname)
5a79d217ef029e7ba047358526e7408423855066
demlook/Python_test
/testcode/function.py
5,679
4.03125
4
#函数 def favorite_book(book): print("One of my favorite book is " + book + ".") favorite_book('Alice in Wonderland') ############################################### # 1 位置实参,顺序必须与形参一致 def make_shirt(size,phrase): print("This T-shirt's size is " + size + ".") print("Imprinted phrase is " + "\"" + phrase + "\"") make_shirt('L','hello world!') # 2 关键字实参,顺序无关 def make_shirt(size,phrase): print("This T-shirt's size is " + size + ".") print("Imprinted phrase is " + "\"" + phrase + "\"") make_shirt(phrase='hello world!',size='XL') # 3 使用默认值,有默认值的形参必须放形参列表最后 def make_shirt(size,phrase,color='white'): print("This " + color + " T-shirt's size is " + size + ".") print("Imprinted phrase is " + "\"" + phrase + "\"") make_shirt('L','hello world!') make_shirt('XL','smile','black') ########################################################### def city_country(city,country): return city.title() + "," + country.title() print(city_country('beijing','China')) print(city_country('tokyo','Japen')) print(city_country('new york','America')) ########################################################## def make_album(name_1,name_2,number=''): # music_albums = {} # music_albums['singer'] = name music_albums = {'singer':name_1,'album_name':name_2} if number: music_albums['amount'] = number return music_albums while True: print("You can enter 'q' to quit at any time!") s_name = input("What's the singer's name? ") if s_name == 'q': break a_name = input("What about the name of the music album? ") if a_name == 'q': break album_1 = make_album(s_name,a_name) print(album_1) ############################################################### def show_magicians(magicians): for magician in magicians: print(magician) def make_great(magicians): for n in range(0,len(magicians)): magicians[n] = "the Great " + magicians[n] return magicians ''' for magician in magicians: magician = "the Great " + magician for magician in magicians: print(magician) 该方式并不能修改列表元素,只能通过索引修改 ''' names = ['zhangsan','lisi','wangwu'] names_2 = [] # 使用切片表示法为 names 列表创建副本 names_2 = make_great(names[:]) show_magicians(names_2) show_magicians(names) ##################################################################### #传递任意数量的实参 ''' *topping 使用*号 让python创建一个名为topping的空元组, 并将收到的所有值都封装到这个元组中 ''' def make_sandwich(*toppings): print("You order the sandwich with:") for topping in toppings: print("-" + topping) make_sandwich('tomato','egg','ham') make_sandwich('egg') make_sandwich('meat','fruit','tomato','pepper') #使用任意数量关键字实参 ''' **user_info **让python创建名为user_info的字典, 并将接收到的所有 名称-值 对封装到字典里 ''' # 1 def build_profile(first,last,**user_info): profile = {} profile['first_name'] = first profile['last_name'] = last for key,value in user_info.items(): profile[key] = value return profile user_profile = build_profile('san','zhang',weight='70kg',location='China') print(user_profile) # 2 def make_profile(manufacturer,model_num,**car_info): profile = {} profile['manufacturer'] = manufacturer profile['model_num'] = model_num for k,v in car_info.items(): profile[k] = v return profile car_profile = make_profile('Volkswagen','SUV',calor='black',price='12w-20w') print(car_profile) ######################################################################## #将函数存入模块 #1 导入整个模块 #指定导入模块名称和模块内函数名,并用 . 连接 import printing_function user_profile = printing_function.build_profile('san','zhang',weight='70kg',location='China') print(user_profile) #2 导入特定函数 #from 模块名 import 函数名,调用函数时可以不使用模块名和 . from printing_function import build_profile user_profile = build_profile('si','li',weight='60kg',location='China') print(user_profile) #3 使用as给函数和模块指定别名 import printing_function as pf user_profile = pf.build_profile('san','zhang',weight='70kg',location='China') print(user_profile) from printing_function import build_profile as bp user_profile = bp('si','li',weight='60kg',location='China') print(user_profile) #################################################################### # Python 标准库 # test-1 from collections import OrderedDict favorite_singers = OrderedDict() favorite_singers['Jack'] = 'Taylor' favorite_singers['Tim'] = 'Justin' favorite_singers['Bob'] = 'Rihanna' favorite_singers['Rose'] = 'S.H.E.' for name,singer in favorite_singers.items(): print(name + "'s favorite singer is " + singer) #test-2 from random import randint class Die(): def __init__(self,sides=6): self.sides = sides def roll_die(self): print(randint(1,self.sides)) dice = Die(20) for n in range(1,11): dice.roll_die() ##################################################################### ''' 注意事项: 1.from 模块名 import * ,可以导入模块中的所有函数,且无需使用点号(.)表示法。 然而,如果模块中存在函数名称与本项目中函数名称相同的情况,则可能会导致意料之外的结果。 要么只导入需要使用的函数,要么使用点号(.)表示法。 2.函数应使用描述性名称,且仅使用小写字母和下划线构成 3.给形参或者实参指定默认值时,等号两边不应有空格。 4.参数列表过长时使用换行,如 def function( p_1,p_2,p_3, p_4,p_5): function body... '''
dee96038457eb3f2c39173409ef7d367750b21a5
dan88934/portfo
/server.py
2,551
3.609375
4
from flask import Flask, render_template, url_for, request, redirect import csv app = Flask(__name__) #Here we use the flask class to instantiate an app print(__name__) #Frameworks give us a higher level of abstraction - meaning t #-hat we don't need to know what the code is doing underneigh #We just need to know that the parts give us extra features #The decorators below are called end points @app.route('/') #We pass what is received here, into the hello world name param below def my_home(): return render_template('index.html') #Putting the above alone will not work as flask auto tries to find a folder called templates #So, we must first create a folder called templates @app.route('/<string:page_name>') #This works the same as having the below def html_page(page_name): return render_template(page_name) def write_to_file(data): with open('database.txt', mode='a') as database: #Mode=a appends to the file email = data["email"] subject = data["subject"] message = data["message"] file = database.write(f'\n{email},{subject},{message}') def write_to_csv(data): with open('database.csv', newline='', mode='a') as database2: email = data["email"] subject = data["subject"] message = data["message"] csv_writer = csv.writer(database2, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow([email,subject,message]) @app.route('/submit_form', methods=['POST', 'GET']) def submit_form(): if request.method == 'POST': try: data = request.form.to_dict() # write_to_file(data) write_to_csv(data) return redirect('/thankyou.html') except: return 'Did not save to database' else: return 'somthing went wrong. Try again!' #Rather than using the below, we have created a dynamic version above # @app.route('/work.html') #This is a decorator # def work(): # return render_template('work.html') # @app.route('/about.html') #This is a decorator # def about(): # return render_template('about.html') # @app.route('/index.html') #This is a decorator # def index(): # return render_template('index.html') # @app.route('/works.html') #This is a decorator # def works(): # return render_template('works.html') # @app.route('/contact.html') # def contact(): # return render_template('contact.html') #In order to use HTML, CSS and JS files rather than just passing text into strings #-we use render template
35bccdcf6bbbc5fb7519e6db032b9df30a80a5bf
silvervulpus/storage
/myprogram2.py
957
4
4
''' def age_foo(age): new_age = (age) + 50 return new_age age = float(input("Enter your age?: ")) if age < 150: print(age_foo(age)) else: print ("You are far too old") ''' def Cel_to_Fahr(c): if c <= -273.15: return ("Invalid Input") else: f = c*9/5 + 32 return f tempuratures = [100, 10, 28, -287, -27] for c in tempuratures: print (Cel_to_Fahr(c)) cConvert = str(Cel_to_Fahr(c)) file = open("ftoc.txt", "w+") for l in cConvert: file = open("ftoc.txt", "w+") file.write(cConvert) file.seek(0) content = file.readlines() file.seek(0) print(content) file.close() ''' def Length_of_String(f): length = f return len(f) f = input("Input a string here for its length ") if type(f) == int: print ("We cannot use len on an int") elif type(f) == float: print ("We cannot use len on a float") print (Length_of_String(f)) '''
8b8aafca9ef3b3384231ca7e4cbf6dbbfcae187c
rciurlea/py-ctci
/1.2.py
615
3.96875
4
# Check Permutation: Given two strings, write a method # to decide if one is a permutation of the other. def is_perm(a, b): chars = {} for c in a: if c in chars: chars[c] += 1 else: chars[c] = 1 for c in b: if c in chars: chars[c] -= 1 else: return False for c in chars: if chars[c] != 0: return False return True print(is_perm("", "")) print(is_perm("radu", "udar")) print(is_perm("ana", "aan")) print(is_perm("tttt", "tttt")) print(is_perm("craci", "crac")) print(is_perm("craci", "craca"))
5ec42e033170261361700e31540afddb8f14b9b5
arnabs542/Data-Structures-And-Algorithms
/Bit Manipulation/Different Bits Sum Pairwise.py
1,399
3.765625
4
""" Different Bits Sum Pairwise Problem Description We define f(X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f(2, 7) = 2, since binary representation of 2 and 7 are 010 and 111,respectively. The first and the third bit differ, so f(2, 7) = 2. You are given an array of N positive integers, A1, A2 ,..., AN. Find sum of f(Ai, Aj) for all pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 10^9+7. Problem Constraints 1 <= N <= 100000 1 <= A[i] <= INTMAX Input Format First and only argument of input contains a single integer array A. Output Format Return a single integer denoting the sum. Example Input Input 1: A = [1, 3, 5] Example Output Ouptut 1: 8 Example Explanation Explanation 1: f(1, 1) + f(1, 3) + f(1, 5) + f(3, 1) + f(3, 3) + f(3, 5) + f(5, 1) + f(5, 3) + f(5, 5) = 0 + 1 + 1 + 1 + 0 + 2 + 1 + 2 + 0 """ class Solution: # @param A : list of integers # @return an integer def cntBits(self, A): ans = 0 for i in range(31): count0, count1 = 0, 0 for j in range(len(A)): if (A[j] & (1<<i)) != 0: count1 += 1 else: count0 += 1 ans = (ans + 2*count0*count1)%(10**9+7) return ans
01ca8a939f2b04bf6f4628418703d61050499ceb
jaybhanushali3195/Datapreprocessing-Visualization-Tutorials
/data cleaning/chapter5/FillMissingValues.py
272
3.5
4
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(2, 2), index=['1', '3'], columns=['key_1', 'val_1'] ) df = df.reindex(['1', '2']) print(df) print("NaN replaced with '0':") print(df.fillna(0))
36b18f675eb648774a6e8af2fef79123024e4ff8
goutkannan/HackerRank
/python/design_pattern/decorator.py
438
3.875
4
import time def timeit(func): def decorated(*args,**kwargs): start = time.time() result = func(*args,**kwargs) end = float(time.time() -start) print("Ran in seconds",end) return result return decorated #typical decorator usage @timeit def factorial(num): fact =1 for i in range(2,num+1): fact*=i return fact print("Calculation factorial of 20") print(factorial(90))
0e00dd96a21b54913d9e79fb869e3ebf26d5b30b
kibazohb/Leetcode-Grind
/Medium/similarSentences/solution_01.py
1,255
3.59375
4
from collections import defaultdict class Solution: def areSentencesSimilarTwo(self, words1: List[str], words2: List[str], pairs: List[List[str]]) -> bool: #base cases if len(words1) != len(words2): return False if len(pairs) == 0 and words1 == words2: return True #put components in adjacent list graph = defaultdict(set) for pair in pairs: graph[pair[0]].add(pair[1]) graph[pair[1]].add(pair[0]) def dfs(w1,w2, visited) -> bool: if w1 == w2: return True if w2 in graph: for neighbour in graph[w2]: if (w1,neighbour) not in visited: visited.add((w1,neighbour)) if dfs(w1,neighbour,visited): print(visited) return True return False else: return False for word1,word2 in zip(words1,words2): if not dfs(word1, word2, visited = set()): return False return True
b02229082b43f1fd777606f88f2c9b80ac2e6c59
adqz/interview_practice
/algo_expert/p55_suffix_trie.py
909
3.890625
4
class SuffixTrie: def __init__(self, string): self.root = {} self.endSymbol = "*" self.populateSuffixTrieFrom(string) def populateSuffixTrieFrom(self, string): for i in range(len(string)): self.createSuffixTrie(i, string) def createSuffixTrie(self, i, string): node = self.root for j in range(i, len(string)): char = string[j] if char not in node: node[char] = {} node = node[char] node[self.endSymbol] = True def contains(self, string): node = self.root # Traverse string for char in string: if char not in node: return False node = node[char] # Check if we've reached the end in the Trie if self.endSymbol in node: return True else: return False
260e4a07beec9abbaab641ea3750fc606e939e2d
padma108raj/python
/String_Programs/splitnJoin.py
197
3.765625
4
s="Diabetic paitents are more in india" l=s.split() ll=[] for x in l: ll.append(x) print('list',ll) #syntax join string = seperator.join(group of strings) s=":".join(ll) print("The String:",s)
60385e178b9ade4d54f454efa22bd83aad956f0e
apalania/python2018
/PlackettBurmanDesign/PB_design.py
2,126
3.890625
4
from pyDOE import pbdesign import math #for arranging F values in increasing order def BubbleSort(Fval): sort=Fval n = len(sort) #corresponding to every element in the array for i in range(n): for j in range(0, n-i-1): if (sort[j] > sort[j+1]): # swapping if the element is greater than next element sort[j]= sort[j+1] sort[j+1]=sort[j] return sort n=int(raw_input("Enter the number of parameters:")) matrix=pbdesign(n) print "Each column corresponds to a parameter ranging from A to Z, and then A1 to Z1 and so on" print matrix print "Enter the number of dummy variables:" dum_num=int(raw_input()) dum_pos=[] num=0 for j in range(0,dum_num): print "Enter the position of dummy variable:" num=int(raw_input()) dum_pos.append(num-1) #accept the response values corresponding to each experimental trial res=[] for i in range(0,n+1): print "The yield for the",i+1,"th trial:" val=float(raw_input()) res.append(val) #list of all differences for each parameter difference=[] for column in range(0,n): sum=0.0 for row in range(0,n+1): sum+=(matrix[row][column])*res[row] difference.append(sum) print "Difference b/w high and low values:",difference #variance Mean_sqr=[] for val in difference: MS=(math.pow(val,2))/(n+1) Mean_sqr.append(MS) MSE=0.0 Mean=0.0 #determination of mean square error for i in range(0,dum_num): Mean+=Mean_sqr[dum_pos[i]] MSE=Mean/len(dum_pos) print "Variance:",Mean_sqr print "Mean square error:",MSE #F test value for each parameter F_value=[] for i in range(0,n): F_value.append(Mean_sqr[i]/MSE) print "F value for the given set of parameters:",F_value dict={} for char,val in [A-Z],F_value: #corresponding to the given parameters dict={char:val} print dict #dictionary mapping the varibales to their corresponding F values print "Order of significance of the parameter on the system:",BubbleSort(dict.values())
26d5e42bb4593d6c8c5fc9cdc6cbd4bb87822f29
ksenia629/IvanovaK
/Lab1/mygroup.py
1,358
3.546875
4
def print_students(students): print(u"Имя".ljust(10), u"Фамилия".ljust(10), u"Экзамены".ljust(50), u"Оценки".ljust(20)) for student in students: print(student["name"].ljust(10), student["surname"].ljust(10), str(student["exams"]).ljust(50), str(student["marks"]).ljust(20)) def filter(groupmates, sb): id = 0 idd = [] for groupmate in groupmates: id =int( id + 1) ss = 0 for mark in groupmate["marks"]: ss = ss + mark ss = ss / 3 if ss >= sb: idd.append(id) return idd groupmates = [ { "name": "Александр", "surname": "Иванов", "exams": ["Информатика", "ЭЭиС", "Web"], "marks": [4, 3, 5] }, { "name": "Иван", "surname": "Петров", "exams": ["История", "АиГ", "КТП"], "marks": [4, 4, 4] }, { "name": "Кирилл", "surname": "Смирнов", "exams": ["Философия", "ИС", "КТП"], "marks": [5, 5, 5] } ] print_students(groupmates) print('') sb = int(input('Введите средний балл - ')) print('') ids = filter(groupmates, sb) filter = [] for elem in ids: filter.append(groupmates[elem]) print_students(filter)
5df79f7e46efcdafc3235c7114ab7d9e5c4cb6ea
p-lots/codewars
/7-kyu/shorter-concat-[reverse-longer]/python/solution.py
198
3.671875
4
def shorter_reverse_longer(a, b): short, long = min(a, b, key=len), max(a, b, key=len) if len(a) == len(b): short = b long = a return f'{short}{long[::-1]}{short}'
755c42fc3cefd94e5787bfba8c05b9cfbf06fce9
jbanerje/Beginners_Python_Coding
/coding_bat_1.py
122
4
4
test_str = input('Enter the String:') rep = int(input('How many times you want to repeat:')) print(test_str * rep)
a0550d3bf01acc4d856953015a0bd399b37a7fb4
Aasthaengg/IBMdataset
/Python_codes/p03352/s635501060.py
211
3.75
4
from math import sqrt x = int(input()) l = [] if x == 1: print(1) exit() for i in range(1, int(sqrt(x))+1): for j in range(2, x+1): if 1 <= i**j <= x: l.append(i**j) print(max(l))
ca4e104d974e044175012491a49639e5a523f33d
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/9_3.py
2,733
4.375
4
Python Program to Compute Life Path Number Given a String of date of format YYYYMMDD, our task is to compute the life path number. **Life Path Number** is the number obtained by summation of individual digits of each element repeatedly till single digit, of datestring. Used in Numerology Predictions. **Examples:** > **Input :** test_str = “19970314” > > **Output :** 7 > > **Explanation :** 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 3 = 3 [ > month ] ; 1 + 4 = 5 [ day ]. 5 + 3 + 8 = 16 ; 1 + 6 = 7. > > > > > > > > **Input :** test_str = “19970104” > > **Output :** 4 > > **Explanation :** 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 1 = 1 [ > month ] ; 0 + 4 = 4 [ day ]. 4 + 1 + 8 = 13 ; 1 + 3 = 4. **Method 1: Using loop** The logic behind computing this is getting a summation of each digit and perform %10 at each step. This way result curlers to single digit if it goes to double-digit. ## Python3 __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Life Path Number # Using loop # initializing string test_str = "19970314" # printing original string print("The original string is : " + str(test_str)) res = 0 for num in test_str: res += int(num) # modulation in case of 2 digit number if res > 9: res = res % 10 + res // 10 # printing result print("Life Path Number : " + str(res)) --- __ __ **Output:** The original string is : 19970314 Life Path Number : 7 **Method 2: Using recursion** Similar way as above, the difference being the recursive function is used for repeated modulation in case of digit count greater than 1. ## Python3 __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Life Path Number # Using recursion # initializing string test_str = "19970314" # printing original string print("The original string is : " + str(test_str)) # recursion function definition def lpn(num): return num if num < 10 else lpn(num // 10 + num % 10) # recursive function initial call res = lpn(int(test_str)) # printing result print("Life Path Number : " + str(res)) --- __ __ **Output:** The original string is : 19970314 Life Path Number : 7 Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
b06c9b2939028d88752735eb12ba4299f54f54b2
Thorjezar/pythonDemo
/laowang/main.py
3,880
3.5
4
# coding=utf-8 ''' 老王开枪 ''' class Person(object): '''人的类''' def __init__(self, name): super().__init__() self.name = name self.weapon = None # 用来保存枪的引用 self.hp = 100 # 剩余的血量 def __str__(self): if self.weapon: return "%s 的血量是%d,持有武器:%s"%(self.name, self.hp, self.weapon) else: if self.hp > 0: return "%s 的血量是%d,他没有武器"%(self.name, self.hp) else: return "%s 已经阵亡"%self.name def load_bullet(self, dan_jia_temp, bullet_temp): '''子弹上膛的方法,把子弹押入弹夹中''' dan_jia_temp.load_bu(bullet_temp) def load_danjia(self, gun_temp, danjia_temp): '''枪安装弹夹 枪.安装弹夹(弹夹)''' gun_temp.load_danjia(danjia_temp) def holdweapon(self, weapon_name): '''拿起一把枪''' self.weapon = weapon_name def koubanji(self, enemy): '''让枪发射子弹去打到敌人''' self.weapon.openfire(enemy) def blood(self, demage): '''根据伤害掉相应的血量''' self.hp -= demage class Gun(object): '''枪的类''' def __init__(self, name): super().__init__() self.name = name # 初始化枪的名称 self.danjia = None # 初始化弹夹的引用 def __str__(self): if self.danjia: return "枪的信息为:%s, 弹夹的信息为:%s"%(self.name, self.danjia) else: return "枪的信息为:%s" % (self.name) def load_danjia(self, danjia_temp): # 用一个属性保存弹夹 self.danjia = danjia_temp def openfire(self, enemy): '''枪从弹夹中获取一发子弹,然后子弹去击中''' # 第一个步从弹夹中弹出一颗子弹 zidan_temp = self.danjia.tanchu_zidan() # 第二步子弹击打敌人 if zidan_temp: zidan_temp.onfouce(enemy) else: print("弹夹中没有子弹了") class Collection(object): '''弹夹的类''' def __init__(self, max_num): super().__init__() self.max_num = max_num # 用来记录弹夹的最大容量 self.bullet_list = [] # 用来记录所有的子弹的引用 def __str__(self): return "弹夹的容量为:%d/%d"%(len(self.bullet_list), self.max_num) def load_bu(self, zi_dan_temp): # 将子弹押入弹夹中的方法,用一个属性来保存子弹 self.bullet_list.append(zi_dan_temp) def tanchu_zidan(self): '''弹出最上面的一颗子弹''' if self.bullet_list: return self.bullet_list.pop() else: return None class Bullet(object): '''子弹的类''' def __init__(self, demage): super().__init__() self.demage = demage def onfouce(self, enemy): '''打中敌人掉血''' enemy.blood(self.demage) def main(): '''用来控制流程的主程序''' # 1.创建老王对象 laowang = Person("老王") # 2.创建一个枪对象 ak = Gun("ak47") # 3.创建一个弹夹对象 danjia = Collection(20) # 4.创建一些子弹 for i in range(15): bullet = Bullet(10) # 6.老王把子弹安装到弹夹中 laowang.load_bullet(danjia, bullet) # 5.创建一个敌人 gebi_laoli = Person("隔壁老李") # 7.老王把弹夹安装到枪中 laowang.load_danjia(ak, danjia) # 8.老王拿枪 laowang.holdweapon(ak) # 9.老王开枪打敌人 for i in range(12): laowang.koubanji(gebi_laoli) print(gebi_laoli) print(laowang) # 测试 # print(danjia) # print(ak) # print(laowang) # print(gebi_laoli) if __name__ == '__main__': main()
ef6632364a8c432d24181d2f3b1c2137a0b63553
Lasa-beer/python_exp
/exp15.py
561
3.65625
4
# *coding:utf-8 * # Author : silence # Time : 2018/8/8 17:46 # File : exp15.py # IDE : PyCharm # 质数判断 while True: try: num = int(input('请输入一个数字:')) except ValueError: print('您输入的数字不是整数:') continue if num > 1: for i in range(2,num): if num % i == 0: print('{0}不是质数。'.format(num)) break else: print('{0}是质数。'.format(num)) else: print('{0}不是质数。'.format(num))
b8244fe8736ddfbdf163fae96550885587b3daa2
MoonChaserChen/hello
/hello-algorithm/exercise/calcReversePolishNotation.py
1,222
3.5
4
def priv_com(a, b): mul_dev = ['*', '/'] add_sub = ['+', '-'] if (a in mul_dev and b in mul_dev) or (a in add_sub and b in add_sub): return 0 elif a in mul_dev and b in add_sub: return 1 elif a in add_sub and b in mul_dev: return -1 def is_operation(ope): operation = ['+', '-', '*', '/'] if ope in operation: return 1 else: return 0 def transfer(notation): le = len(notation) stack = [] for x in notation: if not is_operation(x): if x == '(': stack.append(x) elif x == ')': while len(stack) != 0 and stack[-1] != '(': print stack.pop(), if len(stack) != 0 and stack[-1] == '(': stack.pop() else: print x, else: while len(stack) != 0 and is_operation(stack[-1]) and ( priv_com(stack[-1], x) == 1 or priv_com(stack[-1], x) == 0): print stack.pop(), stack.append(x) while len(stack) != 0: print stack.pop(), test = ['a', '+', 'b', '*', 'c', '+', '(', 'd', '*', 'e', '+', 'f', ')', '*', 'g'] transfer(test)
f872337a86991e7c77a27a1252eaaf9c11b76fbe
Blackxin/project-random
/Python/Juni 2021/turunan.py
798
3.546875
4
import os def tampilan(x): print("PROGRAM PENGHITUNG TURUNAN FUNGSI") print(f"f(x) = {x}") def turunan(k,v,p): if v=='' : k=0 p=0 h= "0" else : k = k * p p = p - 1 h = f"{k}{v}^{p}" return h tampilan("") k = int(input("Masukkan konstanta : ") or 0) os.system("clear") if k == 0: tampilan("") else: tampilan(k) v = input("Masukkan variabel : ") if v != '': os.system("clear") if k == 0: tampilan(f"{v}") else: tampilan(f"{k}{v}") p = int(input("Masukkan pangkat : ") or 1) else: os.system("clear") p = 1 if v == '': tampilan(f"{k}{v}") else: tampilan(f"{k}{v}^{p}") h = turunan(k,v,p) if h[-2:] == "^1": h = h.replace("^1","") print(f"f'(x) = {h}")
50d847ee96367085af47f92bfc77bdc9b811387a
Ebi-aftahi/Python_Solutions
/data visualization/data_visualization.py
1,476
3.953125
4
title = input('Enter a title for the data:\n') print('You entered: ' + title) print() header_1 = input('Enter the column 1 header:\n') print('You entered: ' + header_1); print(); header_2 = input('Enter the column 2 header:\n') print('You entered: ' + header_2); print(); data = input('Enter a data point (-1 to stop input):\n'); author_books = []; def hasDigit (string): for char in string: if char.isdigit(): return True; else: return False; while(data != '-1'): if ',' not in data: print('Error: No comma in string.'); print(); elif (data.count(',') > 1): print('Error: Too many commas in input.'); print(); elif not hasDigit(data): print('Error: Comma not followed by an integer.'); print(); else: tokens = data.split(','); string = tokens[0].strip(); number = tokens[1].strip(); author_books.append([tokens[0],tokens[1]]); print('Data string: ' + string); print('Data integer: ' + number); data = input('Enter a data point (-1 to stop input):\n'); #print table if(len(author_books)>0): print('{string:>33}'.format(string = title)) format_string = '{name:<20}|{number:>23}'; print(format_string.format(name = header_1, number = header_2)) print('-'*44); for item in author_books: print(format_string.format(name = item[0], number = item[1]));
c20da1c54a557c83bd12542ecb10d7d93bc726dd
NiteshTyagi/geeksforgeeks_solutions
/linkedlist/josephus_problem.py
839
3.828125
4
class Node: def __init__(self, val=None:int): self.val = val self.next = None def getJosephusPosition(m, n): head = Node(1) prev = head for i in range(2, n + 1): prev.next = Node(i) prev = prev.next prev.next = head # Connect last ptr1 = head ptr2 = head # print(ptr1.data,ptr2.data,sep='<---111---->') while (ptr1.next != ptr1): count = 1 while (count != m): ptr2 = ptr1 ptr1 = ptr1.next count += 1 ptr2.next = ptr1.next ptr1 = ptr2.next print("Last person left standing (Josephus Position) is ", ptr1.data) if __name__ == '__main__': # https://www.geeksforgeeks.org/josephus-circle-using-circular-linked-list/ n = 14 m = 2 getJosephusPosition(m, n)
c66a9998244c20dfbb8f371a721f6cf1ce40a3b0
AndrewStudenic/magic-8-ball
/magic8ball.py
932
3.828125
4
import random def magic8ball(AnswerNumber): if AnswerNumber == 1: return 'It is certain.' elif AnswerNumber == 2: return 'Yes.' elif AnswerNumber == 3: return 'It is decidedly so.' elif AnswerNumber == 4: return 'Reply hazy, try again.' elif AnswerNumber == 5: return 'Ask again later.' elif AnswerNumber == 6: return 'Concentrate and ask again.' elif AnswerNumber == 7: return 'My reply is NO.' elif AnswerNumber == 8: return 'Outlook not so good.' elif AnswerNumber == 9: return 'Very doubtful.' r = random.randint(1, 9) goagain = 'y' while goagain == 'y': print('You turn over the magic 8 ball, and it says...') print() print(magic8ball(random.randint(1, 9))) print() r = random.randint(1, 9) goagain = str(input('Would you like to go again? If so, press "y": '))
16867813afc09f8214fdae2c05a3b50e921bd991
aabhishek-chaurasia-au17/MyCoding_Challenge
/assignments/week12/day05/Q.03.py
630
3.703125
4
""" Q-3) Same Tree (5 marks) https://leetcode.com/problems/same-tree/ """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if not p or not q: return p == q if p.val != q.val: return False return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
03a6d1da6caca0a6027c715a4a8eb25628707e2d
ctbgx797/class_sample
/customer.py
978
3.9375
4
class Customer: def __init__(self, first_name, family_name, age): self.first_name = first_name self.family_name = family_name self.age = age def full_name(self): return f"{self.first_name} {self.family_name}" def info_csv(self): return f"{self.full_name()},{self.age}" # 自分の考え def display_profile(self): return f"Name:{self.full_name()} Age:{self.age}" def display_profile_2(self): print(f"Name:{self.full_name()} Age:{self.age}") if __name__ == "__main__": # "Tom Ford" tom = Customer("Tom", "Ford", 57) print(tom.full_name()) print(tom.display_profile()) # 自分の考え # "Name: Tom Ford, Age: 57" tom.display_profile_2() # print(tom.first_name + tom.family_name) # "Ken Yokoyama" ken = Customer("Ken", "Yokoyama", 49) print(ken.full_name()) print(ken.display_profile()) ken.display_profile_2() # print(ken.first_name + ken.family_name)
efd3c60dc9d44cc00369ae93bc693632407a82ad
octaviaaris/salesperson-report
/sales_report.py
1,937
3.859375
4
""" sales_report.py - Generates sales report showing the total number of melons each sales person sold. """ # salespeople = [] # melons_sold = [] # f = open("sales-report.txt") # open file # for line in f: # iterate through lines in file # line = line.rstrip() # strip each line of trailing whitespace # entries = line.split("|") # split each line by | and bind list to entries # salesperson = entries[0] # set 0th item (salesperson name) to salesperson # melons = int(entries[2]) # turn 2nd item (number of melons) to integer and assign to melons # if salesperson in salespeople: # if salesperson is in salespeople # position = salespeople.index(salesperson) # sets position to lowest index at which salesperson is found # melons_sold[position] += melons # adds melons to subtotal for melons_sold # else: # if salesperson not in salespeople # salespeople.append(salesperson) # add salesperson to salespeople # melons_sold.append(melons) # add melons_sold to melons # for i in range(len(salespeople)): # iterate through salespeople # print "{} sold {} melons".format(salespeople[i], melons_sold[i]) # print salesperson and melons_sold at index i # created dictionary containing {salesperson: melons_sold} value pairs # instead of two separate lists sales_info = {} with open("sales-report.txt") as f: for line in f: line = line.rstrip() entries = line.split("|") salesperson = entries[0] melons = int(entries[2]) if salesperson in sales_info: sales_info[salesperson] += melons else: sales_info[salesperson] = melons for name, num_sold in sales_info.iteritems(): print "{} sold {} melons".format(name, num_sold)
95c534314dc29dcd1ff95da4fe1460d549beb3ab
iamdika31/test-arkademy
/5.py
466
3.625
4
import numpy as np def createMatrix(dimensi): a = 1 matrix = [] for i in range(dimensi): row = [] for j in range(dimensi): row.append(a) a+=1 matrix.append(row) matrix = np.array(matrix) print(matrix) diag1=0 diag2=0 for i in range(dimensi): diag1+= matrix[i][i] for i in range(dimensi): diag2+= matrix[i][dimensi-i -1] print(diag1 * diag2) createMatrix(3)
2a63e351410050d2fa7ee195fec3406ae7f9aa44
jbathel/holbertonschool-higher_level_programming
/0x03-python-data_structures/4-new_in_list.py
263
3.65625
4
#!/usr/bin/python3 def new_in_list(my_list, idx, element): if my_list: temp_list = my_list[:] if idx < 0 or idx > len(temp_list) - 1: return temp_list else: temp_list[idx] = element return temp_list
5cbd1bf3bb6d29c4803d0271739dbb3ffc0b98fb
Gilsunho/python_lecture
/for_01.py
175
3.5625
4
for i in "이젠컴퓨터학원": print(i) for i in range(1, 10): print(i) for i in range(10): print(1) if(i%2 == 0): continue print(2)