blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ba934740e3a009ec713f7c3630b71ec56d9bb699
killo21/poker-starting-hand
/cards.py
2,285
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 25 17:30:27 2020 @author: dshlyapnikov """ import random class Card: def __init__(self, suit, val): """Create card of suit suit [str] and value val [int] 1-13 1 - Ace, 2 - 2, 3 - 3,..., 11 - Jack, 12 - Queen, 13 - King suit can be "clubs", "diamonds", "hearts", "spades".""" assert type(suit) is str assert suit == "clubs" or suit == "diamonds" or suit == "hearts" or suit == "spades" assert type(val) is int assert val > 0 and val < 14 self.suit = suit self.val = val def getSuit(self): """A card's suit. Can be "clubs", "diamonds", "hearts", "spades".""" return self.suit def getVal(self): """A card's value. [int] 1-13. 1 - Ace, 2 - 2, 3 - 3,..., 11 - Jack, 12 - Queen, 13 - King""" return self.val def getShortHand(self): """Short hand [str] notation to represent a card. The first character is the chard's value 1-13, J, Q, K, or A. The second char is the card's suit C - clubs, D - diamonds, H - hearts, S - spades.""" result = "" if self.val == 1: result = "A" elif self.val == 11: result = "J" elif self.val == 12: result = "Q" elif self.val == 13: result = "K" else: result = str(self.val) result = result + self.suit[0].capitalize() return result class Deck: def __init__(self): """Creates a shuffled deck of 52 [card] objects.""" self.cardCount = 52 suits = ["clubs", "diamonds", "hearts", "spades"] self.cards = [] for suit in suits: for val in range(1, 14): c = Card(suit, val) self.cards.append(c) random.shuffle(self.cards) def getCount(self): """The [int] number of cards in the deck. Between 0-52 inclusive.""" return self.cardCount def draw(self): """The first [card] in the deck. Removed from the deck without replacement.""" card = self.cards[0] self.cards = self.cards[1:] self.cardCount -= 1 return card
true
141b6d72a3890b96f51838d1b4806763f0c60684
sivaneshl/python_ps
/tuple.py
801
4.25
4
t = ('Norway', 4.953, 4) # similar to list, but use ( ) print(t[1]) # access the elements of a tuple using [] print(len(t)) # length of a tuple for item in t: # items in a tuple can be accessed using a for print(item) print(t + (747, 'Bench')) # can be concatenated using + operator print(t) # immutable print(t * 3) # can be used with multiply operator # nested tuples a = ((120, 567), (747, 950), (474, 748), (747,738)) # nested tuples print(a[3]) print(a[3][1]) # single element tuple h = (849) print(h, type(h)) # this is treated as a int as a math exp h = (858,) # single element tuple with trailing comma print(h, type(h)) e = () # empty tuple print(e, type(e)) # parenthesis of literal tuples may be omitted p = 1, 1, 3, 5, 6, 9 print(p, type(p))
true
a29a778e801e3ca3e9a5904fafca8310de0b0b43
sivaneshl/python_ps
/range.py
541
4.28125
4
# range is a collection # arithmetic progression of integers print(range(5)) # supply the stop value for i in range(5): print(i) range(5, 10) # starting value 5; stop value 10 print(list(range(5, 10))) # wrapping this call to the list print(list(range(0, 10, 2))) # 2 is the step argument # enumerate - to count t = [6, 44, 532, 2232, 534536, 36443643] for i in enumerate(t): # enumerate returns a tuple print(i) # tuple unpacking of enumerate for i, v in enumerate(t): print("i={} v={}".format(i,v))
true
149e32d2ea991a06c3d6a7dd1c18c4cc85c3d378
CcccFz/practice
/python/design_pattern/bigtalk/Behavioral/11_visitor.py
1,326
4.15625
4
# -*- coding: utf-8 -*- # 模式特点:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。 # 程序实例:对于男人和女人(接受访问者的元素,ObjectStructure用于穷举这些元素),不同的遭遇(具体的访问者)引发两种对象的不同行为。 class Action(object): def get_man_conclusion(self): pass def get_woman_conclusion(self): pass class Success(Action): def get_man_conclusion(self): print '男人成功时,背后有个伟大的女人' def get_woman_conclusion(self): print '女人成功时,背后有个不成功的男人' class Failure(Action): def get_man_conclusion(self): print '男人失败时,闷头喝酒,谁也不用劝' def get_woman_conclusion(self): print '女人失败时,眼泪汪汪,谁也劝不了' class Person(object): def accept(self, visitor): pass class Man(Person): def accept(self, visitor): visitor.get_man_conclusion() class Woman(Person): def accept(self, visitor): visitor.get_woman_conclusion() if __name__ == '__main__': man, woman = Man(), Woman() woman.accept(Success()) man.accept(Failure())
false
9f467500632ad90051263cb2282edacfe1258b1b
git-ysz/python
/day5-字符串/05-字符串的查找方法.py
934
4.46875
4
""" 1、字符串序列.find(子串, 查找开始位置下标, 查找结束位置下标) 返回子串出现的初始下标 1.1、rfind()函数查找方向和find()相反 2、字符串序列.index(子串, 查找开始位置下标, 查找结束位置下标) 返回子串出现的初始下标 2.1、rindex()函数查找方向和find()相反 3、字符串序列.count(子串, 查找开始位置下标, 查找结束位置下标) 返回子串出现的次数 ...... """ myStr = 'hello world and itcast and itheima and Python' # find() 函数 print(myStr.find('and')) # 12 print(myStr.find('and', 15, 30)) # 23 print(myStr.find('ands')) # 找不到返回-1 # index()函数 print(myStr.index('and')) # 12 print(myStr.index('and', 15, 30)) # 23 # print(myStr.index('ands')) # 找不到报错 substring not found # count() 函数 print(myStr.count('and', 15, 30)) # 1 print(myStr.count('ands')) # 0
false
5c8e53bc40566dfe596ecf26e8425f65dae57a6a
git-ysz/python
/day15-继承/04-子类调用父类的同名方法和属性.py
1,549
4.3125
4
""" 故事演变: 很多顾客都希望既能够吃到古法又能吃到学校技术的煎饼果子 """ # 师傅类 class Master(object): def __init__(self): self.kongfu = '古法煎饼果子配方' def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子 -- 师父') # 学校类 class School(object): def __init__(self): self.kongfu = '学校煎饼果子配方' def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子 -- 学校') # 徒弟类 - 继承师傅类 《第一种方法》 (第二种方法见06文件super) class Prentice(Master, School): """注意:当一个类有多个父类的时候,默认使用第一个父类的同名属性和方法""" def __init__(self): self.kongfu = '独创煎饼果子配方' def make_cake(self): # 注意:如果先调用了父类的属性和方法,父类属性就会覆盖子类属性 # 故在方法一中,在调用自己类的方法时需要初始化自身类的属性 self.__init__() print(f'运用{self.kongfu}制作煎饼果子 -- 自己') # 注意:调用父类方法,但是为保证调用到的也是父类的属性,必须在调用方法钱调用父类的初始化 def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) tudi = Prentice() tudi.make_cake() tudi.make_master_cake() tudi.make_school_cake() tudi.make_cake()
false
eadb9454aeedd0dff94404ac92f9e6e43f4089c8
git-ysz/python
/day7-字典/04-字典的循环遍历.py
335
4.25
4
dict1 = { 'name': 'Tom', 'age': 20, 'gender': '男' } # 遍历keys for key in dict1.keys(): print(key) # 遍历values for val in dict1.values(): print(val) # 遍历键值对 for item in dict1.items(): print(item, item[0], item[1]) # 键值对拆包 for key, value in dict1.items(): print(f'{key}:{value}')
false
b5bdd6a7b80e23823c3a97def9717da822c0b3b7
git-ysz/python
/day18-模块包/00-导入模块的方法.py
565
4.1875
4
""" 模块: Python模块(module),是一个python文件,以.py结尾,包含了python对象定义和python语句。 模块能定义函数,类和变量,模块里面也能包含可执行的代码 """ import math # 导入指定模块 # from math import sqrt # 导入指定模块内的指定功能 from math import * # 导入指定模块内的所有功能 print(math.sqrt(9)) # 开平方 -- 3.0 print(sqrt(9)) # 开平方 -- 3.0 导入指定模块内的所有功能 print(pi, e) # 3.141592653589793... 导入指定模块内的所有功能
false
511f5e71a988213812fe04a44b1d08bc2fb10ecf
git-ysz/python
/day17-异常处理/01-捕获异常.py
1,261
4.25
4
""" 语法: try: 可能发生错误的代码 except 异常类型: 如果捕获到该异常类型执行的代码 注意: 1、如果尝试执行的代码的异常类型和要捕获的类型不一致,则无法捕获异常 2、一般try下发只放一行尝试执行的代码 """ # 捕获指定异常类型 try: # 找不到num变量 print(num) except NameError: print('NameError:', NameError.__dict__) try: print(1 / 0) except ZeroDivisionError: print('0不能做被除数') # 捕获多个指定异常 try: # print(arr) print(1 / 0) except (NameError, ZeroDivisionError): print('捕获多个指定异常') # 获取异常信息 {ErrorType} as result try: # print(arr) print(1 / 0) except (NameError, ZeroDivisionError) as res: print('捕获多个指定异常(有异常信息):', res) # 捕获所有异常 --- Exception try: print(arr) print(1 / 0) except Exception as res: print('捕获所有异常(有异常信息):', res) # 异常之else --- 没有异常时执行的代码 # 异常之finally --- 有无异常都执行的代码 try: print(111) # print(aaa) except Exception as res: print(res) else: print('else') finally: print('finally')
false
9605013db14a55234a8f79a0f50833ce6f9af675
giselemanuel/programa-Ifood-backend
/modulo-1/exercicios/animal.py
1,227
4.34375
4
""" Programa VamoAI: Aluna: Gisele Rodrigues Manuel Desafio : Animal Descrição do Exercício 3: Criar um programa que: 1. Pergunte ao usuário qual aninal ele gostaria de ser e armazene em uma variável. 2. Exiba na tela o texto: "Num primeiro momento , eu gostaria de ser o <animal> 3. Pergunte ao usuário qual animal ele gostaria de ser no lugar desse e armazene esse novo animal na mesma variável. 4. Exibe na tela o seguinte texto: " Pensando melhor , eu gostaria mesmo de ser um <animal> """ # Cores cores = { 'limpa': '\033[m', 'vermelho': '\033[31m', 'verde': '\033[32m', } # Cabeçalho do programa print('\n') print('-' * 60) print(f'{"PROGRAMA ANIMAL - QUAL ANIMAL VOCÊ SERIA?":^60}') print('-' * 60) # Variável e entradas de valores animal = str(input('{}1. Se você pudesse ser um animal, qual animal seria? {}'.format(cores['verde'], cores['limpa']))) print('Num primeiro momento, eu gostaria de ser um(a) {}{}{}.\n'.format(cores['vermelho'], animal, cores['limpa'])) animal = str(input('{}2. Qual outro animal você gostaria de ser? {}'.format(cores['verde'], cores['limpa']))) print('Pensando melhor, eu gostaria mesmo de ser um(a) {}{}{}\n'.format(cores['vermelho'], animal, cores['limpa']))
false
fdc4109862d6acdaaf3b28b259407310172e9973
giselemanuel/programa-Ifood-backend
/qualified/sem7_qualified_3.py
2,466
4.21875
4
""" Descrição Utilizando as mesmas 4 funções da atividade Pilha - Funções Básicas: cria_pilha() tamanho(pilha) adiciona(pilha, valor) remove(pilha): Implemente a função insere_par_remove_impar(lista) que recebe uma lista de números inteiros como parâmetro e retorna uma pilha de acordo com a seguinte regra: para cada elemento da lista, se o número for par, deve ser inserido na pilha. Caso contrário, deve ser removido. 0 deve ser considerado par. Utilize o funcionamento da pilha para que isso aconteça. Lembre-se: A pilha funciona seguindo a sequência LIFO(Last In First Out) - Último a entrar, primeiro a sair. Em python, a pilha é implementada utilizando a estrutura de uma lista. IMPORTANTE É OBRIGATÓRIO utilizar pelo menos as funções cria_pilha, adiciona e remove da atividade Pilha - Funções Básicas para implementar a função insere_par_remove_impar. Seu código não passará nos testes se elas não forem utilizadas. Exemplos Chamada da função insere_par_remove_impar(lista) Entrada: [1, 2, 3] Saída: [] Entrada: [1, 2, 3, 4] Saída: [4] Entrada: [] Saída: [] Entrada: [1] Saída: [] Entrada: [2, 2, 2, 2, 1, 1, 1] Saída: [2] Entrada: [1, 2, 3, 4, 6, 8] Saída: [4, 6, 8] """ # função cria_pilha ------------------------------- def cria_pilha(): stack = [] # função tamanho ---------------------------------- def tamanho(pilha): return len(pilha) # função cria_pilha ------------------------------- def adiciona(pilha, elemento): if len(pilha) != 0: pilha.append(elemento) else: pilha = None return pilha # função remove ----------------------------------- def remove(pilha): if len(pilha) != 0: remove = pilha.pop() return remove else: pilha = None return pilha # função insere_par_remove_impar ----------------- def insere_par_remove_impar(lista): nova_pilha = [] cria_pilha() # se num da lista par , adicionar na pilha LIFO for num in range(0, len(lista)): if num % 2 == 0: adiciona(nova_pilha, num) elif num % 2 != 0: # se num da lista impar remove(nova_pilha) # retorna None se lista estiver vazia if len(lista) == 0: lista = None return lista # define variáveis ------------------------------ minha_lista = (1, 2, 30) cria_pilha() # chama funções --------------------------------- insere_par_remove_impar(minha_lista)
false
3b831b55e3fc2796d52d1a3298b690cfbe41fdf7
giselemanuel/programa-Ifood-backend
/qualified/sem5_qualified_2.py
1,078
4.4375
4
# função para somar as duas listas """ Descrição Eu sou novo na programação e gostaria da sua ajuda para somar 2 arrays. Na verdade, eu queria somar todos os elementos desses arrays. P.S. Cada array tem somente numeros inteiros e a saída da função é um numero também. Crie uma função chamada array_plus_array que recebe dois arrays(listas) de números e some os valores de todos os elementos dos dois arrays. O resultado deverá ser um número que representa a soma de tudo. Exemplos Entrada: [1, 1, 1], [1, 1, 1] Saída: 6 Entrada: [1, 2, 3], [4, 5, 6] Saída: 21 """ # função que soma os valores das duas listas def array_plus_array(arr1,arr2): soma_l1 = 0 soma_l2 = 0 total = 0 # soma os elemento da lista 1 for l1 in list1: soma_l1 += l1 # soma os elementos da lista 2 for l2 in list2: soma_l2 += l2 # total da soma das duas listas total = soma_l1 + soma_l2 print(total) # difinição das listas list1 = [-1, -2, -3] list2 = [-4, -5, -6] # chama a função e passa a lista array_plus_array(list1,list2)
false
e07cd5a1719c796c980b06b003c83df9d57457f3
giselemanuel/programa-Ifood-backend
/qualified/sem7_qualified_1.py
1,757
4.65625
5
""" Descrição Crie quatro funções básicas para simular uma Pilha: cria_pilha(): Retorna uma pilha vazia. tamanho(pilha): Recebe uma pilha como parâmetro e retorna o seu tamanho. adiciona(pilha, valor): Recebe uma pilha e um valor como parâmetro, adiciona esse valor na pilha e a retorna. remove(pilha): Recebe uma pilha como parâmetro e retorna o valor no topo da pilha. Se a pilha estiver vazia, deve retornar None. Lembre-se: A pilha funciona seguindo a sequência LIFO(Last In First Out) - Último a entrar, primeiro a sair. Em python, a pilha é implementada utilizando a estrutura de uma lista. Exemplos Função cria_pilha() Saída: [] Função tamanho(pilha) # minha_pilha = [9, 1, 2, 3, 100] Entrada: minha_pilha Saída: 5 Função adiciona(pilha, valor) # minha_pilha = [1, 2, 3] Entrada: minha_pilha, 100 Saída: [1, 2, 3, 100] Função remove(pilha) # minha_pilha = [1, 2, 3] Entrada: minha_pilha Saída: [1, 2] # minha_pilha = [] Entrada: minha_pilha Saída: None """ # Função cria_pilha ---------------------------------- def cria_pilha(): pilha = [] return pilha # Função tamanho ------------------------------------- def tamanho(pilha): return len(pilha) # Função adiciona ------------------------------------ def adiciona(pilha, elemento): pilha.append(elemento) return pilha # Função remove -------------------------------------- def remove(pilha): if len(pilha) != 0: removido = pilha.pop() return removido else: pilha = None return pilha # Define variável ----------------------------------- minha_pilha = [1, 2, 3] # Chama Funções ------------------------------------- tamanho(minha_pilha) remove(minha_pilha) adiciona(minha_pilha, 100)
false
003112e87a05bb6da91942b2c5b3db98d082193a
joshua-hampton/my-isc-work
/python_work/functions.py
370
4.1875
4
#!/usr/bin/python def double_it(number): return 2*number def calc_hypo(a,b): if (type(a)==float or type(a)==int) and (type(b)==float or type(b)==int): hypo=((a**2)+(b**2))**0.5 else: print 'Error, wrong value type' hypo=False return hypo if __name__ == '__main__': print double_it(3) print double_it(3.5) print calc_hypo(3,4) print calc_hypo('2',3)
true
a15f72482720e16f831f6e44bece611910eec4d5
Katakhan/TrabalhosPython2
/Aula 5/aula5.2.py
505
4.125
4
#2- Mercado tech... #Solicitar Nome do funcionario #solicitar idade #informar se o funcionario pode adquirir produtos alcoolicos #3- #cadastrar produtos mercado tech #solicitar nome do produto #Solicitar a categoria do produto(alcoolicos e não alcoolicos) #exibir o produto cadastrado nomef = input('informe o nome do funcionário: ') idade = int(input('informe a idade :' )) if idade >=18: print(f'pode dale na cachaça,{nomef}') else: print(f'Vai chapar de energético só se for{nomef}')
false
34fb94928b4521a02ee32683fcc1369b36a03697
Katakhan/TrabalhosPython2
/Aula59/A59C1.py
1,478
4.3125
4
# ---- Rev Classe # ---- Métodos de Classe # ---- Método __init__ # ---- Variáveis de classe # ---- Variáveis privadas # ---- Metodos Getters e Setters class Calc: def __init__(self, numero1, numero2): # Variável de classe self.__n1 = numero1 self.__n2 = numero2 self.__resultado = 0 def set_n1(self, valor): self.__n1 = valor def get_n1(self): return self.__n1 def set_n2(self, valor): self.__n2 = valor def get_n2(self): return self.__n2 def get_resultado(self): return self.__resultado def soma(self): a = self.__resultado = self.__n1 + self.__n2 return a def multiplicacao(self): a = self.__resultado = self.__n1 * self.__n2 return a def subtracao(self): self.__resultado = self.__n1 - self.__n2 return self.__resultado c = Calc(10, 20) assert isinstance(c, Calc) for i in range(1000): c.set_n1(i) assert c.get_n1() == i c.set_n2(i) assert c.get_n2() == i c.set_n1(50) c.set_n2(20) assert c.soma() == 70 assert c.subtracao() == 30 assert c.multiplicacao() == 1000 assert c.soma() == c.get_resultado() assert c.subtracao() == c.get_resultado() assert c.multiplicacao() == c.get_resultado() # Instanciando um objeto da classe Calc # c = Calc(10,20) # print(c.get_n1()) # print(c.get_n2()) # c.set_n1(50) # c.set_n2(100) # print(c.get_n1()) # print(c.get_n2()) # print(c.get_resultado())
false
bbadb83a9436c4fb543e3a703638449549af44e6
Katakhan/TrabalhosPython2
/Aula59/Classe.py
501
4.15625
4
#---- Métodos #---- Argumentos Ordenados #---- Argumentos Nomeados def soma(n1,n2): resultado = n1+n2 return resultado res = soma(10,20) print(res) def multiplicacao(n1,n2,n3): resultado = n1 * n2 * n3 return resultado res = multiplicacao(10,20,30) print(res) def subtracao(n1,n2,n3): resultado = n1-n2-n3 return resultado res2 - subtracao(n1=10,n2=20,n3=10) print(res2) def multiplicacao(n1,n2=1,n3=1): return n1*n2*n3 res3 = multiplicacao(n1,n2,n3) print(res3)
false
27989368586ffa54f5ac5a9599a95b0b3c726709
Raylend/PythonCourse
/hw_G1.py
681
4.15625
4
""" Написать декоратор, сохраняющий последний результат функции в .txt файл с названием функции в имени """ def logger(func): def wrapped(*args, **kwargs): # print(f'[LOG] Вызвана функция {func.__name__} c аргументами: {args}, {kwargs}') f_name = func.__name__ + '.txt' f = open(f_name, "w") result = func(*args) f.write(f'Last result: {result}') f.close() return result return wrapped @logger def my_func(a): c = list(map(lambda x: x ** 3, a)) return c a = {1, 2, 3, 4, 5, 6, 7, 8, 9} b = my_func(a)
false
d2822cfa674d1c3701c46e6fd305bf665f26ace4
nkpydev/Algorithms
/Sorting Algorithms/Selection Sort/selection_sort.py
1,030
4.34375
4
#-------------------------------------------------------------------------# #! Python3 # Author : NK # Desc : Insertion Sort Implementation # Info : Find largest value and move it to the last position. #-------------------------------------------------------------------------# def sort_selection(user_input): l = len(user_input) for i in range(l-1,0,-1): max = 0 for j in range(1,i+1): if user_input[j]>user_input[max]: max = j user_input[max],user_input[i] = user_input[i],user_input[max] return user_input if __name__ == '__main__': final_sorted = [] get_user_input = [int(x) for x in input('\nEnter numbers to be sorted [seperated by ","]:').split(',')] #int(x) is import as we are looking forward to integers and not string value print('\nUser Input before Sorting:\t',get_user_input) final_sorted = sort_selection(get_user_input) print('\nUser Input after Bubble Sort:\t',get_user_input)
true
9197d3d60ded6acd8d76c581de16cc68dc495b5a
ezhk/algo_and_structures_python
/Lesson_2/5.py
691
4.375
4
""" 5. Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно. Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке. """ def print_symbols(pairs_per_line=10): results_in_line = 0 for i in range(32, 127 + 1): print(f"{i}. {chr(i)}\t", end='') results_in_line += 1 if results_in_line == pairs_per_line: print() results_in_line = 0 print() return True if __name__ == '__main__': print_symbols()
false
332dd6971f3b52129b320f93d189f02a688376fd
ezhk/algo_and_structures_python
/Lesson_3/7.py
1,384
4.34375
4
""" 7. В одномерном массиве целых чисел определить два наименьших элемента. Они могут быть как равны между собой (оба являться минимальными), так и различаться. """ def search_two_min(arr): absolute_min = second_min = None for el in arr: if absolute_min is None: absolute_min = el continue if second_min is None: # добавляем с учетом сортировки значения: # absolute_min - самый минимальный, second_min - максимальный из минимальных (absolute_min, second_min) = (el, absolute_min) if el < absolute_min else (absolute_min, el) continue if absolute_min > el: absolute_min, second_min = el, absolute_min continue if second_min > el: second_min = el return absolute_min, second_min if __name__ == "__main__": init_array = input("Введите начальный массив целых чисел, как список элементов через запятую: ").split(',') init_array = list(map(int, init_array)) print(f"Два наименших значения {init_array}: {search_two_min(init_array)}")
false
076d47563c9a8852ea3ca389e3abca680676bb52
melvinkoopmans/high-performance-python
/fibonnaci.py
416
4.125
4
def fibonacci_list(num_items): numbers = [] a, b = 0, 1 while len(numbers) < num_items: numbers.append(a) a, b = b, a+b return numbers def fibonacci_gen(num_items): a, b = 0, 1 while num_items: yield a a, b = b, a+b num_items -= 1 if __name__ == '__main__': # for n in fibonacci_list(100_000): for n in fibonacci_gen(100_000): pass
false
4cb75a34e0f6806c8990bc06079272effbc2451c
patrickdeyoreo/holbertonschool-interview
/0x19-making_change/0-making_change.py
1,161
4.15625
4
#!/usr/bin/python3 """ Given a list of coin denominations, determine the fewest number of coins needed to make a given amount. """ def makeChange(coins, total): """ Determine the fewest number of coins needed to make a given amount. Arguments: coins: list of coin denominations total: total amount to make Return: If the amount cannot be produced by the given denominations, return -1. Otherwise return the fewest number of coins needed to make the amount. """ if total > 0: checked = [True] checked.extend(False for _ in range(total)) n_coins = 0 queue = [0] while queue: n_coins += 1 level = [] for value in queue: for coin in coins: if value + coin == total: return n_coins if value + coin >= total: continue if not checked[value + coin]: checked[value + coin] = True level.append(value + coin) queue = level return -1 return 0
true
31d07fd3332e0b6ca050f4ee3df184451287d710
gauborg/code_snippets_python
/14_power_of_two.py
1,220
4.625
5
''' Description: The aim of this code is to identify if a given numer is a power of 2. The program requires user input. The method keeps bisecting the number by 2 until no further division by 2 is possible. ''' def check_power_of_two(a, val): # first check if a is odd or equal to zero or an integer if (a <= 0): print("Number is zero!") return None elif (a%2 != 0): print("Odd number! Cannot be a power of 2!") return None else: residual = a count = 0 while((residual != 0)): if (residual%2 == 1): return None # go on dividing by 2 every time half = residual/2 residual -= half count += 1 # stop when the final residual reaches 1 if (residual == 1): break return count # user input for number number = int(input("Enter a number = ")) # call function to check if the number is power of 2. power = check_power_of_two(number, 0) if (power != None): print("The number is a power of 2, power =", power) elif(power == None): print("The number is not a power of 2.")
true
f65d53c042bebae591090aebbf16b3b155e0eee2
gauborg/code_snippets_python
/7_random_num_generation.py
1,416
4.5
4
''' This is an example for showing different types of random number generation for quick reference. ''' # code snippet for different random options import os import random # generates a floating point number between 0 and 1 random1 = random.random() print(f"\nRandom floating value value between using random.random() = {random1}\n") # generates a floating number between a given range random2 = random.uniform(1, 5) print(f"Random floating vlaue between 1 and 5 using random.uniform() = {random2}\n") # generates a number using Gaussian distribution random3 = random.gauss(10, 2) print(f"Gaussian distribution with mean 10 and std deviation 2 using random.gauss() = {random3}\n") # generates a random integer between a range random4 = random.randrange(100) print(f"Random integer value between using random.randrange() = {random4}\n") # generates a random integer between a range with inclusion random5 = random.randrange(0, 100, 11) print(f"Random integer value with spacing 11 between using random.randrange() = {random5}\n") # choosing an element from a list at random random6 = random.choice(['win', 'lose', 'draw']) print(f"Random element chosen from the list using random.choice() = {random6}") print("If sequence is empty, it will raise IndexError.\n") # shuffling a list some_numbers = [1.003, 2.2, 5.22, 7.342, 21.5, 76.3, 433, 566, 7567, 65463] random.shuffle(some_numbers) print(some_numbers)
true
2c17e2b6ed89bebf30bbf9a2f25bb8f0793c0019
jkamby/portfolio
/docs/trivia/modulesAndClients/realcalc.py
1,358
4.15625
4
import sys import stdio def add(x, y): """ Returns the addition of two floats """ return float(x) + float(y) def sub(x, y): """ Returns the subtraction of two floats """ return float(x) - float(y) def mul(x, y): """ Returns the multiplication of two floats """ return float(x) * float(y) def div(x, y): """ Returns the division of two floats """ if(float(y) == 0): stdio.writeln("The divisor must not be zero.") return else: return float(x) / float(y) def mod(x, y): """ Returns the modulo of two ints """ if(int(y) == 0): stdio.writeln("The mudulo operand may not be zero.") return else: return int(x) % int(y) def exp(x, y): """ Returns the result of one float raised to the power of the other """ return float(x) ** float(y) def main(): a = sys.argv[1] b = sys.argv[2] stdio.writeln("Addition: " + str(add(a, b))) stdio.writeln("Subtraction: " + str(sub(a, b))) stdio.writeln("Multiplication: " + str(mul(a, b))) stdio.writeln("Division: " + str(div(a, b))) stdio.writeln("Modulo: " + str(mod(a, b))) stdio.writeln("Exponentiation: " + str(exp(a, b))) if __name__ == '__main__': main()
true
a743debf018b5322b6a681783aa0a009fbfd3b61
karingram0s/karanproject-solutions
/fibonacci.py
722
4.34375
4
#####---- checks if input is numerical. loop will break when an integer is entered def checkInput(myinput) : while (myinput.isnumeric() == False) : print('Invalid input, must be a number greater than 0') myinput = input('Enter number: ') return int(myinput) #####---- main print('This will print the Fibonacci sequence up to the desired number.') intinput = checkInput(input('Enter number: ')) while (intinput < 1) : print('Number is 0, please try again') intinput = checkInput(input('Enter number: ')) a = 0 b = 1 temp = 0 for i in range(intinput) : print('{0} '.format(a+b), end='', flush=True) if (i < 1) : continue else : temp = a + b a = b b = temp print('')
true
35fb678edb2369ca09c40eecfb4b8856b5ded353
jlocamuz/Mi_repo
/clase12-08-20/main.py
711
4.15625
4
class Clase(): def __init__(self, atributo=0): # Que yo ponga atributo=0 significa que si yo no le doy valor # A ese atributo por defecto me pone 0 self.atributo = atributo def get_atributo(self): # setter and getter: darle un valor a un atributo y obtener # el valor del atributo return self.atributo def set_atributo(self, value): self.atributo = value if __name__ == "__main__": objeto1 = Clase(1) objeto2 = Clase(2) # objeto1 = Clase(1) # objeto2 = Clase(2) # es lo mismo hacerlo con el setter y getter objeto1.set_atributo(1) objeto2.set_atributo(2) print(objeto1.__dict__) print(objeto2.__dict__)
false
b97a94399afac9b9f793d680ffb01892f041ff25
arononeill/Python
/Variable_Practice/Dictionary_Methods.py
1,290
4.3125
4
import operator # Decalring a Dictionary Variable dictExample = { "student0" : "Bob", "student1" : "Lewis", "student2" : "Paddy", "student3" : "Steve", "student4" : "Pete" } print "\n\nDictionary method get() Returns the value of the searched key\n" find = dictExample.get("student0") print find print "\n\nDictionary method items() returns view of dictionary's (key, value) pair\n" view = dictExample.items() print "\n", view print "\n\nDictionary method keys() Returns View Object of All Keys\n" keys = dictExample.keys() print "\n", keys print "\n\nDictionary method popitem() Returns the dictionary contents\nminus the top key and value as they have been popped off the stack\n" dictExample.popitem() print dictExample print "\n\nDictionary method pop() removes and returns element having given key, student4\n\n" dictExample.pop("student4") print dictExample print "\n\nDictionary method max() returns largest key\n" print "max is ", max(dictExample) print "\nDictionary method min() returns smallest key\n" print "min is ", min(dictExample) print "\nDictionary method sorted() returns sorted keys in ascending order\n" print (sorted(dictExample)) print "\nDictionary method sorted() returns sorted keys in descending order\n" print (sorted(dictExample, reverse=True))
true
e54903690eceffc1bd7b49faa2db0f79d111f974
TheManyHatsClub/EveBot
/src/helpers/fileHelpers.py
711
4.125
4
# Take a file and read it into an array splitting on a given delimiter def parse_file_as_array(file, delimiter=None): # Open the file and get all lines that are not comments or blank with open(file, 'r') as fileHandler: read_data = [(line) for line in fileHandler.readlines() if is_blank_or_comment(line) == False] # If no delimiter is given, split on newlines, else we need to split on the delimiter if delimiter is None: file_array = read_data else: file_array = "".join(read_data).split(delimiter) return file_array # Determines whether a line is either blank or a comment def is_blank_or_comment(line): return line.strip() == '' or line[0:2] == "//"
true
97c80a0bc24deb72d908c283df28b314454bcfc5
KHilse/Python-Stacks-Queues
/Queue.py
2,139
4.15625
4
class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None def isEmpty(self): """Returns True if Queue is empty, False otherwise""" if self.head: return False return True def enqueue(self, item): """Adds an item to the back of queue""" if self.head: current_node = self.head while current_node.next != None: current_node = current_node.next new_node = Node(item) current_node.next = new_node else: new_node = Node(item) self.head = new_node def dequeue(self): """Removes the item from the front of queue. Returns the removed item""" if self.head: popped = self.head self.head = self.head.next return popped.data return False def peek(self): """Returns the first item in the queue, but doesn't remove it""" if self.head: return self.head.data return None def size(self): """Returns the (int) size of the queue""" current_node = self.head index = 0 while current_node: current_node = current_node.next index += 1 return index def __str__(self): """Returns a string representation of all items in queue""" current_node = self.head result = "" while current_node: if result != "": result = result + ", " result = result + current_node.data current_node = current_node.next return result my_queue = Queue() print('Is Queue empty?', my_queue.isEmpty()) my_queue.enqueue('A') my_queue.enqueue('B') my_queue.enqueue('C') my_queue.enqueue('D') print("queue state:", my_queue) print('Dequeued item:', my_queue.dequeue()) print('First item:', my_queue.peek()) print('Here are all the items in the queue:', my_queue) print('The size of my stack is:', my_queue.size()) # BONUS - Implement the Queue with a Linked List
true
485458ce7505e832f81aab7520d9fa16db630e89
kalstoykov/Python-Coding
/isPalindrome.py
1,094
4.375
4
import string def isPalindrome(aString): ''' aString: a string Returns True if aString is a Palindrome String strips punctuation Returns False otherwise. ''' alphabetStr = "abcdefghijklmnopqrstuvwxyz" newStr = "" # converting string to lower case and stripped of extra non alphabet characters aString = aString.lower() for letter in aString: if letter in alphabetStr: newStr += letter # if string is one letter or empty, it is a Palindrome if len(newStr) <= 1: return True # if string has more than 1 letter else: # reversing the string revStr = '' for i in range(len(newStr), 0, -1): revStr += newStr[i-1] # if string equals to reversed string, it is a Palindrome if list(newStr) == list(revStr): return True return False # Test cases print isPalindrome("Madam") # returns True print isPalindrome("Hello World") # returns False print isPalindrome(" Madam") # returns True print isPalindrome("1") # returns True
true
13776998dc9b97cf329928fa2a5632f4be87d37a
Crowiant/learn-homework-1
/2_if2.py
1,196
4.3125
4
""" Домашнее задание №1 Условный оператор: Сравнение строк * Написать функцию, которая принимает на вход две строки * Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 * Если строки одинаковые, вернуть 1 * Если строки разные и первая длиннее, вернуть 2 * Если строки разные и вторая строка 'learn', возвращает 3 * Вызвать функцию несколько раз, передавая ей разные праметры и выводя на экран результаты """ def main(first_str: str, second_str: str): if type(first_str) is not str and type(second_str) is not str: return print(0) elif first_str is not second_str and second_str == 'learn': return print(3) elif first_str is not second_str and len(first_str) > len(second_str): return print(2) if __name__ == "__main__": main(1,2) main('gun', 'gun') main('easy', 'learn')
false
f3d2913606a2b0536ceb12a9b469762cd9d86fc3
giant-xf/python
/untitled/4.0-数据结构/4.02-栈和队列/4.2.2-队列的实现.py
945
4.4375
4
class Queue(object): #创建一个空的队列 def __init__(self): #存储列表的容器 self.__list = [] def enqueue(self,item): #往队列中添加一个item元素 self.__list.append(item) #头插入,头出来,时间复杂度 O(n) #self.__list.insert(0,item) def dequeue(self): #从队列尾部删除一个元素 #return self.__list.pop() #头删除 时间复杂度 O(n) return self.__list.pop(0) def is_empty(self): #判断一个队列是否为空 return not self.__list def size(self): #返回队列的大小 return len(self.__list) if __name__ == '__main__': s = Queue() print(s.is_empty()) s.enqueue(1) s.enqueue(2) s.enqueue(3) print(s.is_empty()) print(s.size()) print(s.dequeue()) print(s.dequeue()) print(s.dequeue())
false
1b0dbc67c509a73b2482d2424987e284c5dbd063
kevinliu2019/CP1404practicals
/prac_05/hex_colours.py
758
4.4375
4
CODE_TO_COlOUR = {"AliceBlue": "#f0f8ff", "AntiqueWhite": "#faebd7", "AntiqueWhite1": "#ffefdb", "AntiqueWhite2": "#eedfcc", "DodgerBlue3": "#1874cd", "gray": "#bebebe", "aquamarine1": "#7fffd4", "OldLace": "#fdf5e6", "aquamarine4": "#458b74", "azure1": "#f0ffff", "azure2": "#e0eeee", "LightCoral": "#f08080", "MediumPurple": "#9370db", "beige": "#f5f5dc", "DarkSalmon": "#e9967a"} print(CODE_TO_COlOUR) colour_name = input("Enter a colour name: ") while colour_name != "": print("The code for \"{}\" is {}".format(colour_name, CODE_TO_COlOUR.get(colour_name))) colour_name = input("Enter a colour name: ")
false
69c90196bf5f5b97440c574eef6df4d6c70bf04c
Danielacvd/Py3
/Errores_y_excepciones/excepciones.py
2,764
4.1875
4
""" Errores y Excepciones en Python Excepciones Son bloques de codigo que nos permiten seguir con la ejecucion del codigo a pesar de que tengamos un error. Bloque Try-Except Para prevenir fallos/errores tenemos que poner el bloque propenso a errores en un bloque TRY, y luego encadenar un bloque except para tratar la situacion excepcional, mostrando que ocurrio un fallo/error try: n = float(input("Introduce un número decimal: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") De esta forma se controlar situaciones excepcionales que generan errores y en vez de que se muestre el error mostramos un mensaje o ejecutamos una pieza de codigo diferente. Tambien al usar excepciones se puede forzar al usuario a introducir un numero valida usando un while, haciendo que introduzca el dato solicitado hasta que lo haga bien, y romper el ciclo con un break. while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) break except: print("Ha ocurrido un error, introduce bien el número") Bloque else: Puedo encadenar un bloque else despues del except (similar al else de un ciclo) para comprobar el caso en que todo salio bien.(Si todo funciona bien, no se ejecuta la excepcion). while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") else: print("Todo ha funcionado correctamente") break Bloque Finally: Este bloque se ejecutara al final del codigo, ocurra o no un error while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") else: print("Todo ha funcionado correctamente") break finally: print("Fin de la iteración") """ try: n = float(input("Introduce un número decimal: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) break except: print("Ha ocurrido un error, introduce bien el número") while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") else: print("Todo ha funcionado correctamente") break
false
db1eedd2b2ea011786f6b26d58a1f72e5349fceb
mirarifhasan/PythonLearn
/function.py
440
4.15625
4
#Function # Printing the round value print(round(3.024)) print(round(-3.024)) print(min(1, 2, 3)) #If we call the function without parameter, it uses the default value def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() #Array passing in function def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits)
true
4235ddfb49c4281b0ecbb62fa93c9098ca025273
davisrao/ds-structures-practice
/06_single_letter_count.py
638
4.28125
4
def single_letter_count(word, letter): """How many times does letter appear in word (case-insensitively)? >>> single_letter_count('Hello World', 'h') 1 >>> single_letter_count('Hello World', 'z') 0 >>> single_letter_count("Hello World", 'l') 3 """ # we need to make the whole string lowercase # normal ltr of word + if statement lowercase_word = word.lower() counter = 0 for ltr in lowercase_word: if ltr == letter: counter +=1 return counter # look into the count method here - this makes thsi a lot easier
true
99db5d93dd6673b1afa97701b1fb8d09294223c0
timseymore/py-scripts
/Scripts/set.py
485
4.125
4
# -*- coding: utf-8 -*- """ Sets numerical sets and operations on them Created on Tue May 19 20:08:17 2020 @author: Tim """ test_set = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # returns a set of numbers in given range (inclusive) # that are divisible by either 2 or 3 def set_mod_2_3(size): temp = {} index = 0 for i in range(1, size + 1): if (i % 2 == 0) or (i % 3 == 0): temp[index] = i index += 1 return temp set1000 = set_mod_2_3(1000)
true
4bdf487e4600dfd927e4419f0c25391cfbfb721c
timseymore/py-scripts
/Scripts/counting.py
2,285
4.5
4
# -*- coding: utf-8 -*- """ Counting examples of counting and recursive counting used in cominatorics We will be implementing a graph consisting of nodes and then use recursive counting to find the number of possible paths from the start node to any given node in the graph. The number of possible paths to any given node is the sum of the possible paths to all of its sub-nodes. Created on Wed May 20 17:58:07 2020 @author: Tim """ # We start by defining a simple node class. class Node: def __init__(self, name: str, subs: list): self.name = name self.subs = subs # We will now create nodes that will # represent the structure of our graph. # It is a one-directional graph, where each sub-node (child) # has an arrow pointing to the parent node (self). # Note that any given node may have any number of parent nodes. N1 = Node("N1", []) N2 = Node("N2", [N1]) N3 = Node("N3", [N1]) N4 = Node("N4", [N2, N3]) N5 = Node("N5", [N2, N4]) N6 = Node("N6", [N3]) N7 = Node("N7", [N5]) N8 = Node("N8", [N5, N7]) N9 = Node("N9", [N6, N7]) N10 = Node("N10", [N8, N9]) # Let's create a function to recursively count # the number of possible paths from start (N1) to any given node n. # This is poor style however, the function should be an inner method of Node. def num_paths(n: Node): # We define a local helper-function to recursively count the paths. # Calling num_paths will be simpler without the need # to pass an accumulator, this will help avoid errors # by ensuring the accumulator is always called starting at 0 def aux(node, acc): if node.subs == []: # This is our base case: a node with no subs has one possible path return acc + 1 else: # Sum the number of paths to each sub and return the result for sub in node.subs: acc += aux(sub, 0) return acc return aux(n, 0) # Some test cases to check that it works correctly print(num_paths(N1) == 1) print(num_paths(N2) == 1) print(num_paths(N3) == 1) print(num_paths(N4) == 2) print(num_paths(N5) == 3) print(num_paths(N6) == 1) print(num_paths(N7) == 3) print(num_paths(N8) == 6) print(num_paths(N9) == 4) print(num_paths(N10) == 10)
true
c75a1774b3d16f850f66a24a24ee1b206adbb9e9
bashmastr/CS101-Introduction-to-Computing-
/Assignments/05/a05.py
1,458
4.125
4
## IMPORTS GO HERE ## END OF IMPORTS #### YOUR CODE FOR is_prime() FUNCTION GOES HERE #### def is_prime(y): if y > 1: x = int(y) if x==y: if x == 1: return False if x == 0: return False if x == 2: return True if x >=2: if x>=2: if x%2==0: return False for i in range(3,int(x**0.5)+1,2): if x%i==0: return False return True else: return False else: return False #### End OF MARKER #### YOUR CODE FOR output_factors() FUNCTION GOES HERE #### def output_factors(x): d = 0 while d < x: d = d + 1 if x % d == 0: print d #### End OF MARKER #### YOUR CODE FOR get_largest_prime() FUNCTION GOES HERE #### def get_largest_prime(z): if z >= 2: x=int(z) if is_prime(x): return int(x) else: x = x-1 return get_largest_prime(x) return None #### End OF MARKER if __name__ == '__main__': print is_prime(499) # should return True print get_largest_prime(10) # should return 7 # print get_largest_prime(100000) # bonus, try with 100k output_factors(10) # should output -- 1 2 5 10 -- one on each line
false
6832a42539daa56e2f4c04a1238236a2cfc31e98
mmuratardag/DS_SpA_all_weeks
/DS_SpA_W10_Recommender_System/03_19/TeachMat/flask-recommender/recommender.py
1,270
4.1875
4
#!/usr/bin/env python import random MOVIES = ["The Green Book", "Django", "Hors de prix"] # def get_recommendation(): # return random.choice(MOVIES) def get_recommendation(user_input: dict): m1 = user_input["movie1"] r1 = user_input["rating1"] m2 = user_input["movie2"] r2 = user_input["rating2"] m3 = user_input["movie3"] r3 = user_input["rating3"] """The rest is up to you....HERE IS SOME PSEUDOCODE: 1. Train the model (NMF), OR the model is already pre-trained. 2. Process the input, e.g. convert movie titles into numbers: movie title -> column numbers 3. Data validation, e.g. spell check.... 4. Convert the user input into an array of length len(df.columns), ~9742 --here is where the cosine similarity will be a bit different-- 5. user_profile = nmf.transform(user_array). The "hidden feature profile" of the user, e.g. (9742, 20) 6. results = np.dot(user_profile, nmf.components_) 7. Sort the array, map the top N values to movie names. 8. Return the titles. """ return random.choice([m1, m2, m3]) if __name__ == "__main__": """good place for test code""" print("HELLO TENSORS!") movie = get_recommendation() print(movie)
true
e47781a543e7ab3ccca376d773ebdcd13e6cc77b
yveslox/Genesisras
/practice-code-orange/programme-python/while-loop.py
245
4.125
4
#!/usr/bin/python3 #while loop num=1 while(num<=5): print ("num : ",num) num=num+1 print ("") # else statement with while loop num=1 while(num<=5): print("num : ",num) num=num+1 else : print("second loop finished.")
false
26fded563d3655f5f06e2cdf582d0cdc564ab9dc
yveslox/Genesisras
/practice-code-blue/programme-python/lists.py
672
4.34375
4
#!/usr/bin/python list=[1,2,3,4,5,6,7,8]; print("list[0] :",list[0]) print("list[1] :",list[1]) print("list[2:5] :",list[2:5]) #updating list list[3] = 44 print("list(after update):",list) #delete element del list[3] print("list(after delete) :",list) #length of list print("length of list : ",len(list)) #appending two lists list2= [99,100] list = list + list2 print("list (after appending another list):",list) #check if an element is a me,berof list print("Is 6 present in list?:", 6 in list) #Iterate list elements for x in list: print (x) print("") #reserse the list list.reverse() print("After Sorting: ") for x in list: print (x)
true
7851912c02fd2481ace43d7727b3ceb42153a088
amtfbky/hfpy191008
/base/0005_input.py
2,249
4.125
4
# -*- coding:utf-8 -*- # import urllib # 关于互联网的类 # print "Enter your name: ", # 逗号用来把多个print语句合并到同一行上,且增加一个空格 # someone = raw_input() # raw_input的简便方法 # someone = raw_input("Enter your name: ") # print "Hi, " + someone + ", nice to meet you!" # temp_string = raw_input() # fahrenheit = float(temp_string) # 以上两句可简写 # print "This program converts Fahrenheit to Celsius" # print "Type in a temperature in Fahrenheit: " # fahrenheit = float(raw_input()) # celsius = (fahrenheit - 32) * 5.0 / 9 # print "That is ", celsius, "degrees Celsius" # int(xxx)把小数转换成整数 # response = raw_input("How many students are in your class: ") # numberOfStudents = int(response) # 从互联网上的一个文件得到输入 # file = urllib.urlopen('https://github.com/amtfbky/amtfbky.github.io/blob/master/test.txt') # message = file.read() # print message # excise # answer = raw_input() # print type(answer) # <type 'str'> # 让raw_input()打印一个提示消息??? # print raw_input("This is a tips: ") # 使用raw_input()得到一个整数 # print raw_input(int()) # 写反了??? # print int(raw_input()) # 3.8这样也不行 # a = raw_input() # print int(a) # 3.8这样还不行 # 使用raw_input()得到一个浮点数 # print raw_input(float()) # 写反了 # print float(raw_input()) # 姓名 # xing = "chen" # ming = "zhen" # print xing, ming # 先问你的姓,再问你的名,然后打印出来 # xing = raw_input("What's your first name: ") # ming = raw_input("what's your last name: ") # print xing, ming # 长方形房间,长多少?宽多少?再算面积 # chang = raw_input("How many the chang: ") # kuang = raw_input("How many the kuang: ") # print int(chang) * int(kuang) # 接着上一题,几平方米的地毯?几平方尺?询问价格/平方尺?总价? # mi = int(chang) * int(kuang) # print mi, "平方米" # chi = mi * 9 # print chi, "平方尺" # rice = raw_input("元/平方尺:") # allRice = int(rice) * chi # print allRice, "元" # 统计零钱,几个五分币?二分币?一分币?总? wu = raw_input() er = raw_input() yi = raw_input() print int(wu) * 5 + int(er) * 2 + int(yi) * 1
false
cbfb4516032f507a384496265b2140ed2d9c5cdd
amtfbky/hfpy191008
/base/0004_data.py
651
4.1875
4
# -*- coding:utf-8 -*- print float(23) print int(23.0) a = 5.99 b = int(a) print a print b a = '3.9' b = float(a) print a print b a = '3.7' b = 3.7 print type(a) print type(b) # cel = 5.0 / 9 * (fahr - 32) # cel float(5) / 9 * (fahr - 32) # cel 5 / float(9) * (fahr - 32) # excise # int()将小数转换为整数,结果是下取整 # cel = float(5 / 9 * (fahr - 32)),cel = 5 / 9 * float(fahr - 32),可以吗?为什么? # 挑战题:除了int()不使用任何其他函数,对一个数四舍五入(即不会只是下取整) print float('12.34') print int(56.78) # 用int()从一个字符串创建整数 print int(float('8.9'))
false
9bac38cd3bc1014cc19216e4cbcda36f138dfef1
Ri8thik/Python-Practice-
/creat wedge using loop/loop.py
2,269
4.40625
4
import tkinter as tk from tkinter import ttk root=tk.Tk() # A) labels #here we create a labels using loop method # first we amke a list in which all the labels are present labels=["user name :-","user email :-","age:-","gender:-",'state:-',"city:-"] #start a for loop so that it print all the labels which are given in above list:- for i in range(len(labels)): # this print the labe[0] which means a current label cur_label="label" +str(i) # here we start a simple method in which we create a label cur_label=tk.Label(root,text=labels[i]) # here we use the padding padx is use for left and right , pady is used for top and bottom cur_label.grid(row=i,column=0,sticky=tk.W, padx=2, pady=2) # B) Entry box # to create a loop for entry bos so that it print many entry #first we create a dictunary in which we store the variable ,and that variable will store the data of the current entry user_info={ 'name': tk.StringVar(), "email" :tk.StringVar(), "age" :tk.StringVar(), "gender" : tk.StringVar(), "state" : tk.StringVar(), "city" : tk.StringVar() } #here is the counter variable which increases the value of row as the loop start counter =0 #here is the loop for i in user_info: #this print the first entry[i] or current entry[i] cur_entry='entry' + i # here is the simple methoid to create a entry and in textvariable we create a dictonaray user_info cur_entry=tk.Entry(root,width=16,textvariable=user_info[i]) # here we use the padding padx is use for left and right , pady is used for top and bottom cur_entry.grid(row=counter,column=1,padx=2, pady=2) # here the counter increment the valuye counter+=1 def submit(): print("user_name is :- " +user_info['name'].get()) print("user_email is :- " +user_info['email'].get()) print("user_age is :- " +user_info['age'].get()) print("gender :- " +user_info['gender'].get()) print("state :- " +user_info['state'].get()) print("city :- " +user_info['city'].get()) submit_btn =ttk.Button(root,text='submit',command=submit) submit_btn.grid(row=6,columnspan=2) root.mainloop()
true
fca8a93a245b027c0cfee51200e9e603c737f5df
rchu6120/python_workshops
/comparison_operators.py
234
4.21875
4
x = [1, 2, 3] y = list(x) # create a NEW list based on the value of x print(x, y) if x is y: print("equal value and identity") elif x == y: print("equal value but unqual identity") else: print("unequal")
true
1ef7c763b40ab15b9bb07313edc9be70f9efd5d6
rchu6120/python_workshops
/logic_hw.py
852
4.375
4
############# Ask the user for an integer ### If it is an even number, print "even" ### If it is an odd number, print "odd" ### If it is not an integer (e.g. character or decimal #), continue asking the user for an input ### THIS PROGRAM SHOULND'T CRASH UNDER THESE CIRCUMSTANCES: # The user enters an alphabet # The user enters a decimal number # The user enters a non numeric character # The user enters a negative number # For example, if the user enters "a", the program should ask the user to try again and enter an integer # Topic: conditionals, user input, loops # Hint: You can use the try except: while True: try: if int(input("Please enter an integer. \n")) % 2 == 0: print("even") break else: print("odd") break except: continue
true
5f5f657ef5fad9d08ad0a1657a97cbe83535cb09
HeyChriss/BYUI-Projects-Spring-2021
/Maclib.py
1,453
4.25
4
print ("Please enter the following: ") adjective = input("adjective: ") animal = input("animal: ") verb1 = input("verb: ") exclamation = input("exclamation: ") verb2 = input("verb : ") verb3 = input("verb: ") print () print ("Your story is: ") print () print (f"The other day, I was really in trouble. It all started when I saw a very") print (f'{adjective} {animal} {verb1} sneeze down the hallway. "{exclamation}!" I yelled. But all') print (f"I could think to do was to {verb2} over and over. Miraculously,") print (f"that caused it to stop, but not before it tried to {verb3}") print (f"right in front of my family. ") # I made it my own during this part forward, I added a second part of the story asking different information # to the person to keep going with the story print () print () print () print () print ("Keep going with the second part of the story...") print ("Please enter the following: ") day = input("day of the week: ") animal1 = input("animal: ") adjective1 = input("adjective: ") exclamation1 = input("exclamation: ") verb4 = input("verb : ") place = input("place: ") print () print ("The second part is: ") print () print (f"I almost died during that time, but on {day}") print (f'I saw a {animal1} and it was so {adjective1}') print (f"I tried to {verb4} but it was useless so I hurted myself and went to the {place} ") print (f"to watch TV :) ") print ("THE END OF THE STORY!")
true
7e46e20703c0a192343772c52686b4846904537d
UnimaidElectrical/PythonForBeginners
/Algorithms/Sorting_Algorithms/Quick_Sort.py
2,603
4.375
4
#Quick Sort Implementation ************************** def quicksort(arr): """ Input: Unsorted list of intergers Returns sorted list of integers using Quicksort Note: This is not an in-place implementation. The In-place implementation with follow shortly after. """ if len(arr) < 2: return arr else: pivot = arr[-1] smaller, equal, larger = [], [], [] for num in arr: if num < pivot: smaller.append(num) elif num == pivot: equal.append(num) else: larger.append(num) return smaller + equal + larger l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(quicksort(l)) ''' *********************** return smaller , equal , larger #For this reason the final list will be returned as a tuple instead of a list. #To stop this from happening we then concatenate the l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(type(quicksort(l))) this will be returned as a tuple. ************************ ''' def quicksort(arr): """ Input: Unsorted list of integers Returns sorted list of integers using Quicksort Note: This is not an in-place implementation. The In-place implementation with follow shortly after. """ if len(arr) < 2: return arr else: pivot = arr[-1] smaller, equal, larger = [], [], [] for num in arr: if num < pivot: smaller.append(num) elif num == pivot: equal.append(num) else: larger.append(num) #running the quick sort algo on the smaller list will return a sorted list in th return smaller + equal + larger l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(type(quicksort(l))) ****************************8 def quicksort(arr): """ Input: Unsorted list of integers Returns sorted list of integers using Quicksort Note: This is not an in-place implementation. The In-place implementation with follow shortly after. """ if len(arr) < 2: return arr else: pivot = arr[-1] smaller, equal, larger = [], [], [] for num in arr: if num < pivot: smaller.append(num) elif num == pivot: equal.append(num) else: larger.append(num) #running the quick sort algo on the smaller list will return a sorted list in th return smaller + equal + larger l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(type(quicksort(l)))
true
1ab91009e990c5f8858a019968d8a1616a9e4c09
UnimaidElectrical/PythonForBeginners
/Algorithms/Sorting_Algorithms/selection_sort.py
2,740
4.46875
4
# Selection Sort # Selection sort is also quite simple but frequently outperforms bubble sort. # With Selection sort, we divide our input list / array into two parts: the sublist # of items already sorted and the sublist of items remaining to be sorted that make up # the rest of the list. # We first find the smallest element in the unsorted sublist and # place it at the end of the sorted sublist. Thus, we are continuously grabbing the smallest # unsorted element and placing it in sorted order in the sorted sublist. # This process continues iteratively until the list is fully sorted. def selection_sort(arr): for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): # Select the smallest value if arr[j] < arr[minimum]: minimum = j # Place it at the front of the # sorted end of the array arr[minimum], arr[i] = arr[i], arr[minimum] return arr arr = [4,1,6,4,8,10,28,-3,-45] selection_sort(arr) print(arr) Insertion sort explained. we need a marker which will move through the list on the outer loop Start iteration and compasins at first element Then check if the number on the second element smaller than the number at the marker. If not we can move to the next element. Next we check the third element with the marker if it is smaller than the marker (First Element) then do a swap else move to the next element on the list. We keep checking the next element with the marker until the end of the list. l = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] bubble_sort(l) def bubble_sort(arr): sort_head = True while sort_head: print("Bubble Sort: " + str(arr)) sort_head = False for num in range(len(arr)-1): if arr[num]>arr[num+1]: sort_head = True arr[num],arr[num+1]=arr[num+1],arr[num] l = [4,1,6,4,8,10,28,-3,-45] bubble_sort(l) def selection_sort(arr): spot_marker=0 while spot_marker < len(arr): for num in range(spot_marker,len(arr)): if arr[num] < arr[spot_marker]: arr[spot_marker],arr[num]=arr[num],arr[spot_marker] #print('Item Swapped') spot_marker += 1 print(arr) l = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] selection_sort(l) def selection_sort(arr): spot_marker = 0 while spot_marker < len(arr): for num in range(spot_marker,len(arr)): if arr[num] < arr[spot_marker]: arr[spot_marker],arr[num]=arr[num],arr[spot_marker] spot_marker += 1 print(arr) l = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] selection_sort(l)
true
38baa3eb890530cac3a056140908e23015070428
UnimaidElectrical/PythonForBeginners
/Random_code_store/If_Else_Statement/If_Else_statement.py
2,375
4.375
4
"""This mimicks the children games where we are asked to choose our own adventure """ print("""You enter a dark room with two doors. Do you go through door #1 or door #2?""") door = input ("> ") if door == "1": print("There's a giant bear here eating a cheese cake.") print("What do you want to do?") print("1. Take the cake.") print("2. Scream at the bear.") bear = input("> ") if bear == "1": print("The bear eats your face off. Good job!") elif bear=="2": print("The bear eats your leg off. Good job!") else: print(f"Well doing, {bear} is probable better.") print("Bear runs away.") elif door == "2": print("You stare into the endless abyss at Cthulhu's retina.") print("1. Blueberries.") print("2. Yellow jacket clothespins.") print("3. Understanding revolvers yelling melodies.") insanity = input("> ") if insanity == "1" or insanity =="2": print("Your body survives powered by the mind of jello.") print("Good Job!") else: print("The insanity rots your eyes into a pool of muck.") print("Good Job!") else: print("You stumble around and fall on a knife and die. Good Job!") # Else Statements # break # continue # The else statement is most commonly used along with the if statement, but it can also follow a for or while loop, which gives it a different meaning. # With the for or while loop, the code within it is called if the loop finishes normally (when a break statement does not cause an exit from the loop). Example: for i in range(10): if i == 999: break else: print("Unbroken 1") for i in range(10): if i == 5: break else: print("Unbroken 2") # The first for loop executes normally, resulting in the printing of "Unbroken 1". # The second loop exits due to a break, which is why it's else statement is not executed. # Try # Except # The else statement can also be used with try/except statements. # In this case, the code within it is only executed if no error occurs in the try statement. # Example: #Example2: try: print(1) except ZeroDivisionError: print(2) else: print(3) try: print(1/0) except ZeroDivisionError: print(4) else: print(5) # Example 2: try: print(1) print(1 + "1" == 2) print(2) except TypeError: print(3) else: print(4)
true
0f509b10fd23df81cd306ea05a6ae07e6b9c13b3
UnimaidElectrical/PythonForBeginners
/Random_code_store/Lists/In_Operators.py
453
4.34375
4
#The In operator in python can be used to determine weather or not a string is a substring of another string. #what is the optcome of these code: nums=[10,9,8,7,6,5] nums[0]=nums[1]-5 if 4 in nums: print(nums[3]) else: print(nums[4]) #To check if an item is not in the list you can use the NOT operator #In this case the pattern doesn't matter. nums=[1,2,3] print(not 4 in nums) print(4 not in nums) print(not 3 in nums) print(3 not in nums)
true
ff97e60837bf32c1dc1f65ef8afda4f658a7116b
lchristopher99/CSE-Python
/CSElab6/turtle lab.py
2,207
4.5625
5
#Name: Jason Hwang, Travis Taliancich, Logan Christopher, Rees Hogue Date Assigned: 10/19/2018 # #Course: CSE 1284 Section 14 Date Due: 10/20/2018 # #File name: Geometry # #Program Description: Make a geometric shape #This is the function for making the circle using turtle def draw_circle(x, y, r): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.circle(r) turtle.penup() #This is the function for making the rectangle using turtle def draw_rectangle(x, y, width, height): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward(width) turtle.left(90) turtle.forward(height) turtle.left(90) turtle.forward(width) turtle.left(90) turtle.forward(height) turtle.penup() #This is the function for making the point using turtle def draw_point(x, y, size): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward(size) turtle.left(180) turtle.forward(size * 2) turtle.left(180) turtle.forward(size) turtle.left(90) turtle.forward(size) turtle.left(180) turtle.forward(size * 2) #This is the function for making the line using turtle def draw_line(x1, y1, x2, y2): import turtle turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) turtle.penup() #This is the function for making the triangle using turtle. def draw_triangle(x, y, side): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward(side) turtle.left(120) turtle.forward(side) turtle.left(120) turtle.forward(side) turtle.penup() #the function that will call all of the functions def main(): draw_circle(-100, -100, 200) draw_circle(100, 100, 200) draw_rectangle(10, 10, 50, 70) draw_rectangle(90, 90, 100, 150) draw_point(0, 0, 50) draw_point(70, 70, 50) draw_line(20, 20, 30, 70) draw_line(300, 200, 100, 150) draw_triangle(100, 100, 50) draw_triangle(-100, -150, 50) main()
true
5e447702f51cd3318fd5595a131da34c2bc498d5
endreujhelyi/endreujhelyi
/week-04/day-3/04.py
528
4.3125
4
# create a 300x300 canvas. # create a line drawing function that takes 2 parameters: # the x and y coordinates of the line's starting point # and draws a line from that point to the center of the canvas. # draw 3 lines with that function. from tkinter import * top = Tk() size = 300 canvas = Canvas(top, bg="#222", height=size, width=size) def line_drawer(x, y): return canvas.create_line(x, y, size/2, size/2, fill='coral') line_drawer(20, 40) line_drawer(130, 50) line_drawer(220, 100) canvas.pack() top.mainloop()
true
0c2563d42a29e81071c4a2667ace0495477ac241
endreujhelyi/endreujhelyi
/week-04/day-3/08.py
534
4.1875
4
# create a 300x300 canvas. # create a square drawing function that takes 2 parameters: # the x and y coordinates of the square's top left corner # and draws a 50x50 square from that point. # draw 3 squares with that function. from tkinter import * top = Tk() size = 300 lines = 3 canvas = Canvas(top, bg="#222", height=size, width=size) def square_drawer(x, y): return canvas.create_rectangle(x, y, x+50, y+50, fill='coral') square_drawer(20, 40) square_drawer(130, 50) square_drawer(220, 100) canvas.pack() top.mainloop()
true
506d0bbf89cbbeeb0a5343c43d955b853a526556
endreujhelyi/endreujhelyi
/week-04/day-4/02.py
212
4.1875
4
# 2. write a recursive function # that takes one parameter: n # and adds numbers from 1 to n def recursive(n): if n == 1: return (n) else: return n + recursive(n-1) print (recursive(5))
false
dc27b4d07c81d4faed52867851a4b623ac3a7ca3
jonathan-potter/MathStuff
/primes/SieveOfAtkin.py
1,824
4.21875
4
########################################################################## # # Programmer: Jonathan Potter # ########################################################################## import numpy as np ########################################################################## # Determine the sum of all prime numbers less than an input number ########################################################################## def SieveOfAtkin(limit): """usage SieveOfAtkin(limit) This function returns a list of all primes below a given limit. It is an implimentation of the Sieve of Atkin. The primary logic is a reimplimentation of the example on Wikipedia. en.m.wikipedia/wiki/Sieve_of_Atkin""" # calculate and store the square root of the limit sqrtLimit = np.int(np.ceil(np.sqrt(limit))); # initialize the sieve isPrime = [False] * limit; # this script considers 1 to be prime. If you don't like it, # subtract 1 from the result isPrime[1:3] = [True] * 3; # impliment the sieve for x in range (1,sqrtLimit+1): for y in range(1,sqrtLimit+1): n = 4 * x**2 + y**2; if (n <= limit and (n % 12 == 1 or n % 12 == 5)): isPrime[n] = not(isPrime[n]); n = 3 * x**2 + y**2; if (n <= limit and n % 12 == 7): isPrime[n] = not(isPrime[n]); n = 3 * x**2 - y**2; if (n <= limit and x > y and n % 12 == 11): isPrime[n] = not(isPrime[n]); # for prime n: ensure that all of the multiples of n^2 are not flagged as prime for n in range(5,sqrtLimit+1): if isPrime[n]: isPrime[n**2::n**2] = [False] * len(isPrime[n**2::n**2]); # create array of prime numbers below limit primeArray = []; for n in range(limit + 1): if isPrime[n] == True: primeArray.append(n); # return the result return primeArray;
true
6733b7b848e1e271f7f3d313284348f9e9fab0a8
gyhou/DS-Unit-3-Sprint-2-SQL-and-Databases
/SC/northwind.py
2,546
4.5625
5
import sqlite3 # Connect to sqlite3 file conn = sqlite3.connect('northwind_small.sqlite3') curs = conn.cursor() # Get names of table in database print(curs.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;").fetchall()) # What are the ten most expensive items (per unit price) in the database? """[('Côte de Blaye',), ('Thüringer Rostbratwurst',), ('Mishi Kobe Niku',), ("Sir Rodney's Marmalade",), ('Carnarvon Tigers',), ('Raclette Courdavault',), ('Manjimup Dried Apples',), ('Tarte au sucre',), ('Ipoh Coffee',), ('Rössle Sauerkraut',)]""" print(curs.execute(""" SELECT ProductName, SupplierId FROM Product ORDER BY UnitPrice DESC LIMIT 10;""").fetchall()) # What is the average age of an employee at the time of their hiring? (Hint: a lot of arithmetic works with dates.) # 37.22 years old print(curs.execute(""" SELECT AVG(age) FROM ( SELECT HireDate-BirthDate AS age FROM Employee GROUP BY Id);""").fetchall()) # (Stretch) How does the average age of employee at hire vary by city? """[('Kirkland', 29.0), ('London', 32.5), ('Redmond', 56.0), ('Seattle', 40.0), ('Tacoma', 40.0)]""" print(curs.execute(""" SELECT City, AVG(age) FROM ( SELECT City, HireDate-BirthDate AS age FROM Employee GROUP BY Id) GROUP BY City;""").fetchall()) # What are the ten most expensive items (per unit price) in the database and their suppliers? """[('Côte de Blaye', 'Aux joyeux ecclésiastiques'), ('Thüringer Rostbratwurst', 'Plutzer Lebensmittelgroßmärkte AG'), ('Mishi Kobe Niku', 'Tokyo Traders'), ("Sir Rodney's Marmalade", 'Specialty Biscuits, Ltd.'), ('Carnarvon Tigers', 'Pavlova, Ltd.'), ('Raclette Courdavault', 'Gai pâturage'), ('Manjimup Dried Apples', "G'day, Mate"), ('Tarte au sucre', "Forêts d'érables"), ('Ipoh Coffee', 'Leka Trading'), ('Rössle Sauerkraut', 'Plutzer Lebensmittelgroßmärkte AG')]""" print(curs.execute(""" SELECT ProductName, CompanyName FROM Supplier, ( SELECT ProductName, SupplierId FROM Product ORDER BY UnitPrice DESC) WHERE Id=SupplierId LIMIT 10;""").fetchall()) # What is the largest category (by number of unique products in it)? # Category: Confections (13 unique products) """[('Confections', 13)]""" print(curs.execute(""" SELECT CategoryName, MAX(cat_id_count) FROM Category, ( SELECT CategoryId, COUNT(CategoryId) AS cat_id_count FROM Product GROUP BY CategoryId) WHERE Id=CategoryId;""").fetchall()) # (Stretch) Who's the employee with the most territories? # Robert King with 10 territories """[('King', 'Robert', 10)]""" print(curs.execute(""" SELECT LastName, FirstName, MAX(terri_id_count) FROM Employee, ( SELECT EmployeeId, COUNT(TerritoryID) AS terri_id_count FROM EmployeeTerritory GROUP BY EmployeeId) WHERE EmployeeId=Id;""").fetchall())
true
75ee01282c6ac7032782e7c7c5e41918976ea2f4
mattwu4/Python-Easy-Questions
/Check Primality Functions/Solution.py
638
4.15625
4
while True: number = input("Choose any number you want! ") number = int(number) if number == 2: print("PRIME!") elif number == 3: print("PRIME!") elif number == 5: print("PRIME!") elif number == 7: print("PRIME!") elif number == 11: print("PRIME!") elif (number % 2) == 0: print("NOT PRIME!!") elif (number % 3) == 0: print("NOT PRIME!!") elif (number % 5) == 0: print("NOT PRIME!!") elif (number % 7) == 0: print("NOT PRIME!!") elif (number % 11) == 0: print("NOT PRIME!!") else: print("PRIME!!")
false
c653a1e85345ac2bd9dabf58da510c86a43afdac
jrabin/GenCyber-2016
/Base_Day.py
309
4.21875
4
# -*- coding: utf-8 -* """ Created on Wed Jul 6 10:24:01 2016 @author: student """ #Create your own command for binary conversion #// gives quotient and % gives remainder ''' hex_digit=input("Hex input:") print(chr(int("0x"+hex_digit,16))) ''' letter=input("Enter letter:") print(hex(int(ord(letter))))
true
8de2a3d8d21d1ccc75b71500424728f5ec707a5f
yestodorrow/py
/init.py
486
4.15625
4
print("hello, Python"); if True: print("true") else: print("flase") # 需要连字符的情况 item_one=1 item_two=2 item_three=3 total = item_one+\ item_two+\ item_three print(total) item_one="hello" item_two="," item_three="python" total = item_one+\ item_two+\ item_three print(total) # 不需要连字符的情况 days=["Monday","Tuesday","Wednesday","Thursday", "Friday"] print(days) name="this is a comment" # this is a comment
false
f7c954329701b44dd381aa844cf6f7a11ba1461e
KritiBhardwaj/PythonExercises
/loops.py
1,940
4.28125
4
# # Q1) Continuously ask the user to enter a number until they provide a blank input. Output the sum of all the # # numbers # # number = 0 # # sum = 0 # # while number != '': # # number = input("Enter a number: ") # # if number: # # sum = sum + int(number) # # print(sum) # # sum = 0 # # number = 'number' # # while len(number) > 0: # # number = input("Enter number: ") # # sum = sum + int(number) # # print(f"The sum is {sum}") number = 0 sum = 0 while number != "": sum = sum + int(number) number = input("Enter a number:") print(sum) # Q2) Use a for loop to format and print the following list: mailing_list = [ ["Roary", "roary@moth.catchers"], ["Remus", "remus@kapers.dog"], ["Prince Thomas of Whitepaw", "hrh.thomas@royalty.wp"], ["Biscuit", "biscuit@whippies.park"], ["Rory", "rory@whippies.park"], ] for contact in mailing_list: # print(f"{item[0]: <20} ${item[1]: .2f}") print(f"{contact[0]:} : {contact[1]}") # Q3) Use a while loop to ask the user for three names and append them to a list, use a for loop to print the list. count = 0 nameList = [] while count < 3: name = input("Enter name: ") nameList.append(name) count += 1 print() for name in nameList: print(name) #4 Ask the user how many units of each item they bought, then output the corresponding receipt groceries = [ ["Baby Spinach", 2.78], ["Hot Chocolate", 3.70], ["Crackers", 2.10], ["Bacon", 9.00], ["Carrots", 0.56], ["Oranges", 3.08] ] newList = [] groceryCost = 0 for item in groceries: n = input(f"How many {item[0]}: ") totalItemCost = item[1] * int(n) groceryCost = groceryCost + totalItemCost # print(f"{item[0]:<20} : {totalItemCost:}") newList.append([item[0], totalItemCost]) print(newList) print() print(f"====Izzy's Food Emporium====") for item in newList: # print(f"{newList[0]:<20} : {newList[1]:2f}") print(f"{item[0]:<20} : ${item[1]:.2f}") print('============================') print(f"{'$':>24}{groceryCost:.2f}")
true
dbe0e4b02b87fc67dd2e4de9cbaa7c0226f9e58e
geekidharsh/elements-of-programming
/primitive-types/bits.py
1,870
4.5
4
# The Operators: # x << y # Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). # This is the same as multiplying x by 2**y. # ex: 2 or 0010, so 2<<2 = 8 or 1000. # x >> y # Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y. # ex: 8 or 1000, so 8>>2 = 2 or 0010. # x & y # Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, # otherwise it's 0. # x | y # Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, # otherwise it's 1. # ~ x # Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. # This is the same as -x - 1. # x ^ y # Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if # that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1. # https://www.hackerearth.com/practice/notes/bit-manipulation/ # bit fiddle trick is that: # 1. numbers that are a power of 2, have only one bit set. # all other numbers will have more than one bit set i.e 1 in more that one places # in their binary representation # so 2, 4, 8, 16 etc. # 2. binary representation of (x-1) can be obtained by simply flipping all the bits # to the right of rightmost 1 in x and also including the rightmost 1. # so, x&(x-1) is basically, # will have all the bits equal to the x except for the rightmost 1 in x. # 3. def number_of_bits(x): # as in number of set bits bits = 0 while x: bits += x&1 # right shift by 1 bit every move x >>=1 return bits def pos_of_bits(x): # input: integer output: bit_pos = [] bits = 0 while x: bit_pos.append(x&1) x >>=1 return ''.join([str(i) for i in reversed(bit_pos)]) print(pos_of_bits('a'))
true
3a60bae93f01f1e9205430277f924390825c598f
geekidharsh/elements-of-programming
/binary-trees/binary-search-tree.py
1,229
4.15625
4
"""a binary search tree, in which for every node x and it's left and right nodes y and z, respectively. y <= x >= z""" class BinaryTreeNode: """docstring for BT Node""" def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right # TRAVERSING OPERATION def preorder(root): # preorder processes root before left and then finally right child if root: print(root.data) preorder(root.left) preorder(root.right) def inorder(root): # inorder processes left then root and then finally right child if root: inorder(root.left) print(root.data) inorder(root.right) def postorder(root): if root: postorder(root.right) postorder(root.left) print(root.data) # SEARCH in a Binary search tree def bst_search_recursive(root, key): if key == root.data or root is None: return root if key < root.data: return bst_search_recursive(root.left, key) if key > root.data: return bst_search_recursive(root.right, key) # TEST # ---- # sample node a a = BinaryTreeNode(18) a.left = BinaryTreeNode(15) a.right= BinaryTreeNode(21) # TRAVERSING a binary search tree inorder(a) preorder(a) postorder(a) # searching print(bst_search_recursive(a, 14))
true
4c05bf6d559bd0275323dbdb217edc1a2208f59c
geekidharsh/elements-of-programming
/arrays/generate_primes.py
613
4.1875
4
# Take an integer argument 'n' and generate all primes between 1 and that integer n # example: n = 18 # return: 2,3,5,7,11,13,17 def generate_primes(n): # run i, 2 to n # any val between i to n is prime, store integer # remove any multiples of i from computation primes = [] #generate a flag array for all element in 0 till n. initialize all items to True is_primes = [False, False] + [True]*(n-1) for p in range(2,n+1): if is_primes[p]: primes.append(p) # remove all multiples of p for i in range(p,n+1,p): is_primes[i] = False return primes print(generate_primes(35))
true
51a3ae2e607f52ab2c79c59344699e52030e1c15
justindarcy/CodefightsProjects
/isCryptSolution.py
2,657
4.46875
4
#A cryptarithm is a mathematical puzzle for which the goal is to find the correspondence between letters and digits, #such that the given arithmetic equation consisting of letters holds true when the letters are converted to digits. #You have an array of strings crypt, the cryptarithm, and an an array containing the mapping of letters and digits, #solution. The array crypt will contain three non-empty strings that follow the structure: [word1, word2, word3], #which should be interpreted as the word1 + word2 = word3 cryptarithm. #If crypt, when it is decoded by replacing all of the letters in the cryptarithm with digits using the mapping in #solution, becomes a valid arithmetic equation containing no numbers with leading zeroes, the answer is true. If it #does not become a valid arithmetic solution, the answer is false. def isCryptSolution(crypt, solution): word3len=len(crypt[2]) num1 = [] num2 = [] num3 = [] def wordgrab(crypt, solution): #here i pull a single word from crypt and pass it to wordtonum. I also pass which # word i'm sending word_count=0 for word in crypt: word_count=word_count+1 word_letter(word,word_count, solution) def word_letter(word, word_count, solution): #here i will pass in a single word and this will pull out each letter #in turn and pass it to letter_num letter_count=0 for letter in word: letter_count+=1 letter_num(letter, word_count, solution,letter_count) def letter_num(letter, word_count, solution,letter_count): # here i take a letter and use solution to translate the letter to a #num and create num1-3 for list in solution: if letter == list[0] and word_count==1: num1.append(list[1]) elif letter == list[0] and word_count==2: num2.append(list[1]) elif letter == list[0] and word_count==3: num3.append(list[1]) if word_count==3 and letter_count==word3len: global answer answer = output(num1, num2, num3) def output(num1, num2, num3): if num1[0]=='0' and len(num1)>1: return False elif num2[0]=='0' and len(num2)>1: return False elif num3[0]=='0' and len(num3)>1: return False number1=int("".join(num1)) number2=int("".join(num2)) number3=int("".join(num3)) if number1 + number2==number3: return True else: return False wordgrab(crypt, solution) return(answer)
true
9c01fc72c243846886a7e1f44e5a0ebcce008f7b
sgirimont/projecteuler
/euler1.py
1,153
4.15625
4
################################### # Each new term in the Fibonacci sequence is generated by adding the previous two terms. # By starting with 1 and 2, the first 10 terms will be: # # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # # By considering the terms in the Fibonacci sequence whose values do not exceed four million, # find the sum of the even-valued terms. ################################### def product_finder(factors, limit): product_list = [] x = 0 if 0 in factors: print('Cannot have a zero as one of the factors.') else: while x < len(factors): if factors[x] > limit: print('Cannot have a factor larger than the limit value.') exit() multiplier = 1 while multiplier <= limit: if factors[x] * multiplier <= limit and factors[x] * multiplier not in product_list: product_list.append(factors[x] * multiplier) else: break multiplier += 1 x += 1 product_list.sort() print(product_list) product_finder([2001, 5032, 8674], 10000)
true
e9acdbfd9ab5a29c06f1e27abcd1d384611c5cf0
chizhangucb/Python_Material
/cs61a/lectures/Week2/Lec_Week2_3.py
2,095
4.21875
4
## Functional arguments def apply_twice(f, x): """Return f(f(x)) >>> apply_twice(square, 2) 16 >>> from math import sqrt >>> apply_twice(sqrt, 16) 2.0 """ return f(f(x)) def square(x): return x * x result = apply_twice(square, 2) ## Nested Defintions # 1. Every user-defined function has a parent environment / frame # 2. The parent of a function is the frame in which it was defined # 3. Every local frame has a parent frame # 4. The parent of a frame is the parent of a function called def make_adder(n): """Return a function that takes one argument k and returns k + n. >>> add_three = make_adder(3) >>> add_three(4) 7 """ def adder(k): return k + n return adder ## Lexical scope and returning functions def f(x, y): return g(x) def g(a): return a + y # f(1, 2) # name 'y' is not defined # This expression causes an error because y is not bound in g. # Because g(a) is NOT defined within f and # g is parent frame is the global frame, which has no "y" defined ## Composition def compose1(f, g): def h(x): return f(g(x)) return h def triple(x): return 3 * x squiple = compose1(square, triple) squiple(5) tripare = compose1(triple, square) tripare(5) squadder = compose1(square, make_adder(2)) squadder(5) compose1(square, make_adder(2))(3) ## Function Decorators # special syntax to apply higher-order functions as part of executing a def statement def trace(fn): """Returns a function that precedes a call to its argument with a print statement that outputs the argument. """ def wrapped(x): print("->", fn, '(', x, ')') return fn(x) return wrapped # @trace affects the execution rule for def # As usual, the function triple is created. # However, the name triple is not bound to this function. # Instead, the name triple is bound to the returned function # value of calling trace on the newly defined triple function @trace def triple(x): return 3 * x triple(12) # The decorator symbol @ may also be followed by a call expression
true
fbd7afe059c5eb0b6d99122e46b1ddbcaac18de0
hammer-spring/PyCharmProject
/pythion3 实例/30_list常用操作.py
1,680
4.1875
4
print("1.list 定义") li = ["a", "b", "mpilgrim", "z", "example"] print(li[1]) print("2.list 负数索引") print(li[-1]) print(li[-3]) print(li[1:3]) print(li[1:-1]) print(li[0:3]) print("3.list 增加元素") li.append("new") print(li) li.insert(2,"new") print(li) li.extend(["two","elements"]) print(li) print("4.list 搜索") a = li.index("new") print(a) print("c" in li) print("5.list 删除元素") li.remove("z") print(li) li.remove("new") # 删除首次出现的一个值 print(li) #li.remove("c") #list 中没有找到值, Python 会引发一个异常 #print(li) print(li.pop()) # pop 会做两件事: 删除 list 的最后一个元素, 然后返回删除元素的值。 print(li) print("6.list 运算符") li = ['a', 'b', 'mpilgrim'] li = li + ['example', 'new'] print(li) li += ['two'] print(li) li = [1, 2] * 3 print(li) print("8.list 分割字符串") li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret'] s = ";".join(li) print(s) print(s.split(";") ) print(s.split(";", 1) ) print("9.list 的映射解析") li = [1, 9, 8, 4] print([elem*2 for elem in li]) li = [elem*2 for elem in li] print(li) print("10.dictionary中的解析") params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} print(params.keys()) print(params.values()) print(params.items()) print([k for k, v in params.items()]) print([v for k, v in params.items()]) print(["%s=%s" % (k, v) for k, v in params.items()]) print("11.list 过滤") li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"] print([elem for elem in li if len(elem) > 1]) print([elem for elem in li if elem != "b"]) print([elem for elem in li if li.count(elem) == 1])
false
99a4589ac6adbe80b7efc1a04fd9761892d09deb
hammer-spring/PyCharmProject
/18-Spider/v23.py
986
4.125
4
''' python中正则模块是re 使用大致步骤: 1. compile函数讲正则表达式的字符串便以为一个Pattern对象 2. 通过Pattern对象的一些列方法对文本进行匹配,匹配结果是一个Match对象 3. 用Match对象的方法,对结果进行操纵 ''' import re # \d表示以数字 # 后面+号表示这个数字可以出现一次或者多次 s = r"\d+" # r表示后面是原生字符串,后面不需要转义 # 返回Pattern对象 pattern = re.compile(s) # 返回一个Match对象 # 默认找到一个匹配就返回 m = pattern.match("one12two2three3") print(type(m)) # 默认匹配从头部开始,所以此次结果为None print(m) # 返回一个Match对象 # 后面为位置参数含义是从哪个位置开始查找,找到哪个位置结束 m = pattern.match("one12two2three3", 3, 10) print(type(m)) # 默认匹配从头部开始,所以此次结果为None print(m) print(m.group()) print(m.start(0)) print(m.end(0)) print(m.span(0))
false
16021ebd861f8d23781064101d52eba228a6f800
mldeveloper01/Coding-1
/Strings/0_Reverse_Words.py
387
4.125
4
""" Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots. """ def reverseWords(s): l = list(s.split('.')) l = reversed(l) return '.'.join(l) if __name__ == "__main__": t = int(input()) for i in range(t): string = str(input()) result = reverseWords(string) print(result)
true
0053bde8153d3559f824aed6a017c528410538ea
JaredD-SWENG/beginnerpythonprojects
/3. QuadraticSolver.py
1,447
4.1875
4
#12.18.2017 #Quadratic Solver 2.4.6 '''Pseudocode: The program is designed to solve qudratics. It finds it's zeros and vertex. It does this by asking the user for the 'a', 'b', and 'c' of the quadratic. With these pieces of information, the program plugs in the variables into the quadratic formula and the formula to solve for the vertex. It then ouputs the information solved for to the user.''' import math print('''Welcome to Quadratic Solver! ax^2+bx+c ''') def FindVertexPoint(A,B,C): if A > 0: x_vertex = (-B)/(2*A) y_vertex = (A*(x_vertex**2))+(B*x_vertex)+C return('Minimum Vertex Point: '+str(x_vertex)+', '+str(y_vertex)) elif A < 0: x_vertex = (-B)/(2*A) y_vertex = (A*(x_vertex**2))+(B*x_vertex)+C return('Maximum Vertex Point: '+str(x_vertex)+', '+str(y_vertex)) def QuadraticFormula(A,B,C): D = (B**2)-(4*(A*C)) if D < 0: return('No real solutions') elif D == 0: x = (-B+math.sqrt((B**2)-(4*(A*C))))/(2*A) return('One solution: '+str(x)) else: x1 = (-B+math.sqrt((B**2)-(4*(A*C))))/(2*A) x2 = (-B-math.sqrt((B**2)-(4*(A*C))))/(2*A) return('Solutions: '+str(x1)+' or '+str(x2)) a = float(input("Quadratic's a: ")) b = float(input("Quadratic's b: ")) c = float(input("Quadratic's c: ")) print('') print(QuadraticFormula(a,b,c)) print(FindVertexPoint(a,b,c))
true
bf217099c4cd2547f792e271d60cefcb696187ad
wellqin/USTC
/DataStructure/字符串/数字.py
1,974
4.1875
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: 数字 Description : Author : wellqin date: 2019/8/1 Change Activity: 2019/8/1 ------------------------------------------------- """ import math # // 得到的并不一定是整数类型的数,它与分母分子的数据类型有关系。 print(7.5//2) # 3.0 print(math.modf(7.5)) # (0.5, 7.0) print(math.modf(7)) # (0.0, 7.0) print(round(3.14159, 4)) # 3.1416 print(round(10.5)) # 10 """ fractions 模块提供了分数类型的支持。 构造函数: class fractions.Fraction(numerator=0, denominator=1) class fractions.Fraction(int|float|str|Decimal|Fraction) 可以同时提供分子(numerator)和分母(denominator)给构造函数用于实例化Fraction类,但两者必须同时是int类型或者numbers.Rational类型,否则会抛出类型错误。当分母为0,初始化的时候会导致抛出异常ZeroDivisionError。 分数类型: from fractions import Fraction >>> x=Fraction(1,3) >>> y=Fraction(4,6) >>> x+y Fraction(1, 1) >>> Fraction('.25') Fraction(1, 4) """ from fractions import Fraction x = Fraction(1,3) y = Fraction(4,6) print(x+y) # 1 print(Fraction('.25')) # 1/4 print(Fraction('3.1415'), type(Fraction('3.1415'))) # 6283/2000 listres = str(Fraction('3.1415')).split("/") print(listres[0], listres[1]) f = 2.5 z = Fraction(*f.as_integer_ratio()) print(z) # 5/2 xx=Fraction(1,3) print(float(xx)) # 0.3333333333333333 # decimal 模块提供了一个 Decimal 数据类型用于浮点数计算,拥有更高的精度。 import decimal decimal.getcontext().prec=4 # 指定精度(4位小数) yy = decimal.Decimal(1) / decimal.Decimal(7) print(yy) # 0.1429 print(yy) # 0.14286 decimal.getcontext().prec=5 # fractions.gcd(a, b) # 用于计算最大公约数。这个函数在Python3.5之后就废弃了,官方建议使用math.gcd()。 print(math.gcd(21, 3)) import math
false
c1b024fe6518776cbeaabb614ca1fa63813b02b7
wellqin/USTC
/PythonBasic/base_pkg/python-06-stdlib-review/chapter-01-Text/1.1-string/py_02_stringTemplate.py
1,422
4.1875
4
### string.Template is an alternative of str object's interpolation (format(), %, +) import string def str_tmp(s, insert_val): t = string.Template(s) return t.substitute(insert_val) def str_interplote(s, insert_val): return s % insert_val def str_format(s, insert_val): return s.format(**insert_val) def str_tmp_safe(s, insert_val): t = string.Template(s) try: return t.substitute(insert_val) except KeyError as e: print('ERROR:', str(e)) return t.safe_substitute(insert_val) val = {'var': 'foo'} # example 01 s = """ template 01: string.Template() Variable : $var Escape : $$ Variable in text: ${var}iable """ print(str_tmp(s, val)) # example 02 s = """ template 02: interpolation %% Variable : %(var)s Escape : %% Variable in text: %(var)siable """ print(str_interplote(s, val)) # example 03 s = """ template 03: format() Variable : {var} Escape : {{}} Variable in text: {var}iable """ print(str_format(s, val)) # example 04 s = """ $var is here but $missing is not provided """ print(str_tmp_safe(s, val)) """ conclusion: - any $ or % or {} is escaped by repeating itself TWICE. - string.Template is using $var or ${var} to identify and insert dynamic values - string.Template.substitute() won't format type of the arguments.. -> using string.Template.safe_substitute() instead in this case """
true
988ab3ba48c2d279c3706a2f12224f3793182a14
wellqin/USTC
/DesignPatterns/behavioral/Adapter.py
1,627
4.21875
4
# -*- coding:utf-8 -*- class Computer: def __init__(self, name): self.name = name def __str__(self): return 'the {} computer'.format(self.name) def execute(self): return self.name + 'executes a program' class Synthesizer: def __init__(self, name): self.name = name def __str__(self): return 'the {} synthesizer'.format(self.name) def play(self): return self.name + 'is playing an electronic song' class Human: def __init__(self, name): self.name = name def __str__(self): return '{} the human'.format(self.name) def speak(self): return self.name + 'says hello' class Adapter: def __init__(self, obj, adapted_methods): self.obj = obj self.__dict__.update(adapted_methods) def __str__(self): return str(self.obj) if __name__ == '__main__': objects = [Computer('Computer')] synth = Synthesizer('Synthesizer') objects.append(Adapter(synth, dict(execute=synth.play))) human = Human('Human') objects.append(Adapter(human, dict(execute=human.speak))) for i in objects: print('{} {}'.format(str(i), i.execute())) print('type is {}'.format(type(i))) print("*" * 20) """ the Computer computer Computerexecutes a program type is <class '__main__.Computer'> the Synthesizer synthesizer Synthesizeris playing an electronic song type is <class '__main__.Adapter'> Human the human Humansays hello type is <class '__main__.Adapter'> """ for i in objects: print(i.obj.name) # i.name
true
a47e31222de348822fbde57861341ea68a4fa5fb
Ph0tonic/TP2_IA
/connection.py
927
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class Connection: """ Class connection which allow to link two cities, contains the length of this connection """ def __init__(self, city1, city2, distance): """ Constructor :param city1: City n°1 :param city2: City n°2 :param distance: distance between the 2 cities """ self.city1 = city1 self.city2 = city2 self.distance = distance def get_linked(self, city): """ get the other city connected via this connection :param city: city from where the connection is coming from :return: city where the connection is going """ return self.city1 if city != self.city1 else self.city2 def __str__(self): """ To String function for debug """ return str(self.city1)+" - "+str(self.city2)
true
92e296b5132802978932b62ddab03030d636785d
elsandkls/SNHU_IT140_itty_bitties
/example_1_list.py
1,593
4.34375
4
# Get our lists from the command line # It's okay if you don't understand this right now import sys list1 = sys.argv[1].split(',') list2 = sys.argv[2].split(',') # # Print the lists. # # Python puts '[]' around the list and seperates the items # by commas. print(list1) print(list2) # # Note that this list has three different types of items # in the container: an Integer, a String, and a Boolean. # list3 = [1,"red", True] print(list3) strList = ['Alice', 'Shahneila', 'Bobx, 'Tariq'] numList = [1, 3.141, 5, 17.1, 100] numList = [] numList.append(4) # create a list aList = [ 'Alice', 'Shahneila', 'Bob', 'Tariq' ] print(aList) # change the second element aList[1] = 'Sean' print(aList) # create an empty list numList = [] # append some items to the empty list numList.append(1) numList.append(2) numList.append(4) print(numList) # insert an element at a specific index numList.insert(2, 3) print(numList) aString = '12345' # use the len() function to get the length of a string print('the string has a length of:') print(len(aString)) aList = [1,2,3,4,5] # you can also use the len() function to get the length of a list print('the list has a length of:') print(len(aList)) myList = [1,3,5,7,9] stop = len(myList) print('the list has ' + str(stop) + ' elements') aRange = range(0, stop) for i in aRange: print(myList[i]) # short version print('a shorter way of creating ranges for looping') for i in range(0, len(myList)): print(myList[i]) # display every second item print('range step of 2') for i in range(0, len(myList), 2): print(myList[i])
true
7add89c47bb6e5b3a49504244acc952a91040d31
MasudHaider/Think-Python-2e
/Exer-5-3(1).py
555
4.21875
4
def is_triangle(length1, length2, length3): case1 = length1 + length2 case2 = length1 + length3 case3 = length2 + length3 if length1 > case3 or length2 > case2 or length3 > case1: print("No") elif length1 == case3 or length2 == case2 or length3 == case1: print("Degenerate triangle") else: print("Yes") prompt = "Enter value for length1: " a = int(input(prompt)) prompt = "Enter value for length2: " b = int(input(prompt)) prompt = "Enter value for length3: " c = int(input(prompt)) is_triangle(a, b, c)
true
afc0ab954176bdcbbb49b4415431c49278c9628c
kchow95/MIS-304
/CreditCardValidaiton.py
2,340
4.15625
4
# Charlene Shu, Omar Olivarez, Kenneth Chow #Program to check card validation #Define main function def main(): input_user = input("Please input a valid credit card number: ") #Checks if the card is valid and prints accordingly if isValid(input_user): print(getTypeCard(input_user[0])) print("The number is valid") else: print("Your credit card number is invalid") #define isvalid returns true if the card is valid def isValid(card_number): valid_card = True #Checks the numbers first check_numbers = (sumOfDoubleEvenPlace(card_number) + sumOfOddPlace(card_number))%10 prefix = getPrefix(card_number) #checks the parameters for the card #not long enough or too long if 13 >= getSize(card_number) >=16: valid_card = False #the numbers don't add up elif(check_numbers != 0): valid_card = False #prefix isn't valid elif prefixMatched(card_number, prefix) == False: print(prefix) valid_card = False return valid_card #sums the even places with double the int def sumOfDoubleEvenPlace(card_number): step = len(card_number)-2 total = 0 while step >= 0: total+= (getDigit(2*int(card_number[step]))) step-=2 return total #Gets the digit for the double even place function, takes out the 10s place and subtracts by one def getDigit(digit): return_digit = digit if(digit >= 10): return_digit = (digit - 10) + 1 return return_digit #Gets the digit for the odd places from the end of the card_number and sums them def sumOfOddPlace(card_number): step = len(card_number)-1 total = 0 while step >= 0: total += int(card_number[step]) step -= 2 return total #Checks the number d if it falls into one of the four categories def prefixMatched(card_number, d): if(int(d) != 4 and int(d) != 5 and int(d) != 6 and int(d) != 37): return False else: return True #returns the size of the card number def getSize(card_number): return len(card_number) #Returns the type of card it is def getTypeCard(num): num = int(num) if(num == 4): return "Your card type is Visa" elif(num == 5): return "Your card type is MasterCard" elif(num == 6): return "Your card type is Discover" else: return "Your card type is American Express" #gets the second number if the card starts with a 3 def getPrefix(card_number): if card_number[0] == "3": return card_number[:2] else: return card_number[0] main()
true
dd7b7315ee7d3cfd75af1a924c0fa5f2d0ab731d
syeutyu/Day_Python
/01_Type/String.py
1,380
4.125
4
# 문자열 문자, 단어 등으로 구성된 문자들의 집합을 나타냅니다. # 파이썬에는 4개의 문자열 표현 방법이 존재합니다. a = "Hello Wolrd" #1 a = 'Hello Python' #2 a = """Python Hello""" #3 a = '''Python String''' #4 # 1. 문자열에 작은 따옴표를 포함시킬경우를 위해 제작 # Python's very good 을문자열로 하기위해서는? a = "Python's very good" # 2. 위와 같이 문자열에 큰 따옴표를 표함하기위해서 제작되었다 # I want Study "Python" => a = 'I want Study "Python"' # 3. 파이썬에서 줄바꿈을 위해서는 \n을 삽입하여 처리한다 # 이러한 불편함을 줄이기위해 3,4번을 사용하는데 # multiLine = ''' # Is very # Simple! ''' # 문자열 처리방법 one = 'this' two = 'is first' print(one + two) # this is first # 일반적인 + 수식을 이용하여 처리하는 문자열 더하기 one = "test" print(one * 2) # testtest # 문자열을 곱하면 파이썬은 곱한수만큼의 문자열을 반복한다 one = "I want Study Python..." print(one[3]) # a # 문자열 슬라이싱을 배열이 아니더라도 문자를 얻을 수 있다. print(one[0:5]) # I want # 문자열 슬라이싱을 [시작번호 : 끝 번호]와 [: 끝번호]로 문자를 얻을 수 있다. # 관련 함수 # count 문자 개수 세기 # count('문자') 문자가 나온 수 출력
false
7ba0531979d8aed9f9af85d74a83cd2b5120426f
PythonTriCities/file_parse
/four.py
637
4.3125
4
#!/usr/bin/env python3 ''' Open a file, count the number of words in that file using a space as a delimeter between character groups. ''' file_name = 'input-files/one.txt' num_lines = 0 num_words = 0 words = [] with open(file_name, 'r') as f: for line in f: print(f'A line looks like this: \n{line}') split_line = line.split() print(f'A split line looks like this: \n{split_line}') length = len(split_line) print(f'The length of the split line is: \n{length}') words.append(length) print(f'Words now looks like this: \n{words}') print(f'Number of words: \n{sum(words)}')
true
d2fd477b8c9df119bccb17f80aceda00c61cd82d
Sai-Sumanth-D/MyProjects
/GuessNumber.py
877
4.15625
4
# first importing random from lib import random as r # to set a random number range num = r.randrange(100) # no of chances for the player to guess the number guess_attempts = 5 # setting the conditions while guess_attempts >= 0: player_guess = int(input('Enter your guess : ')) # for checking the players guess = the actual number def check(x): if player_guess == x: print('You Won!!') elif player_guess > x: print('You are a bit on the higher side of the number, try lower!') else: print('Your guess is a bit on the lower side, try higher!') if guess_attempts > 1: check(num) elif guess_attempts == 1: check(num) print('This is your last chance, try making most of it.') else: print('You Lost') guess_attempts -= 1
true
dbef91a7ddfd4100180f9208c3880d9311e2c94c
Arlisha2019/HelloPython
/hello.py
1,319
4.34375
4
#snake case = first_number #camel case =firstNumber print("Hello") #input function ALWAYS returns a String data type #a = 10 # integer #b = "hello" # String #c = 10.45 # float #d = True # boolean #convert the input from string to int #first_number = float(input("Enter first number: ")) #second_number = float(input("Enter second number: ")) #third_number = float(input("Enter third number: ")) #number = int("45") #first_number_as_int = int("45") #second_number_as_int = int("70") #some_result = first_number_as_int + second_number_as_int #result = first_number + second_number + third_number #result = int(first_number) + int(second_number) #print(result) #name = input("Enter your name: ") #print(name) #name = "John" #age = 20 #version = 3.35 # Print will print the value of name variable to tthe screen #print(name) #name = "Mary" #print(name) #string concatcentration first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") city = input("Enter city: ") state = input("Enter State: ") zip_code = input("Enter Zip Code: ") message = "My name is {0},{1} and I live in {2}, {3}, {4}".format(first_name,last_name,city,state,zip_code) #message = "My name is " + first_name + ", " + last_name + ", " + " and I live in " + city + ", " + state + " " + zip_code print(message)
true
ac42e69bac982862edcbed8567653688ee07f186
GaganDureja/Algorithm-practice
/Vending Machine.py
1,686
4.25
4
# Link: https://edabit.com/challenge/dKLJ4uvssAJwRDtCo # Your task is to create a function that simulates a vending machine. # Given an amount of money (in cents ¢ to make it simpler) and a product_number, #the vending machine should output the correct product name and give back the correct amount of change. # The coins used for the change are the following: [500, 200, 100, 50, 20, 10] # The return value is a dictionary with 2 properties: # product: the product name that the user selected. # change: an array of coins (can be empty, must be sorted in descending order). def vending_machine(products, money, product_number): if product_number not in range(1,10): return 'Enter a valid product number' if money < products[product_number-1]['price']: return 'Not enough money for this product' lst = [500,200,100,50,20,10] count = 0 money-= products[product_number-1]['price'] change = [] while money!=0: if money-lst[count]>=0: money-=lst[count] change.append(lst[count]) else: count+=1 return {'product':products[product_number-1]['name'], 'change': change} # Products available products = [ { 'number': 1, 'price': 100, 'name': 'Orange juice' }, { 'number': 2, 'price': 200, 'name': 'Soda' }, { 'number': 3, 'price': 150, 'name': 'Chocolate snack' }, { 'number': 4, 'price': 250, 'name': 'Cookies' }, { 'number': 5, 'price': 180, 'name': 'Gummy bears' }, { 'number': 6, 'price': 500, 'name': 'Condoms' }, { 'number': 7, 'price': 120, 'name': 'Crackers' }, { 'number': 8, 'price': 220, 'name': 'Potato chips' }, { 'number': 9, 'price': 80, 'name': 'Small snack' } ] print(vending_machine(products, 500, 8))
true
47f8c6b8f6c8b01f0bc66d998fdd4c039bf91572
Tallequalle/Code_wars
/Task15.py
728
4.125
4
#A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant). #Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation. import string def is_pangram(s): s = s.lower() alphabet = ['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'] for i in alphabet: if i in s: continue else: return False return True pangram = "The quick, Brown fox jumps over the lazy dog!" is_pangram(pangram)
true
091718f2cf95ce96ff8d3aa2704068d25e650121
wsargeant/aoc2020
/day_1.py
1,383
4.34375
4
def read_integers(filename): """ Returns list of numbers from file containing list of numbers separated by new lines """ infile = open(filename, "r") number_list = [] while True: num = infile.readline() if len(num) == 0: break if "\n" in num: num = num[:-1] number_list.append(int(num)) return(number_list) def sum_2020(filename): """Returns two numbers from number list in filename which sum to 2020 and their product """ number_list = read_integers(filename) target = 2020 for num1 in number_list: num2 = target - num1 if num2 in number_list and num2 != num1: break return num1, num2, num1*num2 def sum_2020_by_3(filename): """Returns three numbers from number list in filename which sum to 2020 and their product """ number_list = read_integers(filename) #reversed_number_list = number_list.copy() #reversed_number_list.reverse() target = 2020 for i in range(len(number_list)): num1 = number_list[i] for j in range(i,len(number_list)): num2 = number_list[j] num3 = target - num1 - num2 if num3 >= 0 and num3 in number_list: return num1, num2, num3, num1*num2*num3 return False print(sum_2020("day_1.txt")) print(sum_2020_by_3("day_1.txt"))
true
08e800c3cdcbfaa6f37a0aa98863a39d8260242c
AsiakN/flexi-Learn
/sets.py
1,880
4.34375
4
# A set is an unordered collection with no duplicates # Basic use of sets include membership testing and eliminating duplicates in lists # Sets can also implement mathematical operations like union, intersection etc # You can create a set using set() or curly braces. You can only create an empty set using the set() method # Another type of set exists called frozenset. Frozenset is immutable but set is mutable basket = {'Apple', 'Banana', 'Avocado', 'pineapple', 'Apple', 'Orange'} print(sorted(basket)) a = set('abracadabra') b = set('alacazam') print(a.intersection(b)) print(a | b) # The " | " operator means or. It sums elements in both sets. Union operation print(a & b) # The " &" operator means and . It finds the elements in both a and b. Intersection operation print(a ^ b) # The " ^ " operator means not. Finds the elements in one set but not in the other set. Symmetric difference print(a.isdisjoint(b)) print(b.issubset(a)) # SET COMPREHENSIONS s = {x for x in 'abracadabra' if x not in 'abc'} print(s) # METHODS IN SETS # 1. UNION #SYNTAX # setA.union(setB) # 2. INTERSECTION # SYNTAX # setA.intersection(setB) # 3. DIFFERENCE # SYNTAX # setA.difference(setB) # 4. SYMMETRIC DIFFERENCE # SYNTAX # setA.symmetric_difference(SetB) # 5. DISJOINT # SYNTAX # setA.isdisjoint(setB) # Returns true or false value # 6. SUBSET # SYNTAX # setA.issubset(setB) # Returns true or false value # 7. SUPERSET # SYNTAX # setA.issuperset(setB) # Returns true or false value # 8. PROPER SUBSET/SUPERSET # MODIFYING SETS # 1. set.add(element) # 2. set.remove(element) # 3. Set.discard(element) # 4. set.pop() # 5. set.clear() numbers = { 24, 67, 89,90, 78,78, 24 } print(sum(numbers)) print(len(numbers))
true
fe14c4912950ed8ca6bbb77eabc57ce776a1a095
Barleyfield/Language_Practice
/Python/Others/Pr181121/HW09_Substring.py
1,089
4.15625
4
# -*- coding: utf-8 -*- """ 142694 윤이삭 Substring 함수 만들기 <실행예> Enter the first string: asdf Enter the second string: vfrtgasdfnhy asdf is a substring of vfrtgasdfnhy Enter the first string: 깊은바다 Enter the second string: 파란하늘은 깊은바다와 같다 깊은바다 is a substring of 파란하늘은 깊은바다와 같다 """ def Substring(subst,st) : if(st.find(subst) == -1) : print("%s에 해당하는 문자열이 없습니다." % subst) else : start_loc = st.find(subst) # Start Location. 부분문자열의 시작 위치 print("%s is a substring of %s" % (subst,st)) # 0번째부터 계산하기 때문에 몇 번째인가를 반환하려면 1 더해주기 print("부분문자열의 위치는 %d번째부터 %d번째까지입니다." % ( (start_loc+1), (start_loc+1+len(subst)) )) if __name__ == "__main__" : substring = input("Enter the first string : ") string = input("Enter the second string : ") Substring(substring,string)
false
330e62b9b6ff037ff06d0e9a1dc6aa3a930095f0
Alfred-Mountfield/CodingChallenges
/scripts/buy_and_sell_stocks.py
881
4.15625
4
""" Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. """ def max_profit(nums: list): if not nums: return 0 profit = price = 0 for num in reversed(nums): price = max(num, price) profit = max(profit, price - num) return profit if __name__ == "__main__": print(f"[7, 1, 5, 3, 6, 4]: {max_profit([7, 1, 5, 3, 6, 4])}") print(f"[7, 6, 4, 3, 1]: {max_profit([7, 6, 4, 3, 1])}") print(f"[7, 1, 5, 3, 6, 4]: {max_profit([7, 1, 5, 3, 6, 4])}") print(f"[7, 5, 3, 2, 1]: {max_profit([7, 5, 3, 2, 1])}") print(f"[7, 4, 10, 2, 6, 11]: {max_profit([7, 4, 10, 2, 6, 11])}")
true
dc2da5e06755ee1ef83d933b77b4ed1ffa1c6d71
SaikumarS2611/Python-3.9.0
/Packages/Patterns_Packages/Symbols/Equilateral_Triangle.py
479
4.125
4
def for_equilateral_triangle(): """Shape of 'Equilateral Triangle' using Python for loop""" for row in range(12): if row%2!=0: print(' '*(12-row), '* '*row) def while_equilateral_triangle(): """Shape of 'Equilateral Triangle' using Python while loop""" row = 0 while row<12: if row%2!=0: print(' '*(12-row), '* '*row) row += 1
false
97179eb2d9dcaf051c37211d40937166869a0c83
SaikumarS2611/Python-3.9.0
/Packages/Patterns_Packages/Alphabets/Upper_Case_alphabets/D.py
970
4.21875
4
# using for loop def for_D(): """ Upper case Alphabet letter 'D' pattern using Python for loop""" for row in range(6): for col in range(5): if col==0 or row in (0,5) and col<4 or col==4 and row>0 and row<5: print('*', end = ' ') else: print(' ', end = ' ') print() # using while loop def while_D(): """ Upper case Alphabet letter 'D' pattern using Python while loop""" row = 0 while row<6: col = 0 while col<5: if col==0 or row in (0,5) and col<4 or col==4 and row>0 and row<5: print('*', end = ' ') else: print(' ', end = ' ') col +=1 print() row +=1
false
ae17927ae7d2911b505dca233df10577c39efd6e
SaikumarS2611/Python-3.9.0
/Packages/Patterns_Packages/Alphabets/Lower_Case_alphabets/z.py
869
4.125
4
def for_z(): """ Lower case Alphabet letter 'z' pattern using Python for loop""" for row in range(4): for col in range(4): if row==0 or row==3 or row+col==3: print('*', end = ' ') else: print(' ', end = ' ') print() def while_z(): """ Lower case Alphabet letter 'z' pattern using Python while loop""" row = 0 while row<4: col = 0 while col<4: if row==0 or row==3 or row+col==3: print('*', end = ' ') else: print(' ', end = ' ') col += 1 print() row += 1
false
e77e9c67faf6319143afd737cee920a98496cce0
SaikumarS2611/Python-3.9.0
/Packages/Patterns_Packages/Symbols/Reverse_triangle.py
444
4.375
4
def for_reverse_triange(): """Shape of 'Reverse Triangle' using Python for loop """ for row in range(6,0,-1): print(' '*(6-row), '* '*row) def while_reverse_triange(): """Shape of 'Reverse Triangle' using Python while loop """ row = 6 while row>0: print(' '*(6-row), '* '*row) row -= 1
false
35e9d5de6afa12398a59af95f454097f3231d4ad
SaikumarS2611/Python-3.9.0
/Packages/Patterns_Packages/Symbols/Rectangle.py
926
4.34375
4
def for_rectangle(): """Shape of 'Rectangle' using Python for loop """ for row in range(6): for col in range(8): if row==0 or col==0 or row==5 or col==7: print('*', end = ' ') else: print(' ', end = ' ') print() def while_rectangle(): """Shape of 'Rectangle' using Python while loop """ row = 0 while row<6: col = 0 while col<8: if row==0 or col==0 or row==5 or col==7: print('*', end = ' ') else: print(' ', end = ' ') col += 1 print() row += 1
true
b7cf0ad56f664cab16423ec3baeaea62603d29bb
claraqqqq/l_e_e_t
/102_binary_tree_level_order_traversal.py
1,178
4.21875
4
# Binary Tree Level Order Traversal # Given a binary tree, return the level order traversal of its # nodes' values. (ie, from left to right, level by level). # For example: # Given binary tree {3,9,20,#,#,15,7}, # 3 # / \ # 9 20 # / \ # 15 7 # return its level order traversal as: # [ # [3], # [9,20], # [15,7] # ] # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def levelOrder(self, root): if root is None: return [] curNodes = [root] result = [] while curNodes: curNodeVals = [] nextNodes = [] for node in curNodes: curNodeVals.append(node.val) if node.left: nextNodes.append(node.left) if node.right: nextNodes.append(node.right) result.append(curNodeVals) curNodes = nextNodes return result
true
cdd09dafb35bc0077d004e332ab48436810224a7
claraqqqq/l_e_e_t
/150_evaluate_reverse_polish_notation.py
1,079
4.28125
4
# Evaluate Reverse Polish Notation # Evaluate the value of an arithmetic expression in Reverse Polish Notation. # Valid operators are +, -, *, /. Each operand may be an integer or another expression. # Some examples: # # ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 # ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 class Solution: # @param tokens, a list of string # @return an integer def evalRPN(self, tokens): stack = [] for element in tokens: if element not in "+-*/": stack.append(element) else: num2 = int(stack.pop()) num1 = int(stack.pop()) if element == "+": stack.append(str(num1 + num2)) elif element == "-": stack.append(str(num1 - num2)) elif element == "*": stack.append(str(num1 * num2)) elif element == "/": if num1 * num2 > 0: stack.append(str(num1 / num2)) else: stack.append(str(-(abs(num1) / abs(num2)))) return int(stack[0])
true
045ad42fadd7542f7932345050395615896b6543
StevenHowlett/pracs
/prac5/hex_colours.py
468
4.375
4
COLOUR_TO_HEX = {'aliceblue': '#fof8ff', 'antiquewhite': '#faebd7', 'aquamarine': '#7fffd4', 'azure': '#f0ffff', 'beige': '#f5f5dc', 'bisque': 'ffe4c4', 'black': '#000000', 'blue': '#0000ff', 'blueviolet': '8a2be2'} colour = input("Enter colour: ").lower() while colour != "": if colour in COLOUR_TO_HEX: print(colour, "is", COLOUR_TO_HEX[colour]) else: print("colour not listed") colour = input("Enter colour: ").lower()
false
ec541b14059808cf538ba11ffa9645488d70f4f4
BuseMelekOLGAC/GlobalAIHubPythonHomework
/HANGMAN.py
1,602
4.1875
4
print("Please enter your name:") x=input() print("Hello,"+x) import random words = ["corona","lung","pain","hospital","medicine","doctor","ambulance","nurse","intubation"] word = random.choice(words) NumberOfPrediction = 10 harfler = [] x = len(word) z = list('_' * x) print(' '.join(z), end='\n') while NumberOfPrediction > 0: y = input("Guess a letter:") if y in words: print("Please don't tell the letter that you've guessed before!") continue elif len(y) > 1: print("Please just enter one letter!!!") continue elif y not in word: NumberOfPrediction -= 1 print("Misestimation.You have {} prediction justification last!".format(NumberOfPrediction)) else: for i in range(len(word)): if y == word[i]: print("Correct Guess!") z[i] = y words.append(y) print(' '.join(z), end='\n') answer = input("Do you still want to guesss all of the word? ['yes' or 'no'] : ") if answer == "yes": guess = input("You can guess all of the word then : ") if guess == word: print("Congrats!You know right!!!") break else: NumberOfPrediction -= 1 print("Misestimation! You have {} prediction justification last".format(NumberOfPrediction)) if NumberOfPrediction== 0: print("Oh no,you don't have any prediction justification.You lost the game.Your hangman is hanged hahah!") break
true