blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
4e4cd16fac3bd2d47e60c49bbae377358ac88187
danieltran67/All-In-One-Agenda
/venv/Lib/site-packages/somepackage/module1.py
647
3.8125
4
from .module2 import another_function def some_function(): """ Describe here what this function does, its input parameters, and what it returns. """ t = _internal_function('hey ho -') return another_function(t, t) def test_some_function(): assert some_function() == 'HEY HO -HEY HO -' # the underscore signals that this function is not to be used outside def _internal_function(parameter): """ Describe here what this function does, its input parameters, and what it returns. """ return parameter.upper() def test_internal_function(): assert _internal_function('shouting') == 'SHOUTING'
6baf41fdd2caa806dc54bf4500f75657ef2e3f97
ktkrista/SVM
/SVM-p8.py
2,457
3.5
4
from numpy.random import seed from sklearn import svm import numpy as np import sklearn.preprocessing as preprocessing import sklearn.model_selection as selection # Set the random seed to 1 seed(1) # ==================================== # STEP 1: read the training and testing data. # specify path to training data and testing data train_x_location = "x_train8.csv" train_y_location = "y_train8.csv" test_x_location = "x_test.csv" test_y_location = "y_test.csv" print("Reading training data") x_train = np.loadtxt(train_x_location, dtype="uint8", delimiter=",") y_train = np.loadtxt(train_y_location, dtype="uint8", delimiter=",") m, n = x_train.shape # m training examples, each with n features m_labels, = y_train.shape # m2 examples, each with k labels l_min = y_train.min() assert m_labels == m, "x_train and y_train should have same length." assert l_min == 0, "each label should be in the range 0 - k-1." k = y_train.max()+1 print(m, "examples,", n, "features,", k, "categiries.") print("Reading testing data") x_test = np.loadtxt(test_x_location, dtype="uint8", delimiter=",") y_test = np.loadtxt(test_y_location, dtype="uint8", delimiter=",") m_test, n_test = x_test.shape m_test_labels, = y_test.shape l_min = y_train.min() assert m_test_labels == m_test, "x_test and y_test should have same length." assert n_test == n, "train and x_test should have same number of features." print(m_test, "test examples.") # ==================================== # STEP 2: pre processing # Please modify the code in this step. print("Pre processing data") # The same pre processing must be applied to both training and testing data scaler = preprocessing.StandardScaler() x_train = scaler.fit_transform(x_train) x_test = scaler.transform(x_test) # ==================================== # STEP 3: train model. print("---train") params = {'kernel': ['poly'], 'C': [4**i for i in range(-6, 6)], 'degree': [0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5], 'gamma': [4**i for i in range(-6, 6)]} print('Training data and choosing the best parameters...') selector = selection.GridSearchCV(svm.SVC(), params, n_jobs=-1) selector.fit(x_train, y_train) model = svm.SVC(**selector.best_params_, coef0=1) model.fit(x_train, y_train) # ==================================== # STEP3: evaluate model print("---evaluate") print("number of support vectors:", model.n_support_) acc = model.score(x_test, y_test) print("acc:", acc)
11ff68b22418e0eac9e639d5bf2fdb0610cd6345
zhongpei0820/LeetCode-Solution
/Python/100-199/190_Reverse_Bits.py
851
3.90625
4
#Reverse bits of a given 32 bits unsigned integer. # #For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). # # #Follow up: #If this function is called many times, how would you optimize it? # # #Related problem: Reverse Integer # #Credits:Special thanks to @ts for adding this problem and creating all test cases. class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): n = (n >> 16) | (n << 16) n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8) n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4) n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2) n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1) return n
823a128d1bc8806d2be2466d9862d1d26f18d233
zhongpei0820/LeetCode-Solution
/Python/200-299/266_Palindrome_Permutation.py
413
3.796875
4
#Given a string, determine if a permutation of the string could form a palindrome. # #For example, #"code" -> False, "aab" -> True, "carerac" -> True. # from collections import Counter class Solution(object): def canPermutePalindrome(self, s): """ :type s: str :rtype: bool """ return len([item for item in Counter(s).items() if item[1] % 2]) <= 1
76560df649ae4f23f1c9a57c444dabc20cb10a17
zhongpei0820/LeetCode-Solution
/Python/400-499/468_Validate_IP_Address.py
2,941
4.09375
4
# #Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither. # # # #IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1; # # # #Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid. # # # #IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases). # # # # #However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address. # # # #Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid. # # # #Note: #You may assume there is no extra space or special characters in the input string. # # #Example 1: # #Input: "172.16.254.1" # #Output: "IPv4" # #Explanation: This is a valid IPv4 address, return "IPv4". # # # # #Example 2: # #Input: "2001:0db8:85a3:0:0:8A2E:0370:7334" # #Output: "IPv6" # #Explanation: This is a valid IPv6 address, return "IPv6". # # # #Example 3: # #Input: "256.256.256.256" # #Output: "Neither" # #Explanation: This is neither a IPv4 address nor a IPv6 address. # # class Solution(object): def validIPAddress(self, IP): """ :type IP: str :rtype: str """ if '.' in IP: return self.validIPv4(IP) if ':' in IP: return self.validIPv6(IP) return "Neither" def validIPv4(self, IP): strings = IP.split('.') if len(strings) != 4: return "Neither" for string in strings: try: num = int(string) if num < 0 or num > 255 or str(num) != string: return "Neither" except ValueError as e: return "Neither" return "IPv4" def validIPv6(self, IP): strings = IP.split(':') if len(strings) != 8: return "Neither" for string in strings: if len(string) > 4 or '+' in string or '-' in string: return "Neither" try: num = int(string, 16) if num < 0 or num >= 2 ** 16 : return "Neither" except ValueError as e: return "Neither" return "IPv6"
c763d2479b9a97ef88cf96264957e6371ad5054f
zhongpei0820/LeetCode-Solution
/Python/1-99/022_Generate_Parentheses.py
786
3.8125
4
# #Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. # # # #For example, given n = 3, a solution set is: # # #[ # "((()))", # "(()())", # "(())()", # "()(())", # "()()()" #] # class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ ret = [] self.backTracking(n,0,0,'',ret) return ret def backTracking(self,n,left,right,curr,ret): if left == right == n: ret.append(curr) return if left < n: self.backTracking(n,left + 1,right,curr + '(',ret) if right < left: self.backTracking(n,left,right + 1,curr + ')',ret)
1217052aafda56c9f9d22f53c580f739d733219a
zhongpei0820/LeetCode-Solution
/Python/300-399/301_Remove_Invalid_Parentheses.py
1,422
3.546875
4
# #Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. # #Note: The input string may contain letters other than the parentheses ( and ). # # # #Examples: # #"()())()" -> ["()()()", "(())()"] #"(a)())()" -> ["(a)()()", "(a())()"] #")(" -> [""] # # # #Credits:Special thanks to @hpplayer for adding this problem and creating all test cases. class Solution(object): def removeInvalidParentheses(self, s): """ :type s: str :rtype: List[str] """ hashset = set() hashset.add(s) stack = [] for i,ch in enumerate(s): if ch == '(' : stack.append((ch,i)) elif ch == ')' : if len(stack) == 0 : stack.append((ch,i)) elif stack[-1][0] == '(' : stack.pop() else : stack.append((ch,i)) while len(stack) != 0: curr = stack.pop() nextset = set() if curr[0] == '(': for s in hashset: for i in range(curr[1],len(s)): if s[i] == '(' : nextset.add(s[:i] + s[i + 1:]) elif curr[0] == ')': for s in hashset: for i in range(0,curr[1] + 1): if s[i] == ')' : nextset.add(s[:i] + s[i + 1:]) hashset = nextset return list(hashset)
a2c22202813e7a9681a0ae2bf91f92248f2fd365
zhongpei0820/LeetCode-Solution
/Python/1-99/031_Next_Permutation.py
1,385
3.890625
4
# #Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. # # #If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). # # #The replacement must be in-place, do not allocate extra memory. # # #Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. #1,2,3 &#8594; 1,3,2 #3,2,1 &#8594; 1,2,3 #1,1,5 &#8594; 1,5,1 # class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ k = -1 for i in range(len(nums) - 2,-1,-1): if nums[i] < nums[i + 1] : k = i break if k == -1: nums = self.reverse(0,len(nums) - 1,nums) return l = -1 for i in range(len(nums) - 1,k,-1): if nums[i] > nums[k]: l = i break nums[k],nums[l] = nums[l],nums[k] self.reverse(k+1,len(nums) - 1,nums) return def reverse(self,start,end,nums): while start < end: nums[start],nums[end] = nums[end],nums[start] start += 1 end -= 1
c21f12a10c30a740edf988560a441d37379c2940
zhongpei0820/LeetCode-Solution
/Python/1-99/054_Spiral_Matrix.py
1,610
3.84375
4
#Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. # # # #For example, #Given the following matrix: # # #[ # [ 1, 2, 3 ], # [ 4, 5, 6 ], # [ 7, 8, 9 ] #] # # #You should return [1,2,3,6,9,8,7,4,5]. # class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ n = len(matrix) if n == 0 : return matrix m = len(matrix[0]) ret = [] colStart,colEnd,rowStart,rowEnd = 0,m - 1,0,n - 1 while colStart < colEnd and rowStart < rowEnd: i,j = rowStart,colStart for j in range(colStart,colEnd): ret.append(matrix[i][j]) colStart += 1 j += 1 for i in range(rowStart,rowEnd): ret.append(matrix[i][j]) rowStart += 1 i += 1 for j in range(colEnd,colStart - 1,-1): ret.append(matrix[i][j]) colEnd -= 1 j -= 1 for i in range(rowEnd,rowStart - 1,-1): ret.append(matrix[i][j]) rowEnd -= 1 i += 1 if colStart == colEnd and rowStart == rowEnd:ret.append(matrix[colStart][rowStart]) elif colStart == colEnd: for i in range(rowStart,rowEnd + 1): ret.append(matrix[i][colEnd]) elif rowStart == rowEnd: for i in range(colStart,colEnd + 1): ret.append(matrix[rowStart][i]) return ret
964bcfdd68d4ce43ca924220fef16c8016b879cb
budkina/mipt_rosalind
/heap.py
1,080
3.71875
4
def repairHeap(H,i): heap=H largestChild = 0 if i >= len(H)//2: return # choose largest child element of i l = 2*i+1 r = 2*i+2 largestChild = l if (heap[l] >= heap[r]) else r if (heap[i] < heap[largestChild]): heap[i], heap[largestChild] = heap[largestChild], heap[i] repairHeap (heap, largestChild) def buildHeap(A): # alloc heap for array A len n n=len(A) array = A heapSize = 0 for i in range(n): if heapSize>=n: break heapSize = heapSize + 2**i array = array + [float('-inf')]*(heapSize - n) # the indexes of leave elements in heap: n//2...n # repair heap i = len(array)//2 while i>=0: repairHeap(array,i) i-=1 array = list(filter(lambda x: x!= float('-inf'), array)) return array f = open("rosalind_hea.txt", "r") n = f.readline() A_str = f.readline() f.close() heap=buildHeap(list(map(int, A_str.split()))) f = open("rosalind_hea_res.txt", "w") f.write( ' '.join(map(str, heap))) f.close()
b47123c353f795719dcc74aadb58b2f2ec251f98
ntrallosgeorgios/python_Add_remove_org
/getServerName.py
540
3.875
4
def getServerName(search, org): """ Take the name of server at the print it if exist """ # take the list of organisations and take every time one organisation for i in org: # If the seach name is equal with the first element of the organisation # list then return the website of the server if search == i[0]: new = "Server Address: " + i[1] + " \n" + "IP Address: " + i[2] return new # If we don't find the name it's return that string return "Not found"
4a395f599412816ebd9599004457bc5caa16d73c
toledompm/Matematica-Discreta
/programas_1_prova/interseccao.py
1,031
3.84375
4
#recebe um vetor e uma posicao, verifica se algum dos valores anteriores no vetor é igual o que esta na posicao indicada def repete(vet, pos): for i in range(0,pos): if vet[pos] == vet[i]: return True return False #recebe um valor e um vetor, verifica se o valor existe no vetor def existe(vet, val): for i in vet: if val == i: return True return False #leia os 2 conjuntos print("escreva os valores do conjunto A separados por um espaco(ex: '1 2 3 4')") conjuntoA = input().split(" ") print("escreva os valores do conjunto B separados por um espaco(ex: '1 2 3 4')") conjuntoB = input().split(" ") #define o vetor da interseccao interseccao = [] #para x = todo valor de A for x in range(len(conjuntoA)): #se nao repete if not repete(conjuntoA,x): #se existe no outro conjunto if existe(conjuntoB,conjuntoA[x]): #adiciona a interseccao interseccao.append(conjuntoA[x]) #escreva a interseccao print(";".join(interseccao))
c963bc56677e8542cf2e5057a93668938816f812
Javharbek-Yuldashev/game-find-word
/functions.py
1,857
4.0625
4
def get_word(): from random import choice from uzwords import words word = choice(words) while "-" in word or " " in word or "‘" in word or "’" in word: word = choice(words) return (word).upper() def display(user_letters, word): display_letter = "" for letter in word: if letter in user_letters.upper(): display_letter += letter else: display_letter += "-" return display_letter # user_letter = list(user_letters).upper() # word_letter = list(word).upper() # natija = [] # for letter in word_letter: # if letter in user_letter: # natija.append(letter) # else: # natija.append('-') # matn = ' '.join(map(str,natija)) # return matn def play(): savol = True while savol: word = get_word() word_letter = set(word) print(f"\nMen {len(word)} ta harfdan iborat so'z o'yladim. Topa olasizmi?") user_letters = '' while len(word_letter)>0: print(display(user_letters,word)) if len(user_letters)>0: print(f"Shu vaqtgacha kiritgan harflaringiz: {user_letters}") letter = input("Harf kiriting: ").upper() if letter in user_letters: print("Bu harfni avval kiritgansiz. Boshqa harf kiriting") continue elif letter in word: word_letter.remove(letter) print(f"{letter} harfi to'g'ri") else: print("Bunday harf yo'q") user_letters += letter print(f"Tabriklayman. Siz {word} so'zini {len(user_letters)} ta urinish bilan topdingiz!") savol = int(input("Yana o'ynashni xohlaysizmi?: Ha(1), Yo'q(0): ")) print("\nRahmat!")
db34081655237708a347a56c6bf73a40ec4301f6
GuilhermePeyflo/loja-python
/Sistema/Menu.py
20,909
3.578125
4
from datetime import datetime from Categoria import Categoria from Cliente import Cliente from Produto import Produto from Cartao import Cartao from Venda import Venda class Menu: """ Classe para representar a função do menu de interação com o usuário do sistema de Loja. """ def __init__(self): self.cartao_class = Cartao() self.categoria_class = Categoria() self.produto_class = Produto() self.cliente_class = Cliente() self.venda_class = Venda() self.carrinho = [] self.total = 0 """ cartao_class = Cartao() categoria_class = Categoria() produto_class = Produto() cliente_class = Cliente() venda_class = Venda() carrinho = [] total = 0 """ def run(self): while True: print("*" * 100) print("Menu Principal:\n") print("\t1) Nova Venda") print("\t2) Produtos") print("\t3) Consultas") print("\t4) Cadastro de Cliente") print("\t5) Sair\n") opcao_menu_principal = input("Selecione uma opção:\n") print("-" * 100) if opcao_menu_principal == "1": self.carrinho.clear() while True: cpf_user = input("Digite seu CPF (somente números): ") if len(cpf_user) == 11: break else: print("CPF inválido!") if self.cliente_class.verificar_cliente(cpf_user): for i in self.cliente_class.listar_clientes(): if i['cpf'] == cpf_user: print(f"Bem Vindo {i['nome']}!") break self.menu_vendas() else: novo_cadastro = input("CPF não cadastrado, deseja cadastrar? \n 1) Sim\n 2) Não\n") if novo_cadastro == '1': self.menu_cadastrar_cliente() self.menu_vendas() elif novo_cadastro == "2": self.menu_vendas() else: print("Opção inválida!") elif opcao_menu_principal == "2": self.menu_produtos() elif opcao_menu_principal == "3": self.menu_consultas() elif opcao_menu_principal == "4": self.menu_cadastrar_cliente() elif opcao_menu_principal == "5": print("Saindo do sistema...") break def menu_vendas(self): while True: print("-" * 100) print("Menu venda:\n") print("1) Adicionar Produto") print("2) Deletar Produto") print("3) Receber Pagamento") print("4) Cancelar compra") opcao_menu_venda = input("Selecione uma opção:\n") if opcao_menu_venda == "1": while True: print("Categorias cadastradas:\n") lista_categorias = self.categoria_class.listar_categorias() for cat in range(0, len(lista_categorias)): print(f"{cat + 1}) {lista_categorias[cat]}") opcao_categoria = input("Os produtos de qual categoria deseja ver?\n") try: selec_categoria = lista_categorias[int(opcao_categoria) - 1] break except: print("Opção inválida!") produtos_categoria = self.produto_class.pesquisar_produtos(selec_categoria) if not produtos_categoria: print("Nenhum produto encontrado!") else: print("ID |\tNome |\tPreço") for prod in range(len(produtos_categoria)): print(f"{prod + 1}) |\t{produtos_categoria[prod]['nome']} |\t{produtos_categoria[prod]['preco']}") add_prod = input("Selecione o produto para adicionar ao carrinho:\n") try: self.carrinho.append(produtos_categoria[int(add_prod) - 1]) print("Produtos no carrinho:") print("ID |\tNome |\tPreço |\tCategoria") for prod in range(len(self.carrinho)): print( f"{prod + 1}) |\t{self.carrinho[prod]['nome']} |\t{self.carrinho[prod]['preco']} " f"|\t{self.carrinho[prod]['categoria']}") except: print("Este item não está na lista!") pass elif opcao_menu_venda == "2": print("Produtos no carrinho:") print("ID |\tNome |\tPreço |\tCategoria") for prod in range(len(self.carrinho)): print( f"{prod + 1}) |\t{self.carrinho[prod]['nome']} |\t{self.carrinho[prod]['preco']} " f"|\t{self.carrinho[prod]['categoria']}") del_produto = input("Qual produto deseja excluir?\n") try: self.carrinho.pop(int(del_produto) - 1) print("Item excluido!") except: print("Item não encontrado!") pass elif opcao_menu_venda == "3": print("Realizar Pagamento:") total = 0 for i in self.carrinho: total += float(i["preco"]) print(f"O preço total da compra é R${total:0.2f}") if total == 0: print("O carrinho está vazio! Adicione produtos antes de finalizar a compra!") else: forma_pagamento = input("Selecione a forma de pagamento:\n 1) Dinheiro\n 2) Cartão\n") if forma_pagamento == "1": pagar = input("Insira quantos reais você usará para pagar a compra?\n") try: if float(pagar) >= total: troco = float(pagar) - total print(f"Seu troco foi de R${troco}") venda = {"data_hora": str(datetime.today()), "itens_venda": self.carrinho, "total_venda": total} if self.venda_class.cadastrar_venda(venda): print("Venda finalizada!") else: print("Ocorreu um erro ao cadastrar a venda!") break else: print("Valor insuficiente!") except: print("O valor digitado não é valido!") elif forma_pagamento == "2": numero_cartao = input("Informe o numero do cartão: ") senha_cartao = input("Informe a senha do cartão: ") resposta = self.cartao_class.verificar_cartao(numero_cartao, senha_cartao, total) if resposta == 1: print("Saldo insuficiente!") elif resposta == 2: print("Validade do cartão expirada!") elif resposta == 3: print("Senha incorreta!") elif resposta == 4: print("Número de cartão inválido!") else: print("Compra realizado com sucesso!") venda = {"data_hora": str(datetime.today()), "itens_venda": self.carrinho, "total_venda": total} self.venda_class.cadastrar_venda(venda) print("Venda finalizada!") break else: print("Forma de pagamento Inválida!") elif opcao_menu_venda == "4": print("Compra cancelada!") break else: print("Opção inválida") def menu_produtos(self): """ """ while True: print("-" * 100) print("Menu produtos:\n") print("\t1) Cadastrar novo produto") print("\t2) Cadastrar nova categoria") print("\t3) Alterar Produto") print("\t4) Listar produtos") print("\t5) Listar categorias") print("\t6) Deletar produto") print("\t7) Deletar categoria") print("\t8) Voltar ao Menu Principal") opcao_menu_produtos = input("Selecione uma opção:\n") if opcao_menu_produtos == "1": categorias = self.categoria_class.listar_categorias() if not categorias: print("Cadastre uma categoria antes de cadastrar um produto!\n") else: while True: codigo_produto = input("Qual o codigo do produto: ") if len(codigo_produto) == 0: print("Código inválido!") elif self.produto_class.verificar_produto(codigo_produto): print("Código já cadastrado!") break else: while True: nome_produto = input("Qual o nome do produto: ") if len(nome_produto) > 0 and not nome_produto.isnumeric(): break else: print("Nome inválido!") while True: preco_produto = input("Qual o preço do produto: ") try: if float(preco_produto) > 0: break else: print("Preço inválido!") except: print("Preço inválido!") while True: print("Categorias cadastradas:") for i in range(0, len(categorias)): print(f"{i + 1}) {categorias[i]}") try: categoria_produto = categorias[int(input("Escolha a categoria do " "produto a ser cadastrado: ")) - 1] break except: print("Opção inválida!") novo_produto = {"codigo": codigo_produto, "nome": nome_produto,"preco": preco_produto, "categoria": categoria_produto} if self.produto_class.cadastrar_produto(novo_produto): print("Produto cadastrado com sucesso!") else: print("Erro ao cadastrar o novo produto!") break elif opcao_menu_produtos == "2": print("-" * 100) nome_categoria = input("Digite o nome da categoria que deseja cadastrar: ") if self.categoria_class.cadastrar_categoria(nome_categoria): print("Categoria cadastrada com sucesso!") else: print("Erro ao cadastrar nova categoria!") elif opcao_menu_produtos == "3": print("-" * 100) produtos = self.produto_class.listar_produtos() print("Produtos cadastrados:") if not produtos: print("Nenhum produto cadastrado!") else: print("Codigo |\t Nome |\tPreço |\t Categoria") for p in produtos: print(f"{p['codigo']} |\t{p['nome']} |\t{p['preco']} |\t{p['categoria']}") print("-" * 100) while True: codigo_produto_alterado = input("Qual o codigo do produto?\n") if self.produto_class.verificar_produto(codigo_produto_alterado): break else: print("Código não encontrado!") while True: nome_produto_alterado = input("Qual o nome do produto?\n") if nome_produto_alterado == "" and not nome_produto_alterado.isnumeric(): print("Nome inválido!") else: break while True: preco_produto_alterado = input("Qual o preço do produto: ") try: if float(preco_produto_alterado) > 0: break else: print("Preço inválido!") except: print("Preço inválido!") while True: print("Categorias cadastradas:") categorias = self.categoria_class.listar_categorias() for i in range(0, len(categorias)): print(f"{i + 1}) {categorias[i]}") try: categoria_produto_alterado = categorias[ int(input("Escolha a nova categoria do produto: ")) - 1] break except: print("Opção inválida!") produto_alterado = {"codigo": codigo_produto_alterado, "nome": nome_produto_alterado, "preco": preco_produto_alterado, "categoria": categoria_produto_alterado} if self.produto_class.alterar_produto(produto_alterado): print("Produto alterado com sucesso!") else: print("Erro ao alterar o produto!") elif opcao_menu_produtos == "4": print("-" * 100) print("Produtos cadastrados:\n") lista_produtos = self.produto_class.listar_produtos() if not lista_produtos: print("Nenhum produto cadastrado!") else: print("Codigo |\t Nome |\tPreço |\t Categoria") for prod in lista_produtos: print(f"{prod['codigo']} |\t{prod['nome']} |\t{prod['preco']} |\t{prod['categoria']}") elif opcao_menu_produtos == "5": print("-" * 100) print("Categorias cadastradas:\n") lista_categorias = self.categoria_class.listar_categorias() if not lista_categorias: print("Nenhuma categoria cadastrada!") else: print("Nome:") for cat in lista_categorias: print(f"{cat}") elif opcao_menu_produtos == "6": print("-" * 100) print("Produtos cadastrados:\n") lista_produtos = self.produto_class.listar_produtos() if not lista_produtos: print("Nenhum produto cadastrado!") else: print("Codigo |\t Nome |\tPreço |\t Categoria") for prod in lista_produtos: print(f"{prod['codigo']} |\t{prod['nome']} |\t{prod['preco']} |\t{prod['categoria']}") print("-" * 100) codigo_produto = input("Informe o codigo do produto que deseja deletar:\n") if self.produto_class.excluir_produto(codigo_produto): print("Produto deletado com sucesso!") else: print("Produto não encontrado!") elif opcao_menu_produtos == "7": print("-" * 100) print("Categorias cadastradas:\n") lista_categorias = self.categoria_class.listar_categorias() if not lista_categorias: print("Nenhuma categoria cadastrada!") else: for cat in range(len(lista_categorias)): print(f"{cat + 1}) {lista_categorias[cat]}") try: num_categoria = int(input("Digite o número da categoria que deseja excluir: ")) if self.categoria_class.excluir_categoria(lista_categorias[int(num_categoria) - 1]): print("Categoria deletada com sucesso") else: print("A categoria None não pode ser deletada") except: print("Número inválido!") elif opcao_menu_produtos == "8": print("Voltando ao menu principal...") break else: print("Opção inválida") def menu_consultas(self): """ """ while True: print("-" * 100) print("Menu consultas:\n") print("\t1) Listar Clientes cadastrados") print("\t2) Histórico de Vendas") print("\t3) Voltar ao menu principal") opcao_menu_consultas = input("Selecione uma opção:\n") if opcao_menu_consultas == "1": clientes = self.cliente_class.listar_clientes() print(f"Nome\t\tCPF\t\tIdade") for cliente in clientes: print(f"{cliente['nome']}\t\t{cliente['cpf']}\t\t{cliente['idade']}") print("\n") elif opcao_menu_consultas == "2": vendas = self.venda_class.listar_vendas() if not vendas: print("O histórico de vendas está vazio!") else: print("Vendas efetuadas:") print("." * 100) for v in vendas: print(f"\tData e hora: {v['data_hora']}") print(f"\tValor Total: {v['total_venda']}") print("\tItens da Venda:") for i in v['itens_venda']: print( f"\t\tCodigo: {i['codigo']} \tNome: {i['nome']} \tPreço: {i['preco']} \tCategoria: {i['categoria']}") print("." * 100) elif opcao_menu_consultas == "3": print("Voltando ao menu principal...") break else: print("Opção inválida") def menu_cadastrar_cliente(self): """ Método para interação com o usuário quando for necessário cadastrar um novo cliente. Realiza validações de entrada de dados. """ print("-" * 100) print("Cadastrando cliente...") while True: cpf_cliente = input("Digite seu CPF (somente números): ") if len(cpf_cliente) == 11: break else: print("CPF inválido!") while True: nome_cliente = input("Digite seu nome: ") if len(nome_cliente) > 0: break else: print("Nome é um campo obrigatório!") while True: idade_cliente = input("Digite sua idade: ") try: if int(idade_cliente) > 0: break else: print("Valor inválido!") except: print("Valor inválido!") novo_cliente = {"nome": nome_cliente, "cpf": cpf_cliente, "idade": idade_cliente} if self.cliente_class.cadastrar_cliente(novo_cliente): print(f"Bem Vindo {novo_cliente['nome']}!") else: print("Ocorreu um erro ao cadastrar o novo cliente!") if __name__ == "__main__": print("Iniciando sistema...") Menu().run()
ffb500f887d8bcbcf33ce505ead46306f72e262e
anuragknp/algorithms
/float_str.py
285
4.1875
4
def convert_to_binary(n): bin = '' while n > 1: bin = str(n%2) + bin n = n/2 bin = str(n) + bin return bin def convert_float_to_binary(n): bin = '' while n != 0: n = n*2 bin += str(int(n)) n -= int(n) return bin print convert_float_to_binary(0.625)
3097f3df840469b1d88d9c69645f5fa1605f0fc2
anuragknp/algorithms
/linked_list.py
788
4
4
class Node: def __init__(self, val): self.val = val self.next = None class LinkedList: def __init__(self): self._head = None def insert(self, val): node = Node(val) node.next = self._head self._head = node def reverse(self): ptr = self._head prev = None while ptr != None: next = ptr.next ptr.next = prev prev = ptr ptr = next self._head = prev def print_list(self): ptr = self._head while ptr != None: print ptr.val ptr = ptr.next if __name__ == '__main__': list = LinkedList() list.insert(10) list.insert(20) list.insert(30) list.insert(40) list.insert(50) list.insert(60) list.insert(70) list.insert(80) list.print_list() list.reverse() list.print_list()
f4565567fcda0a73ea760e305bc1bcf9db3f39d2
SeuperHakkerJa/Project-Euler-Solutions
/python_sol/p004.py
896
4.0625
4
# # Solution to Project Euler problem 4 # # Author: Xiaochen Li # Date: May 11, 2019 # # # Problem: Find the largest palindrome made from the product of two # 3-digit numbers. # # The largest palindrome made from the product of two 2-digit numbers is # 9009 = 91 × 99. # ''' 1. check from 999 x 999 to 100 x 100 get the first palindrome ######## however this is wrong, just like 4x4 is larger than 5x3 while program ######## stop at 5x3 first ## 1* find the max through all these calcs 2. brute force? 3. isPalindrom ''' from utils import timeout def isPalindrom( n ): return n == int(str(n)[::-1]) ## int -> slice str -> int @timeout(report_time=True) def largest_palindrom(): return max( i * j for i in range (999,99,-1) for j in range (999,99,-1) ## to include 100 if ( isPalindrom( i * j ) ) ) if __name__ == "__main__": print( largest_palindrom() )
21a8c7b37dfa2568af6eb2ca900088f23a9184a5
nate-fleming/python_tutorial
/lambdas.py
295
3.59375
4
def cube(num): return num ** 3 print(cube(2)) def decrement_list(numbers): return list(map(lambda num: num - 1, numbers)) print(decrement_list([1, 2, 3])) def remove_negatives(numbers): return list(filter(lambda num: num > 0, numbers)) print(remove_negatives([-1, 3, 4, -99]))
04f4fb2ff014ebf818edbc2c98f62fc9a7683879
min-yeong/Python-Basic
/basic_set.py
3,238
3.8125
4
# Set 연습 evens = {0, 2, 4, 6, 8} # 짝수 집합 odds = {1, 3, 5, 7, 9} # 홀수 집합 numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # 전체 집합 mthree = {0, 3, 6, 9} # 3의 배수 집합 def define_set(): """ Set 정의 연습 - 순서가 없고 중복 불허 - 인덱싱, 슬라이싱 불가 - len, 포함여부(in, not in) 정도만 사용 가능 - 집합을 표현하는 자료형(집합 연산 가능) """ # 리터럴 기호 {} -> set과 dict에서 둘다 사용하기 때문에 비어있는 set을 표현할 때는 리터럴기호 사용불가 s = set() # 비어있는 Set 표현 방법 print("s:", type(s)) # 길이와 포함 여부(2가 각 집합에 포함되어 있는가) print(numbers, "의 길이:", len(numbers)) print(2 in numbers, 2 in evens, 2 not in odds, 2 not in mthree) # Set 객체 함수를 이용해서 다른 순차 자료형을 Set으로 캐스팅할 수 있음 s = "Python Programming" print(s, "length:", len(s)) chars = set(s.upper()) print(chars, "length:", len(chars)) # 순서가 없고 중복이 제거됌 -> 리스트 등 자료형에서 중복을 제거할 때 사용 lst = "Python Programming Java Programming R Programming".split() print(lst) lst = list(set(lst)) print("중복제거:", lst) def set_methods(): """ Set의 메서드 """ # 요소의 추가 numbers.add(10) print(numbers) print("evens:", evens) evens.add(2) print("evens:", evens) # 중복된 값 추가 불가 # 요소 삭제 : discard(요소를 삭제하되 존재하지 않는 값이여도 오류가 나지않는다), remove(요소를 삭제하되 존재하지 않는 값이면 오류발생) numbers.discard(15) print("numbers:", numbers) numbers.discard(5) print("numbers:", numbers) if 15 in numbers: numbers.remove(15) else: numbers.remove(4) print("remove:", numbers) evens.update({10, 12, 14, 16}) # 여러 요소가 한번에 업데이트 print("evens:", evens) evens.clear() # Set 비우기 print("evens:", evens) def set_oper(): """ 집합 연산 - 합집합, 모집합, 부분집합, 교집합, 차집합 """ # 합집합 : |, union 메서드 print("짝수 합집합 홀수:", evens.union(odds)) print(evens.union(odds) == numbers) print(evens | odds == numbers) # 모집합, 부분집합의 판단 issuperset, issubset print(numbers.issuperset(evens), numbers.issuperset(odds)) print(evens.issubset(numbers), odds.issubset(numbers)) print(evens.issuperset(odds)) # 교집합 : &, intersection 메서드 print(evens.intersection(mthree) == {0, 6}) # 짝수와 3의 배수와 교집합 print(odds & mthree == {3, 9}) # 차집합 : -, difference 메서드 print(numbers.difference(evens) == odds) # 전체수와 짝수의 차집합 print(numbers - odds == evens) # 전체수와 홀수의 차집합 def loop(): """ Set의 순환 """ print("numbers:", numbers) # 순회 for number in numbers: print(number, end=" ") print() if __name__ == "__main__": #define_set() #set_methods() #set_oper() loop()
d86282ee11cb7cf8d31feac6eabd8bd6eeccc295
wieczszy/Project-Euler
/problem042.py
1,265
3.625
4
def generate_triangle_numbers(): triangle_numbers = [] for i in range(10000): t_number = int(0.5 * i * (i + 1)) triangle_numbers.append(t_number) return triangle_numbers def check_if_triangle(number): triangle_numbers = generate_triangle_numbers() if number in triangle_numbers: return 1 return 0 def calculate_word_value(word): word = str(word).upper() word_value = 0 alphabet = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, 'P': 16, 'Q': 17, 'R': 18, 'S': 19,'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26} for i in range(len(word)): word_value += alphabet[word[i]] return word_value def read_words(filename): word_list = [] file = open(filename) for word in file.read().split(','): word_list.append(word.replace('"', '')) file.close() return word_list def main(): result = 0 word_list = read_words('words.txt') for word in word_list: word_value = calculate_word_value(word) if check_if_triangle(word_value) == 1: result += 1 print(result) if __name__ == "__main__": main()
5c216863d2424c1f2eba9c3a796b1b8d9e5df3ef
wieczszy/Project-Euler
/problem041.py
510
3.609375
4
def get_primes(x): assert(x >= 0) sieve = [1] * (x + 1) primes = [] for i in range(2, x + 1): if sieve[i] == 1: primes.append(i) for j in range(i, x + 1, i): sieve[j] = 0 return primes primes = get_primes(10000000) result = 0 for prime in primes: tmp = [] n = str(prime) digits = list(range(1, len(n)+1)) for char in n: tmp.append(int(char)) tmp.sort() if tmp == digits: result = prime print(result)
958718e8a3414f0271687d4be32493d7fd50460e
MOGAAAAAAAAAA/magajiabraham
/defining functions 2.py
328
4.125
4
text="Python rocks" text2 = text + " AAA" print(text2) def reverseString(text): for letter in range(len(text)-1,-1,-1): print(text[letter],end="") def reverseReturn(text): result="" for letter in range(len(text)-1,-1,-1): result = result + text[letter] return result print(reverseReturn("zoom"))
4c343f3c47cbcb5450ffd8262ce82f29ba752172
MOGAAAAAAAAAA/magajiabraham
/division of numbers.py
258
4.0625
4
usernumber1 =int(input("Pick a number:")) if usernumber1 %2 ==0 and usernumber1 %4 != 0: print ("Your number is even") elif usernumber1 %2 ==1: print ("Your number is odd") elif usernumber1 %4 ==0: print ("Your number is even and divisible by 4")
7d534a8b400370807db155de1f9fc9f2ed182bad
dLac-biXi1/Keylogger
/keylogger.py
819
3.515625
4
from pynput.keyboard import Key,Listener class Keylogger: def __init__(self) -> None: self.n = 0 with Listener(self.onPress,self.onRelease) as listener : listener.join() def appendFile(self,key): with open(f"log{self.n}.txt", "a+", encoding="UTF-8") as file : file.write(key) def onPress(self,key): if key == Key.enter: self.appendFile("\n") elif key == Key.space: self.appendFile(" ") else: if str(key).find("key") != 0: self.appendFile(str(key).replace("'", "")) if open(f"log{self.n}.txt", "r+").read().count("\n") == 5 : self.n+=1 def onRelease(self,key): if key == Key.esc: print("Exit") return False Keylogger()
19456c41fc9d4a7f76af8b2c5d60772338c56979
cheesepuff90/code-kata
/day12.py
567
3.578125
4
def reverse_string(s): for i in range(len(s)//2): s[i], s[-i-1] = s[-i-1], s[i] return s # a, b = 0, len(s) - 1 # while a < b: # s[a], s[b] = s[b], s[a] # a += 1 # b -= 1 # return s # 문자로 구성된 배열을 input으로 전달하면, 문자를 뒤집어서 return 해주세요. # 새로운 배열을 선언하면 안 됩니다. # 인자로 받은 배열을 수정해서 만들어주세요. # Input: ["h","e","l","l","o"] # Output: ["o","l","l","e","h"] # Input: ["H","a","n","n","a","h"] # Output: ["h","a","n","n","a","H"]
b3d8417d12409175a8c97b6b0a9344d0d52c9edd
SekouDiaoNlp/sandbox
/processing_tibetan.py
3,036
3.765625
4
# coding: utf-8 # In[12]: import re # In[13]: #chunk = re.sub(r'([^།])\s', r'\1', chunk) # eliminate the extra spaces added by the segmentation in words # In[14]: # syllable = re.sub("་", "", syllable) # In[7]: def add_tsheg(line_list): ''' takes as input a list of text splitted at the tshek. It deals with the final ། and the extra tshek added to ང་ ''' to_del = 0 for s in range(len(line_list)): if line_list[s].endswith("།") or line_list[s].endswith("། ") or line_list[s].endswith("_")or line_list[s].endswith(" ") or line_list[s] == "": s = s elif line_list[s].endswith("ང") and line_list[s+1].startswith("།"): line_list[s] = line_list[s]+"་"+line_list[s+1] to_del = s+1 else: line_list[s] += "་" if to_del != 0: del line_list[to_del] return line_list line = "།བཅོམ་ལྡན་འདས་དེའི་ཚེ་ན་ཚེ་དང་ལྡན་པ་ཀུན་དགང་།ཀུན ་ཀུན་" splitted = line.split("་") print(add_tsheg(splitted)) # In[9]: def joinedword_list(word, line): ''' splits by tsheks a tibetan string(line) splits by tsheks a given multi-syllabled tibetan word puts together the syllables of the word in the splitted string ''' word_syllables = [] if "་" in word: if word.endswith("་"): word_syllables = word.split("་") del(word_syllables[len(word_syllables)-1]) else: word_syllables = word.split("་") word_syllables = add_tsheg(word_syllables) syllabled = line.split("་") syllabled = add_tsheg(syllabled) occurences = [] for s in range(len(syllabled)-len(word_syllables)): temp = [] for m in range(len(word_syllables)): if word_syllables[m] == syllabled[s+m].strip("།"):# temp.append(s+m) if len(temp) == len(word_syllables): up = temp[0] down = temp[len(temp)-1] occurences.append((up,"".join(syllabled[up:down+1]))) # replace first syllable with joined word for o in range(len(occurences)): syllabled[occurences[o][0]] = occurences[o][1] number = len(word_syllables)-1 no = 0 for o in range(len(occurences)): for i in range(number): del syllabled[occurences[o][0]+1-o-no] no = no+1 return syllabled line = "།བཅོམ་ལྡན་འདས་དེའི་ཚེ་ན་ཚེ་དང་ལྡན་པ་ཀུན་དགའ་བོ་བཅོམ་ལྡན་འདས་ཀྱི་སྣམ་ལོགས་ན་བསིལ་ཡབ་ཐོགས་ཏེ་བཅོམ་ལྡན་འདས་ལ་བསིལ་ཡབ་ཀྱིས་གཡོབ་ཅིང་འདུག་བཅོམ་ལྡན་འདས་" word = "བཅོམ་ལྡན་འདས་" print(joinedword_list(word, line)) # In[ ]:
a28faa5287000d5c056df0058c3834f299dccb1c
Guilherme-Galli77/Curso-Python-Mundo-3
/Teoria-e-Testes/Aula023 - Tratamento de Erros e Exceções/main2.py
1,173
4.15625
4
try: a = int(input("Num: ")) # 8 b = int(input("Denominador: ")) # 0 r = a / b except: print(f"Erro!") else: print(f"resposta: {r}") # Divisão por zero --> erro finally: print("FIM DO CODIGO") print("="*50) # Outro formato de tratamento de exceção try: a = int(input("Num: ")) # 8 b = int(input("Denominador: ")) # 0 r = a / b except Exception as erro: print(f"Problema encontrado foi {erro.__class__}") else: print(f"resposta: {r}") # Divisão por zero --> erro finally: print("FIM DO CODIGO") print("="*50) # Outro formato de tratamento de exceção, agora com varias exceções/erros try: a = int(input("Num: ")) # 8 b = int(input("Denominador: ")) # 0 r = a / b except (ValueError, TypeError): print(f"Problema com os tipos de dados digitados") except ZeroDivisionError: print("Não é possível dividir um numero por zero ") except KeyboardInterrupt: print("O usuario optou por nao informar os dados") except Exception as erro: print(f"Erro encontrado foi {erro.__cause__}") else: print(f"resposta: {r}") # Divisão por zero --> erro finally: print("FIM DO CODIGO")
fc017550df1a79ae77378faba63cbcaee9793ec8
Guilherme-Galli77/Curso-Python-Mundo-3
/Exercicios/Ex081 - Extraindo dados de uma Lista.py
850
4.1875
4
# Exercício Python 081: Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre: # A) Quantos números foram digitados. # B) A lista de valores, ordenada de forma decrescente. # C) Se o valor 5 foi digitado e está ou não na lista. c = 0 lista = list() while True: valor = int(input("Digite um valor: ")) lista.append(valor) c += 1 r = str(input("Deseja continuar? [S/N] ")).strip().upper() while r not in "SsNn": r = str(input("Deseja continuar? [S/N] ")).strip().upper() if r == "N": break print(f"Você digitou {c} elementos") #posso usar len(lista) ao invés de um contador lista.sort(reverse=True) print(f"Os valores em ordem decrescente são: {lista}") if 5 in lista: print("O valor 5 faz parte da lista!") else: print("O valor 5 não faz parte da lista!")
096ace50fea78a700ab0dad3900b7df4284e45d6
Guilherme-Galli77/Curso-Python-Mundo-3
/Exercicios/Ex079 - Valores únicos em uma Lista.py
680
4.25
4
#Exercício Python 079: Crie um programa onde o usuário possa digitar vários valores numéricos # e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. # No final, serão exibidos todos os valores únicos digitados, em ordem crescente. Lista = list() while True: valor = int(input("Digite um valor: ")) if valor not in Lista: Lista.append(valor) print("Valor adicionado! ") else: print("Valor duplicado! Não vou adicionar na lista! ") continuar = str(input("Quer continuar [S/N] ? ")).strip().upper() if continuar == "N": break Lista.sort() print(f"Você digitou os valores {Lista}")
889d79103018cde6d0d033a9726d97dfb590f8a5
Guilherme-Galli77/Curso-Python-Mundo-3
/Exercicios/Ex077 - Contando vogais em Tupla.py
341
3.890625
4
palavras = ("teste", "codigo", "programar", "casa", "livro", "python", "programacao", "caneta", "cachorro", "gato", "cadeira", "verde" "maça", "arroz") for p in palavras: print(f"\nNa palavra {p.upper()} temos: ", end="") for letra in p: if letra.lower() in "aeiou": print(letra, end="")
26a3838fea00d6c73fd418d569e7d6871caf58cb
Guilherme-Galli77/Curso-Python-Mundo-3
/Exercicios/Ex097 - Um print especial.py
468
3.890625
4
# Exercício Python 097: Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como # parâmetro e mostre uma mensagem com tamanho adaptável. Ex: # escreva(‘Olá, Mundo!’) Saída: # ~~~~~~~~~ # Olá, Mundo! # ~~~~~~~~~ def printEspecial(msg): tam = len(msg) print("~"*tam) print(msg) print("~"*tam) printEspecial("Guilherme") printEspecial("Curso de Python") printEspecial("Teste")
e213daa5f9d78a730b3977de1f5c45aafa7b9db3
Guilherme-Galli77/Curso-Python-Mundo-3
/Exercicios/Ex089 - Boletim com listas compostas.py
1,073
3.9375
4
# Exercício Python 089: Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista # composta. No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de # cada aluno individualmente. dados = list() while True: nome = str(input("Nome: ")) n1 = float(input("Nota 1: ")) n2 = float(input("Nota 2: ")) media = (n1+n2)/2 dados.append([nome, [n1, n2], media]) r = str(input("Quer continuar? [S/N] ")).strip().upper() while r not in "NnSs": print("Entrada inválida, digite novamente! ") r = str(input("Quer continuar? [S/N] ")).strip().upper() if r == "N": break print(f"{'No.':<4} {'NOME':<10} {'MEDIA':>8}") print("="*40) for i, a in enumerate(dados): print(f"{i:<4} {a[0]:<10}{a[2]:>8.1f}") print("="*40) while True: opc = int(input("Mostrar notas de qual aluno ? (999 interrompe) ")) if opc == 999: break if opc <= len(dados) -1: print(f"Notas do aluno {dados[opc][0]} : {dados[opc][1]}") print("FIM")
4dab86694d10f4214fd440961073d51fd0468853
naila20/hackinscience
/exercises/097/solution.py
386
3.671875
4
def love_meet(bob, alice): list = [] for i in bob: for j in alice: if i == j: list.append(i) list2 = set(list) return set(list2) def affair_meet(bob, alice, silvester): res = [] for j in alice: for k in silvester: if j == k and j not in bob: res.append(j) return set(res)
e0b3379e82d7287b4ea4e150366c0d6f3b241b3e
fotonus/PythonLessons
/lesson_002/04_my_family.py
974
3.84375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Создайте списки: # моя семья (минимум 3 элемента, есть еще дедушки и бабушки, если что) my_family = ['отец', 'Бабушка Валя', 'Дедушка Петя' ] # список списков приблизителного роста членов вашей семьи my_family_height = [[my_family[0],188], [my_family[1], 156], [my_family[2], 162]] # Выведите на консоль рост отца в формате # Рост отца - ХХ см print('Рост отца - ', my_family_height[0][1], ' см') # Выведите на консоль общий рост вашей семьи как сумму ростов всех членов # Общий рост моей семьи - ХХ см height_my_family = my_family_height[0][1] + my_family_height[1][1] + my_family_height[2][1] print('Общий рост моей семьи - ', height_my_family, ' см')
66a5ea8a7ae8c68417882705a0492c282e5e26f3
akshaychanna/all
/data/akshay/python/short_if.py
109
3.9375
4
a = 2 b = 23 #if b > a : print("b is greater") print("b is greater") if b > a else print("a is greater")
8ec60e5c57bc06dee3c675e5b5a1b7c63c264a5f
hms1707/source
/tk연습03.py
202
3.53125
4
from tkinter import * window = Tk() btnList = [None] *10 for i in range(0,10) : btnList[i] = Button(window, text="버튼"+str(i+1)) for btn in btnList : btn.pack(side=LEFT) window.mainloop()
e98133b98b62a1a35398e275fa12fc08935eb831
Remco123/CactusOS
/tools/fontGenerator/fontgen.py
4,503
3.53125
4
# import required classes from PIL import Image, ImageDraw, ImageFont from time import sleep import sys # Array that holds a collection of data for each character characterData = [] # Print iterations progress def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) printEnd - Optional : end character (e.g. "\r", "\r\n") (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd) # Print New Line on Complete if iteration == total: print() def ProcessCharacter(char, fontengine): global characterData msg = ''.join(char) charsize = font.getsize(msg) # create new image for this character image = Image.new(mode = "RGBA", size = charsize) # initialise the drawing context with # the image object as background draw = ImageDraw.Draw(image) # Set coordinates (x, y) = (0, 0) color = 'rgb(0, 0, 0)' # black color # draw the message on the background draw.text((x, y), msg, fill=color, font=font) width,height = charsize # create new bytearray for storage data = bytearray(2 + width * height) # Fill in first 2 data values with width and height of character data[0] = width data[1] = height # Fill in data by iterating trough all individial pixels for x in range(width): for y in range(height): pix = image.getpixel((x,y)) data[y * width + x + 2] = pix[3] # Get alpha component only from tupple # Add this dataset to the global list characterData.append(data) # Start of main program if(len(sys.argv) == 1): print('Missing argument! Exiting application') exit() sizeindots = int(sys.argv[1]) headersize = 392 # Create font for drawing the text font = ImageFont.truetype('tools/fontGenerator/font.ttf', size=sizeindots) fontname = font.getname()[0] print('Parsing font ' + fontname) # Show initial progressbar printProgressBar(0, 127-32, prefix = 'Progress:', suffix = 'Complete', length = 50) # To hold progress d = 0 # Loop through all characters for c in (chr(i) for i in range(32,127)): ProcessCharacter(c, font) printProgressBar(d + 1, 127-32, prefix = 'Progress:', suffix = 'Complete -> ' + c, length = 50) d += 1 # Print sumary of parsing print('Got a total of {0} characters in array'.format(len(characterData))) # // Header of a CactusOS Font File (CFF) # struct CFFHeader # { # uint32_t Magic; // Magic number containing 0xCFF # uint8_t Version; // Version of this font file, propably 1 # uint16_t FontSize; // Size of font in dots # uint32_t FontNameOffset; // Offset in file data where font name is stored # # uint32_t CharacterOffsets[127-32]; // Table which contains offsets to the data for each character # }; # Start saving to file f = open("isofiles/fonts/" + fontname + str(sizeindots) + '.cff', "wb") print('Writing header....') # Write header f.write((0xCFF).to_bytes(4, 'little', signed=False)) f.write((0x1).to_bytes(1, 'little', signed=False)) f.write((sizeindots).to_bytes(2, 'little', signed=False)) f.write((headersize-1).to_bytes(4, 'little', signed=False)) # Write offsets charDataOffset = headersize + len(fontname) for i in range(len(characterData)): f.write((charDataOffset).to_bytes(4, 'little', signed=False)) charDataOffset += len(characterData[i]) # Write fontname after header f.write(bytes(fontname + '\0', 'utf-8')) print('Writing character data....') # Write actual data for i in range(len(characterData)): f.write(characterData[i]) print('Done! Filesize ~= {0} Kb'.format(int(f.tell() / 1024))) # Finally close the file f.close()
4bb7bb6e2a7d1c1aeb4b132b781607ddb54d9f4e
McWixy/college_snake
/game.py
2,438
3.796875
4
from random import randint from snake import Snake class Game: def __init__(self, game_size : int): self.size = game_size self.map = [] for _ in range(self.size): ligne = [] for _ in range(self.size): ligne.append(0) self.map.append(ligne) self.pomme_is_there = False def __repr__(self): info = "[ Game of size " info += str(self.size) info += " ]" return info def set_snake(self, snake): self.snake = snake for x, y in self.snake.segment: self.map[x][y] = 2 def show_game(self): for i in range(self.size): for j in range(self.size): Ax, Ay = self.apple if self.snake_there(i, j): print('S', end=' ') elif Ax == i and Ay == j: print('#', end=' ') else: print('.', end=' ') print() def snake_there(self, x, y): liste = self.snake.segment for segment in liste: Sx, Sy = segment if Sx == x and Sy == y: return True return False def add_apple(self): if self.pomme_is_there == False: while True: x = randint(0, self.size - 1) y = randint(0, self.size - 1) if self.snake_there(x, y) == True: continue self.apple = (x, y) break self.pomme_is_there = True def set_snake(self, snake): self.snake = snake print(self.snake.segment) for x, y in self.snake.segment: self.map[x][y] = 2 def update_game(self): direction = input("Direction") print('a') """ a/q => gauche = 1 d/d => droite = 2 w/z => haut = 3 s/s => bas = 4 """ eat = False if direction == "a": eat = self.snake.moveLeft(self.apple) elif direction == "d": eat = self.snake.moveRight(self.apple) elif direction == "w": eat = self.snake.moveUp(self.apple) elif direction == "s": eat = self.snake.moveDown(self.apple) if eat: self.pomme_is_there = False self.add_apple()
eedd795007ad76013cf69832637e39178046e84d
EgorVezhnin/2021_ZHIGALSKII_infa
/laba3python/ex2.py
5,002
3.515625
4
import turtle lenbit = 20 diagonal = (2 ** 0.5)*lenbit dlinlenbin = 2 * lenbit def printzero(): global lenbit global diagonal global dlinlenbin turtle.pendown() turtle.forward(lenbit) turtle.right(90) turtle.forward(dlinlenbin) turtle.right(90) turtle.forward(lenbit) turtle.right(90) turtle.forward(dlinlenbin) turtle.right(90) turtle.penup() turtle.forward(dlinlenbin) def printone(): global lenbit global diagonal global dlinlenbin turtle.right(90) turtle.forward(lenbit) turtle.pendown() turtle.left(135) turtle.forward(diagonal) turtle.right(135) turtle.forward(dlinlenbin) turtle.penup() turtle.left(180) turtle.forward(dlinlenbin) turtle.right(90) turtle.forward(lenbit) def printtwo(): global lenbit global diagonal global dlinlenbin turtle.pendown() turtle.forward(lenbit) turtle.right(90) turtle.forward(lenbit) turtle.right(45) turtle.forward(diagonal) turtle.left(135) turtle.forward(lenbit) turtle.penup() turtle.left(90) turtle.forward(dlinlenbin) turtle.right(90) turtle.forward(lenbit) def printthree(): global lenbit global diagonal global dlinlenbin turtle.pendown() turtle.forward(lenbit) turtle.right(135) turtle.forward(diagonal) turtle.left(135) turtle.forward(lenbit) turtle.right(135) turtle.forward(diagonal) turtle.penup() turtle.right(135) turtle.forward(dlinlenbin) turtle.right(90) turtle.forward(dlinlenbin) def printfour(): global lenbit global diagonal global dlinlenbin turtle.right(90) turtle.pendown() turtle.forward(lenbit) turtle.left(90) turtle.forward(lenbit) turtle.right(90) turtle.forward(lenbit) turtle.left(180) turtle.forward(dlinlenbin) turtle.penup() turtle.right(90) turtle.forward(lenbit) def printfive(): global lenbit global diagonal global dlinlenbin turtle.forward(lenbit) turtle.pendown() turtle.right(180) turtle.forward(lenbit) turtle.left(90) turtle.forward(lenbit) turtle.left(90) turtle.forward(lenbit) turtle.right(90) turtle.forward(lenbit) turtle.right(90) turtle.forward(lenbit) turtle.right(180) turtle.penup() turtle.forward(lenbit) turtle.left(90) turtle.forward(dlinlenbin) turtle.right(90) turtle.forward(lenbit) def printsix(): global lenbit global diagonal global dlinlenbin turtle.forward(lenbit) turtle.pendown() turtle.right(135) turtle.forward(diagonal) turtle.left(45) turtle.forward(lenbit) turtle.left(90) turtle.forward(lenbit) turtle.left(90) turtle.forward(lenbit) turtle.left(90) turtle.forward(lenbit) turtle.right(135) turtle.penup() turtle.forward(diagonal) turtle.right(45) turtle.forward(lenbit) def printseven(): global lenbit global diagonal global dlinlenbin turtle.pendown() turtle.forward(lenbit) turtle.right(135) turtle.forward(diagonal) turtle.left(45) turtle.forward(lenbit) turtle.penup() turtle.left(180) turtle.forward(dlinlenbin) turtle.right(90) turtle.forward(dlinlenbin) def printeight(): global lenbit global diagonal global dlinlenbin turtle.pendown() turtle.right(90) turtle.forward(dlinlenbin) turtle.left(90) turtle.forward(lenbit) turtle.left(90) turtle.forward(lenbit) turtle.left(90) turtle.forward(lenbit) turtle.right(180) turtle.forward(lenbit) turtle.left(90) turtle.forward(lenbit) turtle.left(90) turtle.forward(lenbit) turtle.right(180) turtle.penup() turtle.forward(dlinlenbin) def printnine(): global lenbit global diagonal global dlinlenbin turtle.forward(lenbit) turtle.right(90) turtle.forward(lenbit) turtle.right(90) turtle.pendown() turtle.forward(lenbit) turtle.right(90) turtle.forward(lenbit) turtle.right(90) turtle.forward(lenbit) turtle.right(90) turtle.forward(lenbit) turtle.right(45) turtle.forward(diagonal) turtle.left(135) turtle.penup() turtle.forward(lenbit) turtle.left(90) turtle.forward(dlinlenbin) turtle.right(90) turtle.forward(lenbit) def printnumber(k): if k == 0: printzero() elif k == 1: printone() elif k == 2: printtwo() elif k == 3: printthree() elif k == 4: printfour() elif k == 5: printfive() elif k == 6: printsix() elif k == 7: printseven() elif k == 8: printeight() elif k == 9: printnine() index = tuple(input()) turtle.shape('turtle') turtle.speed(4) turtle.penup() try: for k in index: printnumber(int(k)) except: print("ошибка") turtle.hideturtle() turtle.exitonclick()
1617b07865d687b10ba15984a39d0f2148940ddb
EgorVezhnin/2021_ZHIGALSKII_infa
/laba2python/ex11.py
572
3.921875
4
import turtle as t t.shape('turtle') t.speed(0) t.left(90) def paintfigure(n, razmer, napravlenie): startrazmer = 20 / n if napravlenie == "left": for i in range(n): t.forward(startrazmer + razmer) t.left(360 / n) else: for i in range(n): t.forward(startrazmer + razmer) t.right(360 / n) def paintkrilia(n, razmer): paintfigure(n, razmer, "left") paintfigure(n, razmer, "right") n = 100 razmer = 3 for i in range(10): paintkrilia(n, razmer) razmer += 0.5 t.exitonclick()
570a82d9a3a3cf97ee913efb2d1779b6edbbeb25
psJnttl/RaspberryPI
/python/wordPuzzleSolver/FoundWordsList.py
3,597
3.921875
4
''' contains a list of Words found during searchPath -- + InsertWord( + WordsFound() returns a list of words found - SortList before solutionlist returned it's sorted based on points and alphabets public? ''' from Word import * import json class FoundWordsList(): def __init__(self): self.wordList = [] self.sortedList = [] def InsertWord(self, word): duplicate = False for aWord in self.wordList: #if aWord.WordAsStr() == word.WordAsStr(): # a duplicate! if aWord.InitWord() == word.InitWord(): # a duplicate! duplicate = True if word.Points > aWord.Points(): # can happen with digram, either/or self.RemoveWord(aWord) self.wordList.append(word.Copy()) if False == duplicate: self.wordList.append(word.Copy()) def WordsFound(self): for aWord in self.wordList: aWord.Print() def RemoveWord(self, word): # retain everything but tmpList = [] for item in self.wordList: if item.InitWord() != word.InitWord(): tmpList.append(item) self.wordList = tmpList def Sort(self): # based on 1. points, 2. in case equal points: alphabetically self.sortedList = [] for aWord in self.wordList: word = aWord.InitWord() points = aWord.Points() path = aWord.Path() self.sortedList.append((points, word, path)) self.sortedList.sort(reverse=True) # sort based on descencing points amount currentPoints=0; previousPoints=0; blockSize=1 for i in range(len(self.sortedList)): # indexing needed to access items in list currentPoints, currentWord, currentPath = self.sortedList[i] if currentPoints == previousPoints: blockSize += 1 else: # if blockSize > 1: # block is limited from sortedList[i-blockSize] to sortedList[i-1] startIndex = i-blockSize endIndex = i #;print startIndex, endIndex for j in range(startIndex, endIndex): #print 'j: ', j for k in range(j+1, endIndex): #print 'k: ', k pA, wordA, pthA = self.sortedList[j]; pB, wordB, pthB = self.sortedList[k] #print wordA, wordB # no equals, duplicates have been removed if wordA > wordB: tmp = self.sortedList[j] self.sortedList[j] = self.sortedList[k] self.sortedList[k] = tmp blockSize = 1 previousPoints = currentPoints print 'Words found: ', len(self.sortedList) for item in self.sortedList: print item def saveFindingsToFileJSON(self, filename): # [(pts,word,path),(pts,word,path),] self.Sort() filePtr = open(filename, 'w') dstList = list() for item in self.sortedList: points, aWord, path = item tmpDict = dict() tmpDict['points'] = points tmpDict['word'] = aWord tmptmpDict = dict() tmptmpDict['path'] = path tmpDict['wordPath'] = tmptmpDict dstList.append(tmpDict) filePtr.write( json.dumps(dstList) ) filePtr.write('\n') filePtr.close()
f62276e3aade3eddcffa424d40f24716558a6586
sachanraveesh/python-advanced
/lru_cache.py
1,620
3.65625
4
from collections import deque class LRUCache: def __init__(self, capacity:int): self.c = capacity self.m = dict() self.deq = deque() def get(self, key: int) -> int: if key in self.m: value = self.m[key] self.deq.remove(key) self.deq.appendleft(key) return value else: return -1 def put(self, key: int, value: int) -> None: if key not in self.m: if len(self.deq) == self.c: oldest = self.deq.pop() del self.m[oldest] else: self.deq.remove(key) self.m[key] = value self.deq.appendleft(key) lru_cache = LRUCache(4) #item = lru_cache.get(2) #if (item == -1): print(' put the value at key 5') lru_cache.put(5,10) print(lru_cache.deq) print(' put the value at key 4') lru_cache.put(4,11) print(lru_cache.deq) print(' put the value at key 3') lru_cache.put(3,12) print(lru_cache.deq) print(' put the value at key 2') lru_cache.put(2,15) print(lru_cache.deq) print(' put the value at key 1') lru_cache.put(1,20) print(lru_cache.deq) print(' get the value at key 5') print(lru_cache.get(5)) print(lru_cache.deq) print(' put the value 23 at key 3') lru_cache.put(3, 23) print(lru_cache.deq) print(' get the value at key 3') print(lru_cache.get(3)) print(lru_cache.deq) print(' get the value at key 1') print(lru_cache.get(1)) print(lru_cache.deq) print(' get the value at key 4') print(lru_cache.get(4)) print(lru_cache.deq) print(' get the value at key 3') print(lru_cache.get(3)) print(lru_cache.deq)
9f6a7da78745464d2508b134e51400d07dbba8fa
wilbrodn/python_tutorials
/Coursework3.py
769
3.90625
4
name = raw_input('What is your name? ') marks = [] grade = [] gps=[] for i in range (1,4): score = input("What is "+str(i)+"th mark?: ") if score>=80: grad="A" gp=4 elif score>=75 and score<80: grad="B" gp=3.5 else: grad="C" gp=3 marks = marks+[score] grade = grade+[grad] gps=gps+[gp] print(name+" 's marks are") print(marks) print("and the respective grades are") print(grade) print("while the respective grade points are") print(gps) import math tgpa=sum(gps) gpa=tgpa/3 a=sum(marks) av=a/4 print(name+"'s gross point average, GPA is") print(float(gpa)) print(name+ "'s average score in the three subjects is") print(float(av)) print(name+ "'s total score in the three subjects is" print(a)
5b2633f2664fb18a4c7dbcb483f00db628f33f78
vtkrishn/EPI
/22_Honors_class/52_Implement_A_Producer_Consumer_Queue/Consumer.py
766
3.734375
4
from threading import Thread, Condition import random import time condition = Condition() MAX_NUM = 10 #Producer thread class Consumer(Thread): def set(self,q, l): self.queue = q self.lock = l #consume def run(self): global queue while True: #get the lock #self.lock.acquire() condition.acquire() if not queue: print 'No elements in queue' condition.wait() #consume the queue data num = self.queue.pop(0) print 'Consumed :: ', num condition.notify() #release the lock #self.lock.release() condition.release() time.sleep(random.random())
d19ff58945bad7e67ba9308119a5b8a6d23cfa88
sakars1/python
/num_digit validation.py
494
4.21875
4
while 1: name = input("Enter your name: ") age = input("Enter your date of birth: ") num = input("Enter your phone number: ") if name == '' or num == '' or age == '': print("Any field should not be blank...") elif name.isalpha() and age.isdigit() and int(age) > 18 and num.isdigit(): print(name, '\n', age, '\n', num) break else: print("Name must only contain alphabets. Age must be greater than 18. Age and Number must be numeric...")
ee43539f557136ebc8168d15f90bde533935dd07
sakars1/python
/oop.py
453
3.796875
4
# class Student: # def __init__(self): # print("Hello") # def display(self): # print("this is the display func") # s1=Student() # s1.display() # s1=Student # s1.display(s1) class Student: def __init__(self,name,age): self.age=age self.name=name def display(self): print("name: ",self.name) print("Age: ",self.age) s1=Student('sakar',24) s1.display() s2=Student('sabin',19) s2.display()
287ae427798413284cc5c9ee99545de0f36f0931
sakars1/python
/inheritance.py
476
3.890625
4
class Child: def __init__(self,name,age): self.age=age self.name=name def display(self): print("Name: ",self.name) print("Age: ",self.age) class Student(Child): def __init__(self,degree,Child): self.degree=degree self.name=Child.name self.age=Child.age def details(self): print(self.name) print("Degree :",self.degree) s1=Child('sakar',24) s2=Student(12,s1) s2.display() s2.details()
9796ff0fcb53c619510d7fdfb387177a2c27415f
eirvandelden/2IA05
/FP/assignment3/hs2lhs.py
741
3.71875
4
# this python script converts a hs file to a lhs file input_file = open("picoParser2011.hs", "r") output_file = open("picoParser2011.lhs", "w") consecutive_comment = False for line in input_file: if len(line) >= 2: if line.startswith("--"): line = line[2:len(line)].strip() + '\n' consecutive_comment = True elif line.strip().startswith("--"): line = line.strip()[2:len(line)].strip() + '\n' consecutive_comment = True else: if consecutive_comment: output_file.write('\n') consecutive_comment = False line = '>' + line output_file.write(line)
2c07ac8b9390a494a8b2838b93962808410cc129
taddes/algos_python
/Recursion/factorial_tail_recursion.py
360
3.953125
4
# Tail recursion implementation # Eliminate dependancy on stack frames. There is no need for back tracking. # Does not require you to return a value after each function call to pass # to next, due to accumulator def factorial_tail(n, accumulator=1): # base case if n == 1: return accumulator return factorial_tail(n-1, n * accumulator)
728f6e51eb42897c5bcdd390ae706596bb2c073d
taddes/algos_python
/Interview Questions/Sudoku/sudoku_solve.py
1,503
4.28125
4
# sudokusolve.py """ Sudoku Solver Note: A description of the sudoku puzzle can be found at: https://en.wikipedia.org/wiki/Sudoku Given a string in SDM format, described below, write a program to find and return the solution for the sudoku puzzle in the string. The solution should be returned in the same SDM format as the input. Some puzzles will not be solvable. In that case, return the string "Unsolvable". https://realpython.com/python-practice-problems/#python-practice-problem-1-sum-of-a-range-of-integers The general SDM format is described here: http://www.sudocue.net/fileformats.php For our purposes, each SDM string will be a sequence of 81 digits, one for each position on the sudoku puzzle. Known numbers will be given, and unknown positions will have a zero value. For example, assume you're given this string of digits (split into two lines for readability): 0040060790000006020560923000780610305090004 06020540890007410920105000000840600100 The string represents this starting sudoku puzzle: 0 0 4 0 0 6 0 7 9 0 0 0 0 0 0 6 0 2 0 5 6 0 9 2 3 0 0 0 7 8 0 6 1 0 3 0 5 0 9 0 0 0 4 0 6 0 2 0 5 4 0 8 9 0 0 0 7 4 1 0 9 2 0 1 0 5 0 0 0 0 0 0 8 4 0 6 0 0 1 0 0 The provided unit tests may take a while to run, so be patient. """
f6763623fb0d75530abcb8723f786f46fae76fea
taddes/algos_python
/Binary Search Tree/binary_search_tree.py
2,251
4.09375
4
class Node: """Vertex in the search tree""" def __init__(self, data, parent): self.data = data self.left_child = None self.right_child = None self.parent = parent class BinarySearchTree: def __init__(self): self.root = None def insert_node(self, data, node): if data < node.data: if node.left_child: self.insert_node(data, node.left_child) else: node.left_child = Node(data, node) elif data > node.data: if node.right_child: self.insert_node(data, node.right_child) else: node.right_child = Node(data, node) def insert(self, data): if self.root is None: self.root = Node(data, None) else: self.insert_node(data, self.root) def traverse_in_order(self, node): """ Recursively visiting each subsequent node on each side. """ if node.left_child: self.traverse_in_order(node.left_child) print(node.data) if node.right_child: self.traverse_in_order(node.right_child) def traverse(self): if self.root is not None: self.traverse_in_order(self.root) def get_max_value(self): if self.root: return self.get_max(self.root) def get_max(self, node): if node.right_child: return self.get_max(node.right_child) return node.data def get_max_iter(self): actual = self.root while actual.right_child is not None: actual = actual.right_child return actual.data def git_min_value(self): if self.root: return self.get_min(self.root) def get_min(self, node): if node.left_child: return self.get_min(node.left_child) return node.data def get_min_iter(self): actual = self.root while actual.left_child is not None: actual = actual.left_child return actual bst = BinarySearchTree() bst.insert(4) bst.insert(5) bst.insert(24) bst.traverse() print(bst.get_max_value()) bst.insert(62) print(bst.get_max_iter())
1c2e4eb1290ba9e81ba77f2ef7b3e743fd466a69
azul-007/tools
/network_analysis/binary.py
328
3.578125
4
#!/usr/bin/python3 #Author: azul007 #Date: 03/11/2020 def bin_num(): for num in range(256): bin_a = bin(num) bin_a = bin_a[2:] #Strip "0b" if len(bin_a) < 8: diff = 8 - len(bin_a) add_zero = "0" * diff print("*", num, "\t", str(add_zero + bin_a)) else: print("*", num, "\t", bin_a) bin_num()
b29f723ed11f5c2537e673b44ac9628046fc3777
Diego415-Creador/Prueba
/tiposdedatos.py
235
3.640625
4
#Programa para calcular las raices de una ecuacion de segundo grado from math import sqrt a = 1 b = 0 c = 1 x_1 = 0 x_2 = 0 x1 = (-b + cmath.sqtr(b**2 - 4*a*C)/2 x2 = (-b - cmath.sqtr(b**2 - 4*a*C)/2 print(x_1, 'n') print(x_2)
f6948df6bdc398de4e17f693aa029ca4da965e7d
vk312/todo
/todo5.py
3,895
3.546875
4
class todo: def __init__(self): self.lis = [] self.items = [] self.temp = [] self.i = 1 def addtask(self, task): global i self.lis.append({'task':task,'id':self.i, 'is_deleted': False, 'is_complete': False}) self.i += 1 print("task is added in your list") print("-----*****------") return 1 def viewtask(self): if not self.lis: print('empty list') else: print("-----*****------") for l in self.lis: if not l['is_deleted']: print(l['id'], l['task']) print("-----*****------") return def delete_one_task(self, number): if not self.lis: print("-----*****------") print('empty list ') print("-----*****------") else: print("-----*****------") for l in self.lis: if number == l['id']: print(' your task is deleted') l['is_deleted'] = True print("-----*****------") return 1 def completed_task(self, c): if not self.lis: print('empty list') return 1 else: print("-----*****------") for i in self.lis: if c == i['id']: print('task marked As completed') i['is_complete'] = True print("-----*****------") def completed_list(self): if not self.lis: print("-----*****------") print("no task is completed") print("-----*****------") return 0 else: print("-----*****------") print('completed tasks are') for l in self.lis: if l['is_complete'] == True: print(l['id'], l['task']) print("-----*****------") return 1 def delete_all(self): self.lis.clear() print("-----*****------") print('all tasks are deleted') if self.lis.length == 0: return 1 else: return 0 def delete_multiple(self, many): print("-----*****------") for i in many: for l in self.lis: if i == l['id']: l['is_deleted'] = True print('seleced tasks r deleted') if __name__ == '__main__': t = todo() press = 0 while press <= 8: press = int(input('\n 1.to add task \n 2.to view task \n 3.delete any task \n.4.enter task which is completed \n 5.view completed task\n 6.exit\n7.delete all\n8.delete selected tasks\nENTER YOUR CHOICE-->')) if press == 1: task = input('enter the task--> ') t.addtask(task) elif press == 2: t.viewtask() elif press == 3: number = int(input('enter key to delete the task \n')) t.delete_one_task(number) elif press == 4: c = int(input('enter which task is completed ?')) t.completed_task(c) elif press == 5: t.completed_list() elif press == 7: t.delete_all() elif press == 6: print("thank u") break elif press == 8: many = [] n = int(input("enter how many elements u want to delete?")) for i in range(n): many.append(int(input('enter task id to be deleted'))) t.delete_multiple(many) else: print('wrong choice') choice = input("do u want to continue yea/no?") if choice == 'yes' or choice == 'y': press = 7 else: break
f9560d72aff3355785d71742a48b1ca950d41a61
krishxx/python
/practice/Prg100Plus/Pr113.py
177
4.125
4
''' 113. Write a program to Count the Number of Digits in a Number ''' num=int(input("enter a number: ")) count=0 while num!=0: count=count+1 num = int(num/10) print(count)
ed52487eea3210a5020cb7ecd5f7d77dc00db997
krishxx/python
/practice/lphw/ex44d.py
659
3.609375
4
# -*- coding: utf-8 -*- """ Created on Fri May 25 17:37:03 2018 @author: Srikrishna.Sadula """ class Parent(object): def override(self): print ("PARENT override()") def implicit(self): print ("PARENT implicit()") def altered(self): print ("PARENT altered()") class Child(Parent): def override(self): print ("CHILD override()") def altered(self): print ("CHILD, BEFORE PARENT altered()") super(Child, self).altered() print ("CHILD, AFTER PARENT altered()") dad = Parent() son = Child() dad.implicit() son.implicit() dad.override() son.override() dad.altered() son.altered()
c036e74da29234ee9cd9e0caaa29955cc45a9e12
krishxx/python
/practice/Prg100Plus/Pr115.py
175
4.15625
4
''' 115. Write a program to Print all Integers that Aren't Divisible by Either 2 or 3 and Lie between 1 and 50. ''' for i in range(1,51): if i%2!=0 or i%3!=0: print(i)
fadd06193eb3ae24ee17ada185a248199306506b
krishxx/python
/practice/Prg100Plus/Pr130.py
402
4.21875
4
''' 130. Write a program to Print Largest Even and Largest Odd Number in a List ''' li=list() print("enter numbers in to the list") num=input() while num!='': li.append(int(num)) num=input() sz=len(li) i=0 lo=-1 le=-1 while i<sz: if li[i]%2==0 and li[i]>le: le=li[i] i=i+1 elif li[i]%2!=0 and li[i]>lo: lo=li[i] i=i+1 print("Largest even: %d and Largest Odd: %d in the list" %(le,lo))
fee66281c1b6b4443c664c8aa0f452b926620ca5
krishxx/python
/practice/cp_sols/pr32.py
338
4.0625
4
# -*- coding: utf-8 -*- """ Created on Sun May 27 07:25:48 2018 @author: Srikrishna.Sadula """ def checkValue(n): if n%2 == 0: print ("It is an even number") val = 1 else: print ("It is an odd number") val = 0 return val #checkValue(7) if(checkValue(8) == 1): print ("even number")
f7d755b926d5f9789c6e470f19f3b26f82108edc
krishxx/python
/practice/cp_sols/Pr56.py
388
3.859375
4
'''Question: 56 Write a function to compute 5/0 and use try/except to catch the exceptions. Hints: Use try/except to catch exceptions. Solution: ''' def throws(): 5/0 #err print("tintintitin") return try: throws() except ZeroDivisionError: print ("division by zero!") except Exception: print ('Caught an exception') finally: print ('In finally block for cleanup')
69c86dc61b1da9b98e2566a9e37b717a61758631
krishxx/python
/practice/Prg100Plus/Pr118.py
227
4.40625
4
''' 118. Write a program to Print an Identity Matrix ''' num=int(input("enter size of sq matrix: ")) for i in range(1,num+1): for j in range (1,num+1): if i==j: print(1,end=' ') else: print(0,end=' ') print("\n")
fe6f43a9e0f4335c28d5b63292c37542a1e2b932
ovwane/leetcode-1
/src/MaximumAverageSubarrayI.py
703
3.6875
4
''' LeetCode: Reverse Integer description: Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. author: Ehco1996 time: 2017-08-11 ''' class Solution(object): def findMaxAverage(self, nums, k): """ :type nums: List[int] :type k: int :rtype: float """ sums = sum(nums[:k]) res = sums * 1.0 for i in range(k, len(nums)): sums += nums[i] - nums[i - k] * 1.0 res = max(res, sums) return res / k l = [1, 12, -5, -6, 50, 3, -30, 25] k = 4 print(Solution().findMaxAverage(l, k))
f3f3fc1759292472e8e27cde3df49393c1877b55
ovwane/leetcode-1
/src/PalindromeNumber.py
632
3.953125
4
''' LeetCode: Palindrome Number description: Determine whether an integer is a palindrome. Do this without extra space. author: Ehco1996 time: 2017-10-27 ''' class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False elif x == 0: return True else: # 反转这个数并比较是否相等 bakx = x num = 0 while x != 0: num = num * 10 + x % 10 x = x // 10 return bakx == num print(Solution().isPalindrome(0))
beb4a3820cde261ffc047371048e6a018126f7e8
ovwane/leetcode-1
/src/ArrayPartitionI.py
695
3.734375
4
''' LeetCode: Add Two Numbers description: Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). author: Ehco1996 time: 2017-11-17 ''' class Solution: def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ l = sorted(nums) s = 0 for i in range(0,len(l),2): s += l[i] return s print (Solution().arrayPairSum([1,3,2,4,7,8]))
ee3c0a88f1a98acb948dce04574274c5a7f12765
jacobtread/Freddys-Fast-Food
/order.py
6,085
3.671875
4
from random import random from typing import Dict, List, NoReturn class Order: order_id: str # The id of the order name: str # The name of the user phone: str # The phone number of the user address: str # The address of the user delivery: bool # Whether or not to deliver the order fish: Dict[str, int] # The fish and the amount ordered chips: List[float] # The amounts of the chips ordered frozen: bool # Whether or not the order is frozen max_per_fish: int # The maximum amount of fish per type max_amount_chips: int # The maximum sets of chips that max_scoops_chips: float # The maximum amount of scoops one lot of chips can have frozen_discount: float # The discount amount per frozen fish item gst_amount: float # The amount of GST (Government Service Tax) delivery_charge: float # The amount charged for delivery def __init__(self, max_per_fish: int, max_amount_chips: int, max_scoops_chips: float, frozen_discount: float, gst_amount: float, delivery_charge: float) -> None: """ :param max_per_fish: The maximum amount of fish per type :param max_amount_chips: The maximum sets of chips that :param max_scoops_chips: The maximum amount of scoops one lot of chips can have :param frozen_discount: The discount amount per frozen fish item :param gst_amount: The amount of GST (Government Service Tax) """ # The order id is a randomly generated number between 1,000 and 10,000 self.order_id = str(round((random() * 9000) + 1000)) self.max_per_fish = max_per_fish self.max_amount_chips = max_amount_chips self.max_scoops_chips = max_scoops_chips self.frozen_discount = frozen_discount self.gst_amount = gst_amount self.delivery_charge = delivery_charge self.fish = {} self.chips = [] def calculate_prices(self, types: List[dict]) -> (int, int, int, int): """ Calculates the total price, the amount of gst and the gst inclusive price :param types: The menu types list (this contains pricing) :return: The total price, gst amount, and gst inclusive price """ # The total calculated price total_price: float = 0 # The total amount discounted from the order frozen_discount: float = 0 if self.empty(): # The current order is empty so we return 0 for all prices return 0, 0, 0, 0, self.delivery_charge for menu_type in types: # The price this type of item price: float = menu_type['price'] # If this menu has items if 'items' in menu_type: for fish_type in self.fish: # See if this type contains the fish type if fish_type in menu_type['items']: # Get the amount we have of that fish amount: int = self.fish[fish_type] # Increase the price by the amount * price total_price += amount * price if self.frozen: # If the order is frozen we apply a discount total_price -= self.frozen_discount # Decrease the total by the discount frozen_discount += self.frozen_discount # Increase the total discount size elif menu_type['name'] == 'Chips': # Special handling for the chips for amount in self.chips: # Increase the price by the amount of chips * price total_price += price * amount if self.delivery: # If the order is being delivered total_price += self.delivery_charge # Add the delivery charge to the price # The gst amount of the total (e.g $total * 0.15 aka 15%) total_gst: float = total_price * self.gst_amount # The total amount inclusive of gst (total + gst) total_inc_gst: float = total_price + total_gst # Return the totals return frozen_discount, total_price, total_gst, total_inc_gst def get_remaining_chips(self) -> int: """ Calculates the remaining number of chips that can be added :return: The remaining number of chip that can be added """ # The total amount of sets of scoops total_chips: int = len(self.chips) # The remaining amount is the difference between the max and total return self.max_amount_chips - total_chips def get_remaining_fish(self, fish_type: str) -> int: """ Calculates the remaining number of fish that can be added for a specific fish type :param fish_type: The fish type to check :return: The remaining number of fish that can be added """ if fish_type in self.fish: existing_amount: int = self.fish[fish_type] remaining: int = self.max_per_fish - existing_amount return remaining return self.max_per_fish def add_fish(self, fish_type: str, amount: int) -> NoReturn: """ Adds the specified amount of fish to the order :param fish_type: The type of the fish to add :param amount: The amount of that fish to add """ # If the fish type already has an amount we want # to add onto that instead of replacing it if fish_type in self.fish: # Retrieve the existing amount existing_amount: int = self.fish[fish_type] # Set the amount to the existing and the new self.fish[fish_type] = existing_amount + amount else: # We don't have any already so we can just directly set it # Assign the fish type to the amount self.fish[fish_type] = amount def empty(self) -> bool: """ Determine if the order is empty or not :return: Whether or not the order is empty """ return len(self.fish) == 0 and len(self.chips) == 0
0426a2503a4ada50099c08799ec5ee689da9df3f
Tonu-2020/python
/cycle5/bank.py
947
3.875
4
class bankaccount: def __init__(self,accno,name,acctype,balance): self.accno= accno self.name= name self.acctype= acctype self.balance= balance def deposit(self): amount = float(input("\nenter amount to be deposited : ")) amount = amount + self.balance print("\namount deposited :", amount) def withdraw(self): amount = float(input("enter amount to be writhdrawn")) if self.balance >= amount: self.balance -= amount print("\nYou withdrew :", amount) else: print("\nInsufficient balance !!! ") def display(self): print("\n account number",self.accno) print("Holder Name : ", self.name) print("Account Type : ", self.acctype) print("Net available Balance : ", self.balance) t=bankaccount(1232414,"ryan","savings",10000) t.deposit() t.withdraw() t.display()
b9372fca8ccb71c852e23e2ecb265ed51744639b
ssam9423/Physics
/E-Field Motion.py
5,652
3.65625
4
#!/usr/bin/env python # coding: utf-8 # # PHYS 301 Problem Set 2 # # Computational Part # # Sammy Song | 94237328 # # Motion of a Charge Through a Charged Ring # # Write down the formula for the electric field along the axis of a charged ring of radius $R$ that carries a total charge $-Q$. Imagine that a charge $Q=1\,{\rm \mu C}$ of mass $m=100\,g$ is released from a point $x_0$ on the axis at time $t=0$. Compute the trajectory of the charge assuming $R=1m$ and that the ring carries the opposite charge $-Q$ up to $t=1000\,s$ for $x_0=1\,m$ and $x_0=10\,m$. # # In order to do this, we need to numerically integrate Newton's equation of motion ${\bf F}=m{\bf a}$. This is a second order ordinary differential equation. Without getting into any details about numerical methods for integrating ODEs, all of them are essentially based on a Taylor expansion in time for a small time time increment $\Delta t$. A suitable algorithm for this particular kind is the "velocity Verlet" method. Let us denote position, velocity and acceleration at time $t$ with $x(t)$, $v(t)$ and $a(t)$ then these quantities after a small time step $\Delta t$ can be obtained as follows: # # # $$v(t+\Delta t/2)=v(t)+ a(t)\Delta t/2$$ # $$x(t+\Delta t)=x(t)+ v(t+\Delta t/2)\Delta t$$ # $$v(t+\Delta t)=v(t+\Delta t/2)+ a(t+\Delta t)\Delta t/2$$ # # These equations are in a form that can be directly implemented in a computer program. First define all relevant constants and a function that returns the force or acceleration as a function of position $x(t)$, and initialize the position to $x(0)=x_0$ and the velocity to $v(0)=0$. Then advance $x(t)$ and $y(t)$ according to the algorithm above and store the trajectory in an array. Your answer should consist of a plot of this trajectory (position versus time) for the two initial positions given above. Comment on the differences between these trajectories. Make sure you integrate long enough to see the characteristic pattern of the motion in each case. # # Hints: By considering the symmetry of the problem, you should notice that the charge moves in one dimension only. You can try out different values of the timestep $\Delta t$ (what happens qualitatively), but a possible value for the parameters given above is $\Delta t=1s$. Also, ignore gravity. If you have time, experiment with the paramenters of the problem (mass, charge, size of ring, etc.) # # # In[1]: import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import rcParams #rcParams.update({'font.size':12}) #optional to change default font size # define constants m = 0.1 R = 1 Q = 10**(-6) t_i = 0 t_f = 1000 dt = 1 x_01 = 1 x_02 = 10 v_0 = 0 a_0 = 0 e_0 = 8.8541878128 * 10**(-12) # set up arrays for position and time time = np.arange(t_i, t_f, dt) index = np.arange(len(time) - 1) # set initial position and velocity pos1 = np.array(x_01) pos2 = np.array(x_02) vel1 = np.array(v_0) vel2 = np.array(v_0) # define a function that returns the force or acceleration def acc(arr, ind): numerator = -Q*Q* arr[ind] denomenator = 4*np.pi*e_0*(R**2+arr[ind]**2)**(3/2) force = numerator / denomenator return force / m # integrate equation of motion # For initial position 1: for i in index: if i == 0: num = -Q*Q* pos1 den = 4*np.pi*e_0*(R**2+pos1**2)**(3/2) f = num / den a = f/m vel_half = vel1 + a*dt/2 pos_full = pos1 + vel_half * dt pos1 = np.append(pos1, pos_full) vel_full = vel_half + acc(pos1, i+1) * dt/2 vel1 = np.append(vel1, vel_full) else: a = acc(pos1, i) vel_half = vel1[i] + a*dt/2 pos_full = pos1[i] + vel_half * dt pos1 = np.append(pos1, pos_full) vel_full = vel_half + acc(pos1, i+1) * dt/2 vel1 = np.append(vel1, vel_full) # For initial position 2: for i in index: if i == 0: num = -Q*Q* pos2 den = 4*np.pi*e_0*(R**2+pos2**2)**(3/2) f = num / den a = f/m vel_half = vel2 + a*dt/2 pos_full = pos2 + vel_half * dt pos2 = np.append(pos2, pos_full) vel_full = vel_half + acc(pos2, i+1) * dt/2 vel2 = np.append(vel2, vel_full) else: a = acc(pos2, i) vel_half = vel2[i] + a*dt/2 pos_full = pos2[i] + vel_half * dt pos2 = np.append(pos2, pos_full) vel_full = vel_half + acc(pos2, i+1) * dt/2 vel2 = np.append(vel2, vel_full) # plot trajectories plt.figure() plt.plot(time, pos1, c='r', label=('x_0 = '+str(x_01)+' m')) plt.plot(time, pos2, c='b', label=('x_0 = '+str(x_02)+' m')) plt.legend() plt.grid() plt.xlabel('Time (s)') plt.ylabel('Distance (m)') ##################### COMMENTS ##################### # The behaviour of both charges is similar to that of a mass # on a spring. This isn't that much of a surprise as the charges # are free to move through the ring of charges, and there is no # dampening force to slow the charges enough to slow them to a halt. # The charge with the larger initial distance from the ring has # both a larger amplitude and a larger period than the charge with # the smaller initial distance from the ring. This makes sense # as the force acting on the charge initially is small, however # as the charge gets closer to the ring, it speeds up a lot to # the point where it shoots past the ring and travels 10 m in the # opposite direction until the force of the ring charge pulls # enough on the charge to a velocity of zero and repeat the cycle # over and over again.
aa151ee9827460075e609151b9062dc9601cd847
yanminglun0519/Exercise-3
/tableCheck.py
247
3.96875
4
import sqlite3 conn = sqlite3.connect('wordCount.db') cursor = conn.cursor() print("Connected") sql = '''select * from wordCount''' results = cursor.execute(sql) all_words = results.fetchall() for word in all_words: print(word)
0caf21ad24399368799cd001509dd4ea8d85fc11
LeroySalih/aoc_2020
/day5/main.py
950
3.515625
4
def getRow(code, low, high): #length of the list is 2**length of code if len(code) == 1 and code == code[0] in ["F", "L"]: return low if len(code) == 1 and code == code[0] in ["B", "R"]: return high if code[0] in ["F", "L"]: return getRow(code[1:], low, (low + high) // 2) else: return getRow(code[1:], ((low + high) // 2) + 1, high) def getSeatId(ticketCode): rowCode = ticketCode[:7] columnCode = ticketCode[-3:] row = getRow(rowCode, 0, 127) column = getRow(columnCode, 0, 7) return (row * 8) + column seatIds = [] f = open("data.txt", "rt") lines = list(f.readlines()) highest = 0 for line in lines: seatId = getSeatId(line.rstrip()) seatIds.append(seatId) f.close() seatIds = sorted(seatIds) myList = seatIds[1:len(seatIds)-1] print(len(seatIds)) print(len(myList)) # loop through all numbers for index in range(len(myList)): if not (index in myList): print (index)
5abaf19fbc586fa30f55a44253c4be963cce9970
NSCC-Fall-2020/PROG1700-da-course-notes
/blackjack.py
2,665
3.53125
4
# Game of Blackjack # Deal the user two random cards and show their values (assume Ace = 11) cards = { 'Two of Clubs': 2, 'Three of Clubs': 3, 'Four of Clubs': 4, 'Five of Clubs': 5, 'Six of Clubs': 6, 'Seven of Clubs': 7, 'Eight of Clubs': 8, 'Nine of Clubs': 9, 'Ten of Clubs': 10, 'Jack of Clubs': 10, 'Queen of Clubs': 10, 'King of Clubs': 10, 'Ace of Clubs': 11, 'Two of Spades': 2, 'Three of Spades': 3, 'Four of Spades': 4, 'Five of Spades': 5, 'Six of Spades': 6, 'Seven of Spades': 7, 'Eight of Spades': 8, 'Nine of Spades': 9, 'Ten of Spades': 10, 'Jack of Spades': 10, 'Queen of Spades': 10, 'King of Spades': 10, 'Ace of Spades': 11, 'Two of Hearts': 2, 'Three of Hearts': 3, 'Four of Hearts': 4, 'Five of Hearts': 5, 'Six of Hearts': 6, 'Seven of Hearts': 7, 'Eight of Hearts': 8, 'Nine of Hearts': 9, 'Ten of Hearts': 10, 'Jack of Hearts': 10, 'Queen of Hearts': 10, 'King of Hearts': 10, 'Ace of Hearts': 11, 'Two of Diamonds': 2, 'Three of Diamonds': 3, 'Four of Diamonds': 4, 'Five of Diamonds': 5, 'Six of Diamonds': 6, 'Seven of Diamonds': 7, 'Eight of Diamonds': 8, 'Nine of Diamonds': 9, 'Ten of Diamonds': 10, 'Jack of Diamonds': 10, 'Queen of Diamonds': 10, 'King of Diamonds': 10, 'Ace of Diamonds': 11, } import random deck = list(cards.keys()) random.shuffle(deck) # players initial cards card_one = cards[deck.pop()] card_two = cards[deck.pop()] hand_total = card_one + card_two print(f"player: {hand_total}") # dealers initial cards card_one = cards[deck.pop()] card_two = cards[deck.pop()] dealer_total = card_one + card_two print(f"dealer: {dealer_total}") hand_over = False while not hand_over: if hand_total == 21: print("Blackjack!") hand_over = True elif hand_total > 21: print("Bust!") hand_over = True else: another_card = input("Would you like another card (Y/N)? ") if another_card == "Y": hand_total += cards[deck.pop()] else: hand_over = True print(f"Player hand: {hand_total}") # dealer's decisions hand_over = False while not hand_over: if dealer_total >= 17: hand_over = True else: dealer_total += cards[deck.pop()] print(f"Dealer hand: {dealer_total}") if hand_total > dealer_total and dealer_total <= 21 and hand_total <= 21 \ or hand_total == 21 and dealer_total != 21 \ or hand_total <= 21 and dealer_total > 21: print("You WIN!") else: print("You LOSE!")
615b4972f4f0bef35073f90566e9f61a85a9d2fb
davidiwu/TensorFlowForBeginner
/tfMNISTTutorial.py
1,447
3.578125
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # load the MNIST data mnist = input_data.read_data_sets("MNIST_data", one_hot=True) # batch size: number of pics per batch batch_size = 100 # number of batches n_batch = mnist.train.num_examples // batch_size x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None, 10]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) prediction = tf.nn.softmax(tf.matmul(x, W) + b) # activation function: softmax function #loss = tf.reduce_mean(tf.square(y-prediction)) # cost function: standard square mean cross_entropy = -tf.reduce_sum(y * tf.log(prediction), reduction_indices=[1]) # cost function: cross-entropy loss = tf.reduce_mean(cross_entropy) train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss) init = tf.global_variables_initializer() correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: sess.run(init) for epoch in range(100): for batch in range(n_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) sess.run(train_step, feed_dict={x:batch_xs, y:batch_ys}) acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels}) print("Iter " + str(epoch) + ", Testing Accuracy " + str(acc))
9949436544cadcda6713f86cae3e348f8dcad041
davidiwu/TensorFlowForBeginner
/mcts-easy.py
5,569
3.796875
4
from math import * import random class GameState: def __init__(self): self.playerJustMoved = 2 def Clone(self): st = GameState() st.playerJustMoved = self.playerJustMoved return st def DoMove(self, move): self.playerJustMoved = 3 - self.playerJustMoved def GetMoves(self): # Get all possible moves from this state. pass def GetResult(self, playerjm): # Get the game result from the viewpoint of playerjm pass def __repr__(self): pass class NimState: """ A state of the game Nim. In Nim, players alternately take 1,2 or 3 chips with the winner being the player to take the last chip. In Nim any initial state of the form 4n+k for k = 1,2,3 is a win for player 1 (by choosing k) chips. Any initial state of the form 4n is a win for player 2. """ def __init__(self, ch): self.playerJustMoved = 2 # At the root pretend the player just moved is p2 - p1 has the first move self.chips = ch def Clone(self): """ Create a deep clone of this game state. """ st = NimState(self.chips) st.playerJustMoved = self.playerJustMoved return st def DoMove(self, move): """ Update a state by carrying out the given move. Must update playerJustMoved. """ assert move >= 1 and move <= 3 and move == int(move) self.chips -= move self.playerJustMoved = 3 - self.playerJustMoved def GetMoves(self): """ Get all possible moves from this state. """ return range(1,min([4, self.chips + 1])) def GetResult(self, playerjm): """ Get the game result from the viewpoint of playerjm. """ assert self.chips == 0 if self.playerJustMoved == playerjm: return 1.0 # playerjm took the last chip and has won else: return 0.0 # playerjm's opponent took the last chip and has won def __repr__(self): s = "Chips:" + str(self.chips) + " JustPlayed:" + str(self.playerJustMoved) return s class Node: ''' a node in the game tree. node wins is always from the viewpoint of playerJustMoved. crashes if state not specified ''' def __init__(self, move = None, parent = None, state = None): self.move = move self.parentNode = parent self.childNodes = [] self.wins = 0 self.visits = 0 self.untriedMoves = list(state.GetMoves()) self.playerJustMoved = state.playerJustMoved def UCTSelectChild(self): ''' use the UCB1 formula to select a child node. ''' s = sorted(self.childNodes, key = lambda c: c.wins/c.visits + sqrt(2 * log(self.visits)/c.visits))[-1] return s def AddChild(self, m, s): n = Node(move = m, parent = self, state = s) self.untriedMoves.remove(m) self.childNodes.append(n) return n def Update(self, result): self.visits += 1 self.wins += result def __repr__(self): return '[M: ' + str(self.move) + ' W/V: ' + str(self.wins) + '/' + str(self.visits) + '=' + str(self.wins/self.visits) + ']' def TreeToString(self, indent): s = self.IndentString(indent) + str(self) for c in self.childNodes: s += c.TreeToString(indent + 1) return s def IndentString(self, indent): s = '\n' for i in range(1, indent + 1): s += '| ' return s def ChildrenToString(self): s = '' for c in self.childNodes: s += str(c) + '\n' return s def UCT(rootstate, itermax, verbose = False): rootnode = Node(state=rootstate) for i in range(itermax): node = rootnode state = rootstate.Clone() # Select while node.untriedMoves == [] and node.childNodes != []: node = node.UCTSelectChild() state.DoMove(node.move) # Expand if node.untriedMoves != []: m = random.choice(node.untriedMoves) state.DoMove(m) node = node.AddChild(m, state) # Rollout - this can often be made orders of magnitude quicker using # a state.GetRandomMove() function temp = state.GetMoves() while state.GetMoves() != []: temp = state.GetMoves() if len(temp) == 0: break state.DoMove(random.choice(temp)) # Backpropagate while node != None: result = state.GetResult(node.playerJustMoved) node.Update(result) node = node.parentNode if(verbose): print(rootnode.TreeToString(0)) else: print(rootnode.ChildrenToString()) return sorted(rootnode.childNodes, key=lambda c: c.visits)[-1].move def UCTPlayGame(): state = NimState(15) while (state.GetMoves() != []): temp = state.GetMoves() if len(temp) == 0: break print(str(state)) if state.playerJustMoved == 1: m = UCT(rootstate = state, itermax = 1000, verbose=False) else: m = UCT(rootstate= state, itermax = 100, verbose=False) state.DoMove(m) result = state.GetResult(state.playerJustMoved) if result == 1.0 or result == 0.0: print('Player ' + str(state.playerJustMoved) + ' : result ' + str(result)) else: print('Nobody wins') if __name__ == '__main__': UCTPlayGame()
cc72801fc66d1c6097b987ae7ee7a43bae4ab2e1
Ashutos-h/python-L15
/4.py
282
3.75
4
#Answer 4 from tkinter import * def display(): global lbl lbl.configure(text=namE.get()) root=Tk() nam=Label(root,text="Enter your name") namE=Entry(root) btn=Button(root,text="Submit",command=display) lbl=Label(root) nam.pack() namE.pack() btn.pack() lbl.pack() root.mainloop()
8fe52274b12326cdbcf108019ac4aff7fa9c685a
juanfcreyes/python-exercises
/np/np_random.py
1,327
3.71875
4
from numpy import random import numpy as np ## ramdom numbers x = random.randint(100) print('random integer number under 100: ', x) x = random.rand() print('\nrandom number between 0 and 1:', x) x=random.randint(100, size=(5)) print('\nrandom integer number array of five elements:', x) x = random.randint(100, size=(3, 5)) print('\n2-D array with 3 rows, each row containing 5 random numbers:') print(x) x = random.rand(5) print('\n1-D array containing 5 random floats') print(x) x = random.rand(3, 5) print('\n2-D array with 3 rows, each row containing 5 random numbers:') print(x) ## data distribution x = random.choice([3, 5, 7, 9], p=[0.4, 0.3, 0.2, 0.1], size=(100)) print('data distribution base on probabilities in an array of one hundred elements:', x) print(len(x[x == 3 ]) / 100) print(len(x[x == 5 ]) / 100) print(len(x[x == 7 ]) / 100) print(len(x[x == 9 ]) / 100) print('data distribution base on probabilities that return an 2-D array with 3 rows, each containging 5 values.') x = random.choice([3, 5, 7, 9], p=[0.1, 0.3, 0.6, 0.0], size=(3, 5)) print(x) ## random permutations arr = np.array([1, 2, 3, 4, 5]) random.shuffle(arr) print('suffle the array order:', np.array([1, 2, 3, 4, 5]), arr) arr = np.array([1, 2, 3, 4, 5]) print('get a random permutation of arr:', arr, random.permutation(arr))
4f1c683a98d112484891549d7ea6a08a21a00056
juanfcreyes/python-exercises
/more_dictionaries.py
613
4.15625
4
def anagrams(array): wordsMap = {} for item in array: if "".join(sorted(item)) in wordsMap: wordsMap.get("".join(sorted(item))).append(item) else: wordsMap.setdefault("".join(sorted(item)),[item]) return wordsMap valuesort = lambda m: [pair[1] for pair in sorted(m.items(), key = lambda x : x[0])] invertdict = lambda m: {pair[1]:pair[0] for pair in m.items()} print("anagrams", anagrams(['eat', 'ate', 'done', 'tea', 'soup', 'node'])) print("valuesort", valuesort({'x': 1, 'y': 2, 'a': 3})) print("invertdict", invertdict({'x': 1, 'y': 2, 'z': 3}))
badb954ac5b0cc4a3ba768b4090ff07cec30eeb1
juanfcreyes/python-exercises
/functional_programing/json_decode.py
1,327
3.59375
4
def json_encode(data): if isinstance(data, bool): if data: return "true" else: return "false" elif isinstance(data, (int, float)): return str(data) elif isinstance(data, str): print('str', data) return '"' + escape_string(data) + '"' elif isinstance(data, list): return "[" + ", ".join(json_encode(d) for d in data) + "]" elif isinstance(data, dict): result = [] for v, k in data.items(): result.append(json_encode(v) + " : " + json_encode(k)) return "{" + ", ".join(result) + " }" else: raise TypeError("%s is not JSON serializable" % repr(data)) def escape_string(s): """Escapes double-quote, tab and new line characters in a string.""" s = s.replace('"', '\\"') s = s.replace("'", "\\'") s = s.replace("\t", "\\t") s = s.replace("\n", "\\n") return s data = { 'firts name' : 'Juan', 'last name' : 'Castillo', 'country' : { 'id' : '456fd4ds4897f', 'name' : 'Ecuador' }, 'single' : True, 'participants': [ { 'name': 'Participant 1', 'email': 'email1@example.com' }, { 'name': 'Participant 2', 'email': 'email2@example.com' } ] } print(json_encode(data))
9b9d4e0de5866fc84ab558987ed6141e1dfd92d2
juanfcreyes/python-exercises
/make_slug.py
315
3.703125
4
import re def make_slug(text): pattern = '[^a-zA-Z0-9\s]' slug = re.sub(pattern, '', text) slug = re.sub('\s', '-', slug.strip()) slug = re.sub('-{2,}', '-', slug) return slug print(make_slug("hello world")) print(make_slug("hello world!")) print(make_slug(" --hello- world--"))
676e9904c7e8ebf8c84fd721d9e07288555d3ebb
juanfcreyes/python-exercises
/np/np_practice_l2.py
1,245
3.546875
4
import numpy as np def maxx(x, y): """Get the maximum of two items""" if x >= y: return x else: return y pair_max = np.vectorize(maxx, otypes=[float]) a = np.array([5, 7, 9, 8, 6, 4, 5]) b = np.array([6, 3, 4, 8, 9, 7, 1]) print(np.where(a >= b, a, b)) print(pair_max(a, b)) arr = np.arange(9).reshape(3,3) print('swap colum 0 and 1') print(arr[:, [1,0,2]]) print('swap colum 1 and 2') print(arr[:, [0,2,1]]) print('swap colum 0 and 2') print(arr[:, [2,1,0]]) print('swap row 2-d array (reverse)') print('method 1 arr[[2, 1, 0],:]') print(arr[[2, 1, 0],:]) print('method 2 arr[::-1]') print(arr[::-1]) print('2D array of shape 5×3 that contain random decimal numbers between 5 and 10') print('method 1 (5 * np.random.random_sample((5, 3))) + 5') limited_values = (5 * np.random.random_sample((5, 3))) + 5 print(limited_values) print(limited_values[:, 2]) print('method 2 np.random.uniform(5,10, size=(5,3))') print(np.random.uniform(5,10, size=(5,3))) print('method 3 np.random.randint(low=5, high=10, size=(5,3)) + np.random.random((5,3))') print(np.random.randint(low=5, high=10, size=(5,3)) + np.random.random((5,3))) rand_arr = np.random.random((5,3)) np.set_printoptions(precision=3) print(rand_arr)
d62c34c059c0074ca01d4196d5c26202be417145
Banerjeed/grocerylist_2.0
/shoppinglist_practice.py
1,228
4.09375
4
groceries = [ ] def addone_shopping(item): global groceries if item in groceries: print "Error: that item is already on your grocery list" else: item.lower() groceries.append(item) groceries.sort() return groceries def delete_shopping(R_item): R_item.lower() if R_item not in groceries: print "Error: that item is not on your list. You cannot remove items that are not on your list" else: return groceries.remove(R_item) def main(): answer = raw_input("Hello! Enter 1- if you want to add something to your shopping list; Enter 2 if you want to delete something from your shopping list; Enter 3 if you want to see your shopping list") if answer == "1": answer2 = raw_input("Enter the item you want to add") addone_shopping(answer2) return main() elif answer == "2": answer3 = raw_input("Enter the item you want to delete") delete_shopping(answer3) print answer3, " has now been deleted from your shopping list" answer4 = raw_input("Would you like to go back to the main menu? Enter 1 if yes; Enter 2 if no") if answer4 == "1": return main() else: print "OK, happy shopping!" else: print groceries return main() if __name__ == '__main__': main()
c0e7f61eb85f4aaf4c72c9aa3144fe38a5383e25
sadikul1500/wumpus-world-simulation
/world.py
2,993
3.515625
4
import random class Percept: def __init__(self): self.wumpus = False self.pit = False self.glitter = False self.stench = 0 self.breeze = False self.visited = False self.pitValue = 0 self.wumpusValue = 0 self.visitedValue = 0 self.weight = 0 self.move = 0 class World: def __init__(self, numberOfWumpus, numberOfArrow, numberOfPit): self.row = 10 self.col = 10 self.board = [[Percept() for j in range (self.col)] for i in range(self.row)] self.numberOfWumpus = numberOfWumpus self.numberOfArrow = numberOfArrow self.numberOfPit = numberOfPit self.addPit() self.addWumpus() self.addGold() #self.result = None def addPit(self): #totalPits = int((self.row * self.col) * .2) i = 0 while i < self.numberOfPit: row = random.randint(0, self.row - 1) col = random.randint(0, self.col - 1) if row + col > 0: #avoid cell 0,0 i += 1 self.board[row][col].pit = True self.addBreeze(row, col) def addWumpus(self): #wumpus and pit can overlap i = 0 while i < self.numberOfWumpus: row = random.randint(0, self.row - 1) col = random.randint(0, self.col - 1) if row + col > 0 : #or self.board[row][col].pit == False i += 1 self.board[row][col].wumpus = True self.addStench(row, col) def addGold(self): #one gold while (True): row = random.randint(0, self.row - 1) col = random.randint(0, self.col - 1) if self.board[row][col].pit or self.board[row][col].wumpus: continue else: self.board[row][col].glitter = True break def addBreeze(self, row, col): if (row - 1 >= 0): self.board[row - 1][col].breeze = True if (row + 1 < self.row): self.board[row + 1][col].breeze = True if (col - 1 >= 0): self.board[row][col - 1].breeze = True if (col + 1 < self.col): self.board[row][col + 1].breeze = True def addStench(self, row, col): if (row - 1 >= 0): self.board[row - 1][col].stench += 1 #True if (row + 1 < self.row): self.board[row + 1][col].stench += 1 #True if (col - 1 >= 0): self.board[row][col - 1].stench += 1 #True if (col + 1 < self.col): self.board[row][col + 1].stench += 1 #True def show(self): for r in range(self.row): for c in range(self.col): print(r, c, self.board[r][c].glitter)
eb603fd134b839074fbdf831b142c3c7ca33a5f9
ByteLorde/RSEnterprise
/src/base/modules/Drawable/Color/Color.py
1,683
3.65625
4
class Color: @staticmethod def RED(): return Color(90, 0, 0) @staticmethod def GREEN(): return Color(0, 90, 0) @staticmethod def BLUE(): return Color(0, 0, 90) def __init__(self, red=0, green=0, blue=0): self._red = ColorValue(red) self._blue = ColorValue(blue) self._green = ColorValue(green) def getRed(self): return self._red.getValue() def getGreen(self): return self._green.getValue() def getBlue(self): return self._blue.getValue() def setRed(self, red): self._red.setValue(red) def setGreen(self, green): self._green.setValue(green) def setBlue(self, blue): self._blue.setValue(blue) def lighter(self): self._red.lighter() self._green.lighter() self._blue.lighter() def darker(self): self._red.darker() self._green.darker() self._blue.darker() class ColorValue: def __init__(self, value=0): self.setValue(value) def lighter(self): self += 15 def darker(self): self -= 15 def getValue(self): return self._value def setValue(self, value): assert isinstance(value, int), 'Value must be a number!' if value < 0: value = 0 if value > 255: value = 255 self._value = value def __eq__(self, value): self.setValue(value) def __add__(self, value): newValue = self.getValue() + value self.setValue(newValue) def __sub__(self, value): newValue = self.getValue() - value self.setValue(newValue)
51f556851248fb22defdbdeda57597b7cd35fe63
ByteLorde/RSEnterprise
/src/tests/Tests1/ChatTest.py
904
3.546875
4
from chatterbot import ChatBot import os from gtts import gTTS chatbot = ChatBot( 'Ron Obvious', trainer='chatterbot.trainers.ChatterBotCorpusTrainer' ) # Train based on the english corpus chatbot.train("chatterbot.corpus.english") # Get a response to an input statement text = input("YOU: ") # Language in which you want to convert language = 'en' # Passing the text and language to the engine, # here we have marked slow=False. Which tells # the module that the converted audio should # have a high speed # Saving the converted audio in a mp3 file named # welcome # Playing the converted file while text != "!": response = str(chatbot.get_response(text)) myobj = gTTS(text=response, lang=language, slow=False) myobj.save("welcome.mp3") os.system('mpg123 /home/syndicate/PycharmProjects/Iris/test/Tests1/welcome.mp3') print("BOT:", response) text = input("YOU: ")
06e11a4041d7be64059dd1b27ae2212e7ca51f73
Husnah-The-Programmer/simple-interest
/Simple interest.py
300
4.125
4
# program to calculate simple interest def simple_interest(Principal,Rate,Time): SI = (Principal * Rate * Time)/100 return SI P =float(input("Enter Principal\n")) R =float(input("Enter Rate\n")) T =float(input("Enter Time\n")) print("Simple Interest is",simple_interest(P,R,T))
32aa5e979a48e4fdf35a6d61f57a71a5de6d58e2
josephimathias/Beer-Hypothesis-Testing
/test_modules.py
4,505
3.734375
4
"""This module contains functions used to perform hypotesis testing.""" # Data analysis packages: # import pandas as pd import numpy as np import scipy.stats as stats import seaborn as sns def welch_t(a, b): """Return Welch's t statistic for two samples.""" # welch t calculation numerator = a.mean() - b.mean() # “ddof = Delta Degrees of Freedom”: the divisor used in N- ddof, # where N represents the number of elements. By default ddof is zero. denominator = np.sqrt(a.var(ddof=1)/a.size + b.var(ddof=1)/b.size) return np.abs(numerator/denominator) def welch_df(a, b): """Return the effective degrees of freedom for two samples welch test.""" # calculate welch df s1, s2 = a.var(ddof=1), b.var(ddof=1) n1, n2 = a.size, b.size numerator = (s1/n1 + s2/n2)**2 denominator = (s1 / n1)**2/(n1 - 1) + (s2 / n2)**2/(n2 - 1) df = numerator/denominator return df def p_value_welch_ttest(a, b, two_sided=False, alpha=0.05): """Return the p-value for Welch's t-test given two samples.""" """ By default, the returned p-value is for a one-sided t-test. Set the two-sided parameter to True if you wish to perform a two-sided t-test instead. """ t_welch = welch_t(a, b) df = welch_df(a, b) # Calculate the critical t-value t_crit = stats.t.ppf(1-alpha/2, df=df) p_welch = (1-stats.t.cdf(np.abs(t_welch), df)) * 2 # return results if (t_welch > t_crit and p_welch < alpha): print(f"""Null hypohesis rejected. Results are statistically significant with: t_value = {round(t_welch, 4)}, critical t_value = {round(t_crit, 4)}, and p-value = {round(p_welch, 4)}""") else: print(f"""We fail to reject the Null hypothesis with: t_value = {round(t_welch, 4)}, critical t_value = {round(t_crit, 4)}, and p_value = {round(p_welch, 4)}""") if two_sided: return 2 * p_welch else: return p_welch # Two sample t-test def sample_variance(sample): """Calculates sample varaiance.""" sample_mean = np.mean(sample) return np.sum((sample-sample_mean)**2)/(len(sample) - 1) def pooled_variance(sample1, sample2): """retun pooled sample variance.""" n_1, n_2 = len(sample1), len(sample2) var_1, var_2 = sample_variance(sample1), sample_variance(sample2) return ((n_1 - 1) * var_1 + (n_2 - 1) * var_2)/(n_1 + n_2 - 2) def twosample_tstatistic(expr, ctrl, alpha=0.05): """Plot two_tailed t-distibution.""" # Visualize sample distribution for normality sns.set(color_codes=True) sns.set(rc={'figure.figsize': (12, 10)}) exp_mean, ctrl_mean = np.mean(expr), np.mean(ctrl) pool_var = pooled_variance(expr, ctrl) n_e, n_c = len(expr), len(ctrl) num = exp_mean - ctrl_mean denom = np.sqrt(pool_var * ((1/n_e) + (1/n_c))) # Calculate the critical t-value df = len(expr) + len(ctrl) - 2 t_crit = stats.t.ppf(1-alpha/2, df=df) t_stat = num/denom p_value = (1 - stats.t.cdf(t_stat, df=df)) * 2 # p_value = stats.t.cdf(t_stat, df=df) # return results if (t_stat > t_crit and p_value < alpha): print("Null hypohesis rejected. Results are statistically significant with:", "\n", "t-statistic =", round(t_stat, 4), "\n", "critical t-value =", round(t_crit, 4), "and", "\n" "p-value =", round(p_value, 4), '\n') else: print("Null hypothesis is True with:", "\n", "t-statistic =", round(t_stat, 4), "\n", "critical t-value =", round(t_crit, 4), "and", "\n", "p-value = ", round(p_value, 4), '\n') print(">> We fail to reject the Null Hypothesis", "\n") print('----- Groups info -----') print(f"""The groups contain {len(expr)} , and {len(ctrl)} observations. The means are {np.round(exp_mean, 4)}, and {np.round(ctrl_mean, 4)} respectivelly""") return t_stat def coast_list(df): regions = [] wc = ['CA', 'CO', 'WA', 'OR', 'AK'] ec = ['FL', 'NY', 'MD', 'GA', 'DC', 'VA', 'SC', 'NC', 'CT', 'DE', 'NJ', 'VT', 'ME', 'NH', 'MA', 'RI', 'PA'] for state in df.state: if state in wc: regions.append('wc') elif state in ec: regions.append('ec') else: regions.append(None) df['region'] = regions return df[['beer_name', 'brewery_name', 'ibu', 'state', 'region']].dropna()
e37504cb15e63c012fa902aabdea7d0ed4bd098c
JigarShah110/Python
/Pattern/pattern7.py
325
3.546875
4
from __future__ import print_function class Pattern: def __init__(self): self.row_counter = 1 self.max_no = input("Enter Max. No: ") def draw(self): for self.row_counter in range(1, self.max_no+1): for count in range(self.row_counter, 0, -1): print (count, end="") print ("") obj1 = Pattern() obj1.draw()
793eb68ce13b595cc55e8b2e1f7b42adbd68d999
JigarShah110/Python
/Pattern/pattern6.py
412
3.65625
4
from __future__ import print_function class Pattern: def __init__(self): self.row_counter = 1 self.space = " " self.max_no = input("Enter Max. No: ") def draw(self): for self.row_counter in range(1,self.max_no+1): print (self.space*(self.row_counter-1), end=" ") for count in range(self.max_no-self.row_counter+1, 0, -1): print (count, end = "") print (" ") obj1 = Pattern() obj1.draw()
91e24f837e6f4508995577eeb9b9cf149665d63e
michelejolie/PDX-Code-Guild
/happy_sad.py
320
3.671875
4
how_many_children_do_you_have x =3+5 print(how_many_children_do_you_have) #3 integer(int) how_much_do_you_weigh_in_Kg class2 = ('float') print(how_much_do_you_weigh_in_Kg) #75.6 float what_is_your_name class3 = ('str') print(what_is_your_name) #"Jeff" string(str) are_you_happy class4 = ('bool') #true Boolean
b2352c3fca442ba2280b8a535d627917d562eb96
michelejolie/PDX-Code-Guild
/converttemperuter.py
223
4.25
4
# This program converts from Celsius to Fahrenheit user_response=input('Please input a temperature in celsius :') #celsius=int(user_response) celsius=float(user_response) fahrentheit=((celsius *9) /5)+32 print(fahrentheit)
df4675e51ae70067d8d5747071d440216ceb2ba0
michelejolie/PDX-Code-Guild
/file_io.py
1,223
3.546875
4
from pig_latin import pig_latin def read_file(file_path): with open(file_path, 'r') as file: return file.readlines() def write_file(file_path, new_lines): with open(file_path, 'w') as file: for line in new_lines: file.write(line + '\n') def append_to_file(file_path): with open(file_path, 'a') as file: times = int(input('How many lines would you like to add?: ')) ran = 0 list_of_lines = [] while ran < times: list_of_lines.append(input("What would you like to write to this file?: ")) ran += 1 for line in list_of_lines: file.write(line + '\n') def translate_to_pig_latin(orig_file, dest_file): orig_lines_list = read_file(orig_file) dest_file_lines = [] for line in orig_lines_list: new_line = [] for word in line.split(): new_line.append(pig_latin(word)) dest_file_lines.append(' '.join(new_line)) write_file(dest_file, dest_file_lines) orig_file = 'sample.txt' new_file = 'translated_pig_latin1.txt' translate_to_pig_latin('sample.txt', new_file) for line in read_file(new_file): print(line)
488ab904ea898c452ff5c2eecbd832a8de6fac3e
michelejolie/PDX-Code-Guild
/phonebook.py
509
3.640625
4
f = open('filename.py', 'w') f.close() def main(): name = input("jon snow (or press enter to end input): ") number = input("555-555-5555: ") Phonebook['jon snow'] = 555-555-5555 name = input("adam jones (or press enter to end input): ") number = input("666-666-6666: ") Phonebook['adam jones'] = 666-666-6666 #name = input("first last name (or press enter to end input): ") #if name == 'adam jones':666-666-6666 print("Thank You!") #print("Your phonebook contains the following entries:\n",phoneBook) main()
d5a9c22ede263e457f0b76d6f6ebe01406d8da0b
michelejolie/PDX-Code-Guild
/Chris/hello_beautiful.py
192
4.0625
4
# print('hello beautiful') # # #input("how's it going?") name = input('what is your name? ') #print('hello' +name) #conditional logic if name == "michele": print('you are learning')
48d494fbc16f2458590d4a9bbfcbddfd1a951cff
michelejolie/PDX-Code-Guild
/sunday.py
829
4.15625
4
# how to use decorators from time import time #def add(x, y=10): #return x + y #before = time() #print('add(10)', add(10)) #after = time() #print('time taken:', after - before) #before = time() #print('add(20,30)', add(20, 30)) #after = time() #print('time taken:', after - before) #before = time() #print('add("a", "b")', add("a", "b")) #after = time() #print('time taken:', after - before) #@time is a decorator from time import time def timer(func): def f(*args, **Kargs): before = time() runvalue = func(*args, **Kargs) after = time() print('elapsed', after - before) return runvalue return f @timer def add(x, y=10): return x + y @timer def sub(x, y=10): return x - y print('add(20,30)', add(20, 30)) print('add("a", "b")', add("a", "b"))
1b932e62aca7800ad491fe4f39f818dafaa44683
bamboodew/Python_Cookbook
/Chapter01_data_structures_and_algorithms/12/The_element_with_the_most_occurrences_in_the_sequence.py
1,676
3.921875
4
''' Created on 2018年3月18日 怎样找出一个序列中出现次数最多的元素呢? @author: Administrator ''' # collections.Counter 类就是专门为这类问题而设计的, # 它甚至有一个有用的most_common() 方法直接给了你答案。 # 为了演示,先假设你有一个单词列表并且想找出哪个单词出现频率最高。 # 你可以这样做: words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] from collections import Counter word_counts = Counter(words) # 出现频率最高的 3个单词 top_three = word_counts.most_common(3) print(top_three) # 作为输入,Counter 对象可以接受任意的由可哈希(hashable)元素构成的【序列】对象。 # 在底层实现上,一个 Counter 对象就是一个字典,将元素映射到它出现的次数上。比如: print('not出现的次数:', word_counts['not']) print('eyes出现的次数:', word_counts['eyes']) # 如果你想手动增加计数,可以简单的用加法: morewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes'] for word in morewords: word_counts[word] += 1 print('eyes的最新累积出现次数是:', word_counts['eyes']) print('not的最新累积出现次数是:', word_counts['not']) # 或者你可以使用 update() 方法: word_counts.update(morewords) print('eyes的最新累积出现次数是:', word_counts['eyes']) print('not的最新累积出现次数是:', word_counts['not'])
bc0d8df23d35c840f7aad94bd9da6c8ce27720e2
bamboodew/Python_Cookbook
/Chapter01_data_structures_and_algorithms/16/Filter_sequence_element.py
1,364
3.640625
4
''' Created on 2018年3月20日 你有一个数据序列,想利用一些规则从中提取出需要的值或者是缩短序列 @author: Administrator ''' # 最简单的过滤序列元素的方法就是使用列表推导。比如: mylist = [1, 4, -5, 10, -7, 2, 3, -1] list1 = [n for n in mylist if n > 0] print(list1) list2 = [n for n in mylist if n < 0] print(list2) # 使用列表推导的一个潜在缺陷就是如果输入非常大的时候会产生一个非常大的结果集, # 占用大量内存。如果你对内存比较敏感, # 那么你可以使用生成器表达式迭代产生过滤的元素。比如: pos = (n for n in mylist if n > 0) print(pos) for x in pos: print(x) # 有时候,过滤规则比较复杂,不能简单的在列表推导或者生成器表达式中表达出来。 # 比如,假设过滤的时候需要处理一些异常或者其他复杂情况。 # 这时候你可以将过滤代码放到一个函数中,然后使用内建的 filter() 函数。示例如下: values = ['1', '2', '-3', '-', '4', 'N/A', '5'] def is_int(val): try: x = int(val) return True except ValueError: return False ivals = list(filter(is_int, values)) print(ivals) # filter() 函数创建了一个迭代器, # 因此如果你想得到一个列表的话,就得像示例那样使用 list() 去转换。
a3cce1eae429024007c681ca4b8213b5a7ba053e
chrisadbr/python-101
/loop.py
551
4.03125
4
''' https://github.com/BenestaBiseko/python-101/invitations ''' ''' Write a simple script that demonstrate your understanding of loops in python ''' ''' Write a simple script that demonstrate your understanding of loops in python ''' # Start with wile loop i = 1 while i <= 7: print(i) i += 1 if i == 4: break # For Loop x = (1, 2, "Python") for i in x: print(i) # Nested Loop x = [1, 2, 3] y = ["a", "b", "c"] for i in x: for j in y: print(j, end="") print(i, end="")
33a1a4a041ceb5b931720b6ae018ab73fbee20bb
SixroomSandwich/infa_2021_fomicheva
/laba2/turtle5.py
138
3.703125
4
import turtle as t from random import * t.shape('turtle') for i in range(100): t.forward(randint(0, 40)) t.left(randint(0, 360))
d7614f9207bbd81611bf28b2dc6a2f246aabc976
zxs1215/LeetCode
/19_Remove_Nth_Node_From_End_of_List.py
825
3.75
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @return a ListNode def removeNthFromEnd(self, head, n): if head == None: return node = head count = 1 while node.next != None: node = node.next count += 1 node = head print(count) print(node.val) i = 1 while i < count - n: node = node.next i += 1 print(node.val) prev = node if prev.next == None: return None else: prev.next = prev.next.next return head node = ListNode(1) next = ListNode(2) node.next = next sol = Solution() sol.removeNthFromEnd(node, 2) input()
f5f6d942565e076577c15ce93bd4a4da936b9c33
zxs1215/LeetCode
/208_implement_trie.py
1,505
4.125
4
class TrieNode(object): def __init__(self): """ Initialize your data structure here. """ self.val = None self.children = [] self.has_word = False def next(self, val): for child in self.children: if child.val == val: return child class Trie(object): def __init__(self): self.root = TrieNode() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ check = self.check_it(word,True) check.has_word = True def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ check = self.check_it(word) return check != None and check.has_word def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ return self.check_it(prefix) != None def check_it(self, word, add = False): check = self.root for ch in word: node = check.next(ch) if node == None: if add: node = TrieNode() node.val = ch check.children.append(node) else: return None check = node return check
52821198076dadf7db6e06e9de2ac0a8ca7ebc26
Veena-Wanjari/My_Programs
/fizzbuzz.py
392
3.796875
4
n = 100 FIZZ = [] BUZZ = [] FIZZBUZZ = [] number = [] for i in range(1,n): if (i % 3 == 0) and (i % 5 == 0): FIZZBUZZ.append(i) elif (i % 3 == 0): FIZZ.append(i) elif (i % 5 == 0): BUZZ.append(i) else: number.append(i) print(f" FIZZ : {FIZZ} \n BUZZ: {BUZZ} \n FIZZBUZZ: {FIZZBUZZ} \n number: {number}")
a795f4d70c99ac5c5844f8762d867570ee527363
Veena-Wanjari/My_Programs
/season_guess.py
477
4
4
guess = input("Please guess the season : ") guess.lower() if guess == 'winter': print("Yes .. You are right !!") elif guess == 'summer': print("OOPS !! Try again....") elif guess == 'spring': print("OOPS !! Try again....") elif guess == 'autumn': print("OOPS !! Try again....") elif guess == 'rainy': print("OOPS !! Try again....") else: print("This is not the season") print('You have choosen', guess.capitalize())