blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
48d2fe2df2355969ac7e2545d4a634aa36b34250
erik-t-irgens/algorithmic-toolbox-assignments
/lcm.py
451
3.859375
4
# Uses python3 import sys def lcm_naive(a, b): for l in range(1, a*b + 1): if l % a == 0 and l % b == 0: return l return a*b def compute_gcd(x, y): while(y): x, y = y, x % y return x # This function computes LCM def compute_lcm(x, y): lcm = (x*y)//compute_gcd(x,y) return lcm if __name__ == '__main__': input = sys.stdin.read() a, b = map(int, input.split()) print(compute_lcm(a, b))
fecf0c1cffc0eb53850f947ea9647e17da7c5e93
yusufferdemm/PythonApps
/[9]AtmProgram.py
908
3.984375
4
print(""" **************************** Welcome to ATM Program! Operation; 1.Balance inquiry 2.Pay Into 3.Withdraw Money Press 'q' to exit the program. **************************** """) balance=1000 while True: operation = input("Select Action:") if operation == "q": print("We hope you come again.") break elif operation == "1": print("Your Balance Is {}.".format(balance)) elif operation == "2": payinto=int(input("enter quantity:")) balance+=payinto elif operation == "3": Withdraw=int(input("Plase enter quantity:")) if balance - Withdraw < 0: print("Your balance is insufficient. Please enter a value in the range 0-{}.".format(balance)) continue # Bunu silsemde de islemi yapip en basa dondu. else: balance = balance - Withdraw else: print("Invalid Action.")
f3e804a8e5b5889d2e7ab322d9a7203b8c9f936f
lbmello/router-config
/routerconfig/queue/queue.py
1,763
3.9375
4
"""Modulo Queue.""" from .node import Node class Queue: """Gerencia a fila.""" def __init__(self): self.first_element = None self.last_element = None self.size = 0 def push(self, element): """ ADICIONA ELEMENTOS NA FILA. """ node = Node(element) # PREENCHE DADOS SEMPRE NA ULTIMA POSIÇÃO if self.last_element is None: self.last_element = node else: self.last_element.next = node self.last_element = node # PREENCHE DADOS NA PRIMEIRA POSIÇÃO if self.first_element is None: self.first_element = node # AUMENTA TAMANHO DA FILA self.size = self.size + 1 def pop(self): """ REMOVE ELEMENTO DA PRIMEIRA POSIÇÃO NA FILA. """ if self.size > 0: # VALOR DO PRIMEIRO CAMPO PARA RETORNO element = self.first_element.data # AVANÇA AS POSIÇÕES DA FILA self.first_element = self.first_element.next # DIMINUI TAMANHO DA FILA self.size = self.size - 1 return element return IndexError('Fila Vazia!') def peek(self): """ LÊ PRIMEIRO ELEMENTO DA FILA. """ if self.size > 0: # VALOR DO PRIMEIRO CAMPO PARA RETORNO element = self.first_element.data return element return IndexError('Fila Vazia!') def len(self): """ RETORNA TAMANHO DA FILA. """ def __repr__(self): r = "" pointer = self.first_element while (pointer != None): r = r + str(pointer.data) return r
c99442ed74dca0dde9268e1c513f144b53498e9f
mutasimm/Bookleted
/Bookletify.py
3,232
3.71875
4
# Reorders the pages of a pdf file and makes a 1 x 2 pdf in booklet format. The pages are arranged in sets 32 pages (8 sheets of paper). # Permutation of the pages of a set of 32 pages, divided among 8 sheets of paper. This could also be done with the seq4KGen function by setting k = 8, but the permutation is shown here to demonstrate how the pages are being reordered. seq32 = [32, 1, 2, 31, 30, 3, 4, 29, 28, 5, 6, 27, 26, 7, 8, 25, 24, 9, 10, 23, 22, 11, 12, 21, 20, 13, 14, 19, 18, 15, 16, 17] #Required Python libraries. PyPDF2 actually handles the pdf format. from PyPDF2 import PdfFileReader, PdfFileWriter import math, copy # The blank_a4.pdf is a one-page pdf with no content. If the number of pages in the input pdf is not a multiple of 4, copis of this blank sheet is appended to the file to be processed. blank_path = 'blank_a4.pdf' # Path is the address of the file to be processed. Use your own path, or keep the pdf file in the same folder and rename it to "input.pdf" path = 'input.pdf' n, n1 = PdfFileReader(path).getNumPages(), PdfFileReader(path).getNumPages() pdf_reader = PdfFileReader(path) blank_pdf_reader = PdfFileReader(blank_path) #generate the booklet style permutation of 4k pages def seq4KGen(k): seq = [] for i in range(k): seq.append(4*k-2*i) seq.append(2*i+1) seq.append(2*i+2) seq.append(4*k-2*i-1) i += 1 return seq # Calculating the number of empty pages to be inserted def normalize_n(): global n n = n + (4 - (n % 4)) # Generating the permutation of all the pages in the file def seqGen(): seq = [] m, p = n//32, (n % 32)//4 for k in range(m): for num in seq32: seq.append(32*k+num-1) if p > 0: seq4K = seq4KGen(p) for num in seq4K: seq.append(num-1+32*m) return seq # Normalized is the pdf generated by adding the required number of copies of the white page. def Normalize(output='normalized.pdf'): pdf_writer = PdfFileWriter() for page in range(n): if page <= n1-1: pdf_writer.addPage(pdf_reader.getPage(page)) else: pdf_writer.addPage(blank_pdf_reader.getPage(0)) with open(output, 'wb') as out: pdf_writer.write(out) # Makes new pdf with pages rearranged def Rearrange(path='normalized.pdf'): pdf = PdfFileWriter() normalized_pdf = PdfFileReader(path) seq = seqGen() for i in seq: pdf.addPage(normalized_pdf.getPage(i)) output = 'rearranged.pdf' with open(output, 'wb') as output_pdf: pdf.write(output_pdf) # Arrages the pages in 1 x 2 format (2 sheets per page in portrait mode), and saves the result in 'output.pdf' def Bookletify(path='rearranged.pdf'): input = PdfFileReader(path) output = PdfFileWriter() for i in range(0,n,2): left_page, right_page = input.getPage(i), input.getPage(i+1) offset_x, offset_y = left_page.mediaBox[2], 0 left_page.mergeTranslatedPage(right_page, offset_x, offset_y, expand=True) output.addPage(left_page) outputpdf = 'output.pdf' with open(outputpdf, 'wb') as duplexed_pdf: output.write(duplexed_pdf) normalize_n() Normalize() Rearrange() Bookletify()
08753b84546689ef314d17e24122ed5be0f9c0e3
mukunddubey10000/DubeyCoin
/dubeycoin_node_5001.py
7,450
3.875
4
"@author : Mukund" "Cryptocurrency" "Uses Flask and Postman" import datetime "To get exact date the blockchain was created" import hashlib "To use Hash functions to hash blocks" import json "To encode the blocks before hashing them" from flask import Flask, jsonify, request #request->connect nodes import requests from uuid import uuid4 from urllib.parse import urlparse "Flask to create web application" "jsonify to interact with blockchain in postman" """Instead of using functions we use class because class has properties, functions, methods, tools and all of them interact with each other which is very practical""" #building a blockchain class Blockchain: "use def to define function" "self refers to the object of Blockchain" def __init__(self): self.chain=[] "it's just a list declared by []" "now create a genesis block which is the 1st block of Blockchain" self.transactions=[] self.create_block(proof=1,previous_hash='0') "prev hash is 0(arbitrary value) coz genesis block is the 1st block" "0 is string type coz SHA 256 accepts only string arguements" self.nodes=set() def create_block(self, proof, previous_hash): block={'index':len(self.chain)+1, 'timestamp': str(datetime.datetime.now()), "proof":proof, 'previous_hash':previous_hash, 'transactions':self.transactions } self.transactions=[] self.chain.append(block) return block def get_previous_block(self): return self.chain[-1] "-1 gives previous index" def proof_of_work(self, previous_proof): new_proof=1 check_proof=False while check_proof is False: hash_operation = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest() "can't take new+prev coz it's == prev+new (associative operation)" """this is a task which miners need to solve so I can make it diff. to mine else who would mine if it's not worth it""" if hash_operation[:4] =='0000' : """miner wins""" check_proof = True else : new_proof+=1 return new_proof def hash(self, block): encoded_block = json.dumps(block, sort_keys = True).encode() return hashlib.sha256(encoded_block).hexdigest() def is_chain_valid(self, chain): "check if whole chain is valid by iterating from start to end" previous_block = chain[0] block_index = 1 while block_index < len(chain): block = chain[block_index] if block['previous_hash'] != self.hash(previous_block): return False previous_proof = previous_block['proof'] proof = block['proof'] hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest() if hash_operation[:4] != '0000': return False previous_block = block block_index += 1 return True def add_transactions(self,sender,reciever,amount): self.transactions.append({'sender':sender, 'reciever':reciever, 'amount':amount }) previous_block = self.get_previous_block() return previous_block['index']+1 def add_node(self,address): parsed_url = urlparse(address) self.nodes.add(parsed_url.netloc) def replace_chain(self): network = self.nodes longest_chain = None max_length = len(self.chain) for node in network : #port 5000 is for 1 node, we need multiple http://127.0.0.1:5000/get_chain response = requests.get(f'http://{node}/get_chain') if response.status_code == 200 : length = response.json()['length'] chain = response.json()['chain'] if length > max_length and self.is_chain_valid(chain): max_length = length longest_chain = chain if longest_chain : #is not None: self.chain = longest_chain return True return False # mining the blockchain app = Flask(__name__) #creating a web app #address creation for node on port 5000 node_address = str(uuid4()).replace('-','') blockchain = Blockchain() #creating a blockchain @app.route('/mine_block', methods = ['GET']) #mining new block def mine_block(): previous_block = blockchain.get_previous_block() previous_proof = previous_block['proof'] proof = blockchain.proof_of_work(previous_proof) previous_hash = blockchain.hash(previous_block) blockchain.add_transactions(sender = node_address, reciever = 'Mukund', amount = 1) block = blockchain.create_block(proof, previous_hash) response = {'message' : 'Congratulations! You mined a block!', 'index' : block['index'], 'timestamp' : block['timestamp'], 'proof' : block['proof'], 'previous_hash' : block['previous_hash'], 'transactions' : block['transactions'] } #response to user using postman return jsonify(response), 200 #get the full blockchain on display @app.route('/get_chain', methods = ['GET']) def get_chain(): response = {'chain': blockchain.chain,'length': len(blockchain.chain)} return jsonify(response), 200 @app.route('/is_valid', methods = ['GET']) def is_valid(): isvalid = blockchain.is_chain_valid(blockchain.chain) if isvalid==True : response = {'message': 'VALID!!'} else : response = {'message': 'INVALID!! '} return jsonify(response), 200 @app.route('/add_transaction', methods = ['POST']) def add_transaction() : json = request.get_json() #json format is like python's dict key only transaction_keys = ['sender', 'reciever', 'amount'] if not all (key in json for key in transaction_keys): return 'Sender,reciver,amount format not followed!!', 400 index = blockchain.add_transactions(json['sender'],json['reciever'],json['amount']) response = {'message': f'This transaction is added to block {index}'} return jsonify(response), 201 #200 is for get but 201 is for post #now decentralization begins @app.route('/connect_node', methods = ['POST']) def connect_node() : json = request.get_json() nodes = json.get('nodes') if nodes is None : return 'No nodes', 400 for node in nodes : blockchain.add_node(node) response = {'message': 'Dubeycoin Blockchain now contains ', 'total nodes':list(blockchain.nodes) } return jsonify(response), 201 #replace longest chain @app.route('/replace_chain', methods = ['GET']) def replace_chain(): is_chain_replaced = blockchain.replace_chain() if is_chain_replaced == True : #if nodes had different chains then it'll be replaced by the longest one response = {'message': 'Replaced!!', 'new_chain':blockchain.chain } else : response = {'message': 'Not replaced!!', 'chain':blockchain.chain } return jsonify(response), 200 #to run app app.run(host = '0.0.0.0', port = 5001)
69b93afa6c9792b6f336e928eb500133674eceff
ponickkhan/unix
/assignment4.py
1,308
3.609375
4
# Name : Md.Rafiuzzaman Khan # ID : 011161017 # Students Result Data student_info = { "Md. Hasan": 92, "Mehrub Hossain": 20, "Md.Rafiuzzaman Khan": 81, "Samiul Ahmed": 67, "Pranto Shikdar": 56, "Nusrat Jahan": 38, "Hasibul Haque": 75, "Abir Hasan": 66, "Tamanna Afroz": 30, "Mobassher Billah": 78 } def result_insight(student_info): minimum = [key for key in student_info if all(student_info[temp] >= student_info[key] for temp in student_info)] maximum = [key for key in student_info if all(student_info[temp] <= student_info[key] for temp in student_info)] # printing result print("Highest Mark:", maximum[0], "(", student_info.get(maximum[0]), ")") print("Lowest Mark:", minimum[0], "(", student_info.get(minimum[0]), ")") lp = 0 # counter for marks bellow 40 hp = 0 # counter for marks above 80 for key in student_info: if student_info[key] > 80: hp = hp + 1 # students that achieved 80 or more if student_info[key] < 40: lp = lp + 1 # students that failed print('{}%'.format(int(round((hp / len(student_info) * 100)))), "students achieved 80 or more") print('{}%'.format(int(round((lp / len(student_info) * 100)))), "students are failed") print("Output:") result_insight(student_info)
84c109154914f003b7e45be2c2723a4a4e21c952
OrlovaNV/learn-homework-2
/2_files.py
1,185
3.9375
4
""" Домашнее задание №2 Работа с файлами 1. Скачайте файл по ссылке https://www.dropbox.com/s/sipsmqpw1gwzd37/referat.txt?dl=0 2. Прочитайте содержимое файла в перменную, подсчитайте длинну получившейся строки 3. Подсчитайте количество слов в тексте 4. Замените точки в тексте на восклицательные знаки 5. Сохраните результат в файл referat2.txt """ from idlelib.replace import replace def main(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ with open('referat.txt', 'r', encoding='utf-8') as f: content = f.read() print(content) Letters = len(content.upper()) word = len(content.split()) print(f"Букв в строке: {Letters}") print(f'Слов в строке: {word}') change = content.replace('.', '!') print(change) if __name__ == "__main__": main()
8ccf9ed5fa5853951c3aae5a44d3286d8fd83076
gachikuku/simple_programming_python
/elementary/elementary9.py
898
4.1875
4
#!/usr/bin/env python3 """ Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed. It counts only as one try if they input the same number multipletimes consecutively. """ from random import randint random_number = randint(1, 10) tries = [] user_number = int(input("Guess : ")); tries.append(user_number) while user_number != random_number: if user_number > random_number: user_number = int(input("Too big, guess again : ")) tries.append(user_number) else: user_number = int(input("Too small, guess again : ")) tries.append(user_number) #'It counts only as one try if they input the same number'. print("Attempt #{}".format(len(list(dict.fromkeys(tries)))))
e3c80f54458d9a5a4d3834d20ac75ce87f5e049c
MaZdan6/workspacePython-InzynieriaOprogramowania
/Python_lab/lab_09/zad1_T1.py
1,052
3.890625
4
from Python_lab.lab_09.zad1 import Bibltioteka '''' #input numberOfBooks=5; listOfBooks=[]; tuple0=("Chatka Puchatka" , "Alan A . Milne" , 2014 , (2014 , 4, 10)); tuple1=("Quo Vadis" , "Henryk Sienkiewicz" , 2010 , (2014 , 1 , 15)); tuple2=("Chatka Puchatka" , "Alan A . Milne" , 1998 , (2013 , 12 , 31)); tuple3=("Pan Tadeusz" , "Adam Mickiewicz" , 2003 , (2012 , 1, 1)); tuple4=("Quo Vadis" , "Henryk Sienkiewicz" , 2010 , (2014 , 1 , 15)); listOfBooks.append(tuple0); listOfBooks.append(tuple1); listOfBooks.append(tuple2); listOfBooks.append(tuple3); listOfBooks.append(tuple4); dateTuple=(2013 , 12 , 31); biblioteka = Bibltioteka(3); listaDanychWyjsciowych=[]; for krotka in listOfBooks: # Wywolywanie odpowiednich funkcji output =biblioteka.dodaj_egzemplarz_ksiazki(krotka[0], krotka[1], krotka[2],krotka[3]) listaDanychWyjsciowych.append(output); for output in listaDanychWyjsciowych: print(output); ''' ''' #Wypisanie danych wejściowych do konsoli print("numberOfBooks: ", numberOfBooks); #print(book); for book in listOfBooks: print(book); print("dateTuple: ", dateTuple) ''' #Test
4fc021edcc67f6c2f9e019c925cde36e77c0f067
BugChef/yandex_alghoritms
/sprint5/binary_search_tree.py
479
3.6875
4
class Node: def __init__(self, value, left=None, right=None): self.value = value self.right = right self.left = left def solution(root: Node) -> bool: stack = [] prev = None while root or stack: while root: stack.append(root) root = root.left root = stack.pop(-1) if prev and root.value <= prev.value: return False prev = root root = root.right return True
64e29c11d950e9f9f6907e35c67a596a0e64c090
tcheung99/ML_Projects
/a3_mod.py
4,787
3.765625
4
import autograd.numpy as np from autograd import value_and_grad def forward_pass(W1, W2, W3, b1, b2, b3, x): """ forward-pass for an fully connected neural network with 2 hidden layers of M neurons Inputs: W1 : (M, 784) weights of first (hidden) layer W2 : (M, M) weights of second (hidden) layer W3 : (10, M) weights of third (output) layer b1 : (M, 1) biases of first (hidden) layer b2 : (M, 1) biases of second (hidden) layer b3 : (10, 1) biases of third (output) layer x : (N, 784) training inputs Outputs: Fhat : (N, 10) output of the neural network at training inputs """ H1 = np.maximum(0, np.dot(x, W1.T) + b1.T) # layer 1 neurons with ReLU activation, shape (N, M) H2 = np.maximum(0, np.dot(H1, W2.T) + b2.T) # layer 2 neurons with ReLU activation, shape (N, M) Fhat = np.dot(H2, W3.T) + b3.T # layer 3 (output) neurons with linear activation, shape (N, 10) # Implement a stable log-softmax activation function at the ouput layer # Compute max of each row a = np.ones(np.shape(Fhat))*np.expand_dims(np.amax(Fhat, axis = 1), axis = 1) # a is typically max of g ; make to the same shape as Fhat log_sum_exp = np.ones(np.shape(Fhat))*np.expand_dims(np.log(np.sum(np.exp(np.subtract(Fhat, a)), axis = 1)), axis = 1) # Compute using logSumExp trick # Element-wise subtraction Fhat = np.subtract(np.subtract(Fhat,a),log_sum_exp) return Fhat def negative_log_likelihood(W1, W2, W3, b1, b2, b3, x, y): """ computes the negative log likelihood of the model `forward_pass` Inputs: W1, W2, W3, b1, b2, b3, x : same as `forward_pass` y : (N, 10) training responses Outputs: nll : negative log likelihood """ Fhat = forward_pass(W1, W2, W3, b1, b2, b3, x) # ######## # Note that this function assumes a Gaussian likelihood (with variance 1) # You must modify this function to consider a categorical (generalized Bernoulli) likelihood # ######## # nll = 0.5*np.sum(np.square(Fhat - y)) + 0.5*y.size*np.log(2.*np.pi) # Gaussian likelihood (argmaxlogPr(y|X,w,sigma^2)) # We wish to consider multi-class classification. Use categoical distribution (gen. Bernoulli distribution for K=10 categories) nll = np.sum(np.sum(np.multiply(y , Fhat), axis = 0)[:, np.newaxis], axis = 0) # Sum across K classes first, then sum across N return nll nll_gradients = value_and_grad(negative_log_likelihood, argnum=[0,1,2,3,4,5]) """ returns the output of `negative_log_likelihood` as well as the gradient of the output with respect to all weights and biases Inputs: same as negative_log_likelihood (W1, W2, W3, b1, b2, b3, x, y) Outputs: (nll, (W1_grad, W2_grad, W3_grad, b1_grad, b2_grad, b3_grad)) nll : output of `negative_log_likelihood` W1_grad : (M, 784) gradient of the nll with respect to the weights of first (hidden) layer W2_grad : (M, M) gradient of the nll with respect to the weights of second (hidden) layer W3_grad : (10, M) gradient of the nll with respect to the weights of third (output) layer b1_grad : (M, 1) gradient of the nll with respect to the biases of first (hidden) layer b2_grad : (M, 1) gradient of the nll with respect to the biases of second (hidden) layer b3_grad : (10, 1) gradient of the nll with respect to the biases of third (output) layer """ def run_example(): """ This example demonstrates computation of the negative log likelihood (nll) as well as the gradient of the nll with respect to all weights and biases of the neural network. We will use 50 neurons per hidden layer and will initialize all weights and biases to zero. """ # load the MNIST_small dataset from data_utils import load_dataset x_train, x_valid, x_test, y_train, y_valid, y_test = load_dataset('mnist_small') # initialize the weights and biases of the network M = 50 # 50 neurons per hidden layer W1 = np.zeros((M, 784)) # weights of first (hidden) layer W2 = np.zeros((M, M)) # weights of second (hidden) layer W3 = np.zeros((10, M)) # weights of third (output) layer b1 = np.zeros((M, 1)) # biases of first (hidden) layer b2 = np.zeros((M, 1)) # biases of second (hidden) layer b3 = np.zeros((10, 1)) # biases of third (output) layer # considering the first 250 points in the training set, # compute the negative log likelihood and its gradients (nll, (W1_grad, W2_grad, W3_grad, b1_grad, b2_grad, b3_grad)) = \ nll_gradients(W1, W2, W3, b1, b2, b3, x_train[:250], y_train[:250]) print("negative log likelihood: %.5f" % nll) if __name__ == "__main__": run_example()
9bc55c95ba9cf0d9bae78c97428cfd59245ec553
AnzhelikaD/PythonLabs
/Davidenko_5_14.py
652
4.0625
4
"""Дано действительное x . Вычислить приближенное значение бесконечной суммы""" def infSum(x, exp): elem = x step = 1 sumElems = elem if abs(elem) > exp else 0 while abs(elem) > exp: step += 2 elem = x**step / step sumElems += elem return sumElems x = float(input("Введите действительное число x ")) exp = float(input("Введите действительное число exp ")) if abs(x) >= 1: print("Ошибка: |x| >= 1") elif exp < 0: print("Ошибка: exp < 0") else: print(infSum(x, exp))
3eb195847354ecf515cab8db61df7145945cfa1e
KJabbusch/Codecademy-Practice
/sparse_search.py
1,641
4.0625
4
def sparse_search(data, search_val): # Printing out the data set print("Data: " + str(data)) # Printing out what we are looking for print("Search Value: " + str(search_val)) # Create two variables. first being the start index and last being end index. first = 0 last = len(data) - 1 # Continuous loop until condition is met while first <= last: # Determining the middle index mid = (first+last)//2 # If nothing exists at middle index, we check to the left and right # moving one step at a time if not data[mid]: left = mid - 1 right = mid + 1 # Continuously looking left and right until a value found while True: # Making sure we stop when we reach the upper and lower bounds of list if left < first and right > last: print("{0} is not in the dataset.".format(search_val)) return # If we find any value on right side, establish new mid elif right <= last and data[right]: mid = right break # If we find any value on left side, establish new mid elif left >= first and data[left]: mid = left break left -= 1 right += 1 # Once we find data, we check if the data is what we are looking for if data[mid] == search_val: print("{0} is found at position {1}".format(search_val, mid)) return # Cut off the right side of list elif search_val < data[mid]: last = mid - 1 # Cut off the left side of list elif search_val > data[mid]: first = mid + 1 print("{0} is not in the dataset".format(search_val))
b48bfad4893acf4259175f369c6dce3dced850b4
Stefanh18/python_projects
/mimir/assingnment_10/q3.py
546
4.1875
4
# Your functions should appear here def triple_list(a_list): outcome = a_list * 3 return outcome def populate_list(a_list): new = True while new == True: user_input = input("Enter value to be added to list: ") if user_input.lower() == "exit": new = False else: a_list.append(user_input) return user_input # Main program starts here - DO NOT change it. initial_list = [] populate_list(initial_list) new_list = triple_list(initial_list) for items in new_list: print(items)
2b1240ad035e5d8fbd80da15afc6fd6d967a02fa
nwyche9/my_converters
/Converters.py
4,769
4.3125
4
#Main screen #Currency converter def currency(): user_choice = input("Dollars to Euros? choose D. \nDollars to Pounds? choose P. \nDollars to Chinese Yuan? choose C. \nDollars to Japanese Yen? choose J. \nExit? choose E. ") while user_choice != "E".lower(): if user_choice == "D".lower(): Dollars_to_Euros() user_choice = input("Do you want to convert again? ") elif user_choice == "P".lower(): Dollars_to_Pounds() user_choice = input("Do you want to convert again? ") elif user_choice == "C".lower(): Dollars_to_Chinese() user_choice = input("Do you want to convert again? ") elif user_choice == "J".lower(): Dollars_to_Japanese() user_choice = input("Do you want to convert again? ") else: user_choice = ("Do you want to try something else? ") print("Thanks for using my converter!!") def Dollars_to_Euros(): d = float(eval(input("Please enter the current dollar amount :\n"))) formula = d/1.18 print("%d Amount in Dollars, results in %d Euros" %(d,formula)) def Dollars_to_Pounds(): d = float(eval(input("Please enter the current dollar amount :\n"))) formula = d/1.35 print("%d Amount in Dollars, results in %d Pounds" %(d,formula)) def Dollars_to_Chinese(): d = float(eval(input("Please enter the current dollar amount :\n"))) formula = d/0.16 print("%d Amount in Dollars, results in %d Yuan" %(d,formula)) def Dollars_to_Japanese(): d = float(eval(input("Please enter the current dollar amount :\n"))) formula = d/0.0091 print("%d Amount in Dollars, results in %d Yen" %(d,formula)) currency() #Temperature Converter def temperature(): user_choice = input("If you want to convert Celsius to Fahrenehit, choose C. \nIf you want to convert Fahrenheit to Celsius choose F. \nIf you want to quit, choose Q ") while user_choice != "q": if user_choice == "c": # call the Celsius to Fahrenheit function, ask if they want to repeat calculation Celsius_to_Fahrenheit() user_choice = input("Do you want to convert again? ") elif user_choice == "f": # call the Fahrenheit to Celsius function, ask if the user wants to repeat calculation Fahrenheit_to_Celsius() user_choice = input("Do you want to convert again? ") elif user_choice !="c" and user_choice !="f": # invalid character user_choice = input("Please enter a valid character ") else: # ask if they wish to repeat calculation user_choice = ("Do you want to try again? ") print("Thanks and now exiting this converter!!") def Celsius_to_Fahrenheit(): c = eval(input("Please enter the current temperature in Celsius :\n")) f = (9/5) * c + 32 print("%d degrees in Celsius result in %d degrees Fahrenheit" %(c,f)) def Fahrenheit_to_Celsius(): f = eval(input("Please enter the current temperature in Fahrenheit :\n")) c = (f-32) * 5/9 print("%d degrees in Fahrenehit result in %d degrees Celsius" %(f,c)) temperature() #units converter def measurements(): user_choice = input("What would you like to convert?\n Ounces to Grams, choose O\n Miles to Kilometers, choose M\n Feet to Meters, choose A\n If you are done, choose E ") while user_choice != "E".lower(): if user_choice == "O".lower(): #Ounces to grams Ounces_to_Grams() user_choice = input("Do you want to convert again? ") elif user_choice == "M".lower(): #Miles to kilometers Miles_to_Kilometers() user_choice = input("Do you want to convert again? ") elif user_choice == "A".lower(): #Feet to meters Feet_to_Meters() user_choice = input("Do you want to convert again? ") else: user_choice = ("Do you want to try again? ") print("Thanks and now exiting this converter!!") def Ounces_to_Grams(): g = eval(input("Please enter the amount of ounces :\n")) h = g * 28.3495 print("%d Ounces results in %d Grams" %(g,h)) def Miles_to_Kilometers(): g = eval(input("Please enter the amount of miles :\n")) h = g * 1.60934 print("%d Miles results in %d Kilometers" %(g,h)) def Feet_to_Meters(): g = eval(input("Please enter the amount of feet :\n")) h = g * 0.3048 print("%d Feet results in %d Meters" %(g,h)) measurements()
4ed2d9c6fc8f1bf2aa37fc735e97879f767f49cc
MasatakeShirai/Python
/chap8/8-1.py
1,078
4.40625
4
#条件分岐 #if-then-else a=1 if a>0: print(True) else: print(False) #else-ifパート # 複数条件を評価する場合は,elifを使う n=5 if n<0: print('n<0') elif n==0: print('n==0') elif n==5: print('n==5') elif n<10: print('n<10') else: print('else') #条件式 #無や負に相当するものはfalse,1や実体の存在するものはtrueになる print(bool('')) print(bool('python')) print(bool(1)) print(bool(0)) if '': print('HELLO') if 'python': print('hello') #論理演算子 #and,or,notがあり,優先度はnot>and>or. # orは先にTrueの評価が行われた時点でTrueを返す. # andは先にfalseの評価が行われた時点でfalseを返す. print(bool('' or 0 or 1 or False or [])) print(bool(1 and [1,2,3] and 0 and True and 'python')) #三項演算子 # 構文:成功した時の値 if 条件式 else 失敗した時の値 #用いない場合 py='python' if py=='python': ans='Hello.py' else: ans='goodby' print(ans) #用いる場合 print('Hello.py' if py=='python' else 'goodby')
faa145a8d07f0e3e0b84b31503ef3a931b85f52e
afeefebrahim/anand-python
/chap2/ex5.py
221
4.1875
4
#a function name 'reverse' to reverse a list def reverse (num): rev = [] i=0 while i < len(num): rev.insert(i,num.pop()) i=i+1 return rev print reverse([1,2,3,4,5]) print reverse(reverse([1,2,3,4,5]))
0cb7915d02a35fc6a2e3df7267ac7fc8d21de198
Divya9j/testyp
/MultiDimLists/sum2D.py
232
3.546875
4
def sum2D(dlist): tot = 0 for i in range(0,len(dlist)): for j in range(0,len(dlist[i])): #print(dlist[i][j]) tot = tot + dlist[i][j]; return tot print(sum2D([[1, 2, 3, 4], [1, 2, 3, 4]]))
c7c8ab89a7b793934c71a36536cb5c349050004c
OwnNightmare/CookBook
/resultant.py
1,993
3.515625
4
class File: new_str_sign = '\n' def __init__(self, name, path='sort_in_file/'): self.content = '' self.length = 0 self.name = name self.path = path def reading(self, mode='r', buffering=1, encoding='utf8'): with open(self.path + self.name, mode, buffering, encoding) as file: for line in file: self.content += f"{line.rstrip()}{File.new_str_sign}" self.length += 1 self.content = self.content.rstrip() def __gt__(self, other): return self.length > other.length def __lt__(self, other): return self.length < other.length def __eq__(self, other): return self.length == other.length def assign_files(): first_file = File('story_one.txt') second_file = File('story_two.txt') third_file = File('story_three.txt') files = [third_file, first_file, second_file] return files def read_and_write(read_from, write_to, mode='a', buffering=2, encoding='utf8'): if type(read_from) == list: for file in read_from: file.reading() for file in sorted(read_from): with open(write_to, mode, buffering, encoding) as writing_in: writing_in.write(file.name + '\n') writing_in.write(str(file.length) + '\n') writing_in.write(file.content + '\n') print(f'file {writing_in.name} was written') elif type(read_from) == File: read_from.reading() with open(write_to, mode, buffering, encoding) as writing_in: writing_in.write(read_from.name + '\n') writing_in.write(str(read_from.length) + '\n') writing_in.write(read_from.content + '\n') print(f'file {writing_in.name} was written') def clear_file(path, mode='w'): with open(path, mode) as cleared_file: cleared_file.write('') clear_file('sort_in_file/United.txt') read_and_write(assign_files(), 'sort_in_file/United.txt')
8820a11caf563da68ef1c587730123a2f4d6c357
lwoiceshyn/leetcode
/longest-common-subsequence.py
1,775
4.15625
4
''' https://www.hackerrank.com/challenges/dynamic-programming-classics-the-longest-common-subsequence/problem ''' ''' The recursive formula for this problem is as follows. Define the two inputs as sequence a of length n, and sequence b of length m. There are three potential cases when examining these two sequences. 1) The sequences end in the same value. 2) The sequences end in a different value. 3) One of the two sequences is empty. In the first case, the LCS is the simply the shared element plus the LCS of the two sequences minus their last element. LCS = LCS(a[1...n-1], b[1...m-1]) + a[-1] In the second case, the LCS is either LCS(a[1...n-1], b[1...m]) or LCS(a[1...n], b[1...m-1]), whichever of these two sequences is longer. The last case is the base case, in which the LCS of the two sequences is zero, since there is no intersection. The following is the top-down solution using recursion plus memoization. Since the problem on hackerrank is using a list of integers for some reason, I use a helper function to map the sequences into strings so they are hashable and thus usable as keys for the memo dictionary. Time Complexity: O(m*n) Space Complexity: O(m*n) ''' memo = {} def strmap(a,b): return(''.join(map(str,a)), ''.join(map(str,b))) def longestCommonSubsequence(a, b): if len(a) == 0 or len(b) == 0: return [] if strmap(a,b) not in memo: if a[-1] == b[-1]: memo[strmap(a,b)] = longestCommonSubsequence(a[:-1], b[:-1]) + [a[-1]] else: x = longestCommonSubsequence(a[:-1],b) y = longestCommonSubsequence(a, b[:-1]) if len(x) > len(y): memo[strmap(a,b)] = x else: memo[strmap(a,b)] = y return memo[strmap(a,b)]
316bb890e07a121f1f52cded921bd348252bd526
kokje/insight_challenge
/src/median.py
1,426
3.9375
4
import sys uniquewordcounts = [0] * 140 def readTweets(inputfile, outputfile): """ Read tweets and use a hashmap with entries as count of unique words to determine median """ try: f = open(inputfile, 'r') o = open(outputfile, 'w') count = 0 for tweet in f: #Read tweets and use a set to get count of unique words words = set(tweet.split()) numuniquewords = len(words) #Add this count to the hashtable uniquewordcounts[numuniquewords] += 1 #Keep a count of number of tweets so far count += 1 getMedian(count, o) except IOError: print "Unexpected error" f.close() o.close def getMedian(count, o): """ Compute median value from the frequency hashtable for total number of tweets n """ sum = 0 medianval = int(count / 2) + 1 # Need to know previous non zero value when n is even prevval = 0 for i in range(1, 20): sum += uniquewordcounts[i] # If n is even, median is avg of n/2 and n/2 + 1 if count % 2 == 0: if sum >= medianval: if uniquewordcounts[i] == 1: median = float(prevval + i) / 2 o.write("%.2f\n" % median) break else: o.write("%.2f\n" % i) break if uniquewordcounts[i] != 0: prevval = i # If n is odd, median is n/2 + 1 else: if sum >= medianval: o.write("%.2f\n" % i) break if __name__ == '__main__': if len(sys.argv) != 3: print "Insufficient input parameters" readTweets(sys.argv[1],sys.argv[2])
2c57d04757f3e042dd12eb733f710fca4d4674a9
shen-huang/selfteaching-python-camp
/exercises/1901020006/d07/mymodule/stats_word.py
2,336
3.890625
4
# 封装统计英文单词词频的函数 def stats_text_en(text): elements = text.split() words = [] symbols = ',.*-!' for element in elements: for symbol in symbols: element = element.replace(symbol,'') # master # 用 str 类型的 isascii 方法判断是否是英文单词 if len(element) and element.isascii: #======= if len(element): # master words.append(element) counter = {} word_set = set(words) for word in word_set: counter[word] = words.count(word) return sorted(counter.items(),key=lambda x:x[1],reverse=True) # 统计参数中每个中文汉字出现的次数 def stats_text_cn(text): cn_characters = [] for character in text: if'u4e00' <= character <= '\u9fff': cn_characters.append(character) counter = {} cn_character_set = set(cn_characters) for character in cn_character_set: counter[character] = character.count(character) return sorted(counter.items(),key=lambda x:x[1],reverse=True) en_text = ''' The Zen of Python, by Tim Peters ''' cn_text = ''' 优美胜于丑陋 ''' #搜索 __name__ ==__main__ # 一般情况下在文件内 测试 代码的事后以下面的形式进行 if __name__ =='__main__': en_result = stats_text_en(en_text) cn_result = stats_text_cn(cn_text) print('统计参数中每个英文单词出现的次数 ==>\n', en_result) print('统计参数中每个英文单词出现的次数 ==>\n', cn_result) # master def stats_text(text): ''' 合并 英文词频 和 中文词频 的结果 ''' return stats_text_en(text) + stats_text_cn(text) # def stats_text_cn(text): #定义函数,参数text可变 setb=set(text) #设定集合set,并把集合元素赋值给setb d = [] #设定列表 for char in setb: #char从集合setb中取值 if char >= u'\u4e00' and char <= u'\u9fa5': #如果c是在u4e00 到u9fa5之间(汉字) count=text.count(char) #统计每个汉字的数量 n=(char,count) d.append(n) #将y加到x列表中 x=sorted(d,key=lambda kv:kv[1],reverse=True) #按重复次数,由大到小排列 return x #print('\n按照出现次数降序输出所有汉字:\n') #print(x) # master
75698837e7212a6a5ad86da3db319d291fc2647e
Robert0202/Atividades
/Algoritmo_Logica/Lista_For/q10.py
346
4.125
4
media = 0 for x in range (1, 31): n = int(input(" informe a nota final: ")) media += n if x == 0 : maior = menor = n else: if maior <n: maior = n elif menor > n: menor = n media = media / 30 print(" media da turma ", media) print(" maior nota ", maior) print(" menor nota ", menor)
39086fa0bc9b7fcc75c46ad7e263ac523a18680a
16044037/secu2002_-16044037-
/lab04/strings.py
1,399
4.15625
4
#Task 1 #Example 1 of the string mysep.join(mylist) #Define my list with a list of colours mylist = ['blue', 'pink', 'purple', 'red', 'green'] #Define a separator as a space mysep = ' ' print 'should return: blue pink purple red green' print 'is returning', mysep.join(mylist) print '-------------' #Example 2 of the string mysep.join(mylist) #Define my list with a list of foods mylist = ['crisps','chocolate','biscuits','cereal','soup'] #Define a separator as a space mysep = ' ' print 'should return: crisps chocolate biscuits cereal soup' print 'is returning', mysep.join(mylist) print '-------------' #MYJOIN: joins together mylist and mysep using i and mystr #input: list (my_list) and a separator (mysep) #output: mylist and mysep joined together my_list = ['a','b','c','d'] mysep = ' ' print mysep.join(my_list) print '-------------' def my_join(my_list,mysep): mystr = '' for i in my_list: mystr += i+mysep mystr=mystr[:-1] return mystr mysep = '***' print my_join(my_list,mysep) print '-------------' #Task 2 #SORT_STRING: alphabetically sort a string #input: a string (mystr) and a separator (mysep) #output: an alphabetically sorted string of letters mystr = ['b','e','a','d','c'] def sort_string(mystr): mysep = ' ' L = list(mystr) L.sort() mystr = mysep.join(L) return mystr print sort_string(mystr) print '-------------'
9cc5867beb9e1182b0e8ad2d8c318246a6dc2881
rnaster/python-study
/closure.py
876
3.53125
4
""" closure the following class and two functions are same. """ class Average1: def __init__(self): self.series = [] def __call__(self, new_value): self.series.append(new_value) return sum(self.series) / len(self.series) def average2(): series = [] def average(new_value): series.append(new_value) return sum(series) / len(series) return average def average3(): total = 0 count = 0 def average(new_value): nonlocal total, count total += new_value count += 1 return total / count return average if __name__ == '__main__': avg1 = Average1() avg2 = average2() avg3 = average3() import random for _ in range(5): num = random.randint(0, 10) print('avg1: %.2f, avg2: %.2f, avg3: %.2f' % (avg1(num), avg2(num), avg3(num)))
ddc3d8778a07f2223a25b8adfa49867f5f947cc6
VanceJarwell/pythonActivities
/CH0708/Exercise1.py
164
4.1875
4
def backwards(word): index = len(word) - 1 while index >= 0: print(word[index]) index -= 1 word = input("Enter a word: ") backwards(word)
56ec7f9f799fe13f505baca20636fd205e261039
lima-BEAN/python-workbook
/programming-exercises/ch2/stock-transaction.py
2,110
3.65625
4
## Last month Joe purchased some stock in Acme Software Inc. Here are the ## details of the purchase: ## - The number of shares that Joe purchased was 2,000 ## - When Joe purchased the stock, he paid $40.00 per share. ## - Joe paid his stockbroker a commission that amounted to 3 percent of the ## amount he paid for the stock ## Two weeks later Joe sold the stock. Here are the details of the sale: ## - The number of shares that Joe sold was 2,000 ## - He sold the stock for $42.75 per share ## - He paid his stockbroker another commission that amounted to 3 percent ## of the amount he received for the stock. ## Write a program that displays the following info: ## - Amount of money Joe paid for the stock ## - Amount of commission Joe paid his broker when he bought the stock ## - Amount that Joe sold the stock for ## - Amount of commission Joe paid his broker when he sold the stock ## - Display the amount of money that Joe had left when he sold the stock ## and paid his broker (both times). If this amount is positive, then ## Joe made a profit . If the amount is negative, then Joe lost his money # Shares bought purchased_shares = 2000 purchased_dollar_per_share = 40 total_stock_purchase = (purchased_shares * purchased_dollar_per_share) purchased_broker_commission = total_stock_purchase * 0.03 total_purchase = total_stock_purchase + purchased_broker_commission # Shares sold sold_shares = 2000 sold_dollar_per_share = 42.75 total_stock_sale = (sold_shares * sold_dollar_per_share) sold_broker_commission = total_stock_sale * 0.03 total_sale = total_stock_sale - sold_broker_commission # Profit/Loss profit_or_loss = total_sale - (total_purchase) # Display Stock Transaction print("Cost for", purchased_shares, "shares at", purchased_dollar_per_share," per share:", total_stock_purchase, "\n\tBroker's commission:", purchased_broker_commission, "\nSold", sold_shares, "shares at", sold_dollar_per_share, "per share. For a total sale of:", total_stock_sale, "\n\tBroker's commission:", sold_broker_commission, "\nJoe made:", format(profit_or_loss, '.2f'))
c4dbde0f8ef90f7a6adbf42804f2c0ea13726541
miaojia527/python
/cipher.py
426
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def translationCipher(msg,key): result = [""]*key for i in range(key):#把每一列元素按照顺序相加组成新的字符序列 pointer = i while i<len(msg): result[pointer]+=msg[i] i+=key return ''.join(result) def main(): print translationCipher("hello,world",4)#以4个字母为一行进行换位加密 if __name__=="__main__": main()
b444bb4e43efc2e4f97b34272788f825827cbc4b
DanyHe/test
/条件判断.py
1,790
3.640625
4
#if-elif-else #С1.7580.5kgBMIʽسߵƽСBMIָBMIָ #18.5 #318.5-25 #25-28 #28-32 #32ط height = 1.75 weight =83 BMI =weight/(height*height) if BMI > 32: print('ط') elif BMI > 28: print('') elif BMI > 25: print('') elif BMI >18.5: print('') else: print('') #ѭ names = ['jack','jones','lily'] for name in names: print(name) sum = 0 for x in range(101): sum = sum + x print(sum) #printforѭУforѭУôӡÿӵĽ #while sum = 0 n =99 while n >0: sum =sum +n n = n -2 print(sum) #printwhileѭͬfor L = ['Bart', 'Lisa', 'Adam'] for x in L: print('hello,%s!'%x) #break ǰ˳ѭ #continue ǰѭֱӿʼһֵѭҪifʹ #dict dictionary *,*,* key-value ÿռʱ dictkeyDzɱ󡣸keyvalueĴ洢λãͨkeyλõ㷨Ϊϣ㷨Hash; #ҪkeyڵĴ֣1.tom in d ture/false 2.d.get('tom',-1) ĬϷnoneҲԶ巵-1 #ɾd.pop(key)ӦvalueҲdictɾ #set([list]),ظļϣظݱԶˣaddkeyظӣЧremovekey #setdictΨһͬľsetûд洢ӦvalueͬöⷽҲıݣֻ½һ󷵻ء
de7c96a7f9acd86619dc8f3c2a0b07103ad9e410
ghwlchlaks/old_otter
/appFolder/wordcount_search1.py
785
3.515625
4
from pyspark import SparkContext import argparse #spark context sc = SparkContext() #make & receved outer argument parser = argparse.ArgumentParser() parser.add_argument("--file", help=": file name") parser.add_argument("--user", help=": user name") parser.add_argument("--word", help=": search word name") filename = parser.parse_args().file username = parser.parse_args().user search = parser.parse_args().word #read file route text_file = sc.textFile("hdfs:///"+username+"/"+ filename) #word search and count counts = text_file.flatMap(lambda line: line.split(" "))\ .filter(lambda i : i == search)\ .map(lambda word: (word, 1)) \ .reduceByKey(lambda a, b: a + b) #print wordcount print counts.collect()
8dca8295b70ee195f727e222699ef9a3fcd76831
prasant73/python
/programs/dictionaries.py
716
3.96875
4
from inputs import list_input def add_list_to_dict(l1,l2): d = {} # for i in range(len(l2)): # d[l1[i]] = l2[i] # print(i) # for i in range(i+1, len(l1)): # d[l1[i]] = 0 # return d for i in range(len(l1)): if i < len(l2): d[l1[i]] = l2[i] else: d[l1[i]] = 0 return d def make_dict_by_2_list(l1, l2): if len(l1) > len(l2): return(add_list_to_dict(l1, l2)) else: return(add_list_to_dict(l2, l1)) # l1 = ['a','b','c','d', 'e', 'f'] # l2 = [1,2,3,4] l1 = list_input(int(input("enter the length you want : "))) l2 = list_input(int(input("enter the length you want : "))) print(make_dict_by_2_list(l1, l2))
40c280d22825da95cc72e7d18dfb239c7552109b
apurbahasan1994/Algo
/coin_change.py
836
3.625
4
coin=[1,2,5] sum=5 n=3 # def coin_chnage(sum,n): # if n==0 and sum==0: # return 1 # if n == 0: # return 0 # if sum == 0: # return 1 # # if coin[n-1]<=sum: # return coin_change(sum,n-1)+coin_chnage(sum-coin[n-1],n) # else: # return coin_chnage(sum,n-1) # # print(coin_chnage(sum,n)) def coin_change(sum,n): t=[[0]*(sum+1) for _ in range(n+1)] for i in range(n+1): for j in range(sum+1): if i==0: t[i][j]=0 if j==0: t[i][j]=1 for i in range(1,n+1): for j in range(1,sum+1): if coin[i-1]<=j: t[i][j]=t[i-1][j]+t[i][j-coin[i-1]] else: t[i][j]=t[i-1][j] for r in t: print(r) return (t[n][sum]) print(coin_change(sum,n))
ab3d04960496ed1abe06ade6914bc72af749bd9f
rishcodelib/PythonPro-Bootcamp2021
/Day1/main.py
249
4.3125
4
# Band Name Generator # Project 1 ("String Concatenation in Python") print("Welcome to the Band name Generator") city = input("Enter city name?") petname = input("enter your petname ") print(" Your Band Name Could be: " + city + " " + petname)
e1f7604c2af82efc8b01127deb2cf4e454a25fa0
scikit-learn-contrib/imbalanced-learn
/examples/over-sampling/plot_shrinkage_effect.py
3,929
4
4
""" ====================================================== Effect of the shrinkage factor in random over-sampling ====================================================== This example shows the effect of the shrinkage factor used to generate the smoothed bootstrap using the :class:`~imblearn.over_sampling.RandomOverSampler`. """ # Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com> # License: MIT # %% print(__doc__) import seaborn as sns sns.set_context("poster") # %% # First, we will generate a toy classification dataset with only few samples. # The ratio between the classes will be imbalanced. from collections import Counter from sklearn.datasets import make_classification X, y = make_classification( n_samples=100, n_features=2, n_redundant=0, weights=[0.1, 0.9], random_state=0, ) Counter(y) # %% import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(7, 7)) scatter = plt.scatter(X[:, 0], X[:, 1], c=y, alpha=0.4) class_legend = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes") ax.add_artist(class_legend) ax.set_xlabel("Feature #1") _ = ax.set_ylabel("Feature #2") plt.tight_layout() # %% # Now, we will use a :class:`~imblearn.over_sampling.RandomOverSampler` to # generate a bootstrap for the minority class with as many samples as in the # majority class. from imblearn.over_sampling import RandomOverSampler sampler = RandomOverSampler(random_state=0) X_res, y_res = sampler.fit_resample(X, y) Counter(y_res) # %% fig, ax = plt.subplots(figsize=(7, 7)) scatter = plt.scatter(X_res[:, 0], X_res[:, 1], c=y_res, alpha=0.4) class_legend = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes") ax.add_artist(class_legend) ax.set_xlabel("Feature #1") _ = ax.set_ylabel("Feature #2") plt.tight_layout() # %% # We observe that the minority samples are less transparent than the samples # from the majority class. Indeed, it is due to the fact that these samples # of the minority class are repeated during the bootstrap generation. # # We can set `shrinkage` to a floating value to add a small perturbation to the # samples created and therefore create a smoothed bootstrap. sampler = RandomOverSampler(shrinkage=1, random_state=0) X_res, y_res = sampler.fit_resample(X, y) Counter(y_res) # %% fig, ax = plt.subplots(figsize=(7, 7)) scatter = plt.scatter(X_res[:, 0], X_res[:, 1], c=y_res, alpha=0.4) class_legend = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes") ax.add_artist(class_legend) ax.set_xlabel("Feature #1") _ = ax.set_ylabel("Feature #2") plt.tight_layout() # %% # In this case, we see that the samples in the minority class are not # overlapping anymore due to the added noise. # # The parameter `shrinkage` allows to add more or less perturbation. Let's # add more perturbation when generating the smoothed bootstrap. sampler = RandomOverSampler(shrinkage=3, random_state=0) X_res, y_res = sampler.fit_resample(X, y) Counter(y_res) # %% fig, ax = plt.subplots(figsize=(7, 7)) scatter = plt.scatter(X_res[:, 0], X_res[:, 1], c=y_res, alpha=0.4) class_legend = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes") ax.add_artist(class_legend) ax.set_xlabel("Feature #1") _ = ax.set_ylabel("Feature #2") plt.tight_layout() # %% # Increasing the value of `shrinkage` will disperse the new samples. Forcing # the shrinkage to 0 will be equivalent to generating a normal bootstrap. sampler = RandomOverSampler(shrinkage=0, random_state=0) X_res, y_res = sampler.fit_resample(X, y) Counter(y_res) # %% fig, ax = plt.subplots(figsize=(7, 7)) scatter = plt.scatter(X_res[:, 0], X_res[:, 1], c=y_res, alpha=0.4) class_legend = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes") ax.add_artist(class_legend) ax.set_xlabel("Feature #1") _ = ax.set_ylabel("Feature #2") plt.tight_layout() # %% # Therefore, the `shrinkage` is handy to manually tune the dispersion of the # new samples.
67dc20d09ea74741a12722ce73db8ea4f11d9935
seanloe/PythonHome
/Python_Execercises/mytest.py
2,360
3.828125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import threading,time, copy from queue import Queue class Myclass: species = 'human' def __init__(self, name, gender,age): self.name = name self.gender = gender self.age = age def run(self): print(self.name, ' is running') def eat(self, food): print(self.name, ' is eating ', food) class Man(Myclass): def fastrun(self): self.run() print('This time run very fast') #test to build a 3D matrix 4X4X3 matrix S_list=[[[x, x**2, 3*x] for x in np.random.randint(0,100,4)] for num in range(4)] def thread_job(lock, list,q): while len(list)>0: #time.sleep(1) lock.acquire() try: i = list.pop() #print(time.asctime(time.localtime()), threading.current_thread(), 'get %d'%i) q.put(i**5) except Exception as e: print("Error!",e) lock.release() def multi_thread(lock, l,q): threadlist = [] for i in range(8): thread = threading.Thread(target = thread_job, name= 'T'+str(i), args =(lock,l,q)) thread.start() threadlist.append(thread) for t in threadlist: t.join() def normal_run(lock,list,q): while len(list)>0: #time.sleep(1) lock.acquire() try: i = list.pop() #print(time.asctime(time.localtime()), threading.current_thread(), 'get %d'%i) q.put(i**5) except Exception as e: print("Error!",e) lock.release() def main(): lock = threading.Lock() a = np.arange(1,10000,1) mylist = a.tolist() mylist2 = copy.deepcopy(mylist) q = Queue() t_start = time.time() multi_thread(lock,mylist,q) t_finish = time.time() #print(threading.active_count()) #print(threading.enumerate()) print("Total thread execution time:", t_finish-t_start) result = 0 for _ in range(q.qsize()): result += q.get() print(result) print('Now normal run') t_start = time.time() normal_run(lock,mylist2,q) t_finish = time.time() result = 0 print('Now normal run execution time:',t_finish-t_start) for _ in range(q.qsize()): result += q.get() print(result) if __name__ == '__main__': main()
b22dd2f585507c90d469cfbb6fcdc71bca015f1b
LourdesOshiroIgarashi/algorithms-and-programming-1-ufms
/Lists/Lista 1/Lourdes/10.py
254
3.546875
4
lista = [] n = int(input()) for i in range(n): lista.append(int(input())) print(lista) if n % 2 == 0: elemento1 = n//2 - 1 elemento2 = n//2 print(lista[elemento1], lista[elemento2]) else: elemento = n//2 print(lista[elemento])
349e660ba3bd9db92efeb584f57e7027e8e5fe6a
pathakamaresh86/python_class_prgms
/oop_complex.py
2,546
3.6875
4
#!/usr/bin/python class complex: #constructor def __init__(self,real=0,img=0): self.real=real #object attribute self.img=img #object attribute #destructor def __del__(self): #print "Destructing self", self print def add2ComplexNo(self,c1): c3=complex() if type(c1)==int:#if isinstance(c1,int): c3.real=self.real + c1 c3.img=self.img else: c3.real=self.real + c1.real c3.img=self.img + c1.img return c3 def sub2ComplexNo(self,c1): c3=complex() c3.real=self.real - c1.real c3.img=self.img - c1.img return c3 #Operator opverloading def __add__(self,c1): c3=complex() if isinstance(c1,int): c3.real=self.real + c1 c3.img = self.img else: c3.real=self.real + c1.real c3.img=self.img + c1.img return c3 def __sub__(self,c1): c3=complex() if isinstance(c1,int): c3.real=self.real - c1 c3.img = self.img else: c3.real=self.real - c1.real c3.img=self.img - c1.img return c3 def __mul__(self,c1): c3=complex() c3.real=self.real * c1.real c3.img=self.img * c1.img return c3 def __eq__(self,c1): if self.real == c1.real and self.img == c1.img: return True return False def __gt__(self,c1): if self.real > c1.real and self.img > c1.img: return True return False def __lt__(self,c1): if self.real < c1.real and self.img < c1.img: return True return False def __ge__(self,c1): if self.real >= c1.real and self.img >= c1.img: return True return False def __le__(self,c1): if self.real <= c1.real and self.img <= c1.img: return True return False def __repr__(self): return str(self.real) + " + "+ str(self.img) + "i" def main(): c1=complex(10,8) c2=complex(3,2) print c1 + c2 print c1 + 4 print c1 - c2 print c1 - 4 print c1 * c2 print c1 > c2 print c1 < c2 print c1 >= c2 print c1 <= c2 c1=complex(10,8) c2=complex(10,8) print c1 == c2 ''' c3 = c1.add2ComplexNo(c2) print(c3) c3 = c1.add2ComplexNo(4) print(c3) c3 = c1.sub2ComplexNo(c2) print(c3) ''' if __name__=="__main__": main() ''' D:\F DATA\python_class>python oop_complex.py 13 + 10i Destructing self 13 + 10i 14 + 8i Destructing self 14 + 8i 7 + 6i Destructing self 10 + 8i Destructing self 3 + 2i Destructing self 7 + 6i ''' ''' D:\F DATA\python_class>python oop_complex.py 13 + 10i 14 + 8i 7 + 6i 6 + 8i 30 + 16i True False True False True '''
f4a9a5e7352b60dc4ad3cf4f52606730fb13e006
platform6/ga_python
/class_notes/W4/day-01/2.py
1,007
3.90625
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 6 18:03:08 2020 @author: platf """ class HR: def __init__(self): self.__name = None self.__age = None self.__address = None def __set_name(self, name): self.__name = name def __get_name(self): return self.__name def __set_age(self, age): self.__age = age def __get_age(self): return self.__age def __get_address(self): return self.__address def __set_address(self, address): self.__address = address address = property(fset= __set_address, fget= __get_address) name = property(fset= __set_name, fget= __get_name) age = property(fset= __set_age, fget= __get_age) # control read / write ability through the property attribute employee_john = HR() employee_john.name = "John" print(employee_john.name) employee_john.age = 12 print(employee_john.age) employee_john.address = "113 Main St" print(employee_john.address)
f83bb455bee33575ec2da2479fd28893e9954345
xiaogy0318/coding-exercises
/python/copy_array.py
526
3.84375
4
#"Write a function with the following specification: Input: a list. Output: a copy of the list with duplicates removed." #from array import array array1 = [] array2 = [] count_string = raw_input("Number of strings please (default is 3): ") count = 3 try: count = int(count_string) except ValueError: count = 3 for i in range(count): user_input = raw_input("Some input please: ") # or`input("Some...` array1.append(user_input) array2.append(user_input) for i in range(count): array2.append(array1[i]) print(array2)
2823e46f466450230dfb1f70ebc292d2f4b940b6
Salor69/CS01-Salor
/CS01-Max Min.py
197
3.90625
4
Num = int(input('Enter Your Loop: ')) Numtotal = [] for i in range(Num): num = int(input('Enter Your Number:')) Numtotal += [num] print(Numtotal) print(min(Numtotal)) print(max(Numtotal))
e1beaa798985f64ed3adf77bcbea76edf45295b0
consbio/trefoil
/trefoil/utilities/format.py
1,253
3.5625
4
import numpy MAX_PRECISION = 6 class PrecisionFormatter(object): """ Utility class to provide cleaner handling of decimal precision for string outputs """ def __init__(self, values, max_precision=6): """ Extract the maximum precision required to represent the precision of values. Must be <= 6 (python truncates beyond this point), and less than max_precision. If input is an instance of a numpy array, uses numpy methods instead for better efficiency. """ assert max_precision <= 6 self._precision = 0 decimal_strs = set(["{:g}".format(float(x) - int(round(x))) for x in values]) if '0' in decimal_strs: decimal_strs.remove('0') if decimal_strs: self._precision = max([len(x) for x in decimal_strs]) - 2 if max_precision is not None: self._precision = min(self._precision, max_precision) self._precision = min(self._precision, MAX_PRECISION) def format(self, value): if self._precision == 0: return str(int(round(float(value), 0))) else: return ("{:.%if}" % self._precision).format(float(value)).rstrip('0').rstrip('.')
8acf366a767976cdfd3a3fb5ea7d04eafaaf1705
Shubham8037/Project-Euler-Challenge
/Problem 1 - Multiples of 3 and 5/Problem_1.py
1,090
4.4375
4
#!/bin/python3 """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below the provided parameter value number """ def solLogic(multipleOf, actualRange): # Range is updated since problem says numbers below 10000 actualRange -= 1 # Number or terms is calculated number_of_terms = actualRange//multipleOf # Formula for Finite Arithmetic Progression sum_of_terms = (number_of_terms)*(number_of_terms+1)/2 # Sum of series is returned by multiplying the multiple to calculate its sum return int(sum_of_terms*(multipleOf)) def sumOfMultiples(number): # Calculates sum of terms up to the given range sumOf3 = solLogic(3, number) sumOf5 = solLogic(5, number) sumOf15 = solLogic(15, number) # Multiple of 15 is duplicated so 1 multiple needs to be removed final_value = sumOf3+sumOf5-sumOf15 # Finally Sum is returned return final_value if __name__ == '__main__': print(sumOfMultiples(1000))
349712a5d78871e464ccbe83605a59995e081a3d
KingGenius5/Tech-Int-Prac-Prob
/coding-syntax/find_duplicates.py
238
3.890625
4
def find_duplicates(list): rep = {} for item in list: if item in rep: return item else: rep[item] = 1 if __name__ == "__main__": list = [0,2,2,3,4,5,7] print(find_duplicates(list))
f983071afdc326e07f7ca4b84b626ada972ddb36
harshv47/Artemis-arrow
/songs/youtube.py
527
3.578125
4
import playlist as pl import songs as sg def single(service,playlist_id,song): """ A single song is added to the playlist represented by the playlist id if it is not already present """ song_id = sg.video_id(service,song) playlist_songs_id = pl.playlist_list(service,playlist_id) if song_id not in playlist_songs_id: pl.playlistItem_insert(service,playlist_id,song_id) print("Adding Song .....") else: print("Skipping song, song already in playlist")
283e668c8583c7240947d907f49fad5a612ef355
TinkerGen/bit_maker_lite_covid_prevention
/bitmaker_covid.py
3,580
3.625
4
from microbit import * import time import speech class Servo: """ A simple class for controlling hobby servos. Args: pin (pin0 .. pin3): The pin where servo is connected. freq (int): The frequency of the signal, in hertz. min_us (int): The minimum signal length supported by the servo. max_us (int): The maximum signal length supported by the servo. angle (int): The angle between minimum and maximum positions. Usage: SG90 @ 3.3v servo connected to pin0 = Servo(pin0).write_angle(90) """ def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180): self.min_us = min_us self.max_us = max_us self.us = 0 self.freq = freq self.angle = angle self.analog_period = 0 self.pin = pin analog_period = round((1/self.freq) * 1000) # hertz to miliseconds self.pin.set_analog_period(analog_period) def write_us(self, us): us = min(self.max_us, max(self.min_us, us)) duty = round(us * 1024 * self.freq // 1000000) self.pin.write_analog(duty) sleep(100) #self.pin.write_digital(0) # turn the pin off def write_angle(self, degrees=None): degrees = degrees % 360 total_range = self.max_us - self.min_us us = self.min_us + total_range * degrees // self.angle self.write_us(us) _TIMEOUT1 = 1000 _TIMEOUT2 = 10000 def _get_distance(pin): pin.write_digital(0) time.sleep_us(2) pin.write_digital(1) time.sleep_us(10) pin.write_digital(0) t0 = time.ticks_us() count = 0 while count < _TIMEOUT1: if pin.read_digital(): break count += 1 if count >= _TIMEOUT1: return -1 t1 = time.ticks_us() count = 0 while count < _TIMEOUT2: if not pin.read_digital(): break count += 1 if count >= _TIMEOUT2: return -1 t2 = time.ticks_us() dt = int(time.ticks_diff(t1,t0)) if dt > 5300: return -1 distance = (time.ticks_diff(t2,t1) / 29 / 2) # cm return distance display.clear() stage = 0 start_time = 0 sv1 = Servo(pin1) sv1.write_angle(90) # turn servo to 90 degrees while True: distance = _get_distance(pin2) if distance <= 10 and distance > 0: if time.ticks_diff(time.ticks_ms(), start_time) >= 1000: stage += 1 start_time = time.ticks_ms() if stage == 1: speech.say("COMMENCING EXTERMINATION OF CORONA-VIRUS", speed=120, pitch=100, throat=100, mouth=200) sv1.write_angle(80) if stage == 2: speech.say("CORONA-VIRUS WILL BE EXTER-MI-NATED", speed=120, pitch=100, throat=100, mouth=200) sv1.write_angle(70) if stage == 3: speech.say("CORONA-VIRUS WILL BE EXTER-MI-NATED", speed=120, pitch=100, throat=100, mouth=200) sv1.write_angle(60) if stage == 4: speech.say("VICTORY OVER CORONA-VIRUS IS NEAR", speed=120, pitch=100, throat=100, mouth=200) sv1.write_angle(50) if stage == 5: speech.say("CORONA-VIRUS HAS BEEN EXTER-MI-NATED", speed=120, pitch=100, throat=100, mouth=200) sv1.write_angle(40) stage = 0 sleep(1000) else: if stage == 0: sv1.write_angle(90) if stage != 0: speech.say("CORONA-VIRUS IS ESCAPING ", speed=120, pitch=100, throat=100, mouth=200) sv1.write_angle(90) stage = 0
3cf09e2f06f9b101b721eed53268aff53b56fdb8
kameronlightheart14/projects
/DataCollection/WebTechnologies/web_technologies.py
10,212
3.625
4
# web_technologies.py """ Kameron Lightheart 9/7/19 MATH 403 """ import json import socket from matplotlib import pyplot as plt import numpy as np # Problem 1 def prob1(filename="nyc_traffic.json"): """Load the data from the specified JSON file. Look at the first few entries of the dataset and decide how to gather information about the cause(s) of each accident. Make a readable, sorted bar chart showing the total number of times that each of the 7 most common reasons for accidents are listed in the data set. """ with open(filename, 'r') as infile: traffic_data = json.load(infile) cause_dict = {} for report in traffic_data: if ("contributing_factor_vehicle_1" in report.keys()): cause = report["contributing_factor_vehicle_1"] if (cause in cause_dict.keys()): cause_dict[cause] += 1 else: cause_dict[cause] = 1 if ("contributing_factor_vehicle_2" in report.keys()): cause = report["contributing_factor_vehicle_2"] if (cause in cause_dict.keys()): cause_dict[cause] += 1 else: cause_dict[cause] = 1 print(cause_dict.values()) top_seven_keys = sorted(cause_dict, key=cause_dict.get, reverse=True)[:7] print(top_seven_keys) for key in top_seven_keys: plt.bar(key + " (" + str(cause_dict[key]) + ")", cause_dict[key], align='center') plt.title("Causes of Accidents in New York") plt.xticks(rotation=90) plt.tight_layout() plt.show() class TicTacToe: def __init__(self): """Initialize an empty board. The O's go first.""" self.board = [[' ']*3 for _ in range(3)] self.turn, self.winner = "O", None def move(self, i, j): """Mark an O or X in the (i,j)th box and check for a winner.""" if self.winner is not None: raise ValueError("the game is over!") elif self.board[i][j] != ' ': raise ValueError("space ({},{}) already taken".format(i,j)) self.board[i][j] = self.turn # Determine if the game is over. b = self.board if any(sum(s == self.turn for s in r)==3 for r in b): self.winner = self.turn # 3 in a row. elif any(sum(r[i] == self.turn for r in b)==3 for i in range(3)): self.winner = self.turn # 3 in a column. elif b[0][0] == b[1][1] == b[2][2] == self.turn: self.winner = self.turn # 3 in a diagonal. elif b[0][2] == b[1][1] == b[2][0] == self.turn: self.winner = self.turn # 3 in a diagonal. else: self.turn = "O" if self.turn == "X" else "X" def empty_spaces(self): """Return the list of coordinates for the empty boxes.""" return [(i,j) for i in range(3) for j in range(3) if self.board[i][j] == ' ' ] def __str__(self): return "\n---------\n".join(" | ".join(r) for r in self.board) # Problem 2 class TicTacToeEncoder(json.JSONEncoder): """A custom JSON Encoder for TicTacToe objects.""" def default(self, obj): if not isinstance(obj, TicTacToe): raise TypeError("Expected a TicTacToe data type for encoding") return {"dtype": "TicTacToe", "data": [obj.board, obj.turn, obj.winner]} # Problem 2 def tic_tac_toe_decoder(obj): """A custom JSON decoder for TicTacToe objects.""" if "dtype" in obj: if obj["dtype"] != "TicTacToe" or "data" not in obj: raise ValueError("Expected TicTacToe message from TicTacToeEncoder") game = TicTacToe() game.board = obj["data"][0] game.turn = obj["data"][1] game.winner = obj["data"][2] return game raise ValueError("Expected TicTacToe message from TicTacToeEncoder") def mirror_server(server_address=("0.0.0.0", 33333)): """A server for reflecting strings back to clients in reverse order.""" print("Starting mirror server on {}".format(server_address)) # Specify the socket type, which determines how clients will connect. server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_sock.bind(server_address) # Assign this socket to an address. server_sock.listen(1) # Start listening for clients. while True: # Wait for a client to connect to the server. print("\nWaiting for a connection...") connection, client_address = server_sock.accept() try: # Receive data from the client. print("Connection accepted from {}.".format(client_address)) in_data = connection.recv(1024).decode() # Receive data. print("Received '{}' from client".format(in_data)) # Process the received data and send something back to the client. out_data = in_data[::-1] print("Sending '{}' back to the client".format(out_data)) connection.sendall(out_data.encode()) # Send data. # Make sure the connection is closed securely. finally: connection.close() print("Closing connection from {}".format(client_address)) def mirror_client(server_address=("0.0.0.0", 33333)): """A client program for mirror_server().""" print("Attempting to connect to server at {}...".format(server_address)) # Set up the socket to be the same type as the server. client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_sock.connect(server_address) # Attempt to connect to the server. print("Connected!") # Send some data from the client user to the server. out_data = input("Type a message to send: ") client_sock.sendall(out_data.encode()) # Send data. # Wait to receive a response back from the server. in_data = client_sock.recv(1024).decode() # Receive data. print("Received '{}' from the server".format(in_data)) # Close the client socket. client_sock.close() # Problem 3 def tic_tac_toe_server(server_address=("0.0.0.0", 44444)): """A server for playing tic-tac-toe with random moves.""" print("Starting TicTacToe server on {}".format(server_address)) # Specify the socket type, which determines how clients will connect. server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_sock.bind(server_address) # Assign this socket to an address. server_sock.listen(1) # Start listening for clients. # Wait for a client to connect to the server. print("\nWaiting for a connection...") while True: connection, client_address = server_sock.accept() connection_open = True while connection_open: # Receive data from the client. #print("Connection accepted from {}.".format(client_address)) in_data = connection.recv(1024).decode() # Receive data. #print("Received '{}' from client".format(in_data)) game = json.loads(in_data, object_hook=tic_tac_toe_decoder) # Process the received data and send something back to the client. if game.winner is "O": connection.sendall("WIN".encode()) connection.close() connection_open = False elif len(game.empty_spaces()) == 0 and game.winner is None: connection.sendall("DRAW".encode()) connection.close() connection_open = False else: i, j = game.empty_spaces()[np.random.randint(0, len(game.empty_spaces()))] game.move(i, j) if game.winner != None: connection.sendall("LOSE".encode()) out_data = json.dumps(game, cls=TicTacToeEncoder) #print("Sending", out_data, "to the client") connection.sendall(out_data.encode()) connection.close() connection_open = False else: out_data = json.dumps(game, cls=TicTacToeEncoder) #print("Sending", out_data, "to the client") connection.sendall(out_data.encode()) # Problem 4 def tic_tac_toe_client(server_address=("0.0.0.0", 44444)): """A client program for tic_tac_toe_server().""" #print("Attempting to connect to server at {}...".format(server_address)) # Set up the socket to be the same type as the server. client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_sock.connect(server_address) # Attempt to connect to the server. #print("Connected!") game = TicTacToe() in_data = "" while game.winner is None and in_data != "DRAW": print(game) move = input("Please make a move in format \"0-2 0-2\": ").split(" ") move = [int(move[i]) for i in range(len(move))] while len(move) != 2 or move[0] not in [0, 1, 2]\ or move[1] not in [0, 1, 2] or (move[0], move[1]) not in game.empty_spaces(): try: move = input("Please make a move in format \"0-2 0-2\": ").split(" ") move = [int(move[i]) for i in range(len(move))] except Exception as e: pass game.move(move[0], move[1]) out_data = json.dumps(game, cls=TicTacToeEncoder) client_sock.sendall(out_data.encode()) # Send data. # Wait to receive a response back from the server. in_data = client_sock.recv(1024).decode() # Receive data. #print("Received '{}' from the server".format(in_data)) if (len(in_data) <= 5): print(in_data) else: game = json.loads(in_data, object_hook = tic_tac_toe_decoder) print(game) # Close the client socket. client_sock.close() def test_encoder_decoder(): game = TicTacToe() tictactoe_message = json.dumps(game, cls=TicTacToeEncoder) print("Encoded:", tictactoe_message) game = json.loads(tictactoe_message, object_hook=tic_tac_toe_decoder) print("Decoded:", game.board, game.turn, game.winner)
0408aa6362540532e93737b5e1d8306aa725825f
rafaelpederiva/Resposta_Python_Brasil
/Exercícios de Estrutura de Repetição/Exercício 46 - Salto em Distância.py
2,023
3.765625
4
#Exercício 46 '''Em uma competição de salto em distância cada atleta tem direito a cinco saltos. No final da série de saltos de cada atleta, o melhor e o pior resultados são eliminados. O seu resultado fica sendo a média dos três valores restantes. Você deve fazer um programa que receba o nome e as cinco distâncias alcançadas pelo atleta em seus saltos e depois informe a média dos saltos conforme a descrição acima informada (retirar o melhor e o pior salto e depois calcular a média). Faça uso de uma lista para armazenar os saltos. Os saltos são informados na ordem da execução, portanto não são ordenados. O programa deve ser encerrado quando não for informado o nome do atleta. A saída do programa deve ser conforme o exemplo abaixo: Atleta: Rodrigo Curvêllo ------------------------------- Primeiro Salto: 6.5 m Segundo Salto: 6.1 m Terceiro Salto: 6.2 m Quarto Salto: 5.4 m Quinto Salto: 5.3 m ------------------------------- Melhor salto: 6.5 m Pior salto: 5.3 m Média dos demais saltos: 5.9 m ------------------------------- Resultado final: Rodrigo Curvêllo: 5.9 m''' lista = [] lista2 = ['Primeiro', 'Segundo', 'Terceiro', 'Quarto', 'Quinto'] nome = input('Nome do Atleta: ') if nome != "": for i in range(0,5): salto = float(input('%s Salto: ' %(lista2[i]))) lista.append(salto) lista_ordenada = sorted(lista, reverse=True) melhor_salto = lista_ordenada[0] pior_salto = lista_ordenada[4] soma = lista_ordenada[1] + lista_ordenada[2] + lista_ordenada[3] media = soma / 3 print('\n\nAtleta: ', nome) print('-------------------------------') for f in range(0,5): print(lista2[f], 'Salto: ', lista_ordenada[f]) print('-------------------------------') print('Melhor Salto: ', melhor_salto) print('Pior Salto: ', pior_salto) print('Média dos demais Saltos: %2.2f' %media) print('-------------------------------') print('Resultado final:') print(nome,': %2.2f' %media) else: print('Programa Encerrado')
daa51f7e7fcbc9b6f8bb8d46a00f043168b9b59d
Karenahv/holbertonschool-machine_learning
/math/0x00-linear_algebra/7-gettin_cozy.py
480
3.75
4
#!/usr/bin/env python3 """concatenates two matrix""" def cat_matrices2D(mat1, mat2, axis=0): """concatenates two matrix""" if (len(mat1[0]) == len(mat2[0]) and axis == 0): result = [] result += [elem.copy() for elem in mat1] result += [elem.copy() for elem in mat2] return result elif (len(mat1) == len(mat2) and axis == 1): res = [mat1[i] + mat2[i] for i in range(len(mat1))] return res else: return None
d04a9d22a8c828a0df7b77b12c042fec9d2bd0f3
fxy1018/Leetcode
/41_First_Missing_Positive.py
265
3.640625
4
""" Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. """ ''' Created on Feb 20, 2017 @author: fanxueyi '''
53246242559337f536ea020acca15f9f7640aabb
BrechtVandevoort/AdventOfCode
/2020/day_08/day_08.py
1,187
3.65625
4
def simulate_code(instructions): acc = 0 visited = [] current_instr = 0 while current_instr not in visited and 0 <= current_instr < len(instructions): visited.append(current_instr) instr, value = instructions[current_instr].split() value = int(value) if instr == "acc": acc += value elif instr == "jmp": current_instr += value - 1 current_instr += 1 return acc, current_instr == len(instructions) def solve_1(data): return simulate_code(data)[0] def solve_2(data): for i, line in enumerate(data): instr, value = line.split() if instr in ("jmp", "nop"): new_instr = "jmp" if instr == "nop" else "nop" new_instr += " " + value new_instructions = data[:i] + [new_instr] + data[i+1:] acc, success = simulate_code(new_instructions) if success: return acc def main(): with open("input.txt") as fp: data = list(map(lambda x: x.strip(), fp.readlines())) print(f"Solution part 1: {solve_1(data)}") print(f"Solution part 2: {solve_2(data)}") if __name__ == '__main__': main()
f78ce98b80b05d278c214f68b8853d20937e4be0
vivekyadav6838/Data-Structures-and-Algorithms-for-Interviews
/Python/Recursion/Fiboanacci.py
159
4.0625
4
def fibonacci(n): if (n == 1 or n == 2): return 1 return fibonacci(n - 1) + fibonacci(n - 2) if __name__ == '__main__': n = 10 print(fibonacci(n))
19cc19da3564256299b2f0b4930e7aa7676ba0e1
sagynangare/I2IT
/class_ex1.py
236
3.59375
4
class Demo: def __init__(self, a, b): print('Demo is initialized.......') self.a = a self.b = b def display(self): print('A: ', self.a, '\n', 'B: ', self.b) obj= Demo(5, 8) obj.display()
9e244c6bcf51a91993e863be9b0375bec35fc13d
lunar-r/sword-to-offer-python
/leetcode/62. Unique Paths.py
1,838
3.640625
4
# -*- coding: utf-8 -*- """ File Name: 62. Unique Paths Description : Author : simon date: 19-3-26 """ class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ self.cnt = 0 # 如果是list 可以不用加self duiyu def DFS(i, j, idx): if check(i, j): if idx == m + n - 1: self.cnt += 1 DFS(i + 1, j, idx + 1) DFS(i, j + 1, idx + 1) def check(i, j): return i < m and j < n DFS(0, 0, 1) return self.cnt # 空间复杂度 O(m*n) def uniquePaths_DP(self, m, n): DP = [[1]*n for _ in range(m)] for i in range(1,m): for j in range(1,n): DP[i][j] = DP[i-1][j] + DP[i][j-1] # 这里发现每一次更新只需要上一行的结果 和 这一行的结果 i-1行 i行 return DP[-1][-1] # 空间复杂度 O(n) def uniquePaths_DP1(self, m, n): pre = [1] * n # 上一行的结果 cur = [1] * n # 这一行的结果 for i in range(1,m): for j in range(1,n): cur[j] = pre[j] + cur[j-1] pre = cur return cur[-1] def uniquePaths_DP2(self, m, n): cur = [1] * n # 这一行的结果 for i in range(1, m): for j in range(1, n): cur[j] = cur[j] + cur[j - 1] return cur[-1] def uniquePaths_math(self, m, n): def factorial(num): res = 1 for i in range(1,num+1): res *= i return res return factorial(m+n-2) // factorial(m-1) // factorial(n-1) if __name__ == '__main__': solu = Solution() print(solu.dp2(2, 2))
485b9057d1fe88d2d8d8551d83134fcfd50767c0
KishoreMayank/CodingChallenges
/Interview Cake/Linked Lists/ReverseLinkedList.py
392
4.375
4
''' Reverse Linked List: Write a function to reverse a linked list ''' def reverse(head): curr = head prev = None next_node = None while curr: # iterate till the end next_node = curr.next # copy pointer to next node curr.next = prev # Reverse the 'next' pointer prev = curr # Step forward in the list curr = next_node return prev
0ecca80ef97f6c3b22629b79e5178b66a186487b
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_2/sebadzia/pancakes_revenge.py
1,075
3.5
4
def counter(function): def wrapper(*args): wrapper.called += 1 return function(*args) wrapper.called = 0 wrapper.__name__ = function.__name__ return wrapper @counter def flip(stack, index): left, right = stack[:index+1], stack[index+1:] return invert(left[::-1]) + right def invert(stack): return stack.replace('-', '%temp%').replace('+', '-').replace('%temp%', '+') def any_unhappy(stack): return any([sign == '-' for sign in stack]) def find_last_unhappy(stack): return stack.rfind('-') def find_first_unhappy(stack): return stack.find('-') def solution(stack): flip.called = 0 while any_unhappy(stack): first_unhappy = find_first_unhappy(stack) if first_unhappy > 0: stack = flip(stack, first_unhappy-1) stack = flip(stack, find_last_unhappy(stack)) return flip.called with open('input', 'r') as infile, open('output', 'w') as out: next(infile) for index, line in enumerate(infile): out.write("Case #{0}: {1}\n".format(index+1, solution(line)))
409968b36f37b761d4a6c7a9d573f412aba008c2
viharivnv/DSA
/Hw_1_2/quickunion.py
2,209
3.625
4
#The code was run on PYCHARM IDE on WINDOWS python version 3.x ''' Steps to recreate: 1)Open PYCHARM 2)Create a new project 3) Add a new python file and paste the code 4) Run the code ''' import time file=input("enter the file name excluding '.txt' extension for example 8pair:\n") file=file+".txt" # referred "https://stackoverflow.com/questions/47872237/how-to-read-an-input-file-of-integers-separated-by-a-space-using-readlines-in-py/47872327" for splitting try: # stores each line in the file as a string in the array of strings text with open(file, 'r') as f: text = f.read() text = text.split("\n") i = 0 arr = [] a = [] b = [] p = [] q = [] count = 0 # Stores the two strings sepersted by whitespace as seperate elements of the array for i in range(0, len(text) - 1): left = text[i].split() for x in left: arr.append(x) # stores the numbers read to p and q for i in range(0, len(arr)): if i % 2 == 0: p.append(arr[i]) else: q.append(arr[i]) for x in p: t = int(x) a.append(t) for y in q: t = int(y) b.append(t) id = [] # referred "https://stackoverflow.com/questions/5998245/get-current-time-in-milliseconds-in-python" for getting time in milliseconds start = time.time_ns() # initialization of the array for i in range(0, 8192): id.append(i) c = 0 c1 = 0 # defining root() function def root(i): global c1 while i != id[i]: i = id[i] return i # defining union function def un(o, l): i = root(o) j = root(l) id[i] = j count = 0 # Quick-Union Algorithm for i in range(0, len(p)): f = a[i] g = b[i] if root(f) == root(g): c+=1 continue else: c += 1 un(f, g) print('The pairs are :', a[i], b[i],'with root',root(f)) stop = time.time_ns() runtime = stop - start print("The Number of instructions executed", c) print('time taken to execute', runtime, 'ns') except: print('File Not Found!!!')
c26a02e9ea461702f30d13cafcda0601aad3f4bc
cccccccccccccc/Myleetcode
/203/removelinkedlistitems.py
707
3.78125
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: if head is None: return head newhead = ListNode(0) cur = newhead cur.next = head while cur.next: if cur.next.val == val: cur.next = cur.next.next else: cur = cur.next return newhead.next A = Solution() a = ListNode(1) b = ListNode(2) c = ListNode(6) d = ListNode(3) e = ListNode(6) a.next = b b.next = c c.next = d d.next = e val = 6 print(A.removeElements(a,val))
6f287809f27bc8b180415811a0ff34cfdf60a758
Code-Institute-Solutions/proposed_myfirstserver
/4a-http_server_echo_styled_challenge.py
4,015
4.25
4
#!/usr/bin/env python3 """A very very basic http server""" # The socket library which lets us create network connections: import socket # The ip address to listen on: # 127.0.0.1 (aka localhost) only listens to requests from the local computer # while 0.0.0.0 accepts requests from entire network, and is needed in C9 IP = '0.0.0.0' # Port number to listen on: # use any number from 1024 to 65535 (lower numbers are reserved) PORT = 1234 # Number of connections to allow to queue up before rejecting new ones MAXIMUM_QUEUE_SIZE = 5 # The amount of bytes we read from the socket at a time: # basic requests are shorter than this, but to handle longer requests we'd # need to receive multiple times BUFFER_SIZE = 2048 def respond(socket, client_ip_and_port): """Handle a single request from a client socket HTTP requests arrive as a sequence of bytes that contain one or more lines of headers containing the request details, terminating with an empty line. (Some request types (e.g. POST) also contain a data section after the empty line) The response we're constructing has a similar structure, one or more response headers, then an empty line and then the response body, which is usually HTML (other common choices are JSON, XML and plain text). A server generally crafts a response based on the specific request details. In this example, we just return a list with the request headers. """ # Receive the request from the socket: # It arrives as a sequence of bytes, so we first decode it to text request = socket.recv(BUFFER_SIZE).decode() # Split the request into separate lines (each a header) and discard last # empty line request_headers = request.splitlines()[:-1] # The header section we'll return, ending with an empty line: response_headers = 'HTTP/1.1 200 OK\n\n' # Our html response heading: response_body_heading = ('<h1>Hi there at %s:%s, ' % client_ip_and_port + 'here are your request headers:</h1>') # Some more html to display the request headers as an unordered list: response_body_ul = ('<ul><li>%s</li></ul>' % '</li><li>'.join(request_headers)) # Collect the response parts and encode as a byte sequence: encoded_response = (response_headers + response_body_heading + response_body_ul).encode() # Send the response across the socket: socket.send(encoded_response) def serverloop(): """Open a server socket connection and accept incoming client connections A connection consists of a pair of sockets, one for the server and one for the client, each defined by an IP address which identifies the computer, and a port number that identifies the process. So a computer can have multiple sockets open at the same time, but each has to use a separate port. We create a server socket to listen on a preselected port, and we accept incoming client connections, which generally use any available port. For each connection established we get the client socket and handle it in our `respond` function. """ # Create a regular internet socket (TCP/IP): server_socket = socket.socket() # Bind the socket to listen on a specific port on our computer: server_socket.bind((IP, PORT)) # Begin listening on the socket, with a particular queue size: server_socket.listen(MAXIMUM_QUEUE_SIZE) # Do this forever (until server process is killed): while True: # Accept a connection from next client: # for each connection we get the socket and connection details (client_socket, client_ip_and_port) = server_socket.accept() # Process the client's request: respond(client_socket, client_ip_and_port) # Close the client connection: client_socket.close() if __name__ == '__main__': print('Server launched on %s:%s press ctrl+c to kill the server' % (IP, PORT)) serverloop()
658582b1a3e69b45326b6e9ffd79f97da72f29b3
sirjoe29/basic-python-joe
/list.py
128
3.5625
4
mylist = [] mylist.append(10) mylist.append(12) mylist.append(20) print(mylist) print(len(mylist)) mylist[1] = 15 print(mylist)
b01dd2ccf1cb832b11cad275c9762bb62bdd9a93
snanoh/Python-Algorithm-Study
/graph/combine.py
536
3.890625
4
"""전체 수 n을 입력받아 k개의 조합을 리턴한다.""" from typing import List n,k = 5,3 def combine(n: int , k: int) -> List[List[int]]: results = [] def dfs(elements, start: int, k: int): if k == 0: results.append(elements[:]) # 자신 이전의 모든 값을 고정하여 재귀 호출 for i in range(start, n + 1): elements.append(i) dfs(elements, i + 1, k - 1) elements.pop() dfs([],1,k) return results print(combine(n,k))
f6c5aac53ec637cb564a9baf419e4fa4748c8f18
AIA2105/A_Practical_Introduction_to_Python_Programming_Heinold
/Python sheets/GUI6.py
533
3.921875
4
from tkinter import * def welcome(): outpt.configure(text='Welcome '+inpt1.get()+' !') root=Tk() label1=Label(text='Enter your name: ',font=(8)) label1.grid(row=0,column=0, padx=(20,0),pady=(20,0)) inpt1=Entry(width = 20,font=(8)) inpt1.grid(row=0,column=1, padx=(10,20),pady=(20,10)) btn=Button(command=welcome,width = 20,text='Validate',font=(8)) btn.grid(row=1,column=1, padx=(20,20),pady=(0,10)) outpt=Label(font=(8)) outpt.grid(sticky='w',row=2,column=1, padx=(20,20),pady=(10,20)) mainloop()
30938ac4128e71d0477191619d851085327cdf53
Tester1313/Python
/Exercicio 4.py
1,159
3.78125
4
#Thiago Henrique dos Santos i = 9 candidato1 = 0 candidato2 = 0 candidato3 = 0 candidato4 = 0 nulo = 0 branco = 0 total = 0 print('Para o candidato A vote 1') print('Para o candidato B vote 2') print('Para o candidato C vote 3') print('Para o candidato D vote 4') print('Nulo vote 5') print('Branco vote 6') while i != 0: voto = int(input('Informe o número do seu candidato:' )) i = voto if voto == 1: candidato1 += 1 elif voto == 2: candidato2 += 1 elif voto == 3: candidato3 += 1 elif voto == 4: candidato4 += 1 elif voto == 5: nulo += 1 elif voto == 6: branco += 1 else: print ('Candidato não cadastrado') total = candidato1 + candidato2 + candidato3 + candidato4 + nulo + branco print('Total de votos do candidato 1 :', candidato1); print('Total de votos do candidato 2 :', candidato2); print('Total de votos do candidato 3 :', candidato3); print('Total de votos do candidato 4 :', candidato4); print('Total de votos nulos :', nulo, ' percentual de nulos :',(nulo*100)/total); print('Total de votos brancos :', branco, 'percentual de brancos :',(branco*100)/total);
3c32d6c8c436d9cf7734851e3d0d86a7e70f66b7
stungkit/Leetcode-Data-Structures-Algorithms
/06 Heap/719. Find K-th Smallest Pair Distance.py
1,108
3.984375
4
# Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B. # Example 1: # Input: # nums = [1,3,1] # k = 1 # Output: 0 # Explanation: # Here are all the pairs: # (1,3) -> 2 # (1,1) -> 0 # (3,1) -> 2 # Then the 1st smallest distance pair is (1,1), and its distance is 0. class Solution(object): def smallestDistancePair(self, nums, k): nums.sort() heap = [(nums[i+1] - nums[i], i, i+1) for i in range(len(nums)-1)] heapq.heapify(heap) for _ in range(k): diff, root, nei = heapq.heappop(heap) if nei + 1 < len(nums): heapq.heappush(heap, (nums[nei+1]-nums[root], root, nei+1)) return diff # Time: O((N+klogN+NlogN), where N is the length of nums. O(klogN) + O(N) + O(klogN) # Space: O(N), the space used to store our heap of at most N-1 elements. # index: i = 0,1,2,3,4 # example: [3,1,4,5,1] ---> [1,1,3,4,5] # diff: = 0,2,1,1
152abc8cc738659443907693895e27a33a4dfd70
SeungHune/Programming-Basic
/과제 2/실습 2-2.py
258
3.984375
4
def smaller(x,y): pass # fill your code here if (x>y): return(y) elif (x<y): return(x) else: return(x) print(smaller(3,5)) # returns 3 print(smaller(5,3)) # returns 3 print(smaller(3,3)) # returns 3
f0cec5bbb77f3601fba561251ee2be7fce5835d0
kundan8474/python-specialisation
/py4e/exercises/functions/pseudorandom.py
328
4.125
4
import random as r # range function iterates from 0 to argument in range # random generate a random number between 0.0 and 1.0 but excluding them for i in range(5): print(r.random(),'\n') # randint(min, max) will generate a random integer between min and max, including both for i in range(5): print(r.randint(i,10))
e92760e11557f20d81de486c4af048247d479d64
thirstfortruth/diving-in-python
/w2/generator_3.py
396
3.671875
4
def accumulator(): total = 0 while True: value = yield total print('Got: {}'.format(value)) if not value: break total += value generator = accumulator() next(generator) print('Accumulated: {}'.format(generator.send(1))) print('Accumulated: {}'.format(generator.send(2))) next(generator) print('Accumulated: {}'.format(generator.send(1))) next(generator)
251f347edf6915a3256dd615dce646a6c4997dca
wkswilliam/challenges
/CSES/Sorting and Searching/ferris_wheel.py
641
3.90625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 11 16:18:54 2020 @author: william """ def ferris_wheel(n, x, weight): weight.sort(reverse=True) # x maximum wei head = 0 tail = n -1 count = 0 while head <= tail: if weight[head] + weight[tail]<=x: count+=1 head+=1 tail-=1 else: count+=1 head+=1 return count def main(): n, x = map(int, input().split(" ")) p = list(map(int, input().split(" "))) res = ferris_wheel(n, x, p) print(res) return None if __name__=="__main__": main()
a3936122c2f25fa0f3b4883f7a8f595d7dcf5bbf
stevenhorsman/advent-of-code-2015
/day-24/hangs_in_the_balance.py
1,533
3.65625
4
import itertools, operator from functools import reduce input_file = 'day-24/input.txt' def does_remainder_split(weights, split_groups): target_weight = sum(weights) // split_groups for group_size in range(1, len(weights)): for group in [comb for comb in itertools.combinations(weights, group_size) if sum(comb) == target_weight]: if split_groups == 2: return True #we've found a valid split, return up the stack to calculate the best approach else: return does_remainder_split(list(set(weights) - set(group)), split_groups - 1) def get_best_entanglement(weights, split_groups): target_weight = sum(weights) // split_groups for group_size in range(1, len(weights)): # automatically finishes once we find the smallest group one candidate_groups = [comb for comb in itertools.combinations(weights, group_size) if sum(comb) == target_weight] valid_groups = [group for group in candidate_groups if does_remainder_split(list(set(weights) - set(group)), split_groups - 1)] if len(valid_groups) > 0: products = list(map(lambda group: reduce(operator.mul, group, 1), valid_groups)) return sorted(products)[0] def part1(input): packages = list(map(int, input.splitlines())) return get_best_entanglement(packages, 3) def part2(input): packages = list(map(int, input.splitlines())) return get_best_entanglement(packages, 4) if __name__ == "__main__": with open(input_file) as f: data = f.read() print("Part 1: ", part1(data)) print("Part 2: ", part2(data))
4fe2f4c4652f1b178ebb1b185d610e763bdfb29c
Oussema3/Python-Programming
/equation.py
181
3.640625
4
def solve_eq(equation): x, add, num1, equal, num2 =equation.split() num1, num2 = int(num1), int(num2) return "x= " + str(num2 - num1) print(solve_eq("x + 23 = 196"))
f0b92e65e48bef75e52297cdf5af0525080d7986
hsindorf/madlib-cli
/madlibs/file_io.py
1,132
4.375
4
"""Functions for reading/writing files""" def read_file(filename): """ Reads file and returns output input: string, a filename to be opened output: string, the file contents """ if type(filename) is not str: raise TypeError('filename must be a string') try: with open(filename + '.txt') as f: return f.read() except FileNotFoundError: raise FileNotFoundError('Your file was not found') except IOError: raise IOError('There was an error reading your file') def write_file(content, filename): """ Receives input, writes to new txt file input: content: string, to be written filename: filename to be written to output: string, confirmation """ if type(content) is not str or type(filename) is not str: raise TypeError('You must enter valid content and filename') try: with open(filename + '.txt', 'w') as f: f.write(content) return ('Successfully saved!') except IOError: return('Failed!') if __name__ == "__main__": print(read_file('empty'))
ffaf00899f4ddd2eb3ed9c87b6a1441ffffeb324
gabriellaec/desoft-analise-exercicios
/backup/user_286/ch162_2020_06_09_20_34_40_106192.py
311
3.53125
4
def verifica_lista(lista): if lista == []: return 'misturado' i = 0 p = 0 for num in lista: if num % 2 == 0: p += 1 else: i += 1 if p == 0: return 'ímpar' elif i == 0: return 'par' else: return 'misturado'
b69433fc6c318c8beb48090f9d0aa103b2a1984b
I82Much/TI-Tech-Tree-Helper
/scripts/topo.py
7,803
3.796875
4
from xml.sax.saxutils import escape from collections import defaultdict # Original topological sort code written by Ofer Faigon (www.bitformation.com) and used with permission def topological_sort(items, partial_order): """Perform topological sort. items is a list of items to be sorted. partial_order is a list of pairs. If pair (a,b) is in it, it means that item a should appear before item b. Returns a list of the items in one of the possible orders, or None if partial_order contains a loop. """ def add_node(graph, node): """Add a node to the graph if not already exists.""" if not graph.has_key(node): graph[node] = [0] # 0 = number of arcs coming into this node. def add_arc(graph, fromnode, tonode): """Add an arc to a graph. Can create multiple arcs. The end nodes must already exist.""" graph[fromnode].append(tonode) # Update the count of incoming arcs in tonode. graph[tonode][0] = graph[tonode][0] + 1 # step 1 - create a directed graph with an arc a->b for each input # pair (a,b). # The graph is represented by a dictionary. The dictionary contains # a pair item:list for each node in the graph. /item/ is the value # of the node. /list/'s 1st item is the count of incoming arcs, and # the rest are the destinations of the outgoing arcs. For example: # {'a':[0,'b','c'], 'b':[1], 'c':[1]} # represents the graph: c <-- a --> b # The graph may contain loops and multiple arcs. # Note that our representation does not contain reference loops to # cause GC problems even when the represented graph contains loops, # because we keep the node names rather than references to the nodes. graph = {} for v in items: add_node(graph, v) for a,b in partial_order: add_arc(graph, a, b) # Step 2 - find all roots (nodes with zero incoming arcs). roots = [node for (node,nodeinfo) in graph.items() if nodeinfo[0] == 0] # step 3 - repeatedly emit a root and remove it from the graph. Removing # a node may convert some of the node's direct children into roots. # Whenever that happens, we append the new roots to the list of # current roots. sorted = [] while len(roots) != 0: # If len(roots) is always 1 when we get here, it means that # the input describes a complete ordering and there is only # one possible output. # When len(roots) > 1, we can choose any root to send to the # output; this freedom represents the multiple complete orderings # that satisfy the input restrictions. We arbitrarily take one of # the roots using pop(). Note that for the algorithm to be efficient, # this operation must be done in O(1) time. root = roots.pop() sorted.append(root) for child in graph[root][1:]: graph[child][0] = graph[child][0] - 1 if graph[child][0] == 0: roots.append(child) del graph[root] if len(graph.items()) != 0: # There is a loop in the input. return None return sorted def main(): dependencies = { 'Advanced Fighters': ['Type IV Drive'], 'Antimass Deflectors': [], # AND 'Assault Cannon': [True, 'Deep Space Cannon', 'Cybernetics'], 'Cybernetics': ['Antimass Deflectors', 'Stasis Capsules'], 'Dacxive Animators': ['Neural Motivator'], 'Deep Space Cannon': ['Hylar V Assault Laser'], 'Enviro Compensator': [], 'Fleet Logistics': ['Graviton Negator'], 'Gen Synthesis': ['Cybernetics'], 'Graviton Laser System': ['Deep Space Cannon'], 'Graviton Negator': ['Assault Cannon'], 'Hylar V Assault Laser': [], # AND 'Integrated Economy': [True, 'Cybernetics', 'Micro Technology'], 'Light/Wave Deflectors': ['XRD Transporters', 'Magen Defense Grid'], 'Magen Defense Grid': ['Deep Space Cannon'], 'Micro Technology': ['Stasis Capsules', 'Sarween Tools'], 'Neural Motivator': ['Micro Technology', 'Stasis Capsules'], 'Sarween Tools': ['Enviro Compensator'], 'Stasis Capsules': ['Enviro Compensator'], 'Transit Diodes': ['Light/Wave Deflectors', 'Dacxive Animators'], # AND 'Type IV Drive': [True, 'Neural Motivator', 'XRD Transporters'], # AND 'War Sun': [True, 'Sarween Tools', 'Deep Space Cannon'], 'XRD Transporters': ['Antimass Deflectors'], 'X-89 Bacterial Weapon': ['Assault Cannon', 'Transit Diodes'], } tech_type_map = { # Biotech 'Stasis Capsules': 'Biotech', 'Neural Motivator': 'Biotech', 'Dacxive Animators': 'Biotech', 'Cybernetics': 'Biotech', 'Gen Synthesis': 'Biotech', 'X-89 Bacterial Weapon': 'Biotech', # Combat 'Hylar V Assault Laser': 'Combat', 'Deep Space Cannon': 'Combat', 'War Sun': 'Combat', 'Magen Defense Grid': 'Combat', 'Assault Cannon': 'Combat', 'Graviton Negator': 'Combat', # General 'Enviro Compensator': 'General', 'Sarween Tools': 'General', 'Micro Technology': 'General', 'Integrated Economy': 'General', 'Transit Diodes': 'General', 'Graviton Laser System': 'General', # Logistics 'Antimass Deflectors': 'Logistics', 'XRD Transporters': 'Logistics', 'Type IV Drive': 'Logistics', 'Advanced Fighters': 'Logistics', 'Light/Wave Deflectors': 'Logistics', 'Fleet Logistics': 'Logistics' } keys = dependencies.keys() # TODO(ndunn): Handle distinction between AND and OR partial_order = [] for key, values in dependencies.items(): if values: # TODO(ndunn): Find a better hack all_req = values[0] == True # All are required if all_req: for dep in values[1:]: partial_order.append((dep, key)) # Any of these are required else: for dep in values: partial_order.append((dep, key)) print partial_order topo_order = topological_sort(keys, partial_order) # TODO need to expand the dependencies to include dependencies of their children num_deps = defaultdict(lambda:0) for tech in topo_order: dependent_techs = dependencies[tech] if dependent_techs: # All # TODO(ndunn): doesn't take into account if two techs depend on same one. Overcounting if True == dependent_techs[0]: for dep_tech in dependent_techs[1:]: num_deps[tech] += 1 + num_deps[dep_tech] else: # Cheapest technology path min_cost = min([1 + num_deps[dep_tech] for dep_tech in dependent_techs]) num_deps[tech] += min_cost print num_deps for tech_type in ['Biotech', 'Combat', 'General', 'Logistics']: print tech_type for tech in topo_order: if tech_type_map[tech] == tech_type: num_tech_prereqs = num_deps[tech] print '._%d %s' %(num_tech_prereqs, tech) # Grid grid_tmpl = """ <control controlID="{id}" controlTypeID="com.balsamiq.mockups::TextInput" x="{x}" y="{y}" w="{w}" h="{h}" measuredW="150" measuredH="100" zOrder="2" locked="false" isInGroup="-1"> <controlProperties> <text>{text}</text> </controlProperties> </control> """ width = 100 height= 100 x_offset = 2 * width y_offset = 2 * height identifier = 0 for index, tech_type in enumerate(['Biotech', 'Combat', 'General', 'Logistics']): row = index col = 0 for tech in topo_order: if tech_type_map[tech] == tech_type: identifier += 1 x = x_offset + col * 100 y = y_offset + row * height w = width h = height text = tech.replace(' ', '%20') #print text print grid_tmpl.format(x=x, y=y, w=w, h=h, text=text, id=identifier) col += 1 pass if __name__ == '__main__': main()
b1a83bcc944e46f8827f5390f5687c01467c636c
srinjoychakravarty/formula1_probability_distribution
/sports_analytics.py
10,489
3.6875
4
from bs4 import BeautifulSoup from urllib.request import urlopen class ProbDist(dict): """A Probability Distribution; an {outcome: probability} mapping.""" def __init__(self, mapping=(), **kwargs): self.update(mapping, **kwargs) # Make probabilities sum to 1.0; assert no negative probabilities total = sum(self.values()) for outcome in self: self[outcome] = self[outcome] / total assert self[outcome] >= 0 def p(event, space): """The probability of an event, given a sample space of outcomes. event: a collection of outcomes, or a predicate that is true of outcomes in the event. space: a set of outcomes or a probability distribution of {outcome: frequency} pairs.""" # if event is a predicate it, "unroll" it as a collection if is_predicate(event): event = such_that(event, space) # if space is not an equiprobably collection (a simple set), # but a probability distribution instead (a dictionary set), # then add (union) the probabilities for all favorable outcomes if isinstance(space, ProbDist): return sum(space[o] for o in space if o in event) # simplest case: what we played with in our previous lesson else: return Fraction(len(event & space), len(space)) is_predicate = callable # Here we either return a simple collection in the case of equiprobable outcomes, or a dictionary collection in the # case of non-equiprobably outcomes def such_that(predicate, space): """The outcomes in the sample pace for which the predicate is true. If space is a set, return a subset {outcome,...} with outcomes where predicate(element) is true; if space is a ProbDist, return a ProbDist {outcome: frequency,...} with outcomes where predicate(element) is true.""" if isinstance(space, ProbDist): return ProbDist({o:space[o] for o in space if predicate(o)}) else: return {o for o in space if predicate(o)} def joint(A, B, sep=''): """The joint distribution of two independent probability distributions. Result is all entries of the form {a+sep+b: P(a)*P(b)}""" return ProbDist({a + sep + b: A[a] * B[b] for a in A for b in B}) standings_before_singapore_gp = ['https://web.archive.org/web/20190916070017/https://www.formula1.com/en/results.html/2019/drivers.html'] driver_points_before_singapore = [] driver_first_names = [] driver_last_names = [] for driver in standings_before_singapore_gp: html = urlopen('' + driver) soup = BeautifulSoup(html.read(), 'lxml') for pts in soup.find_all("td", class_="dark bold"): total_points = pts.get_text() driver_points_before_singapore.append(int(total_points)) driver_first_names.append([item.get_text()[0] for item in soup.select("span.hide-for-tablet")]) driver_first_names = driver_first_names[0] driver_last_names.append([item.get_text()[0] for item in soup.select("span.hide-for-mobile")]) driver_last_names = driver_last_names[0] driver_full_names = ([''.join(full_name) for full_name in zip(driver_first_names, driver_last_names)]) driver_standings_before_singapore = dict(zip(driver_full_names, driver_points_before_singapore)) driver_points_after_singapore = [] driver_first_names1 = [] driver_last_names1 = [] SGP = ProbDist(driver_standings_before_singapore) standings_after_singapore_gp = ['https://www.formula1.com/en/results.html/2019/drivers.html'] for driver1 in standings_after_singapore_gp: html1 = urlopen('' + driver1) soup1 = BeautifulSoup(html1.read(), 'lxml') for pts1 in soup1.find_all("td", class_="dark bold"): total_points1 = pts1.get_text() driver_points_after_singapore.append(int(total_points1)) driver_first_names1.append([item1.get_text()[0] for item1 in soup1.select("span.hide-for-tablet")]) driver_first_names1 = driver_first_names1[0] driver_last_names1.append([item1.get_text()[0] for item1 in soup1.select("span.hide-for-mobile")]) driver_last_names1 = driver_last_names1[0] driver_full_names1 = ([''.join(full_name1) for full_name1 in zip(driver_first_names1, driver_last_names1)]) driver_standings_after_singapore = dict(zip(driver_full_names1, driver_points_after_singapore)) RGP = ProbDist(driver_standings_after_singapore) driver_win_both = {k: SGP[k]*RGP[k] for k in SGP} print("\033[1m" + "Question 1.1 (20 points)" + "\033[0m" + "\n") print("Probability Distribution for each F1 driver to win the Singaporean Grand Prix: " + str(SGP) + "\n") print("Probability Distribution for each F1 driver to win both Singaporean and Russian Grand Prix: " + str(driver_win_both) + "\n") after_singapore_constructors_url = ['https://www.bbc.com/sport/formula1/constructors-world-championship/standings'] auto_manufacturers_after_singapore = [] constuctors_total_points_list_after_singapore = [] for constructor in after_singapore_constructors_url: html = urlopen('' + constructor) soup = BeautifulSoup(html.read(), 'lxml') for points in soup.find_all("td", class_="table__cell table__cell--right"): points_string = points.get_text() constuctors_total_points_list_after_singapore.append(int(points_string)) for teams in soup.find_all("td", class_="table__cell table__cell--left table__cell--bold"): team_string = teams.get_text() auto_manufacturers_after_singapore.append(team_string) team_standings_after_singapore = dict(zip(auto_manufacturers_after_singapore, constuctors_total_points_list_after_singapore)) points_gotten_in_singapore = {'Mercedes': 22, 'Ferrari': 43, 'Red Bull': 23, 'McLaren': 6, 'Renault': 2, 'Toro Rosso': 4, 'Racing Point': 0, 'Alfa Romeo': 1, 'Haas': 26, 'Williams': 1} team_standings_before_singapore = {key: team_standings_after_singapore[key] - points_gotten_in_singapore.get(key, 0) for key in team_standings_after_singapore.keys()} SGP_teams = ProbDist(team_standings_before_singapore) # Team Probability Distribution for Singapore after Italy Grand Prix RGP_teams = ProbDist(team_standings_after_singapore) # Team Probability Distribution for Russia after Singapore Grand Prix team_win_both = {k: SGP_teams[k]*RGP_teams[k] for k in SGP_teams} team_win_atleast_one = {k: SGP_teams[k]+RGP_teams[k] for k in SGP_teams} print("Mercedes Win Both: " + str(round((team_win_both.get('Mercedes'))*100,2)) + " %" + "\n") print("Mercedes Win Atleast One: " + str(round((team_win_atleast_one.get('Mercedes'))*100,2)) + " %" + "\n") print("Ferrari Win Both: " + str(round((team_win_both.get('Ferrari'))*100,2)) + " %" + "\n") print("Ferrari Win Atleast One: " + str(round((team_win_atleast_one.get('Ferrari'))*100,2)) + " %" + "\n") print("Red Bull Win Both: " + str(round((team_win_both.get('Red Bull'))*100,2)) + " %" + "\n") print("Red Bull Win Atleast One: " + str(round((team_win_atleast_one.get('Red Bull'))*100,2)) + " %" + "\n") print("Renault Win Both: " + str(round((team_win_both.get('Renault'))*100,2)) + " %" + "\n") print("Renault Win Atleast One: " + str(round((team_win_atleast_one.get('Renault'))*100,2)) + " %" + "\n") print("\033[1m" + "Question 1.2 (30 points)" + "\033[0m" + "\n") TeamTeam = joint(SGP_teams, RGP_teams, ' ') def mercedes_and_mercedes(outcome): return 'Mercedes' in outcome and 'Mercedes' in outcome mercedes_win_2 = such_that(mercedes_and_mercedes, TeamTeam) print("If Mercedes wins the first race, probability that Mercedes wins the next one is: " + str(round(mercedes_win_2.get('Mercedes Mercedes')*100, 2)) + " %" + "\n") def ferrari_and_ferrari(outcome): return 'Ferrari' in outcome and 'Ferrari' in outcome ferrari_win_2 = such_that(ferrari_and_ferrari, TeamTeam) print("If Ferrari wins the first race, probability that Ferrari wins the next one is: " + str(round(ferrari_win_2.get('Ferrari Ferrari')*100, 2)) + " %" + "\n") def redbull_and_redbull(outcome): return 'Red Bull' in outcome and 'Red Bull' in outcome redbull_win_2 = such_that(redbull_and_redbull, TeamTeam) print("If Red Bull wins the first race, probability that Red Bull wins the next one is: " + str(round(redbull_win_2.get('Red Bull Red Bull')*100, 2)) + " %" + "\n") def renault_and_renault(outcome): return 'Renault' in outcome and 'Renault' in outcome renault_win_2 = such_that(renault_and_renault, TeamTeam) print("If Renault wins the first race, probability that Renault wins the next one is: " + str(round(renault_win_2.get('Renault Renault')*100, 2)) + " %" + "\n") mercedes_win_both = team_win_both.get('Mercedes') mercedes_win_atleast_one = team_win_atleast_one.get('Mercedes') print("If Mercedes wins at least one of the two races, probability that Mercedes wins both is: " + str(round(((mercedes_win_both/mercedes_win_atleast_one)*100),2)) + " %" + "\n") ferrari_win_both = team_win_both.get('Ferrari') ferrari_win_atleast_one = team_win_atleast_one.get('Ferrari') print("If Ferrari wins at least one of the two races, probability that Ferrari wins both is: " + str(round(((ferrari_win_both/ferrari_win_atleast_one)*100),2)) + " %" + "\n") redbull_win_both = team_win_both.get('Red Bull') redbull_win_atleast_one = team_win_atleast_one.get('Red Bull') print("If Red Bull wins at least one of the two races, probability that Red Bull wins both is: " + str(round(((redbull_win_both/redbull_win_atleast_one)*100),2)) + " %" + "\n") renault_win_both = team_win_both.get('Renault') renault_win_atleast_one = team_win_atleast_one.get('Renault') print("If Renault wins at least one of the two races, probability that Renault wins both is: " + str(round(((renault_win_both/renault_win_atleast_one)*100),2)) + " %" + "\n") print("\033[1m" + "Question 1.3 (50 points)" + "\033[0m" + "\n") weather_dict = {'Rain': 0.2, 'Sun': 0.2, 'Clouds': 0.2, 'Snow': 0.2, 'Fog': 0.2} weather_probability_dist = ProbDist(weather_dict) # unneccesary but follows previous convention TeamWeather_SGP = joint(SGP_teams, weather_probability_dist) TeamWeather_RGP = joint(RGP_teams, weather_probability_dist) TeamWeather_SGP_TeamWeather_RGP = joint(TeamWeather_SGP, TeamWeather_RGP) condition = 'MercedesRain' mercedes_wins_one_on_rainy = [value for key, value in TeamWeather_SGP_TeamWeather_RGP.items() if (condition in key)] mercedes_win_both = team_win_both.get('Mercedes') print("Given Mercedes wins one of the two races on a rainy day, probability that Mercedes wins both races is: " + str(round((mercedes_win_both/sum(mercedes_wins_one_on_rainy)*100), 2)) + " %")
3e986e12dd1a19e7794c9b3def06b833b19d0695
littleyellowbicycle/pythonPrac
/printPrac.py
297
3.90625
4
# -*- coding: utf-8 -*- test="%r %r %r %r" print test %( "this", "is", "a", "test" ) print """ we can say "this is a test" lol ????? """ print "%r" %"\t" print "this is" print "a test" raw_input_A = raw_input("raw_input: ") input_A = input("input: ") print raw_input_A print input_A
3f0e34d8d383ed052cd70f78a70a85d98c428114
alchemyfordummies/march_madness_simulator
/marchmadness_2017.py
7,742
3.765625
4
import random import time #64-team tournament ~.75 seconds class Team: def __init__(self, n, s): self.__name = n; self.__seed = s; self.__games_won = 0; self.__upsets = 0; self.__teams_upset = []; def get_name(self): return self.__name def get_seed(self): return self.__seed def set_upsets(self): self.__upsets += 1 def add_team_upset(self, team_name): self.__teams_upset.append(team_name) def tournament(): print("2016 NCAA Tournament:") num_teams_left = len(teams) while num_teams_left > 1: print_round_message(num_teams_left) tournament_round() num_teams_left = len(teams) simulation_summary() print("####################################################################\n####################################################################\n####################################################################\n") def tournament_round(): round_winners = [] for x in range(0, len(teams) - 1, 2): round_winners.append(game(teams[x], teams[x + 1])) remove_losers(round_winners) def game(team_one, team_two): winner = False if team_one.get_seed() == team_two.get_seed(): winner = (random.randint(0, 100) < 50) else: winner = random.randint(0, 1000) < matchups[team_one.get_seed() - 1][team_two.get_seed() - 1] if (winner): return [team_one, team_two] else: return [team_two, team_one] def remove_losers(winner_array): for winner in winner_array: if winner[0].get_seed() > winner[1].get_seed(): print("UPSET ALERT: no. ", winner[0].get_seed(), winner[0].get_name(), "beat no.", winner[1].get_seed(), winner[1].get_name()) winner[0].set_upsets() winner[0].add_team_upset(winner[1].get_name()) else: print(winner[0].get_name(), winner[0].get_seed()) teams.remove(winner[1]) def print_round_message(num_teams): if num_teams == 16: print("Sweet Sixteen") elif num_teams == 8: print("Elite Eight") elif num_teams == 4: print("Final Four") elif num_teams == 2: print("National Championship Game") #Tournament setup #1 #2 #3 #4 #5 #6 #7 #8 #9 #10 #11 #12 #13 #14 #15 #16 seedone = [500, 528, 606, 686, 840, 687, 833, 805, 904, 857, 500, 993, 990, 890, 920, 999] seedtwo = [472, 500, 623, 444, 200, 722, 722, 444, 500, 600, 929, 955, 830, 860, 937, 920] seedthree = [394, 377, 500, 625, 500, 548, 600, 650, 950, 692, 708, 770, 800, 836, 965, 890] seedfour = [314, 556, 375, 500, 551, 333, 400, 300, 667, 940, 710, 684, 803, 800, 830, 860] seedfive = [160, 800, 500, 449, 500, 530, 530, 250, 333, 930, 680, 669, 800, 770, 990, 830] seedsix = [313, 278, 452, 667, 470, 500, 625, 250, 641, 600, 649, 680, 710, 875, 730, 800] seedseven = [167, 278, 400, 600, 470, 375, 500, 500, 641, 605, 110, 650, 680, 930, 667, 770] seedeight = [195, 556, 350, 700, 750, 750, 500, 500, 526, 560, 790, 310, 925, 680, 710, 740] seednine = [96, 500, 50, 333, 667, 359, 359, 474, 500, 530, 560, 590, 920, 650, 680, 710] seedten = [143, 400, 308, 60, 70, 400, 395, 440, 470, 500, 333, 560, 590, 710, 920, 680] seedeleven = [500, 71, 292, 290, 320, 351, 890, 210, 440, 667, 500, 530, 560, 890, 620, 650] seedtwelve = [7, 45, 230, 316, 331, 320, 350, 690, 410, 440, 470, 500, 727, 560, 590, 620] seedthirteen = [10, 170, 200, 197, 200, 290, 320, 75, 80, 410, 440, 273, 500, 530, 560, 590] seedfourteen = [110, 140, 164, 200, 230, 125, 70, 320, 350, 290, 110, 440, 470, 500, 530, 560] seedfifteen = [80, 63, 35, 170, 200, 230, 333, 290, 320, 80, 380, 410, 440, 470, 500, 530] seedsixteen = [1, 80, 110, 140, 170, 200, 230, 260, 290, 320, 350, 380, 410, 440, 470, 500] matchups = [seedone, seedtwo, seedthree, seedfour, seedfive, seedsix, seedseven, seedeight, seednine, seedten, seedeleven, seedtwelve, seedthirteen, seedfourteen, seedfifteen, seedsixteen] #Simulation statistics roundone = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] roundtwo = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] roundthree = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] roundfour = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] championship = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] winner = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] rounds = [roundone, roundtwo, roundthree, roundfour, championship, winner] winning_teams = {} def fill_teams(): return [Team('Villanova', 1), Team('MSM/UNO', 16), Team('Wisconsin', 8), Team('Virginia Tech', 9), Team('Virginia', 5), Team('UNC Wilmington', 12), Team('Florida', 4), Team('East Tennessee State', 13), Team('SMU', 6), Team('Providence/USC', 11), Team('Baylor', 3), Team('New Mexico State', 14), Team('South Carolina', 7), Team('Marquette', 10), Team('Duke', 2), Team('Troy', 15), Team('Gonzaga', 1), Team('South Dakota St.', 16), Team('Northwestern', 8), Team('Vadnerbilt', 9), Team('Notre Dame', 5), Team('Princeton', 12), Team('West Virginia', 4), Team('Bucknell', 13), Team('Maryland', 6), Team('Xavier', 11), Team('Florida State', 3), Team('Florida Gulf Coast', 14), Team('Saint Mary\s', 7), Team('VCU', 10), Team('Arizona', 2), Team('North Dakota', 15), Team('Kansas', 1), Team('NC Central/UC Davis', 16), Team('Miami (FL)', 8), Team('Michigan St.', 9), Team('Iowa State', 5), Team('Nevada', 12), Team('Purdue', 4), Team('Vermont', 13), Team('Creighton', 6), Team('Rhode Island', 11), Team('Oregon', 3), Team('Iona', 14), Team('Michigan', 7), Team('Oklahoma State', 10), Team('Louiseville', 2), Team('Jacksonville State', 15), Team('UNC', 1), Team('Texas Southern', 16), Team('Arkansas', 8), Team('Seton Hall', 9), Team('Minnesota', 5), Team('Middle Tennessee State', 12), Team('Butler', 4), Team('Winthrop', 13), Team('Cincinnati', 6), Team('Kansas St./Wake Forest', 11), Team('UCLA', 3), Team('Kent State', 14), Team('Dayton', 7), Team('Wichita State', 10), Team('Kentucky', 2), Team('Northern Kentucky', 15)] #all the teams go in here from top to bottom, left to right def simulation_summary(): teams_left = len(teams) active_round = 0 if teams_left == 32: active_round = 1 elif teams_left == 16: active_round = 2 elif teams_left == 8: active_round = 3 elif teams_left == 4: active_round = 4 elif teams_left == 2: active_round = 5 else: active_round = 6 if teams[0].get_name() in winning_teams: winning_teams[teams[0].get_name()] += 1 else: winning_teams[teams[0].get_name()] = 1 for team in teams: rounds[active_round - 1][team.get_seed() - 1] += 1 teams = fill_teams() for x in range(0, 1000): teams = fill_teams() print("TOURNAMENT NO. ", x + 1) tournament() print('\n\n\n\n\n\n\n\n\n\n') print(rounds[0]) print(rounds[1]) print(rounds[2]) print(rounds[3]) print(rounds[4]) print(rounds[5]) for key, value in winning_teams.items(): print(key, value) ''' 1 16 1 8 8 9 1 4 4 13 4 5 5 12 1 2 2 15 2 7 7 10 2 3 3 14 3 6 6 11 '''
b1fdc2281954caca8f46f450bd5eaae8de7189c2
TrangHo/cs838-code
/src/lib/features/feature09.py
777
3.515625
4
import re from lib.constants import prefixKeywords # Whether it has the keywords prefix: "receive", "degree", "M.B.A.", "master" # - Whether it has the prefix: "received a/an (M.B.A.)/(... degree) (in ...) from" # - and received a law degree from the <pos>University of Pennsylvania</pos> # - He graduated cum laude from <pos>Middlebury College</pos> and received an M.B.A. from <pos>Stanford</pos> # - He graduated from <pos>Virginia Tech</pos>, and received an M.B.A. in finance from <pos>Washington University</pos> in St. Louis. def test(str, prefix): nouns = '|'.join(prefixKeywords.PREFIX_KEYWORDS) # pattern = re.compile('(' + nouns + ')\\s' + '\\bat') pattern = re.compile('('+ nouns + ')') return re.search(pattern, prefix) is not None
029b2ce6ee636e94d07b15904a527b8c0688a40a
Sirachenko12/Homework
/zadanie 4.py
110
3.625
4
n = int(input("Podaj liczbę całkowitą: ")) i = 1 while i <= n: print(i * i , end=' ') i += 1 print()
76ef203b71aab063c274874112bf94a78d8c1e8f
s3rvac/talks
/2018-03-05-Introduction-to-Python/examples/13-type-hints.py
440
3.671875
4
# The presence of type hints has no effect on runtime whatsoever. It is used by # source analyzers (e.g. http://mypy-lang.org/). # # Requires Python >= 3.5. def hello(name: str) -> str: return 'Hello ' + name hello('Joe') # Hello Joe hello(5) # Hello 5 # The type hints can be accessed via __annotations__: print(hello.__annotations__) # {'name': <class 'str'>, 'return': <class 'str'>} i: int = 'hey!' # OK i = [1, 2, 3] # OK
20b5a8c2bf021f2593103ae78594c3dbab8b90e5
HaydenInEdinburgh/LintCode
/829_word_pattern_II.py
1,265
3.8125
4
class Solution: """ @param pattern: a string,denote pattern string @param str: a string, denote matching string @return: a boolean """ def wordPatternMatch(self, pattern, str): # write your code here if not pattern or not str: return False p_to_word = {} used = set() return self.dfs(pattern, 0, str, 0, p_to_word, used) def dfs(self, pattern, i, source, j, p_to_word, used): if i == len(pattern): return j == len(source) p = pattern[i] if p in p_to_word: word = p_to_word[p] if not source[j:].startswith(word): return False return self.dfs(pattern, i+1, source, j+len(word), p_to_word, used) for index in range(j, len(source)): word = source[j: index+1] if word in used: continue used.add(word) p_to_word[p] = word if self.dfs(pattern, i+1, source, index+1, p_to_word, used): return True del p_to_word[p] used.remove(word) return False if __name__ == '__main__': s = Solution() pattern = "d" str = "ef" print(s.wordPatternMatch(pattern, str))
cc9c02f97a3876f94db67e57b6a15acedadb088e
evidawei/Hacktoberfest2021-2
/Python/sum_array.py
108
3.65625
4
def sum(arr): sum=0 for i in arr: sum+=i return sum arr=[] arr=[1,2,3] print(sum(arr))
c8062f2b17ec267f6aecab992882f9c64ddcf753
LEE2020/leetcode
/coding_reversion/687_samevaluepath.py
1,367
4.15625
4
''' 给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。 注意:两个节点之间的路径长度由它们之间的边数表示。 示例 1: 输入: 5 / \ 4 5 / \ \ 1 1 5 输出: 2 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-univalue-path 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def longestUnivaluePath(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 global length length = 0 self.maxlength(root,root.val) return length def maxlength(self,root,val): global length if not root: return 0 left = self.maxlength(root.left,root.val) right = self.maxlength(root.right,root.val) length = max(length,left+right) if root.val == val : return max(left,right)+1 return 0
9086fd4f5f9a4843ddfc6a398fe544df1a626d79
wtrnash/LeetCode
/python/040组合总和II/040组合总和II.py
1,539
3.609375
4
""" 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用一次。 说明: 所有数字(包括目标数)都是正整数。 解集不能包含重复的组合。 示例 1: 输入: candidates = [10,1,2,7,6,1,5], target = 8, 所求解集为: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] 示例 2: 输入: candidates = [2,5,2,1,2], target = 5, 所求解集为: [ [1,2,2], [5] ] """ # 解答:相比39题,这题主要是每个元素只能用一次,所以递归的时候start设置要加1。另外还要考虑有相同的元素导致结果重复的问题。 class Solution: def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ result = [] temp = [] candidates.sort() self.dfs(result, temp, candidates, target, 0) return result def dfs(self, result, temp, candidates, target, start): if target < 0: return elif target == 0: result.append(temp[:]) return n = len(candidates) for i in range(start, n): if i > start and candidates[i] == candidates[i - 1]: continue temp.append(candidates[i]) self.dfs(result, temp, candidates, target - candidates[i], i + 1) temp.pop()
adf83a155f22d1d03ad3554378bdacd20b334c54
grockcharger/LXFpython
/slice.py
486
3.875
4
#!/usr/bin/env python in Linux/OS X # -*- coding: utf-8 -*- # 切片 # 1 L = ['Michael','Sarah','Tracy','Bob','Jack'] print L,"\n" print [L[0],L[1],L[2]],"\n" # 2 r = [] n = 3 for i in range(n): r.append(L[i]) print r,"\n" print L[0:3],"\t",L[:3] print L[-2:],"\t",L[-2:-1],"\n" L = range(100) print L,"\n" print L[:10] print L[-10:] print L[:10:2] print L[::5] print L[:],"\n" # tuple ,字符串或者unicode字符串都可以切片 print (1,2,3,4)[:3] print 'ABCDE'[:1]
0a9788e3aca817a8e3c9bfdd55cc60dddfa710ba
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH05/EX5.43.py
341
4.125
4
# 5.43 (Math: combinations) Write a program that displays all possible combinations for # picking two numbers from integers 1 to 7. Also display the total number of combinations. count = 0 for i in range(1, 8): for j in range(i+1, 8): print(i, " ", j) count += 1 print("The total number of all combinations is", count)
04ff4e8bb6e48e265c329b8719f3152a4921adc2
DongGunYoon/Algo_DS
/mar_26th/circularLinkedList.py
967
4.09375
4
class Node: def __init__(self, value, next): self.value = value self.next = next class CircularLinkedList: def __init__(self): self.head = None def append(self, value): if self.head is None: node = Node(value, None) self.head = node node.next = node else: cur_node = self.head while cur_node.next != self.head: cur_node = cur_node.next cur_node.next = Node(value, self.head) def print(self): result = '' cur_node = self.head while cur_node.next != self.head: result += str(cur_node.value) + ' ' cur_node = cur_node.next result += str(cur_node.value) print(result) linked = CircularLinkedList() linked.append(1) linked.append(3) linked.print() linked.append(5) linked.append(7) linked.print() linked.append(9) linked.append(11) linked.print()
571824bb765ae0d6c692c10ca8971438d00c9390
amar-jain123/PythonLoop
/loop/p4.py
508
3.703125
4
''' 1 2 1 4 2 1 8 4 2 1 16 8 4 2 1 32 16 8 4 2 1 ''' # first input the number of rows rows = int(input()) # outer loop for i in range(1, rows+1): # Inner loop start, stop and step for j in range(-1+i, -1, -1): print(2**j, end=' ') # for new lines print('') # list comprehension a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] square = [i*i for i in a if i%2 == 0] print(square) # lambda function map, reduce, filter square_list = list(map(lambda x: x*x, a)) print(square_list)
3df49a86d9156ac566050c989a68abaf175cc96e
harshsinha03/naruto-cv
/imgproc/filter.py
3,969
3.59375
4
""" Filtering functions. """ import numpy as np def filter_col(img, f, mode='same', **kwargs): """ Filter an image with a single column filter. Args: - img: input image (2D numpy array) - f: input filter (1D numpy array) - mode: indicates size of output image ('full', 'same', or 'valid') - kwargs: keyword arguments for padding. If mode is not 'valid', pad mode can be specified using 'pad-type' """ k = len(f) if mode == 'full': if 'pad_type' in kwargs: img_pad = np.pad(img, ((k-1, k-1), (0, 0)), kwargs['pad_type'], **kwargs) else: img_pad = np.pad(img, ((k-1, k-1), (0, 0)), **kwargs) elif mode == 'same': if 'pad_type' in kwargs: img_pad = np.pad(img, ((int(k/2), int(k/2)), (0, 0)), kwargs['pad_type'], **kwargs) else: img_pad = np.pad(img, ((int(k/2), int(k/2)), (0, 0)), **kwargs) elif mode == 'valid': img_pad = img else: raise ValueError('Mode not a valid filter mode.') n, m = img_pad.shape layers = [img_pad[i:n-k+i+1, :].flatten() for i in range(k)] img_mat = np.stack(layers, axis=0) return np.matmul(f, img_mat).reshape((n-k+1, m)) def filter_row(img, f, mode='same', **kwargs): """ Filter an image with a single row filter. Args: - img: input image (2D numpy array) - f: input filter (1D numpy array) - mode: indicates size of output image ('full', 'same', or 'valid') - kwargs: keyword arguments for padding. If mode is not 'valid', pad mode can be specified using 'pad-type' """ k = len(f) if mode == 'full': if 'pad_type' in kwargs: img_pad = np.pad(img, ((0, 0), (k-1, k-1)), mode=kwargs.pop('pad_type'), **kwargs) else: img_pad = np.pad(img, ((0, 0), (k-1, k-1)), **kwargs) elif mode == 'same': if 'pad_type' in kwargs: img_pad = np.pad(img, ((0, 0), (int(k/2), int(k/2))), mode=kwargs.pop('pad_type'), **kwargs) else: img_pad = np.pad(img, ((0, 0), (int(k/2), int(k/2))), **kwargs) elif mode == 'valid': img_pad = img else: raise ValueError('Mode not a valid filter mode.') n, m = img_pad.shape layers = [img_pad[:, i:m-k+i+1].flatten() for i in range(k)] img_mat = np.stack(layers, axis=0) return np.matmul(f, img_mat).reshape((n, m-k+1)) def filter_sep(img, fx, fy, mode='same', **kwargs): """ Filter an image with the given filter components. Args: - img: input image (2D numpy array) - fx: input row filter (1D numpy array) - fy: input column filter (1D numpy array) - mode: indicates size of output image ('full', 'same', or 'valid') - kwargs: keyword arguments for padding. If mode is not 'valid', pad mode can be specified using 'pad-type' """ kx = len(fx) ky = len(fy) if mode == 'full': if 'pad_type' in kwargs: img_pad = np.pad(img, ((ky-1, ky-1), (kx-1, kx-1)), mode=kwargs.pop('pad_type'), **kwargs) else: img_pad = np.pad(img, ((ky-1, ky-1), (kx-1, kx-1)), **kwargs) elif mode == 'same': if 'pad_type' in kwargs: img_pad = np.pad(img, ((int(ky/2), int(ky/2)), (int(kx/2), int(kx/2))), mode=kwargs.pop('pad_type'), **kwargs) else: img_pad = np.pad(img, ((int(ky/2), int(ky/2)), (int(kx/2), int(kx/2))), **kwargs) elif mode == 'valid': img_pad = img else: raise ValueError('Mode not a valid filter mode.') temp = filter_col(img_pad, fy, mode='valid', **kwargs) return filter_row(temp, fx, mode='valid', **kwargs) if __name__ == '__main__': # filtering example img = np.arange(9).reshape((3,3)) fx = np.array([0,0,1]) fy = np.array([0,0,1]) out = filter_sep(img, fx, fy, mode='same', pad_type='constant', constant_values=0) print(out)
45b6d74202126ea218fb94db98dc0a00db8c5ea6
Fhernd/PythonEjercicios
/Parte002/ex1078_hackerrank_combinaciones_caracteres_itertools.py
687
3.84375
4
# Ejercicio 1078: HackerRank Imprimir en orden lexicográfico las combinaciones de varios caracteres. # Task # You are given a string . # Your task is to print all possible combinations, up to size , of the string in lexicographic sorted order. from itertools import combinations if __name__ == '__main__': s, k = input().split() k = int(k) result = [] s = sorted(s) for r in range(1, k + 1): combinations_r = list(combinations(s, r)) combinations_r = [''.join(c) for c in combinations_r] combinations_r = sorted(combinations_r) result.extend(combinations_r) for c in result: print(c)
4948e685666ba5633a7d723dd468f98e49afec94
yashrajkakkad/Automate-The-Boring-Stuff-Solutions
/chapter-7/regex_strip.py
845
4.03125
4
''' regex_strip.py Author: Yashraj Kakkad Chapter 7, Automate the Boring Stuff with Python ''' import re def regex_strip(string, chars=""): stripRegex = None if chars == "": stripRegex = re.compile(r'\S+.*\S+') stripMatch = stripRegex.search(string) new_string = stripMatch.group(0) # new_string = stripRegex.sub('', string) else: stripRegex = re.compile(chars + r'(.*)' + chars) stripMatch = stripRegex.search(string) new_string = stripMatch.group(1) # print(len(new_string)) # new_string = stripRegex.sub('', string) return new_string def main(): string = input("Enter a string: ") chars = input( "Enter the string to strip. Press enter to remove white-spaces: ") print(regex_strip(string, chars)) if __name__ == "__main__": main()
593c80c763a6a7264ba6217ba93d5612f58ad253
nzevgolisda/tavli.py
/Square.py
246
3.53125
4
from Piece import Piece class Square: def __init__(self, pos): self.pos = pos self.pieces = [] def __str__(self): s = '' for piece in self.pieces: s += str(piece) return s s = Square(0)
863337d82338ca79957742c7bcacfab4791bf41b
alexaquino/HackerEarth
/Problems - Very Easy/ToggleString.py
239
3.703125
4
# Toggle String # https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/modify-the-string/ #input first_line = input() #output output = first_line.swapcase() print(output)
a5c99de7d3243a509f861f29effdf34af513226f
JOLLA99/Algorithm-Study
/04_이남준/week_01/2588.py
201
3.640625
4
num1 = int(input()) num2 = input() num2_1s = int(num2[2]) num2_10s = int(num2[1]) num2_100s = int(num2[0]) print(num1 * num2_1s) print(num1 * num2_10s) print(num1 * num2_100s) print(num1 * int(num2))
8339a54dd030ea3e86f16f6364953c59c502ca9e
milenatteixeira/cc1612-exercicios
/exercicios/lab 9.2/modulo.py
2,019
3.859375
4
def funcao(x): #criaçao de dicionários centena = {1: 'cento',2: 'duzentos',3: 'trezentos',4: 'quatrocentos',5: 'quinhentos',6: 'seicentos',7: 'setecentos',8: 'oitocentos',9: 'novecentos'} dezena = {1:'dez',2:'vinte',3:'trinta',4:'quarenta',5:'cinquenta',6:'sessenta',7:'setenta',8:'oitenta',9:'noventa'} unidade = {1:'um',2:'dois',3:'tres',4:'quatro',5:'cinco',6:'seis',7:'sete',8:'oito',9:'nove'} dezdif = {10: 'dez',11:'onze',12:'doze',13:'treze',14:'catorze',15:'quinze',16:'dezesseis',17:'dezesete',18:'dezoito',19:'dezenove'} x = str(x) #separarando cada número em váriaveis diferentes if len(x)==3: x1 = int(x[0]) x2 = int(x[1]) x3 = int(x[2]) sx2 = str(x2) sx3 = str(x3) y = sx2+sx3 y = int(y) if x3!=0: if x2==0: print(f"{x} = {centena[x1]} e {unidade[x3]}") elif y>10 and y<20: print(f"{x} = {centena[x1]} e {dezdif[y]}") else: print(f"{x} = {centena[x1]} e {dezena[x2]} e {unidade[x3]}") elif x3==0 and x2!=0: print(f"{x} = {centena[x1]} e {dezena[x2]}") elif x=='100': print(f"{x} = cem") else: print(f"{x} = {centena[x1]}") elif len(x)==2: y = int(x) x1 = int(x[0]) x2 = int(x[1]) if x2 != 0: if y>10 and y<20: print(f"{x} = {dezdif[y]}") elif y>=20: print(f"{x} = {dezena[x1]} e {unidade[x2]}") else: print(f"{x} = {dezena[x1]}") elif len(x)==1: x = int(x) if x == 0: print(f"{x} = zero") else: print(f"{x} = {unidade[x]}") else: print("Número incorreto!")
31f955395602ff711f17a057b229cbb2409fb84e
AustinMitchell/ProjectEuler_Python
/Solutions/p003.py
364
3.59375
4
from __future__ import division def isPrime(n): for i in range(2, n//2): if n%i == 0: return False return True largest = 0 n = 600851475143 current = 2 while (n != 1): if (n%current == 0): n = n//current if current > largest: largest = current current = 2 else: current += 1 while (not isPrime(current)): current += 1 print largest
82dce60a2441db9d2d557a2883cdeda230a645dd
ValerieBrave/ITechArt-courses
/tribonacchi.py
827
3.71875
4
class RangeIterator: def __init__(self, size): self.c = 0 self.first = 0 self.second = 0 self.third = 1 self.size = size def __next__(self): self.c += 1 if self.c > self.size: raise StopIteration if self.c == 1: return self.first if self.c == 2: return self.second if self.c == 3: return self.third new_trib = self.first + self.second + self.third self.first = self.second self.second = self.third self.third = new_trib return new_trib class RangeIterable: def __init__(self, size): self.size = size def __iter__(self): return RangeIterator(self.size) main_iter = RangeIterable(32) for line in main_iter: print(line)
c7949cc49a0269af2663b193fc90fcfd0a9d178b
AntimonyAidan/Intro-To-OPP
/PP3.py
4,149
3.828125
4
''' Name: Aidan Latham Email: aidan.latham@slu.edu Current Date: Feb 15th Course Information: CSCI 1300-01 Instructor: Judy Etchison Description: Source code for "Mastermind" code game. Includes user defined functions and loop structures. ''' ''' Import packages ''' # Import cs1graphics package to use for extra credit from cs1graphics import * # Import function to generate code from random import randint ''' Establish Canvas to be used ''' # Create Canvas screen = Canvas(1000,800,'brown') ''' Define necessary functions ''' # define function to check validity of input def valid_check(num_str): if(not num_str.isdigit()): return "ERROR: contains non-numbers, try again" if(len(num_str) != 4): return "ERROR: enter 4 digits, try again" for i in range(4): if(int(num_str[i]) > 5 or int(num_str[i]) < 1): return "ERROR: guess must be comprised of digits 1-5, try again" return '' # define function to check user input code vs. generated code def check_code(code,user_num_str): num_exist = 0 num_right_position = 0 exclude_pos_code = [] exclude_pos_str = [] for i in range(4): if(user_num_str[i] == code[i]): num_right_position += 1 exclude_pos_str.append(i) exclude_pos_code.append(i) for i in range(4): for j in range(4): if(user_num_str[i] == code[j] and not (i in exclude_pos_str) and not (j in exclude_pos_code)): num_exist += 1 exclude_pos_str.append(i) exclude_pos_code.append(j) return [num_exist,num_right_position] # define function to print out circles def display_circles(code,ycod): colors = ['yellow','purple','green','blue','red'] master_xcod = 160 for i in range(4): temp_circ = Circle(20,Point(master_xcod,ycod)) temp_circ.setFillColor(colors[int(code[i])-1]) screen.add(temp_circ) master_xcod += 80 # define function to display right/wrong count def display_pegs(results_list,ycod): exist_text = Text(str(results_list[0]),24,Point(500,ycod)) exist_text.setFontColor('white') right_pos_text = Text(str(results_list[1]),24,Point(540,ycod)) right_pos_text.setFontColor('red') screen.add(exist_text) screen.add(right_pos_text) ''' main body ''' # First, generate code and print start, and display # opening text on canvas master_code = '' for i in range(4): master_code += str(randint(1,5)) print "Ready to play Mastermind!!" print "\n\n" screen.add(Text("Ready to play Mastermind!!",24,Point(800,40))) screen.add(Text("White means num present, but not right position",12,Point(800,80))) screen.add(Text("Red means num present AND right position",12,Point(800,100))) screen.add(Text("Input guess using command prompt",12,Point(800,120))) # Display code in the form of circles at bottom of Canvas, # and hide them with a black rectangle until completion master_ycod = 740 display_circles(master_code,master_ycod) cover = Rectangle(280,40,Point(280,master_ycod)) cover.setFillColor('black') screen.add(cover) # Prompt user for input answer_list = [0,0] num_guess = 0 circ_ycod = 40 while(True): guess = raw_input("Guess?: ") if("ERROR" in valid_check(guess)): print valid_check(guess) else: display_circles(guess,circ_ycod) num_guess += 1 answer_list = check_code(master_code,guess) display_pegs(answer_list,circ_ycod) if(answer_list[1] == 4 or num_guess == 10): break print answer_list[0],"exist but are not in the right position,",answer_list[1], print "are in the right position." circ_ycod += 60 # Display results/remove master code cover print "\n\n" if(guess == master_code): screen.add(Text("You cracked the code!",24,Point(800,700))) print "You guessed the key:",master_code, print "It took you",num_guess,"guesses.\n\n\n" else: screen.add(Text("Oof, wrong!",24,Point(800,700))) print "Sorry, you lost. The code was",master_code,"Try again next time.\n\n\n" screen.remove(cover)
ebafc0930b9e2e2a21ae34d107f30aa16bda81df
sachinpkale/ContactsApp
/src/contacts.py
915
4.03125
4
"""ContactsApp supports two functions: 1. add_contact 2. search_contact Assumptions: 1. Only prefix based search is supported. 2. As data is being stored in in-memory data structure, it will not be available in subsequent runs of the application. """ from src.contacts_app import ContactsApp if __name__ == "__main__": contacts_app = ContactsApp() while(True): choice = int(input("1) Add contact 2) Search 3) Exit\n")) if choice in [1, 2]: contact = str(raw_input("Enter name: ")) if choice == 1: contacts_app.add_contact(contact) else: contacts = contacts_app.search_contact(contact) if contacts: for c in contacts: print c elif choice == 3: print "Happy Searching" break else: print "Please enter 1, 2 or 3"
5d707c6c862bf839d6d820c72b650a49ca1239a3
loggar/py
/py-core/dictionary/dictionary.invert.py
748
4.40625
4
# Use to invert dictionaries that have unique values from collections import defaultdict my_inverted_dict = dict(map(reversed, my_dict.items())) # Use to invert dictionaries that have unique values my_inverted_dict = {value: key for key, value in my_dict.items()} # Use to invert dictionaries that have non-unique values my_inverted_dict = defaultdict(list) {my_inverted_dict[v].append(k) for k, v in my_dict.items()} # Use to invert dictionaries that have non-unique values my_inverted_dict = dict() for key, value in my_dict.items(): my_inverted_dict.setdefault(value, list()).append(key) # Use to invert dictionaries that have lists of values my_dict = {value: key for key in my_inverted_dict for value in my_map[key]}
ebb851f8606e6d71362d13f8c627e7649b54a92a
sqq113/Code
/first work/Action1.py
173
3.71875
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 31 18:12:21 2021 @author: songqianqian """ sum=0 for number in range(2,102,2): sum=sum+number print(sum)
62d3560028d1a9b76743eba009d07627508474c7
a-bereg/my_learning
/ex_03/04_student.py
1,317
4
4
# -*- coding: utf-8 -*- # (цикл while) # Ежемесячная стипендия студента составляет educational_grant руб., а расходы на проживание превышают стипендию # и составляют expenses руб. в месяц. Рост цен ежемесячно увеличивает расходы на 3%, кроме первого месяца # Составьте программу расчета суммы денег, которую необходимо единовременно попросить у родителей, # чтобы можно было прожить учебный год (10 месяцев), используя только эти деньги и стипендию. # Формат вывода: # Студенту надо попросить ХХХ.ХХ рублей educational_grant, expenses = 10000, 12000 month = 1 total_expenses = expenses while month < 10: print('Месяц', month, ':', total_expenses) expenses = expenses + expenses * 0.03 total_expenses += expenses month += 1 print('Все расходы:', round(total_expenses, 2)) parents_money = total_expenses - educational_grant * 10 print('Студенту надо попросить', round(parents_money, 2), 'рублей')