blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
414e495900fabcad180e54d88c31c92abfb0c7fd
mahidhar93988/python-basics-nd-self
/growth.py
265
3.546875
4
n = int(input()) list = [] for i in range(n): element = int(input()) list.append(element) add = 0 for i in range(0, len(list)): add = add + list[i] ave = add / n if ave > 100: print("Excellent!") else: print("Not Excellent!")
73521ec81d51bc78eeda2c636402f9be0e796776
mahidhar93988/python-basics-nd-self
/difference_sum_even_odd_index.py
539
4.125
4
# difference_sum_even_odd_index # You should name your function as difference_sum_even_odd_index # It should take a list of integers # Return an integer def difference_sum_even_odd_index(arr): e = 0 o = 0 for i in range(len(arr)): if i % 2 == 0: e += arr[i] else: o += arr[i] return e-o # Do not change anything below this line if __name__ == "__main__": numbers = [int(i) for i in input().split(' ')] print(difference_sum_even_odd_index(numbers))
2479e27d0408a075e71e9288676ca008737a5156
mahidhar93988/python-basics-nd-self
/natural_numbers_sum.py
163
3.703125
4
# natutral numbers sum n = int(input()) #5 output = 0 for i in range (1,n+1): output = output + i #1 #3 #6 #10 #15 # print(i,output) print(output)
79417b11af9bdfbdb64d3e6858b254fea41d854f
mahidhar93988/python-basics-nd-self
/input_reader.py
723
3.765625
4
# input_reader class input_reader: def __init__(self): self.data = [] def read_strings(self, N): while(N > 0): self.data.append(input()) N -= 1 def read_integers(self, N): while(N > 0): self.data.append(int(input())) N -= 1 def read_float(self, N): while(N > 0): self.data.append(round(float(input()), 2)) N -= 1 N = int(input()) ins = input() temp = input_reader() if(ins == "strings"): temp.read_strings(N) if(ins == "integers"): temp.read_integers(N) if(ins == "float"): temp.read_float(N) for i in range(len(temp.data)): print(i, temp.data[i])
b26ec291617997e5f7e51165a0e364be58e15861
mahidhar93988/python-basics-nd-self
/Life_the_Universe_and_Everything.py
118
3.53125
4
# Life, the Universe, and Everything A = int(input()) while A != 42: print(A) A = int(input()) # nd
4060453ccecbf0e81d6b2771f6ac553613b56186
mahidhar93988/python-basics-nd-self
/cheking_prime_numbers.py
379
3.71875
4
# finding prime number N = int(input()) i = 0 while (i < N): n = int(input()) if (n == 1): print("NO") i += 1 # i = i+1 continue j = 2 ind = 0 while(j <= n-1): if (n % j == 0): ind = 1 j += 1 if(ind == 0): print("Yes") else: print("No") i += 1 # nd
c3e5c1627f1c367a1849a52d7a4cb2fc9597471d
gabymy/siguetucamino
/Eligetucamino.py
1,988
3.90625
4
import random import time def mostrarIntroduccion(): print('Acabas de despertar, en una tierra desconocida. No salis de tu asombro') time.sleep(2) print('ya que te habias dormido placidamente en tu cama.') time.sleep(2) print('Miras alrededor y descubres, dos cuevas:') time.sleep(2) print('ignoras que hay dentro, pero tenes que escoger una sola') time.sleep(2) print('Con la poca luz que hay, distinguis que una cueva esta llena de brillo en su interior') time.sleep(2) print('La otra, enama luces de colores pero es mas brillante') time.sleep(2) print('En las dos hay ruidos que parecen rugidos...') time.sleep(2) def elegirCueva(): cueva = '' while cueva != '1' and cueva != '2': print('¿a que cuevas queres entrar (1 o 2)') cueva = input() return cueva def explorarCueva(cuevaElegida): print('Lleno de temor, te estas acercando a la cueva...') time.sleep(2) print('Descubres que lo que veias era solo una ilusion: Ninguna tiene luces...') time.sleep(2) print('Huele como a azufre y esta muy humedo...') time.sleep(2) print('Subitamente y para tu horrror ¡Un enorme dragon aparece delante tuyo! abre grande sus fauces') print('Te envuelve una rafaga de aliento pestido') time.sleep(2) print('¡No hay escapatoria posible!') print() time.sleep(2) cuevaAmigable = random.randint (1, 2) if cuevaElegida == str(cuevaAmigable): print('y......¡Te despertas en tu cama!') else: print('y.....¡Te come de un solo bocado!') jugarDeNuevo = 'si' while jugarDeNuevo == 'si' or jugarDeNuevo == 's': mostrarIntroduccion() numeroDeCueva = elegirCueva() explorarCueva(numeroDeCueva) print('¿Queres jugar de nuevo? (si o no)') jugarDeNuevo = input()
1ddc3ca40dcd813f75cb572c00bccfb3c2f521bb
Sahandfer/PyBlockChain
/Server/BlockChain.py
2,711
3.59375
4
import time import json import Block from hashlib import sha256 class BlockChain: difficulty = 2 # Difficulty for proof of work def __init__(self): """ Constructor for the `Blockchain` class. """ self.chain = [] # The blockchain self.pending_transactions = [] # Yet-to-be confirmed transactions (pending) def initialize(self): """ A function to create the initial block in the chain. """ initial_block = Block(0, [], time.time(), "0") initial_block.hash = initial_block.calc_hash() self.chain.append(initial_block) @property def last_block(self): """ A getter function for the last block in the chain. """ return self.chain[-1] def proof_of_work(self, block): """ This function tries different nonces to find a fitting hash. :param block: The block whose nonce is to be verified. """ block.nonce = 0 blockHash = block.computeHash() while not blockHash.startswith("0" * BlockChain.difficulty): block.nonce += 1 blockHash = block.calc_hash() return blockHash def verify_proof_of_work(self, block, proof): """ Check if block_hash is valid hash of block and satisfies the difficulty criteria. """ return ( proof.startswith("0" * BlockChain.difficulty) and proof == block.calc_hash() ) def add_block(self, block, proof): """ This function adds a block to the chain by verifying proof of work. :param block: The block that is to be added. :param proof: The proof of work for the block being added. """ prev_block = self.last_block.hash if prev_block != block.prev_block: return False if not BlockChain.verify_proof_of_work(block, proof): return False block.hash = proof self.chain.append(block) return True def add_transaction(self, transaction): self.pending_transactions.append(transaction) def mine(self): """ This function is for mining pending transactions. """ if not self.pending_transactions: return False last_block = self.last_block new_block = Block( index=last_block.index + 1, transactions=self.pending_transactions, timestamp=time.time(), prev_block=last_block.hash, ) proof = self.proof_of_work(new_block) self.add_block(new_block, proof) self.pending_transactions = [] return new_block.index
2c0d032eb368350ce81868ba4fc53b8d66df2244
SharifahS/Python-Challenge
/PyBank/main.py
3,367
3.984375
4
import os import csv filepath = os.path.join('Resources', 'budget_data.csv') # Identify my tile with spacing print(''' Financial Analysis''') print('''...................................... ''') # open and read csv file, then create a variable for the number of rows within the file # number of rows within the file has the same value as number of months with open(filepath, 'r') as file: reader1 = csv.reader(file, delimiter= ',') title = next(reader1) num_month = len(list(reader1)) num_month = str(num_month) print(f' Total Months: {num_month}') # open and read csv file, then create a empty list and a variable with 0 for later use with open(filepath, 'r') as file: reader2 = csv.reader(file, delimiter= ',') title = next(reader2) total = 0 li = [] # create a loop within the csv file, then create a variable to save the loop within the second column # chaged the format of the number to include dollar sign # then using the empty list to store my total for i in reader2: amount = int(i[1]) total = total + amount t = '${}'.format(total) li.append(t) print(f' total: {li[-1]}') # open and read csv file, then create a empty list and a variable with 0 for later use with open(filepath, 'r') as file: reader3 = csv.reader(file, delimiter= ',') title = next(reader3) av = 0 avli = [] # created a loop within the csv file and pulled my loop within row 1 into my empty list above for row in reader3: value = int(row[1]) avli.append(value) # created a nested loop to analyze the changes in profit # change format to include 2 decimal places avli2 = ([x - avli[j - 1] for j, x in enumerate(avli)][1:]) length = len(avli2) flo_num = sum(avli2) / length av_format = '{:.2f}'.format(flo_num) print(f' Average change: $ {av_format}') # open and read csv file, then create 2 empty list for later use with open(filepath, 'r') as file: reader4 = csv.reader(file, delimiter = ',') title = next(reader4) profit = [] date_profit = [] # created a for loop to go through Profit/Losses as well as entire csv file # use max and min function to find the values of the maximum and minimum Profit/losses # use index to reference correct result for i in reader4: record = int(i[1]) drecord = i profit.append(record) date_profit.append(drecord) _max = max(profit) _min = min(profit) dex = profit.index(_min) dex2 = profit.index(_max) min_date = date_profit[dex] max_date = date_profit[dex2] print(f' Greatest Increase in profits: {max_date}') print(f' Greatest Decrease in profits: {min_date}') print(''' ''') # converting variables into strings so that it can be saved in a txt file t = str(t) av_format = str(av_format) min_date = str(min_date) max_date = str(max_date) # opening a txt file with content for Financial Analysis file = open('Output.txt', 'a') file.writelines('Financial Analysis' '\n' '..........................' '\n' ' ' '\n' 'Total Months: ' + num_month + '\n' + 'Total: ' + t + '\n' + 'Average Change: ' + av_format + '\n' + 'Greatest Increase in Profits: ' + max_date + '\n' + 'Greatest Decrease in Profits: ' + min_date) file.close()
777fd7f72d1643d21f6ae9b41c9853b97ab5f6a0
tsubauaaa/CheetahBookPython
/Capter3/3-1.py
188
3.65625
4
def get_max_num(array): ret = array[0] for i in range(1, len(array)): if array[i] > ret: ret = array[i] return ret # print(get_max_num([1, 2, 3, 4, 5]))
0a39b48e8da9d6507d94638673025d2b8fba7c85
naveenshandilya30/Decision-Control-System
/Assignment_5.py
1,241
3.890625
4
#Question_1 year=int(input("enter year")) if year%4==0: print("The year is a leap year") else: print("The year is not a leap year") #Question_2 length= int(input("Enter length:")) breadth= int(input("Enter breadth:")) if length==breadth: print("dimensions are square") else: print("dimensions are rectangle") #Question_3 a=int(input("Enter age of person a:")) b=int(input("Enter age of person b:")) c=int(input("Enter age of person c:")) if (a>b and a>c): print ("a is older") elif (c>b and c>a): print("c is older") elif(b>a and b>c): print("b is older") if(a<b and a<c): print("a is younger") elif(b<a and b<c): print("b is younger") elif(c<a and c<b): print("c is younger") #Question_4 points=int(input("enter the points upto 200:")) if (points >1 and points <=50): print("No prize") elif(points >51 and points<=150): print("wooden dog") elif(points>151 and points<=180): print(" you won book") elif (points>181 and points<=200): print(" you won chocolate") #Question 5 a=int(input("enter the amount:")) print(a) if (a<=1000): print("Sorry, no discount") elif (a*100 > 1000): print ("Cost is",((a*100)-(.1*a*100))) else: print ("Cost is",a*100)
2cc1b81668dd9ab6c64b69f42acbacac27df274f
mlucas-NU/advent_of_code
/2020/day_1/main.py
1,193
3.65625
4
import argparse import logging # Helper functions def part2(expenses): for exp1 in expenses: for exp2 in expenses: for exp3 in expenses: if len(set([exp1, exp2, exp3])) < 3: continue if exp1 + exp2 + exp3 == 2020: return exp1 * exp2 * exp3 raise ValueError('Cannot find answer to Part 2.') # Parse Arguments parser = argparse.ArgumentParser() parser.add_argument('input_file', help='input file to read') parser.add_argument('--verbosity', help='specify verbosity level (DEBUG|INFO)') args = parser.parse_args() verbosity = 'INFO' if args.verbosity: verbosity = args.verbosity logging.getLogger().setLevel(logging.getLevelName(verbosity)) # Load inputs expenses = set() input_file = args.input_file with open(input_file) as f: for line in f.readlines(): expenses.add(int(line)) # Main Logic for expense in expenses: if 2020 - expense in expenses: logging.info(f'Part 1 Answer: {expense * (2020 - expense)}') break else: raise ValueError('Cannot find answer to Part 1.') answer2 = part2(expenses) logging.info(f'Part 2 Answer: {answer2}')
092e6138bec899df4f7ba6a4c68ee9460e0a4065
WilliamCawley/prime-test
/PrimeTest.py
3,191
4.375
4
#!/usr/bin/env python """PrimeTest.py - Processes a provided list of words and then searches this for an anagram provided by the user""" DATA = """\ starlet startle reduces rescued realist recused saltier retails secured """ # The below constant contains the letters of the English language sorted by frequency FREQUENCY_SORTED_LETTERS = "etaoinsrhdlucmfywgpbvkxqjz" # The below constant contains the first 26 prime numbers to match to FREQUENCY_SORTED_LETTERS PRIME_NUMBERS = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] def process(reference): """Takes in the word data provided (reference) and processes it ready for use in searching for anagrams""" reference.lower() # Create a map of letters to prime numbers based on the frequency of letters in the English language letter_to_prime = {} for i in range(len( PRIME_NUMBERS)): letter_to_prime[FREQUENCY_SORTED_LETTERS[i]] = PRIME_NUMBERS[i] word_hash_values = [] for line in reference.splitlines(): hash_value = 1 # The loop below will calculate the hash value of each word. # This is achieved by multiplying the prime number value of the letters. # The hash value of a word always stays the same even if the letters are in a different order for letter in line: if letter in letter_to_prime: hash_value *= letter_to_prime[letter] word_hash_values.append([line, hash_value]) # Add the line and hash value to an array return [letter_to_prime, word_hash_values] # Calculate the provided anagram hash value, and compare with previously processed results def find_anagrams(word_hash_values, letter_to_prime, word): """Using parameters from the 'process' function, this will search the data provided earlier for the anagram""" hash_index = 1 final_string = '' for letter in word: if letter in letter_to_prime: hash_index *= letter_to_prime[letter] for word_hash in word_hash_values: if hash_index == word_hash[1]: if word_hash[0] in word: # Ensure I don't display the original provided anagram continue final_string = final_string + word_hash[0] + "\n" continue else: continue if final_string: return final_string else: return False anagram_params = process(DATA) results = find_anagrams(anagram_params[1], anagram_params[0], word="rescued") print(results) # NOTES: # # There are a few things missing that I feel would take a disproportionate amount of time to include considering this is # the first stage of an interview yet I haven't spoken to anyone from the organisation. # # 1. A proper input method for 10.000.000 words, for example reading in from a txt, json etc # 2. Error handling with informative messages # 3. Further scenarios for special characters and apostrophes __author__ = "William Cawley" __copyright__ = "NA" __version__ = "1.0.0" __maintainer__ = "William Cawley" __email__ = "willjcawley@gmail.com" __status__ = "Development"
4555566a61490ad7e77ec3c83845e765411e6bb7
twodog1953/GUI-Password-Recorder
/main.py
4,095
3.625
4
from tkinter.messagebox import showinfo from tkinter import * import sqlite3 from os import path from datetime import datetime root = Tk() root.title('Password Logger') root.geometry("450x600") # db table if path.exists('password.db') == False: conn = sqlite3.connect('password.db') c = conn.cursor() c.execute("""CREATE TABLE password ( website text, username text, password text )""") conn.commit() conn.close() else: print('DB already exist. \n ------------------------------') # GUI frame = LabelFrame(root, text="input here", padx=20, pady=20) title_label = Label(root, text='This bloody thing will log your passwords for different websites. ', padx=15, pady=15 ) frame.grid(row=1, column=0, columnspan=2, padx=30, pady=30) title_label.grid(row=0, column=0, columnspan=2) website_label = Label(frame, text='Enter the website name here: ', padx=15, pady=15) website_label.grid(row=0, column=0, columnspan=2) e1 = Entry(frame, width=50, bg='white', fg='black', borderwidth=5) e1.grid(row=1, column=0, columnspan=2) name_label = Label(frame, text='Enter the user name here: ', padx=15, pady=15) name_label.grid(row=2, column=0, columnspan=2) e2 = Entry(frame, width=50, bg='white', fg='black', borderwidth=5) e2.grid(row=3, column=0, columnspan=2) password_label = Label(frame, text='Enter the password here: ', padx=15, pady=15) password_label.grid(row=4, column=0, columnspan=2) e3 = Entry(frame, width=50, bg='white', fg='black', borderwidth=5) e3.grid(row=5, column=0, columnspan=2) # functions def store(): website = e1.get() usn = e2.get() pw = e3.get() # sql process conn = sqlite3.connect('password.db') c = conn.cursor() c.execute("INSERT INTO password VALUES ('{}', '{}', '{}')".format(website, usn, pw)) conn.commit() conn.close() e1.delete(0, END) e2.delete(0, END) e3.delete(0, END) def show(): conn = sqlite3.connect('password.db') c = conn.cursor() c.execute("SELECT rowid, * from password") items = c.fetchall() now = datetime.now() print(now.strftime("%H:%M:%S")) for i in items: print('Index: {}. Website: {}. Username: {}. Password: {}. '.format(i[0], i[1], i[2], i[3])) print('------------------------------') conn.commit() conn.close() showinfo(title='Hey brudda', message='The result has been printed in the command window. ') def change(): global e4 top = Toplevel() top.geometry("350x400") change_label1 = Label(top, text='Enter the index of the record you want to delete. ') change_label1.grid(row=0, column=0, padx=10, pady=10) e4 = Entry(top, width=50, bg='white', fg='black', borderwidth=5) e4.grid(row=1, column=0, padx=10, pady=10) btn_exe_change = Button(top, text='Store', width=15, height=3, font=("Helvetica", 12), command=change_exe) btn_exe_change.grid(row=2, column=0, padx=10, pady=10) def change_exe(): del_ind = e4.get() e4.delete(0,END) conn = sqlite3.connect('password.db') c = conn.cursor() c.execute("DELETE from password WHERE rowid = {}".format(str(del_ind))) conn.commit() conn.close() showinfo(message='Record No.{} is deleted. '.format(str(del_ind))) return def quit_all(): root.quit() btn_store = Button(root, text='Store', width=15, height=3, font=("Helvetica", 12), command=store) btn_show = Button(root, text='Show Records', width=15, height=3, font=("Helvetica", 12), command=show) btn_change = Button(root, text='Delete Record', width=15, height=3, font=("Helvetica", 12), command=change) btn_quit = Button(root, text='Quit', width=15, height=3, font=("Helvetica", 12), command=quit_all) btn_store.grid(row=2, column=0, padx=10, pady=10) btn_show.grid(row=2, column=1, padx=10, pady=10) btn_change.grid(row=3, column=0, padx=10, pady=10) btn_quit.grid(row=3, column=1, padx=10, pady=10) root.mainloop()
e6ecde6b0fc4b8de945ee3b2c8b8de9e0e40fdab
yshutaro/study_leetcod
/1252/solution.py
826
3.515625
4
class Solution: def oddCells(self, n: int, m: int, indices: [[int]]) -> int: result = 0 matrix = [[0 for i in range(n)] for j in range(m)] #print("matrix step0:", matrix) for index in indices: row = index[0] col = index[1] #print(row) #print(col) for mat in matrix: mat[row] = mat[row] + 1 #print("matrix_step1:", matrix) matrix = [[ mat + 1 for mat in val] if ind == col else val for ind, val in enumerate(matrix)] #print("matrix:", matrix) result = sum([len(list(filter(lambda x:x%2==1,m))) for m in matrix]) #print("result:", result) return result if __name__ == '__main__': so = Solution() assert 6 == so.oddCells(2, 3, [[0,1],[1,1]]) assert 0 == so.oddCells(2, 2, [[1,1],[0,0]])
9ae94441013e93535eabead119941d52bd727998
harshitashetty1605/Ml
/social.py
1,449
3.703125
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd data3=pd.read_csv('Social_Network_Ads.csv') x=data3.iloc[:,1:4].values y=data3.iloc[:,4].values #plt.scatter(x,y) '''Produces a graph with two separated classes use sigmoid function ie 1/(1-e**(-y))) y=B0+B1x standard scaling=(x-xmean)/Standard deviation(x-xmean)''' from sklearn.preprocessing import LabelEncoder lEncoder=LabelEncoder() #We perform onehotencoding if we have multiple categorical attributes x[:,0]=lEncoder.fit_transform(x[:,0]) from sklearn.preprocessing import StandardScaler sscaler=StandardScaler() x=sscaler.fit_transform(x) from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.2,random_state=0) from sklearn.linear_model import LogisticRegression classifier=LogisticRegression() classifier.fit(x_train,y_train) ypred=classifier.predict(x_test) count=0 for i in range(len(ypred)): if ypred[i]==y_test[i]: count+=1 print(count) from sklearn.metrics import confusion_matrix ''' The no of correct predictions in cmis f00 and f11 The difference btwregrssion and classification is that in regression we can determine the distance btw points Classification ifs used to classify the points into sets''' cm=confusion_matrix(y_test,ypred) print(cm) score=classifier.score(x_test,y_test) from sklearn.metrics import mean_squared_error mse=mean_squared_error(y_test,ypred)**(1/2)
6fa9ed9a92dbd611cd7a8b6645d823e74a7bdce3
presstwice/Python-
/data_camp/lambda_function.py
217
3.828125
4
read_books = {'week 1': 1, 'week 2': 1, 'week 3': 0} for item in read_books: if 'week 3' in read_books == 0: print("You read a book this week") break else: print("You suck")
e140bd8915d97b4402d63d2572c056e61a0d9e5a
presstwice/Python-
/data_camp/simple_pendulum.py
487
4.1875
4
# Initialize offset offset = -6 # Code the while loop while offset != 0 :b # The goal is to get offset to always equal 0 print("correcting...") # Prints correcting to clearly state the loop point if offset > 0: # You start the if statement by checking if the offset is positive offset = offset - 1 # If so bring the offset closer to 0 by -1 else: offset = offset + 1 # if its not positive then it must be negative bring it closer to 0 + 1 print(offset)
eb197ecf36d5ac1020e92ef532d2e6cec5bab744
presstwice/Python-
/pytut1/functions.py
421
3.765625
4
def sayhi(name, age): print("Hello " + name + ", you are " + age) sayhi("Mike", "30") sayhi("Steve", "70") #functions let you break up your code #functions should be all lowercase #functions with more than two words should use _ #A paramter is a piece of information you give to the function #sayhi(name) with (name) beingthe parameter #you can pass any type of data through a function strings, arrays, booleans
2a0e052f6f570ab034285e50daf699aba8428818
jsimmond/App-Jing
/backend/Placement/utils.py
1,345
3.5
4
import copy def sort_and_place(items, *, key, start=1, allow_ties=True): def get_key(item): key_list = key if (isinstance(key, list) or isinstance(key, tuple)) else [key] values = [] for k in key_list: if isinstance(k, str): values.append(item[k] if k[0] != "-" else -item[k[1:]]) elif callable(k): values.append(k(item)) else: raise TypeError( 'key must be a string, callable or list of strings or callables') return values if not isinstance(items, list): raise TypeError('items must be a list') if len(items) == 0: return items items_copy = copy.deepcopy(items) sorted_items = sorted(items_copy, key=get_key, reverse=True) if allow_ties: place_current = start value_current = get_key(sorted_items[0]) for i, item in enumerate(sorted_items, start=start): this_value = get_key(item) if this_value == value_current: item['place'] = place_current else: item['place'] = i place_current = i value_current = this_value else: for i, item in enumerate(sorted_items, start=start): item['place'] = i return sorted_items
50823aaa002f670682669a04b4337d9f508eed24
grem848/Assignment3Python
/module.py
3,932
3.5625
4
import numpy as np import country_codes_english import country_codes # list of country codes of native English-speaking countries country_codes_english = country_codes_english.country_codes_english english_ccs = list(country_codes_english.keys()) # list of country codes of native English-speaking countries country_codes = country_codes.country_codes other_ccs = list(country_codes.keys()) # getting the entire structure from the .csv file def get_data(filename): return np.genfromtxt(filename, delimiter=',', dtype=np.uint, skip_header=1) def number_of_nonenglish_vs_english(year, data): english_sum = 0 non_english_sum = 0 # for each country code in the two lists respectively, sum the number of citizens: for cc in english_ccs: mask = (data[:,0] == year) & (data[:,3] == cc) english_sum +=(sum(data[mask][:,4])) for cc in other_ccs: mask = (data[:,0] == year) & (data[:,3] == cc) non_english_sum +=(sum(data[mask][:,4])) return english_sum, non_english_sum #Now create another function that can take 2 arguments: #1: the dataset in the form of a 2dimensional data array where y=data rows and x=[year, area, age nationality, amount]. #2: the mask in the form: data[:,3] == 5120 to find swedish or data[:,0] == 1999 to filter on year #the return value must be the filtered dataset. def mask_function(data, mask): return data[mask] #Create another function that can take 2 arguments: #a dataset with same characteristics as above and #a value for the x-axis (either year, area, age or nationality) #return value should be the accumulated population for all x-values. #hint: if year is chosen for x then y is all accumulated amounts from all areas, ages and nationalities. def get_dict_of_x_values_and_corresponding_sums(data, x_value): params = {'year':0, 'area':1, 'age':2, 'nationality': 3} x = params[x_value] # array of the unique codes of the chosen x_value: array_of_unique_codes = np.unique(data[:,x]) bef_sum_dict = {} for code in array_of_unique_codes: # masking to only sum data for the unique code, and then adding the k/v-pair to the dict mask = (data[:,x] == code) bef_sum_dict[code] = sum(data[mask][:,4]) return bef_sum_dict def get_age_group_per_year(data, min, max, year): year_mask = (data[:,0] == year) age_group = data[year_mask] age_mask = (age_group[:,2] >= min) & (age_group[:,2] <= max) age_group = age_group[age_mask] return age_group def get_list_of_age_group_sums(area, year, data): area_mask = (data[:,1] == area) data = data[area_mask] year_mask = (data[:,0] == year) data = data[year_mask] age_0_10 = sum(get_age_masked_data(data,0,10)[:,4]) age_11_20 = sum(get_age_masked_data(data,11,20)[:,4]) age_21_30 = sum(get_age_masked_data(data,21,30)[:,4]) age_31_40 = sum(get_age_masked_data(data,31,40)[:,4]) age_41_50 = sum(get_age_masked_data(data,41,50)[:,4]) age_51_60 = sum(get_age_masked_data(data,51,60)[:,4]) age_61_70 = sum(get_age_masked_data(data,61,70)[:,4]) age_71_80 = sum(get_age_masked_data(data,71,80)[:,4]) age_81_90 = sum(get_age_masked_data(data,81,90)[:,4]) age_above_90 = sum(get_age_masked_data(data,91,150)[:,4]) list_of_age_group_sums = [] list_of_age_group_sums.append(age_0_10) list_of_age_group_sums.append(age_11_20) list_of_age_group_sums.append(age_21_30) list_of_age_group_sums.append(age_31_40) list_of_age_group_sums.append(age_41_50) list_of_age_group_sums.append(age_51_60) list_of_age_group_sums.append(age_61_70) list_of_age_group_sums.append(age_71_80) list_of_age_group_sums.append(age_81_90) list_of_age_group_sums.append(age_above_90) return list_of_age_group_sums def get_age_masked_data(data, low_age, high_age): age_mask = ((data[:,2] >= low_age) & (data[:,2] <= high_age)) return data[age_mask]
a7b2b6aa0cf87e8c8e97061350c14730f4d44f32
Thehunk1206/Sorting-alogorithm-comparison
/bubbleSort.py
426
3.859375
4
from random import randrange from time import time NUMBER_OF_ELEMENTS = 10000 a = [randrange(1,100) for i in range(NUMBER_OF_ELEMENTS)] def bubbleSort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] start = time() bubbleSort(a) end = time() print("time taken to sort the element",end-start) del a
9837dff732929ed5f6533c5265e17788d975f76f
scylla/masters_thesis
/code/seq2seq_graph/src/downhill-0.2.2/downhill/dataset.py
7,344
3.71875
4
# -*- coding: utf-8 -*- r'''This module contains a class for handling batched datasets. In many optimization tasks, parameters must be updated by optimizing them with respect to estimates of a loss function. The loss function for many problems is estimated using a set of data that we have measured. ''' import climate import collections import numpy as np logging = climate.get_logger(__name__) class Dataset: '''This class handles batching and shuffling a dataset. In ``downhill``, losses are optimized using sets of data collected from the problem that generated the loss. During optimization, data are grouped into "mini-batches"---that is, chunks that are larger than 1 sample and smaller than the entire set of samples; typically the size of a mini-batch is between 10 and 100, but the specific setting can be varied depending on your model, hardware, dataset, and so forth. These mini-batches must be presented to the optimization algorithm in pseudo-random order to match the underlying stochasticity assumptions of many optimization algorithms. This class handles the process of grouping data into mini-batches as well as iterating and shuffling these mini-batches dynamically as the dataset is consumed by the optimization algorithm. For many tasks, a dataset is obtained as a large block of sample data, which in Python is normally assembled as a ``numpy`` ndarray. To use this class on such a dataset, just pass in a list or tuple containing ``numpy`` arrays; the number of these arrays must match the number of inputs that your loss computation requires. There are some cases when a suitable set of training data would be prohibitively expensive to assemble in memory as a single ``numpy`` array. To handle these cases, this class can also handle a dataset that is provided via a Python callable. For more information on using callables to provide data to your model, see :ref:`data-using-callables`. Parameters ---------- inputs : ndarray, tuple, list, or callable One or more sets of data. If this parameter is callable, then mini-batches will be obtained by calling the callable with no arguments; the callable is expected to return a tuple of ndarrays that will be suitable for optimizing the loss at hand. If this parameter is a list or tuple, it must contain ndarrays (or something similar with a ``shape`` attribute, like a pandas DataFrame). These are assumed to contain data for computing the loss; the length of this tuple or list should match the number of inputs required by the loss computation. If multiple ndarrays are provided, their lengths along the axis given by the ``axis`` parameter (defaults to 0) must match. name : str, optional A string that is used to describe this dataset. Usually something like 'test' or 'train'. batch_size : int, optional The size of the mini-batches to create from the data sequences. Defaults to 32. iteration_size : int, optional The number of batches to yield for each call to iterate(). Defaults to the length of the data divided by batch_size. If the dataset is a callable, then the number is len(callable). If callable has no length, then the number is set to 100. axis : int, optional The axis along which to split the data arrays, if the first parameter is given as one or more ndarrays. If not provided, defaults to 0. rng : :class:`numpy.random.RandomState` or int, optional A random number generator, or an integer seed for a random number generator. If not provided, the random number generator will be created with an automatically chosen seed. ''' _count = 0 def __init__(self, inputs, name=None, batch_size=32, iteration_size=None, axis=0, rng=None): '''Create a minibatch dataset from data arrays or a callable.''' self.name = name or 'dataset{}'.format(Dataset._count) Dataset._count += 1 self.batch_size = batch_size self.iteration_size = iteration_size self.rng = rng if rng is None or isinstance(rng, int): self.rng = np.random.RandomState(rng) self._batches = None self._callable = None if isinstance(inputs, collections.Callable): self._init_callable(inputs) else: self._init_arrays(inputs, axis) def _init_callable(self, inputs): self._callable = inputs if not self.iteration_size: try: self.iteration_size = len(inputs) except (TypeError, AttributeError) as e: # has no len self.iteration_size = 100 logging.info('%s: %d mini-batches from callable', self.name, self.iteration_size) def _init_arrays(self, inputs, axis=0): if not isinstance(inputs, (tuple, list)): inputs = (inputs, ) L = inputs[0].shape[axis] assert all(L == x.shape[axis] for x in inputs), \ 'shapes do not match along axis {}: {}'.format( axis, '; '.join(str(x.shape) for x in inputs)) self._index = 0 self._batches = [] for i in range(0, L, self.batch_size): batch = [] for x in inputs: slices = [slice(None) for _ in x.shape] slices[axis] = slice(i, min(L, i + self.batch_size)) batch.append(x[tuple(slices)]) self._batches.append(batch) self.shuffle() if not self.iteration_size: self.iteration_size = len(self._batches) logging.info('%s: %d of %d mini-batches of %s', self.name, self.iteration_size, len(self._batches), '; '.join(str(x.shape) for x in self._batches[0])) def __iter__(self): return self.iterate(True) def shuffle(self): '''Shuffle the batches in the dataset. If this dataset was constructed using a callable, this method has no effect. ''' if self._batches is not None: self.rng.shuffle(self._batches) def iterate(self, shuffle=True): '''Iterate over batches in the dataset. This method generates ``iteration_size`` batches from the dataset and then returns. Parameters ---------- shuffle : bool, optional Shuffle the batches in this dataset if the iteration reaches the end of the batch list. Defaults to True. Yields ------ batches : data batches A sequence of batches---often from a training, validation, or test dataset. ''' for _ in range(self.iteration_size): if self._callable is not None: yield self._callable() else: yield self._next_batch(shuffle) def _next_batch(self, shuffle=True): value = self._batches[self._index] self._index += 1 if self._index >= len(self._batches): if shuffle: self.shuffle() self._index = 0 return value
dce2e480dec644bec0457b747991857896edd9f8
sebas-mora28/Algoritmos-Estructuras-Datos-II
/Diseño-Algoritmos/Programación-Dinámica/LCS_benchmark.py
3,338
3.5
4
from time import time """ SUBSTRING MAS LARGO Divide y Conquista """ def LCS_recursivo(string1, string2): return LCS_recursivo_aux(string1, string2, len(string1), len(string2)) def LCS_recursivo_aux(string1, string2, size1, size2): if(size1 == 0 or size2 == 0): return 0 if(string1[size1-1] == string2[size2-1]): return 1 + LCS_recursivo_aux(string1, string2, size1-1, size2-1) else: return max(LCS_recursivo_aux(string1, string2, size1, size2-1), LCS_recursivo_aux(string1, string2, size1-1, size2)) """ SUBSTRING MAS LARGO APLICANDO PROGRAMACION DINAMICA """ def LCS(string1, string2): return LCS_aux(string1, string2, len(string1), len(string2)) def LCS_aux(string1, string2, size1, size2): lista = getEmptyArray(size1 +1, size2+1) for i in range(size1+1): for j in range(size2 +1): if(i == 0 or j == 0): lista[i][j]= 0 elif(string1[i-1] == string2[j-1]): lista[i][j] = lista[i-1][j-1] + 1 else: lista[i][j] = max(lista[i-1][j], lista[i][j-1]) return lista[size1][size2] def getEmptyArray(row, columns): lista = [] for i in range(0,row): lista.append([0]*columns) return lista """ BENCHMARK """ def tiempo_ejecucion_LCS_recursivo(string1, string2): inicial = time(); LCS_recursivo(string1, string2) final = time(); return final - inicial def tiempo_ejecucion_LCS_programacion_dinamica(string1, string2): inicial = time(); LCS(string1, string2) final = time(); return final - inicial """ PRIMERA PRUEBA """ print(tiempo_ejecucion_LCS_recursivo("tofoofie", "toody")) print(tiempo_ejecucion_LCS_programacion_dinamica("tofoofie", "toody")) print(); """ SEGUNDA PRUEBA """ print(tiempo_ejecucion_LCS_recursivo("abcas", "baba")) print(tiempo_ejecucion_LCS_programacion_dinamica("abcas", "baca")) print() """ TERCERA PRUEBA """ print(tiempo_ejecucion_LCS_recursivo("ssffkkttff", "xxmmyykk")) print(tiempo_ejecucion_LCS_programacion_dinamica("ssffkkttff", "xxmmyykk")) print() """ CUARTA PRUEBA """ print(tiempo_ejecucion_LCS_recursivo("dffdfogergdgddttt", "mdftttdsdszcx")) print(tiempo_ejecucion_LCS_programacion_dinamica("dffdfogergdgddttt", "mdftttdsdszcx")) print() """ RESULTADOS DEL BENCHMARK SE REALIZARON CUATRO PRUEBAS DISTINTAS EN CON STRING DIFERENTES PARA CALCULAR EL TIEMPO DE EJECUCION ENTRE LOS DOS ENFOQUES PARA RESOLVER EL PROBLEMA: Divide y conquista Programación dinámica 1. 0.0007684 s 1. 0.00009870 s 2. 0.0000605 s 2. 0.00006628 s 3. 0.0263872 s 3. 0.00005459 s 4. 5.1695387 s 4. 0.00025415 s Como podemos observar y como se esperaba la programación dinámica es más eficiente en tiempo de ejecución, sin embargo, en inputs pequeños como el caso de la segunda prueba observamos que los resultados fueron bastantes similares, no así en las cadenas de string mas largos, donde la programación dinámica fue más eficiente. En la cuarta prueba observemos que existen una gran diferencia de tiempo entre los dos enfoques. """
f86dad4088932947d48f2dfa42aa21df0437c208
aaptedata/Sorting
/src/iterative_sorting/iterative_sorting.py
752
4.03125
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements for i in range(0, len(arr)): smallest_index = i for j in range(i+1, len(arr)): if arr[smallest_index] > arr[j]: smallest_index = j arr[i], arr[smallest_index] = arr[smallest_index], arr[i] # Swap return arr # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): for passnum in range(len(arr)-1, 0, -1): for i in range(passnum): if arr[i] > arr[i+1]: arr[i], arr[i+1] = arr[i+1], arr[i] # Swap return arr # STRETCH: implement the Count Sort function below def count_sort(arr, maximum=-1): return arr
fc146ca2a310461c17c85ffd2a3183e84562a9f0
comiee/little_games
/_2048.py
3,052
3.5
4
from tkinter import* import random root=Tk() root.title('2048') root.resizable(0,0) root.geometry('400x400') size=4#边长 def cmplist(a,b): #二维列表比较函数,完全相同返回0 for c,d in zip(a,b): for e,f in zip(c,d): if e!=f: return 1 return 0 class block: def __init__(self): self.text=StringVar() self.label=Label(root,bg='white',relief='solid',borderwidth=1,font='bold',textvariable=self.text) class blocks: def __init__(self): self.blist=[] #存储组件 self.vlist=[] #存储数据 for i in range(size): new=[] newv=[] for j in range(size): newb=block() newb.label.place(width=100,height=100,x=100*j,y=100*i) new.append(newb) newv.append(0) self.blist.append(new) self.vlist.append(newv) x,y=random.randint(0,size-1),random.randint(0,size-1) self.vlist[y][x]=random.randrange(2,5,2) root.bind('<Up>',self.up) root.bind('<Down>',self.down) root.bind('<Left>',self.left) root.bind('<Right>',self.right) def show(self): for i in range(size): for j in range(size): if self.vlist[i][j]==0: self.blist[i][j].text.set('') else: self.blist[i][j].text.set(self.vlist[i][j]) root.update() def do(self): lastlist=[] for i in self.vlist: #备份vlist lastlist.append(i.copy()) for i in self.vlist: while i.count(0): #清除0 i.remove(0) for j in range(len(i)-1): #合并值相同的项 if j+1<len(i) and i[j]==i[j+1]: i[j]+=i.pop(j+1) while len(i)<size: #补充0 i.append(0) if cmplist(self.vlist,lastlist): for i in self.vlist: x,y=random.randint(0,size-1),random.randint(0,size-1) while self.vlist[x][y]!=0: x,y=random.randint(0,size-1),random.randint(0,size-1) else: self.vlist[x][y]=random.randrange(2,5,2) break def up(self,event): self.vlist=list(map(list,zip(*self.vlist))) #将list转置 self.do() self.vlist=list(map(list,zip(*self.vlist))) self.show() def down(self,event): self.vlist.reverse() self.vlist=list(map(list,zip(*self.vlist))) self.do() self.vlist=list(map(list,zip(*self.vlist))) self.vlist.reverse() self.show() def left(self,event): self.do() self.show() def right(self,event): for i in self.vlist: i.reverse() self.do() for i in self.vlist: i.reverse() self.show() game=blocks() game.show() root.mainloop()
09d7398dcfb17295e44aba18d4a97c15b14634f8
YUMI0917/karen_teoria2
/ordenar_listas.py
3,138
3.90625
4
#!/usr/bin/python3 from time import * from random import * import random import string def creaListaObjetos(cantidad): elementos = [] lista_enteros=[] lista_flotantes=[] lista_cadenas=[] listaOrdenada = [] # Llenamos la lista con diferentes tipos while len(elementos) != cantidad: if len(elementos) < cantidad: elementos.append(random.choice(string.ascii_letters)) if len(elementos) < cantidad: elementos.append(float(round(uniform(1.0, 2.0), 1)) ) # con 1 decimal if len(elementos) < cantidad: elementos.append(randint(1,100)) # Ordenamos la lista de objetos inicio = time() for elemento in elementos: if isinstance(elemento, int): # sí es un entero lista_enteros.append(elemento) elif isinstance(elemento, float): lista_flotantes.append(elemento) elif isinstance(elemento, str): lista_cadenas.append(elemento) listaOrdenada = sorted(lista_enteros) + sorted(lista_cadenas) + sorted(lista_flotantes) print("---------------------------------------------------------") print("ORDENAMIENTO EN LA LISTA DE OBJETOS") #print("Lista de objetos ordenada : ", listaOrdenada) final = time() - inicio tiempo = float(final*1000) print("Tiempo : ", tiempo, " ms") return elementos """ Separa lista de objetos en listas A,B,C """ def separaListas(lista, tipo_de_lista): lista_enteros=[] lista_flotantes=[] lista_cadenas=[] # Agregamos a las listas según su tipo for elemento in lista: if isinstance(elemento, int): # sí es un entero lista_enteros.append(elemento) elif isinstance(elemento, float): lista_flotantes.append(elemento) elif isinstance(elemento, str): lista_cadenas.append(elemento) # Ordenamos la lista que haya elegido el usuario inicio = time() try: if tipo_de_lista == 1: lista_cadenas.sort() # Lista de cadenas if tipo_de_lista == 2: lista_flotantes.sort() # Lista de flotantes if tipo_de_lista == 3: lista_enteros.sort() # Lista de enteros except: print("Error inesperado") #print(lista_cadenas, lista_enteros, lista_flotantes) if tipo_de_lista == 1 or tipo_de_lista == 2 or tipo_de_lista == 3: final = time() - inicio tiempo = float(final*1000) print("Tiempo : ", tiempo, " ms") else: print("¡Haz introducido una opción no válida!") objetos=creaListaObjetos(10000) # 10000 elementos print("---------------------------------------------------------") print("ORDENAMIENTO EN LA LISTA DE UN SÓLO DATO") try: # validamos que solo ingrese enteros tipo = int(input("Lista que desea comparar\n 1) Cadena de texto \n 2) Flotante \n 3) Entero\n : ")) lista_unica=separaListas(objetos, tipo) #print("Tiempo lista única : ", lista_unica, " ms") except: print("Haz introducido una entrada que no es un número") print("---------------------------------------------------------")
46d30a2f92ee50af1d92afdd36b673bd5a4c0847
xinshuoyang/algorithm
/src/845_GreatestCommonDivisor/solution.py
748
3.859375
4
#!/usr/bin/python ################################################## # NAME : solution.py # # DESC : # # AUTH : Xinshuo Yang # # DATE : 20180324 # ################################################## class Solution: """ @param a: the given number @param b: another number @return: the greatest common divisor of two numbers """ def gcd(self, a, b): # write your code here if a == 0: return b if b == 0: return a x = max(abs(a), abs(b)) y = min(abs(a), abs(b)) r = x % y while r != 0: x = y y = r r = x % y return y if __name__ == '__main__': sol = Solution() print sol.gcd( - 1, 1)
5c96149135b418e0eb26552b131ef65c28423af8
xinshuoyang/algorithm
/src/224_ImplementThreeStacksbySingleArray/solution.py
1,861
4
4
#!/usr/bin/python ################################################################################ # NAME : solution.py # # DESC : # # AUTH : Xinshuo Yang # # DATE : 20181230 # ################################################################################ class ThreeStacks: """ @param: size: An integer """ def __init__(self, size): # do intialization if necessary self.size = size self.stack = [None]*3*size self.stacklen = [0,0,0] """ @param: stackNum: An integer @param: value: An integer @return: nothing """ def push(self, stackNum, value): # Push value into stackNum stack self.stack[stackNum*self.size+self.stacklen[stackNum]] = value self.stacklen[stackNum] += 1 """ @param: stackNum: An integer @return: the top element """ def pop(self, stackNum): # Pop and return the top element from stackNum stack v = self.stack[stackNum*self.size+self.stacklen[stackNum]-1] self.stack[stackNum*self.size+self.stacklen[stackNum]-1] = None self.stacklen[stackNum] -= 1 return v """ @param: stackNum: An integer @return: the top element """ def peek(self, stackNum): # Return the top element return self.stack[stackNum*self.size+self.stacklen[stackNum]-1] """ @param: stackNum: An integer @return: true if the stack is empty else false """ def isEmpty(self, stackNum): # write your code here return not bool(self.stacklen[stackNum]) if __name__ == "__main__": obj = ThreeStacks(5) obj.push(0, 10) obj.push(0, 11) obj.push(1, 20) obj.push(1, 21) print(obj.pop(0)) print(obj.pop(1)) print(obj.peek(1)) obj.push(2,30) print(obj.pop(2)) print(obj.isEmpty(2)) print(obj.isEmpty(0))
5bcac62a7a4f63b412a53740185bbdd89b9beb1b
xinshuoyang/algorithm
/src/474_ LowestCommonAncestorII/solution.py
1,510
4.0625
4
""" Definition of ParentTreeNode: """ class ParentTreeNode: def __init__(self, val): self.val = val self.parent, self.left, self.right = None, None, None class Solution: """ @param: root: The root of the tree @param: A: node in the tree @param: B: node in the tree @return: The lowest common ancestor of A and B """ def lowestCommonAncestorII(self, root, A, B): # write your code here # find paths from A and B to root pathA = [] pathB = [] self.findpath(root, A, pathA) self.findpath(root, B, pathB) res = root for i in range(-1, - min(len(pathA), len(pathB)) - 1, -1): if pathA[i] is pathB[i]: res = pathA[i] else: break return res def findpath(self, root, node, path): """ find path from node to root """ if node is root: path.append(node) else: path.append(node) self.findpath(root, node.parent, path) if __name__ == '__main__': root = ParentTreeNode(4) root.left = ParentTreeNode(3) root.right = ParentTreeNode(7) root.right.left = ParentTreeNode(5) root.right.right = ParentTreeNode(6) root.right.right.parent = root.right root.right.left.parent = root.right root.left.parent = root root.right.parent = root s = Solution() print s.lowestCommonAncestorII(root, root.right.left, root.left).val
727a1ed9e2b089ae4eaf4ed2b563958f35a534b2
xinshuoyang/algorithm
/src/8_RotateString/solution.py
747
3.859375
4
#!/usr/bin/python ################################################################################ # NAME : solution.py # # DESC : # # AUTH : Xinshuo Yang # # DATE : 20180303 # ################################################################################ class Solution: """ @param str: An array of char @param offset: An integer @return: nothing """ def rotateString(self, s, offset): # write your code here if len(s) > 0: offset = offset % len(s) temp = (s + s)[len(s) - offset : 2 * len(s) - offset] for i in xrange(len(temp)): s[i] = temp[i] if __name__ == '__main__': sol = Solution() s = 'abcdefg' sol.rotateString(s, 3) print s
903c731285d58cda9c6b802ecaeacb0658e76831
xinshuoyang/algorithm
/src/452_RemoveLinkedListElements/solution.py
1,085
3.78125
4
#!/usr/bin/python ################################################## # NAME : solution.py # # DESC : # # AUTH : Xinshuo Yang # # DATE : 20180328 # ################################################## """ Definition for singly-linked list. """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: """ @param: head: a ListNode @param: val: An integer @return: a ListNode """ def removeElements(self, head, val): # write your code here # find new head while head != None: if head.val == val: head = head.next else: break p1 = head if p1 != None: p2 = p1.next else: p2 = None while p2 != None: if p2.val == val: p2 = p2.next p1.next = p2 else: p1 = p2 p2 = p2.next return head if __name__ == '__main__': sol = Solution() print sol.removeElements(None, 2)
395901ee3f32955fe43cdde579de2a5bfaf82710
xinshuoyang/algorithm
/src/617_MaximumAverageSubarrayII/solution.py
1,414
3.640625
4
#!/usr/bin/python ################################################################################ # NAME : solution.py # # DESC : # # AUTH : Xinshuo Yang # # DATE : 20180327 # ################################################################################ class Solution: """ @param: nums: an array with positive and negative numbers @param: k: an integer @return: the maximum average """ def maxAverage(self, nums, k): dmin = float(min(nums)) dmax = float(max(nums)) while abs(dmax - dmin) > 1.0e-5: mid = dmin + (dmax - dmin) / 2.0 if self.checkAverage(nums, k, mid): dmin = mid else: dmax = mid return dmax def checkAverage(self, nums, k, target): """ check whether there exist a subarray of length >= k such that the average of the subarray > target """ s = 0 prev = 0 min_sum = 0 for i in range(k): s += nums[i] - target if s > 0: return True for i in range(k, len(nums)): s += nums[i] - target prev += nums[i - k] - target min_sum = min(min_sum, prev) if s - min_sum > 0: return True return False if __name__ == '__main__': sol = Solution() print sol.maxAverage([1, 12, -5, -6, 50, 3], 3)
6af40ba17bdcc27fed7c81ef5e33d56bf73978e0
xinshuoyang/algorithm
/src/994_ContiguousArray/solution.py
1,095
3.640625
4
#!/usr/bin/python ################################################## # NAME : solution.py # # DESC : # # AUTH : Xinshuo Yang # # DATE : 20190101 # ################################################## class Solution: """ @param nums: a binary array @return: the maximum length of a contiguous subarray """ def findMaxLength(self, nums): # Write your code here if not nums: return 0 maxsize = 0 sumleft = [0] for i in range(len(nums)): if nums[i] is 1: sumleft.append(sumleft[-1]+1) else: sumleft.append(sumleft[-1]-1) if sumleft[-1] is 0: maxsize = i+1 sumleft = sumleft[1:] d = dict.fromkeys(sumleft, -1) for i in range(len(sumleft)): if d[sumleft[i]] is not -1: maxsize = max(maxsize, i-d[sumleft[i]]) else: d[sumleft[i]] = i return maxsize if __name__ == "__main__": obj = Solution() print(obj.findMaxLength([0,0,0,0]))
867fea3d0cc9c8115035a37808c6d9539e2ea46c
xinshuoyang/algorithm
/src/888_ValidWordSquare/solution.py
909
3.78125
4
#!/usr/bin/python ################################################## # NAME : solution.py # # DESC : # # AUTH : Xinshuo Yang # # DATE : 20180328 # ################################################## class Solution: """ @param words: a list of string @return: a boolean """ def validWordSquare(self, words): # Write your code here m = len(words) n = max([len(s) for s in words]) l = max(m, n) for i in range(m): if len(words[i]) < l: words[i] += ' ' * (l - len(words[i])) for i in range(l): row = words[i] col = '' for j in range(m): col += words[j][i] if row != col: return False return True if __name__ == '__main__': sol = Solution() print sol.validWordSquare([ "ball", "area", "read", "lady" ])
52a37613b6dc3222720076be6c2038a93eb71133
xinshuoyang/algorithm
/src/138_SubarraySum/solution.py
897
3.734375
4
#!/usr/bin/python ################################################################################ # NAME : solution.py # # DESC : # # AUTH : Xinshuo Yang # # DATE : 20171212 # ################################################################################ class Solution: """ @param: nums: A list of integers @return: A list of integers includes the index of the first number and the index of the last number """ def subarraySum(self, nums): # write your code here for i in range(len(nums)): if nums[i] == 0: return i, i for i in range(len(nums)): s = nums[i] for j in range(i + 1, len(nums)): s += nums[j] if s == 0: return i, j if __name__ == '__main__': nums = [-3,1,2,-3,4] s = Solution() print s.subarraySum(nums)
8432807124a22d166a2ebf31ee083113a35a0b36
xinshuoyang/algorithm
/src/807_Palindrome_Number_II/solution.py
956
3.765625
4
#!/usr/bin/python ################################################## # NAME : solution.py # # DESC : # # AUTH : Xinshuo Yang # # DATE : 20180217 # ################################################## import math class Solution: """ @param n: non-negative integer n. @return: return whether a binary representation of a non-negative integer n is a palindrome. """ def isPalindrome(self, n): # Write your code here if n == 0: return True binary = [] ppmax = int(math.log(n, 2)) for pp in xrange(ppmax, -1, -1): dig = n / (2 ** pp) if dig == 1: n -= 2 ** pp binary += [dig] # check palindrome for i in xrange(0, len(binary) / 2): if binary[i] != binary[-i-1]: return False return True if __name__ == '__main__': s = Solution() print s.isPalindrome(0)
5bb93386281cf3ef51629fb3a47455393b73b98d
xinshuoyang/algorithm
/src/1482_MinimumSumPath/solution.py
1,163
3.828125
4
#!/usr/bin/python ################################################################################ # NAME : solution.py # # DESC : # # AUTH : Xinshuo Yang # # DATE : 20181228 # ################################################################################ """ Definition of TreeNode: """ class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: the root @return: minimum sum """ def minimumSum(self, root): if not root: return 0 sums = [] self.helper(root,0,sums) return min(sums) def helper(self,node,prev,sums): if node != None: if not node.left and not node.right: sums.append(prev+node.val) else: self.helper(node.left,prev+node.val,sums) self.helper(node.right,prev+node.val,sums) if __name__ == "__main__": root = TreeNode(5) root.left = TreeNode(2) root.right = TreeNode(6) root.left.right = TreeNode(3) root.right.right = TreeNode(8) obj = Solution() print(obj.minimumSum(root))
4c28047a199b9e6d7ac21b0231a0530a4bd50981
Nagumkc/Python-Programing
/Tutorial 4/Source/lab 4/sort.py
77
3.6875
4
str=input("Enter string") li=str.split(",") sr=sorted(li) print(",".join(sr))
747c3e0a5ecf8966b118b61ec8edf3afaba4160e
Nagumkc/Python-Programing
/Tutorial 7/Source/lab7/in-class.py
1,675
3.515625
4
from nltk.corpus import wordnet as w from nltk.tokenize import word_tokenize,sent_tokenize,wordpunct_tokenize from nltk.stem import LancasterStemmer,WordNetLemmatizer from nltk import pos_tag,ne_chunk,ngrams from collections import Counter s="Sport (British English) or sports includes all forms of competitive physical activity or games which,through casual or organised participation, aim to use, maintain or improve physical ability and skills while providing enjoyment to participants, and in some cases, entertainment for spectators.Usually the contest or game is between two sides, each attempting to exceed the other. Some sports allow a tie game; others provide tie-breaking methods, to ensure one winner and one loser. A number of such two-sided contests may be arranged in a tournament producing a champion. Many sports leagues make an annual champion by arranging games in a regular sports season, followed in some cases by playoffs. Hundreds of sports exist, from those between single contestants, through to those with hundreds of simultaneous participants, either in teams or competing as individuals. In certain sports such as racing, many contestants may compete, each against each other, with one winner." res=w.synsets("sport") print("wordnet\n",res) tok=[word_tokenize(t) for t in sent_tokenize(s)] print("tok\n",tok) ste=LancasterStemmer() print("stem\n") for t in tok: print(ste.stem(str(t))) print("pos\n") print(pos_tag(str(tok))) print("lemm\n") l=WordNetLemmatizer() for t in tok: print(l.lemmatize(str(t))) print("ner\n") ner=ne_chunk(pos_tag(wordpunct_tokenize(str(t)))) print(ner) print("try gram\n") ner=ngrams(t,3) print(Counter(ner))
c1c58fb077cd4fbc9c9f60d3424cba85e2a1193a
Lilas-w/python-for-everybody
/cur.py
800
3.546875
4
import json import sqlite3 conn = sqlite3.connect('rosterdb.sqlite') cur = conn.cursor() # Do some setup cur.executescript(''' DROP TABLE IF EXISTS User CREATE TABLE User ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE, count INTEGER ) ''') fname = input('Enter file name: ') if len(fname) < 1: fname = 'roster_data_sample.json' # [ # [ "Charley", "si110", 1 ], # [ "Mea", "si110", 0 ], str_data = open(fname).read() json_data = json.loads(str_data) for entry in json_data: name = entry[0] title = entry[1] print((name, title)) cur.execute(INSERT OR IGNORE INTO User (name) VALUES ( ? ), ( name, ) ) cur.execute('SELECT id FROM User WHERE name = ? ', (name, )) count = cur.fetchone()[0] conn.commit()
b44741056009f67ef7c137ad7f3733f9c97046a1
jhall-ambient/green_button
/green_button.py
5,235
3.515625
4
import sys, datetime from bs4 import BeautifulSoup class Reading(object): """ Reading object, contains cost, value and date""" def __init__(self, date_string, cost, value): """ Date String should be passed as POSIX - Cost is in thousands of a cent 2691 = .02691 cents - Value is Energy used Watt hours. so 897 = .897 kwh """ try: self.cost = int(cost) self.value = int(value) except ValueError as e: print "Couldn't parse cost:%s or value:%s, %s" % (cost, value, e.message) try: self.date = datetime.datetime.utcfromtimestamp(float(date_string)) except Exception, e: print "Couldn't parse date: %s" % e.message def is_weekday(self): if self.date.isoweekday() in [6, 7]: return False else: return True class GreenButton(object): """Green Button object which has the full list of reaings for an address""" def __init__(self, reading_list): self.reading_list = reading_list """ Get all readings for a Given day of the week and start time""" def get_by_day_and_time(self, dow, start_time): readings = [] for reading in self.reading_list: if reading.date.isoweekday() != dow: continue elif reading.date.hour != start_time: continue else: readings.append(reading) return readings def calculate_averages(self, reading_list): """ For a list of readings calculate the averages for Total Paid, cost, value This is used to pass in a list of readings from the same day of week and time to show average cost for this time period. Value returned is tuple that contains averages of 1) Total Paid (divide by 100000000 to get real dollar value) 2) Cost (divide by 100000 for cents) 3) Value (divide by 1000 for KWH) """ r_cnt = 0 real_cost, tot_cost, tot_value = 0, 0, 0 for reading in reading_list: r_cnt += 1 tot_cost += reading.cost tot_value += reading.value real_cost += (reading.value * reading.cost) print "reading %s, value: %s, cost: %s" % (r_cnt, reading.value, reading.cost) print "Total cost for %s readings: %s" % (r_cnt, real_cost) return (real_cost / r_cnt, tot_cost / r_cnt, tot_value / r_cnt) def compare_prices(self, date): """ For a given start time check how much you would save per KWH over The next few hours """ print "Checking prices for %s" % date cost_comparison = {} now_averages = self.calculate_averages(self.get_by_day_and_time(date.isoweekday(), date.hour)) for i in range(1,4): next_date = date + datetime.timedelta(hours=i) next_avgs = self.calculate_averages(self.get_by_day_and_time(next_date.isoweekday(), next_date.hour)) save_per_kwh = (now_averages[1] * 1000) - (next_avgs[1] * 1000) cost_comparison["%s:00" % next_date.hour] = save_per_kwh return cost_comparison def parse_readings(file_name): """ Parse xml file to get a list of all the readings """ print "Going to parse: %s" % file_name soup = BeautifulSoup() try: print "trying this shit out" full_file = open(file_name, 'r') soup = BeautifulSoup(full_file) full_file.close() except (IOError, OSError) as iErr: print "Couln't open file: %s, %s" % (file_name, iErr.message) readings = soup.find_all('intervalreading') reading_list = [] for reading in readings: #print "reading" cost = reading.find('cost').string value = reading.find('value').string start = reading.find('timeperiod').find('start').string try: reading = Reading(start, cost, value) reading_list.append(reading) except Exception, e: print "Exception creating Reading object" return reading_list def main(): file_name = "C:\\Documents and Settings\\Jason\\Desktop\\temp.xml" if len(sys.argv) > 1: file_name = sys.argv[1] readings = parse_readings(file_name) now = datetime.datetime.utcnow() gb = GreenButton(readings) readings_for_nows_timeperiod = gb.get_by_day_and_time(now.isoweekday(), now.hour) avgs = gb.calculate_averages(readings_for_nows_timeperiod) cost_comparison = gb.compare_prices(now) print """ It is currently: %s, The average cost to you for this time period is: %s Your average usage is: %s Average total price for the hour is : %s """ % (now, avgs[1], avgs[2], float(float(avgs[0]) / 100000000)) for k, v in cost_comparison.items(): print "If you wait until %s: You will save %s per KWH" % (k, float(v)/100000000) print "\n All done..." if __name__ == "__main__": main()
2bbc3f90a59cc56dfea769b29e32c3e3e95341e4
saad2999/learn-first
/Login.py
829
3.609375
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ def signup(): n=input("Enter the username:") m=input("Enter the password:") d[n]=m def login(): i=1 while(i<=3): n=input("Enter the username:") m=input("Enter the password:") s=d[n] if(s==m and n==d.key('s')): print("Successfully Login") break; else: print(" try again") i=i+1 if i==4: print("Your chances are over. Please try after sometime") d={} for i in range(ord('A'),ord('Z')): d[chr(i)]=chr(i) print("Welcome to this application",end="") h=int(input("Enter either 1 for Signup or 0 for Login:")) if(h==1): signup() login() elif(h==2): login() else: print("Input not recognised")
1c8af0c8f4739993ef63328d682bf07212004ca6
webclinic017/Predicting-Equity-Prices
/profit_ratios.py
817
3.546875
4
import pandas as pd #Profitability ratios #Importing the csv file df = pd.read_csv (r'sample.csv') #create empty dataframe df1 = pd.DataFrame() #Calculate each ratio and append to the respective column in the dataframe df1['grossMargin'] = df['grossProfit']/df['totalRevenue'] df1['operProfitMargin'] = df['ebitda']/df['totalRevenue'] df1['pretaxProfitMargin'] = df['incomeBeforeTax']/df['totalRevenue'] df1['netProfitMargin'] = df['netIncome']/df['totalRevenue'] df1['returnInvestedCapital'] = df['netIncome']/(df['shortTermDebt']+df['longTermDebt']+df['totalShareholderEquity']) df1['returnOnEquity'] = df['netIncome']/df['totalShareholderEquity'] df1['returnOnAssets'] = df['netIncome']/df['totalAssets'] #Export dataframe into a csv df1.to_csv('profit_ratios.csv', encoding='utf-8', index=False) print (df1)
d22f5a9a6851525504cc7e4f1952a2bbb8ab27ae
BalaRajendran/guvi
/large.py
336
4.21875
4
print ("Find the largest number amoung three numbers"); num=list() arry=int(3); a=1; for i in range(int(arry)): print ('Num :',a); a+=1; n=input(); num.append(int(n)) if (num[0]>num[1] and num[0]>num[2]): print (num[0]); elif (num[1]>num[0] and num[1]>num[2]): print (num[1]); else: print(num[2]);
adbe298bfa10285cc907af9c874bc0251af17b3e
BalaRajendran/guvi
/permutation.py
250
3.890625
4
from itertools import permutations def allPermutations(str): permList = permutations(str) for perm in list(permList): print (''.join(perm)) if __name__ == "__main__": #str = '123' str=str(input()); allPermutations(str)
38c0367fc0c668633ee2dc82c290ea909628fc1a
BalaRajendran/guvi
/range.py
282
3.890625
4
num=list() n=int(input("Enter the number array :")); n1=int(input("Enter the number to count the array: ")); print("Enter the element"); a=int(0); for i in range (n): k=input(); num.append(k); for j in range (n1): a+=int(num[j]); print(a); print (a); #print (num);
2df8a0982b5488d09e4fa60a77ad56a1aed71a01
Sandhya-02/programming
/0 Python old/017_tuples.py
169
3.8125
4
ttuple = ("jack", "manasa", "tanusree") print(ttuple) list = ["jack", "jack"] print(list) a = [10 ,"sandhya" ,30] b = (10 ,"sandhya" ,30) #*angular brackets print(a,b)
d2ac60b5656a50c69828f4e4987fc0f2710879cc
Sandhya-02/programming
/0 Python old/09_change_list.py
2,106
3.796875
4
# dreamers = ["manasa","tanusree","karishma "] # dreamers[2] = "sandhya mama" # print(dreamers) # earth = ["sun","moon","sky","jack","sandhya"] # earth[3:5] = ["manasa","tanusree"] # print(earth) # earth = ["sun","moon","sky","jack","sandhya"] # earth[1:3] = ["manasa","abc","edf"] # print(earth) # earth = ["sun","moon","sky","jack","sandhya"] # earth.insert (3,"manasa") # print(earth) # num = [11,12,13,14,15] # sum = num[0]+num[1] # num.insert(0,sum) # print(num) # num = [11,12,13,14,15] # sum = num[0]+num[1] # num.insert(0,sum) # print(num) # insert # del # pop # extend # replace # remove # list = ["a","m","d","c","e"] # del list[1] # print("after deleting m",list) # list.insert(1,"sandy mama") # print("after inserting sandy mama",list) # list.pop(2) # print("after popping a",list) # list1=["red","hot red","light red","pale red"] # list.extend(list1) # print("after using extend ",list) # list.remove("c") # list.remove("e") # print("after removing e and c",list) # list.remove("a") # list.insert(1,"loves") # print("after inserting loves ",list) name = ["jack ","manasa ","tanusree ","karishma "] character = ["naughty ","hot girl","soft looking","clam girl"] types = ["hot girls to kiss ","hot guy to date like jack ","good guy like jack ","handsome guy to use like a jack "] #!jack is a naughty guy and he want a hot girls to kiss print(name[0],"is a",character[0],"guy and he want a",types[0]) #! manasa is a hot girl and she is searching for a hot guy to date like jack print(name[1], "is a",character[1],"and she is searching for a",types[1]) #! tanusree is a soft looking but she use a good guy like jack print(name[2], "is a",character[2],"but she use a",types[2]) #!karishma is a clam girl but she need a handsome guy to use like a jack print(name[3], "is a ",character[3], "but she need a ",types[3]) list = [ 1, 2, 12, 45, 789, "raj" ] print ("starting :",list) del list[0] print(list) list.pop(3) print(list) a = list.pop(2) print ("Deleted value is : ",a) print(list.pop(2)) print ("Final list :",list) list = ['jack','raj','sri'] print(len(list))
f1e7ec01dfc215f7d36781bfb30c329b757c080a
Sandhya-02/programming
/0 Python old/07_revision.py
266
3.5
4
a = "= igijrdhg7rtyrgtryt tub8yti5yuh4y4utw7 rjy8e t" b = 3 c = 3j d = 3.55 e = 50 print(type(b)) print(type(c)) print(type(d)) print(type(a)) #! int-float float -string string to int print(str("idoit fellow")) print(str(e)) print(float(b)) print(type(float(b)))
349ee9f5d34c45151c671f7a1545eaac7a49d02c
Sandhya-02/programming
/0 Python old/05_lit_to_ml.py
559
3.859375
4
#! liters to ml #! 1 lit = 1000ml # lit=2 # mil = lit * 1000 # print("mil =" ,mil) #! one kid came to shop, shop guy can convert ml to lit and lit to ml #! shop guy asks the kid "denloki convert cheyali" #! kid gives him input and gets the output name= input("em convert cheyali") if name =="ml": value= float(input("yenni ml ni convert cheyali")) lit= value/1000 print("lit =",lit) elif(name=="lit" ): value= float(input("yenni liters ni convert cheyali")) ml= value*1000 print("ml = ",ml) else: print("sarigga adugu ra babu")
ca0409110b5846759427529b9a487ea95a84dadc
Sandhya-02/programming
/0 Python old/09_sandeep_milk_using_list.py
504
4.15625
4
""" mummy and sandeep went for shopping sandeep trolley lo [eggs , meat,small milk packet, bread,jam,] teskocchadu mummy said get big milk packet sandeep small milk packet ni teesesi big milk packet bag lo pettukunnadu """ list = ["eggs","meat","small milk packet","bread","jam"] print(list) if "small milk packet" in list: list.remove("small milk packet") """ del(4) pop(3)""" list.append("big milk packet") """ insert """ print("after removing small milk packet =",list)
ac080a7e3ae251ae8de33e0c59b990164f54c23d
Sandhya-02/programming
/0 Python old/016_function.py
735
3.875
4
first = int(input("enter the number ")) second = int(input("enter the number ")) select =int(input("press 1 to add\n press 2 to sub\n press 3 to mul \n press 4 to div\n ")) print ("what do u want to do\n") if (select == 1): sum = first+second print(first,second," = ",sum) if (select == 2): sub = first-second print(first, second," = ",sub) if (select == 3): mul = first*second print(first, second," = ",mul) if (select == 4): div = first/second print(first, second," = ",div) # def add(): # a,b=getinput() # return a+b # def sub(): # a,b = getinput() # return a-b # def mul(): # a,b = getinput() # return a*b # def div(): # a,b = getinput() # return a//b
6c52df82ce8e9d6f854ca15cb28a7f570729bfcd
Sandhya-02/programming
/python/mid libs.py
188
3.953125
4
""" enter a noun enter another noun enter a verb print noun verb noun """ s1 = input("enter a noun ") s2 = input("enter a noun ") s3 = input("enter a verb ") print(s1 ,"", s3 ,"", s2)
34e5f127fb80d464c06a9ba56636866ade70fd1d
Sandhya-02/programming
/0 Python old/05_if_else.py
99
3.953125
4
a = "male" b = "Male" if(a==b): print("both are equal ") else: print("both are not equal")
6dc3495707c6c437ef7a215abafbb18f58a58816
gplambeck/unit_1
/module03/plambeck_password_challenge.py
1,314
3.953125
4
# Computer guesses what the password is and displays the number of guesses. import random, time # Set the execution limit to 60 seconds t_end = time.time() + 60 characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",\ "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] print('Enter a 4 character password composed only of lower case letters.') my_password = input('Enter password: ') password_length = len(my_password) # The crack() function creates a random combination from the characters list # and compares it to the target password. It repeats this until it guesses the # correct password. def crack(): global my_password, password_length guess_num = 0 done = False while not done: guessed_pw = "" # Create a string from randomly chosen characters while len(guessed_pw) < password_length: # Add a random index from the characters list guessed_pw += random.choice(characters) # Compare guess to the real password if guessed_pw == my_password: print("found it after ", guess_num, " tries") done = True else: guess_num += 1 while my_password != "" and time.time() <= t_end: done = False crack()
f81b7e6712e68a27539f2f7667e23b97921aad5e
gplambeck/unit_1
/module01/plambeck_hello_turtle.py
1,667
3.96875
4
#Draws a picture of the olympic rings logo import turtle my_turtle = turtle.Turtle() #creates a pen my_turtle.width(10) #sets the pen width to 10 #Black ring my_turtle.circle(100) #draws a black circle of radius 100 #Blue ring my_turtle.up() #lifts up the pen my_turtle.backward(225) #moves backward 225 without drawing my_turtle.color('blue') #sets the color blue my_turtle.down() #puts the pen down my_turtle.circle(100) #draws a blue circle of radius 100 #Red ring my_turtle.up() #lifts up the pen my_turtle.forward(450) #moves forward 450 without drawing my_turtle.color('red') #sets the color red my_turtle.down() #puts the pen down my_turtle.circle(100) #draws a red circle of radius 100 #Green ring my_turtle.up() #lifts up the pen my_turtle.left(90) #changes direction to the left 90 degrees my_turtle.forward(100) #moves forward 100 without drawing my_turtle.left(90) #changes direction to the left 90 degrees my_turtle.forward(115) #moves forward 115 without drawing my_turtle.color('green') #sets the color green my_turtle.down() #puts the pen down my_turtle.circle(100) #draws a green circle of radius 100 #Yellow ring my_turtle.up() #lifts up the pen my_turtle.forward(225) #moves forward 225 without drawing my_turtle.color('yellow') #sets the color yellow my_turtle.down() #puts the pen down my_turtle.circle(100) #draws a yellow circle of radius 100
13b1add4604bf1e60ba9d5a6061f00718466e7a1
frarue/mviri_lib
/mviri/mviri_tools/tools_plotting.py
546
3.8125
4
""" this file contains functions for plotting """ import matplotlib.pyplot as plt import numpy as np def printimage(pix,tit,maxi=255,save=0): """ Simple plotting of an MVIRI image Inputs: pix array with pixel values tit title/name of the image """ pix=np.array(pix) pix[pix>maxi]=maxi im=plt.imshow(np.uint8(np.fliplr(pix)),origin='lower', interpolation='none') if save == 0: plt.show() else: print " to: ../tmp/"+tit+".png" plt.savefig("../tmp/"+tit+".png") plt.close()
e1837b3b485e3bb608e00a55d1655fb5dfab16d7
Marina-lyy/basics
/8-爬虫/v23.py
753
3.5
4
import requests from urllib import parse import json baseurl = "http://fanyi.baidu.com/sug" # 存放用来模拟form的数据一定是dict格式 data = { # girl 是翻译输入的英文内容,应该是由用户输入,此处使用编码 'kw': 'girl' } # 我们需要构造一个请求头,请求头部应该至少包含传入的数据的长度 # request要求传入的请求头是一个dict格式 headers ={ # 因为使用post,至少应该包含content-length 字段 'Content-Length': str(len(data)) } # 有了headers,data,URL,就可以尝试发出请求了 rsp = requests.post(baseurl, data=data, headers=headers) print(rsp.text) print(rsp.json()) # for item in json_data['data']: # print(item['k'],"--", item['v'])
cbc817342037d50747ab9fcf58120d33e2762719
jmckinstry/doodles
/fizzbuzz/second.py
729
3.734375
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 28 11:42:25 2019 @author: Asier """ # Pass 2: Extended FizzBuzz. Start and stop with specified ints, allows for modifiable divisors and output words # Finished in 9:07.92 def fizzbuzz( start = 1, stop = 100, words = [(3, 'Fizz'), (5, 'Buzz')] ): assert(start < stop) assert(len(words) > 0) x = start while (x <= stop): s_out = "" for div, word in words: if x % div == 0: s_out += word if len(s_out) > 0: print(s_out) else: print(str(x)) x += 1 fizzbuzz(1, 16) fizzbuzz(1, 10, [(2, 'Even'), (10, 'Tens')])
dd3cc65e39d067a3d516d4ca7d20ce10c3ba3fdd
UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019
/students/FredBallyns/lesson09/assignment/src/jpgdiscover.py
1,648
3.625
4
""" a png discovery program in Python, using recursion, that works from a parent directory called images provided on the command line. The program will take the parent directory as input. As output, it will return a list of lists structured like this: [“full/path/to/files”, [“file1.png”, “file2.png”,…], “another/path”,[], etc] """ import argparse import os from pprint import pprint global list_output list_output = [] def parse_cmd_arguments(): try: parser = argparse.ArgumentParser(description='Find Files.') parser.add_argument('-d', '--directory', help='Starting directory default "..//data"', required=False, default="..//data") parser.add_argument('-e', '--extention', help='Extention type default ".png"', required=False, default=".png") return parser.parse_args() except Exception as exception: print(f"Invalid Arguments. {exception}") def find_files(folder, file_extension): match_extention = [] for item in os.listdir(folder): if item[-1 * len(file_extension):] == file_extension: match_extention.append(item) else: sub_folder = "/".join([folder, item]) find_files(sub_folder, file_extension) if match_extention: list_output.append(folder) list_output.append(match_extention) return list_output if __name__ == "__main__": args = parse_cmd_arguments() pprint(find_files(args.directory, args.extention))
28e38f1d14d545615c1d65f0061811e8dc620653
UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019
/students/PeterB/Lesson01/Assignment/inventory_management/furniture_class.py
741
3.546875
4
from inventory_management.inventory_class import Inventory class Furniture(Inventory): """ This class handles the Furniture Object """ def __init__(self, product_code, description, market_price, rental_price, material, style): # Creates common instance variables from the parent class self.material = material self.style = style super().__init__(product_code, description, market_price, rental_price) def return_as_dictionary(self): """ This returns a dictionary containing the expected fields """ output_dict = super().return_as_dictionary() output_dict['material'] = self.material output_dict['style'] = self.style return output_dict
d1919104c7356cc4ca480107a80e97d6216416b7
UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019
/students/Sally_Shen/lesson09/assignment/src/database.py
799
3.6875
4
from pymongo import MongoClient class MongoDBConnection: def __init__(self, host="localhost", port="27017"): self.host = f"mongodb://{host}:{port}" self.connection = None def __enter__(self): self.connection = MongoClient(self.host) return self def __exit__(self, a, b, c): self.connection.close() with MongoDBConnection() as mongo: conn = mongo.connection db = conn.my_app collection = db.people data = [ {"name": "Jeremy Jay", "age": 23}, {"name": "Michael James", "age": 40} ] collection.insert_many(data) jeremy = collection.find_one({"name": "Jeremy Jay"}) if jeremy: age = jeremy["age"] print(f"Jeremy found, age: {age}") else: print("Jeremy not found")
8db44ab47ac883b22b2ffe5f3d7f6518c741984f
UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019
/students/rimlee_talukdar/lesson09/assignment/src/jpgdiscover.py
680
3.53125
4
import os def list_jpg_files(folder, file_extension=".png", dirs=[], result=[]): dirs.append(folder) print(f"Checking folder: {folder}") current_dir = "/".join(dirs) print(f"current_dir: {current_dir}") for item in os.listdir(current_dir): print(f"Checking directory: {item}") if os.path.isdir(current_dir + "/" + item): list_jpg_files(item, file_extension, dirs, result) else: if item[-1 * len(file_extension):] == file_extension: png_path = "/".join(dirs) + "/" + item print(f"Found png: {png_path}") result.append(png_path) dirs.pop() return result
7defa6a493af5b4a124e65effb0febd9ac569a80
UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019
/students/ArchWu/lesson01/assignment/test_unit.py
6,619
3.875
4
""" Unit tests for inventory management """ from unittest import TestCase, mock import unittest from inventory_management.inventory_class import Inventory from inventory_management.furniture_class import Furniture from inventory_management.electric_appliances_class import ElectricAppliances from inventory_management import main from inventory_management import market_prices class InventoryTest(unittest.TestCase): """test Inventory class""" def test_init(self): """test init function of class""" test_obj = Inventory(1, 2, 3, 4) self.assertEqual(test_obj.product_code, 1) self.assertEqual(test_obj.description, 2) self.assertEqual(test_obj.market_price, 3) self.assertEqual(test_obj.rental_price, 4) def test_return_dict(self): """test return as dict function""" test_obj = Inventory(1, 2, 3, 4).return_as_dictionary() self.assertEqual(test_obj['product_code'], 1) self.assertEqual(test_obj['description'], 2) self.assertEqual(test_obj['market_price'], 3) self.assertEqual(test_obj['rental_price'], 4) class FurnitureTest(unittest.TestCase): """Test Furniture class""" def test_init(self): """Test init""" test_obj = Furniture(1, 2, 3, 4, 5, 6) self.assertEqual(test_obj.product_code, 1) self.assertEqual(test_obj.description, 2) self.assertEqual(test_obj.market_price, 3) self.assertEqual(test_obj.rental_price, 4) self.assertEqual(test_obj.material, 5) self.assertEqual(test_obj.size, 6) def test_return_dict(self): """Test return as dict func""" test_obj = Furniture(1, 2, 3, 4, 5, 6).return_as_dictionary() self.assertEqual(test_obj['product_code'], 1) self.assertEqual(test_obj['description'], 2) self.assertEqual(test_obj['market_price'], 3) self.assertEqual(test_obj['rental_price'], 4) self.assertEqual(test_obj['material'], 5) self.assertEqual(test_obj['size'], 6) class ElectricAppliancesTest(unittest.TestCase): """Test EA class""" def test_init(self): """Test __init__()""" test_obj = ElectricAppliances(1, 2, 3, 4, 5, 6) self.assertEqual(test_obj.product_code, 1) self.assertEqual(test_obj.description, 2) self.assertEqual(test_obj.market_price, 3) self.assertEqual(test_obj.rental_price, 4) self.assertEqual(test_obj.brand, 5) self.assertEqual(test_obj.voltage, 6) def test_return_dict(self): """Test return as dict func""" test_obj = ElectricAppliances(1, 2, 3, 4, 5, 6).return_as_dictionary() self.assertEqual(test_obj['product_code'], 1) self.assertEqual(test_obj['description'], 2) self.assertEqual(test_obj['market_price'], 3) self.assertEqual(test_obj['rental_price'], 4) self.assertEqual(test_obj['brand'], 5) self.assertEqual(test_obj['voltage'], 6) class MainTest(unittest.TestCase): """Test main module""" def test_main(self): """Test main_menu function """ with mock.patch('builtins.input', side_effect=['0', 'q']): with mock.patch('sys.stdout'): with self.assertRaises(SystemExit): main.main_menu() mock.call.write( "Please choose from the following options (1, 2, q)" ).assert_called_once() self.assertRaises(SystemExit, main.exit_program()) @mock.patch('main.market_prices.get_latest_price', return_value=25) def test_add_new_item(self, mocked_get_latest_price): """Test add_new_item function """ with mock.patch('builtins.input', return_value='n'): main.add_new_item() self.assertEqual(main.FULL_INVENTORY['n']['product_code'], 'n') self.assertEqual(main.FULL_INVENTORY['n']['market_price'], 25) mocked_get_latest_price.assert_called_once() with mock.patch('builtins.input', return_value='y'): main.add_new_item() self.assertEqual(main.FULL_INVENTORY['y']['product_code'], 'y') self.assertEqual(main.FULL_INVENTORY['y']['market_price'], 25) self.assertEqual(main.FULL_INVENTORY['y']['size'], 'y') self.assertEqual(main.FULL_INVENTORY['y']['material'], 'y') with mock.patch('builtins.input', side_effect=['1', '2', '3', 'n', 'y', '4', '5']): main.add_new_item() self.assertEqual(main.FULL_INVENTORY['1']['product_code'], '1') self.assertEqual(main.FULL_INVENTORY['1']['market_price'], 25) self.assertEqual(main.FULL_INVENTORY['1']['brand'], '4') self.assertEqual(main.FULL_INVENTORY['1']['voltage'], '5') def test_item_info(self): """Test item info function""" with mock.patch('builtins.input', return_value='0'): with mock.patch('sys.stdout') as fake_stdout: main.item_info() fake_stdout.assert_has_calls( [mock.call.write("Item not found in inventory"), mock.call.write("\n")]) with mock.patch('builtins.input', return_value='n'): with mock.patch('sys.stdout') as fake_stdout: main.item_info() fake_stdout.assert_has_calls( [mock.call.write('product_code:n'), mock.call.write('\n'), mock.call.write('description:n'), mock.call.write('\n'), mock.call.write('market_price:25'), mock.call.write('\n'), mock.call.write('rental_price:n'), mock.call.write('\n')]) def test_get_price(self): """Test get_price function""" with mock.patch('sys.stdout') as fake_stdout: main.get_price('n') # A dummy input fake_stdout.assert_has_calls( [mock.call.write("Get price"), mock.call.write("\n")]) def test_exit_program(self): """Test exit_program function""" with self.assertRaises(SystemExit): self.assertRaises(SystemExit, main.exit_program()) class MarketPriceTest(TestCase): """Test market_price module""" def test_get_latest_price(self): """Test get_latest_price function""" self.assertEqual(market_prices.get_latest_price(''), 24) if __name__ == "__main__": unittest.main()
2e4f2256c5ab9ab4268579e6b162e1317e6f9f16
UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019
/students/rimlee_talukdar/lesson02/assignment/src/charges_calc.py
5,961
3.875
4
""" Returns total price paid for individual rentals """ import argparse import json import datetime import math import logging def parse_cmd_arguments(): """ creates an argument parser for the program """ parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-i', '--input', help='input JSON file', required=True) parser.add_argument('-o', '--output', help='ouput JSON file', required=True) parser.add_argument('-d', '--debug', help='[3: ERROR, 2: WARN, 1: DEBUG, 0: NONE (default)]', required=False, type=int, default=0) return parser.parse_args() def load_rentals_file(filename): """ Opens JSON file and returns data, logs a critical error if there is an error """ try: with open(filename) as file: return json.load(file) except FileNotFoundError as exception: # Log exception if unable to open file logging.critical(f'Unable to open file {filename} due to:\n\t{exception}') exit(1) def calculate_additional_fields(cal_data): """ Calculate the following additional field from the input data 1. total_days as total number of rental days 2. total_price as total price of the rental 3. sqrt_total_price as square root of the rental 4. unit_cost as in unit cost of the rental :param cal_data: the input data :return: updated data """ for key, value in cal_data.items(): logging.debug('*' * 10 + f' Computing for {key} ' + '*' * 10) # Update total days try: rental_start = datetime.datetime.strptime(value['rental_start'], '%m/%d/%y') logging.debug(f'Rental start time {rental_start}') rental_end = datetime.datetime.strptime(value['rental_end'], '%m/%d/%y') logging.debug(f'Rental end time {rental_end}') # If start data is after end date flip the entry total_days = (rental_end - rental_start).days if total_days < 0: logging.debug(f'Start date after end date, hence flipping dates') total_days = -total_days value['total_days'] = total_days logging.debug(f'Rental total days {total_days}') value['total_price'] = total_days * value['price_per_day'] logging.debug(f'Rental total price {value["total_days"]}') value['sqrt_total_price'] = math.sqrt(value['total_price']) logging.debug(f'Rental square root of total price {value["total_days"]}') value['unit_cost'] = value['total_price'] / value['units_rented'] logging.debug(f'Rental unit cost {value["rental_start"]}') except Exception as exception: # Log the warning if any exception is triggered with computation logging.warning(f'{exception.__class__.__name__} exception was raise' + f' while setting total_days for key {key}: {exception}') finally: # Set Unknown if any value couldn't be computed value['total_days'] = 'Unknown' if 'total_days' not in value else value['total_days'] value['total_price'] = 'Unknown' if 'total_price' not in value else value['total_price'] value['sqrt_total_price'] = 'Unknown' if 'sqrt_total_price' not in value \ else value['sqrt_total_price'] value['unit_cost'] = 'Unknown' if 'unit_cost' not in value else value['unit_cost'] logging.info(f'Computed value for key {key}: {value}') return cal_data def save_to_json(filename, data): """ Saves the data into output file :param filename: output filename :param data: data which will be saved into file :return: none """ if '.json' not in filename: filename = f'{filename}.json' try: with open(filename, 'w') as file: json.dump(data, file) except Exception as exception: logging.critical(f'Unable to write file {filename} due to:\n\t{exception}') exit(2) def setup_logger(level=0): """ Setup the logger for the program :param level: The log level for the program [ERROR, WARN, DEBUG, NONE (default)] :return: logger instance """ log_format = "%(asctime)s %(filename)s:%(lineno)-3d %(levelname)s %(message)s" log_file_name = datetime.datetime.now().strftime('%Y-%m-%d') + '.log' logger = logging.getLogger() formatter = logging.Formatter(log_format) file_handler = logging.FileHandler(log_file_name) file_handler.setFormatter(formatter) console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) logging_level = None if level == 3: logging_level = logging.CRITICAL elif level == 2: logging_level = logging.WARN elif level == 1: logging_level = logging.DEBUG if level == 0: logger.disabled = True return logger console_handler.setLevel(logging_level) file_handler.setLevel(logging_level) logger.setLevel(logging_level) logger.addHandler(file_handler) logger.addHandler(console_handler) return logger if __name__ == "__main__": """ Main file for the program """ # Start with Debug logger ARGS = parse_cmd_arguments() LOGGER = setup_logger(ARGS.debug) logging.debug('Starting the program ....') logging.debug(f'Loading the data from the input file {ARGS.input}') DATA = load_rentals_file(ARGS.input) logging.debug(f'File loaded') logging.debug(f'Loading the data from the input file {ARGS.input}') CAL_DATA = calculate_additional_fields(DATA) logging.debug(f'Additional fields calculated') logging.debug(f'Writing output file {ARGS.input}') save_to_json(ARGS.output, CAL_DATA) logging.debug(f'File saved to output file') logging.debug('Exiting the program ....') logging.shutdown()
5e0c461e5b4d1f9e6c328dcc78d88b5c8a08d410
UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019
/students/AndrewMiotke/lesson04/class_work/generators.py
466
4.21875
4
""" Generators are iterators that returns a value """ def y_range(start, stop, step=1): """ Create a generator using yield """ i = start while i < stop: """ yield, like next(), allows you to increment your flow control e.g. inside a loop """ yield i i += step it = y_range(12, 25) next(it) # this returns 12 next(it) # this returns 13 # Generators in a list comprehension [y for y in y_range(12, 25)]
deb811d7c1a936a03ddc2767e5456dcc2316a1f6
4papiez/2017win_gr2_kol2
/kol2.py
4,093
3.875
4
# Class diary # # Create program for handling lesson scores. # Use python to handle student (highscool) class scores, and attendance. # Make it possible to: # - Get students total average score (average across classes) # - get students average score in class # - hold students name and surname # - Count total attendance of student # The default interface for interaction should be python interpreter. # Please, use your imagination and create more functionalities. # Your project should be able to handle entire school. # If you have enough courage and time, try storing (reading/writing) # data in text files (YAML, JSON). # If you have even more courage, try implementing user interface. from functools import reduce from optparse import OptionParser import json option_help = '''choose OPTION: create_course (required course_name)/ create_student (required coursename fname, lname)/ add_grade (required course_name , fname, lname, grade)/ add_presence (required course_name , fname, lname, presence (T/F))/ get_average (required course_name, optional fname, lname)/ get_presence (required course_name, fname, lname)''' def create_course(course_list, course_name): course_list[course_name] = {} def create_student(course_list, course, first_name, last_name): course_list[course][first_name+' '+last_name] = {'Grades' : [], 'Presence' : []} def add_grade(course_list, course, student, grade): course_list[course][student]['Grades'].append(grade) def add_presence(course_list, course, student, is_present): course_list[course][student]['Presence'].append(is_present) def get_average(course_list, course, student = None): result = 0.0 if student is None: for s in course_list[course].items(): result += reduce(lambda x, y: x + y, s[1]['Grades']) / len(s[1]['Grades']) result /= len(course_list[course]) else: result = reduce( lambda x, y: x + y, course_list[course][student]['Grades'] ) / len(course_list[course][student]['Grades'] ) return result def get_presence(course_list, course, student): return '{:0.0f}%'.format( 100 * len([x for x in course_list[course][student]['Presence'] if x]) / len(course_list[course][student]['Presence']) ) def save(course_list): with open('data.json', 'w') as outfile: json.dump(course_list, outfile) def load(): with open('data.json') as data_file: course_list = json.load(data_file) return course_list def make_parser(): parser = OptionParser("usage: %prog [options] arg") parser.add_option('-c', '--course',dest = 'coursename',help="course COURSENAME") parser.add_option('-f', '--firstname',dest = 'firstname',help="student's FIRSTNAME") parser.add_option('-l', '--lastname',dest = 'lastname',help="student's LASTNAME") parser.add_option('-p', '--presence',dest = 'presence',help="student's PRESENCE (True/False)") parser.add_option('-g', '--grade',dest = 'grade',help="student's GRADE") parser.add_option('-o', '--option',dest = 'option',help=option_help) return parser if __name__ == "__main__": course_list = load() parser = make_parser() (options, args) = parser.parse_args() if options.option=='create_course': create_course(course_list, options.coursename) elif options.option=='create_student': create_student( course_list, options.coursename, options.firstname, options.lastname ) elif options.option=='add_grade': add_grade( course_list, options.coursename, options.firstname+' '+options.lastname, float(options.grade) ) elif options.option=='add_presence': add_presence( course_list, options.coursename, options.firstname+' '+options.lastname, True if options.presence=='T' else False ) elif options.option=='get_presence': print get_presence( course_list, options.coursename, options.firstname+' '+options.lastname ) elif options.option=='get_average': print get_average( course_list, options.coursename, options.firstname+' '+options.lastname if options.firstname is not None else None ) else: parser.error("incorrect number or type of arguments") save(course_list)
bb0828b74f6eb99c20ffc39e3cae82f0816ada65
droidy12527/AlgorithmsInPythonandCpp
/anargrams.py
409
4.125
4
def findAnargrams(arr): answers = [] m = {} for elements in arr: make = ''.join(sorted(elements)) if make not in m: m[make] = [] m[make].append(elements) for hello in m.values(): answers.append(hello) return answers arr = [ "eat", "tea", "tan", "ate", "nat", "bat" ] answer = findAnargrams(arr) print('The anargrams are {}'.format(answer))
37d5f6d5ca327f97571c1313d194ae6b15492b66
droidy12527/AlgorithmsInPythonandCpp
/longestsubstringwithnorepeatingchars.py
610
4.03125
4
#Function to Find the longest Substring which has non repeating characters def findLongestSub(s): left = 0 right = 0 m = {} length = len(s) answer = 0 while left < length and right < length: element = s[right] if element in m: left = max(left, m[element]) m[element] = right answer = max(answer, right - left+1) right = right + 1 return answer s = 'ababdhksoia' len_sub = findLongestSub(s) if len_sub == -1: print('There was error with the code') else: print('The length of longest substring is {}'.format(len_sub))
3e41dcdae48b284a2f4dc23b62a8155cce617952
NTR0314/advent_of_code
/2019/day1/fuel.py
424
3.546875
4
f = open("fuel_input.txt", "r") def fuel_mass(x): return (int(int(x) / 3) - 2) def mass_fuel_rec(mass): result = fuel_mass(mass) if fuel_mass(result) > 0: result += mass_fuel_rec(result) return result # A1 if f.mode == 'r': f1 = f.readlines() fuel_a1 = 0 fuel_a2 = 0 for x in f1: fuel_a1 += fuel_mass(x) fuel_a2 += mass_fuel_rec(x) print(fuel_a1) print(fuel_a2)
63d5b174ae1125ddefd58c403cfcb4a2ca1d0e1e
koalaah/aiforgames
/Spike13/Action.py
2,257
3.578125
4
class Action: def __init__(self, description, effects,cost): self.effects = effects self.description = description self.cost = cost # def PerformAction(self): # for effect in self.__effects: # effect["goal"].UpdateGoalInsistance(effect["insistance_change"]) # self.__game_state.money += effect["cost"] # # def GetDiscontent(self): # total_discontent = 0 # goal_counted = False # # for every goal # for goal in self.__game_state.goals: # goal_counted = False # do we have this goal? # if we do, take into account this action # for effect in self.__effects: # if goal == effect["goal"]: # insistance = goal.GetGoalInsistance() # final_insistance = insistance + effect["insistance_change"] # total_discontent += final_insistance * final_insistance # goal_counted = True # break # # if not goal_counted: # total_discontent += goal.GetGoalInsistance() * goal.GetGoalInsistance() # # return total_discontent # # # def AlleviatesGoal(self,goal): # for effect in self.__effects: # if effect["goal"] == goal: # if effect["insistance_change"] < 0: # return True # return False # # def AlleviatesGoal_Affordable(self,goal): # for effect in self.__effects: # if effect["goal"] == goal: # if effect["insistance_change"] < 0: # if effect["cost"] + self.__game_state.money >= 0: # return True # # return False # # def GetActionDescription(self): # return self.__description # # def affordable(self): # print("funds = {}".format(self.__game_state.money)) # can_afford = True # # for effect in self.__effects: # if effect["cost"] + self.__game_state.money < 0: # print("{} is not affordable".format(self.__description)) # return False # # return True
e0792571ee2c9634790529ac5b113627a0a8286e
vineelBoddula/ASCII-Art-Generation
/createAsciiArt.py
3,730
3.828125
4
#Citation 1: Collier, R. "Lectures Notes for COMP1405B – Introduction to Computer Science I" [PDF document]. #Retrieved from cuLearn: https://www.carleton.ca/culearn/ (Fall 2015) from SimpleGraphics import* #function to get file name def file(convChars): fileName = str(input("What is the file name: ")) return(fileName) #user input function gets user image and loads it. Also gets what type of background to run def userInput(): #loop until the image is less than 80 while True: imgName = str(input("Name of the Image: ")) imgLoaded = loadImage(imgName) drawImage(imgLoaded,0,0) if(getWidth(imgLoaded) >80): print("Image width needs to be less than 80") else: break convType = str(input("T if white background or F if black background")) #if its F then black background if(convType == "F"): convType = True convChars = [".",",","*","~","=","/","%","#","$","@"] #else if its T then white background elif(convType== "T"): convType = False convChars = ["@","$","#","%","/","=","~","*",",","."] #else its white background else: print("error, unrecognizable input. Default settings, black background") convChars = [".",",","*","~","=","/","%","#","$","@"] convType =False #returning the image and characters return(imgLoaded,convChars) #this function turns the pixels to greyScale def greyScale(img): print("gray is working") #nested for loop to go through the image for x in range(0, getWidth(img)): for y in range(0, getHeight(img)): # Retrieve the amounts of red, green and blue for the pixel r, g, b = getPixel(img, x, y) # Compute the average intensity avg = (r + g + b) / 3 # Update the pixel so that it has equal amounts of red, green and blue putPixel(img, x, y, avg, avg, avg) # Display the modified image drawImage(img, 0, 0) return img #this function turns the each pixel to ascii art def conversion(img,characters): print("conversion is happening") asciiList = []#2D list convChars =characters #get characters from argument for rows in range(0, getHeight(img)): asciiRow = []#list for the row for column in range(0, getWidth(img)): r, g, b = getPixel(img, column, rows)#get greyscale avg avg = r if (avg >= 0 and avg <= 25.5): asciiRow.append(convChars[0]) elif (avg > 25.5 and avg <= 51): asciiRow.append(convChars[1]) elif (avg > 51 and avg <= 76.5): asciiRow.append(convChars[2]) elif (avg > 76.5 and avg <= 102): asciiRow.append(convChars[3]) elif (avg > 102 and avg <= 127.5): asciiRow.append(convChars[4]) elif (avg > 127.5 and avg <= 153): asciiRow.append(convChars[5]) elif (avg > 153 and avg <= 178.5): asciiRow.append(convChars[6]) elif (avg > 178.5 and avg <= 204): asciiRow.append(convChars[7]) elif (avg > 204 and avg <= 229.5): asciiRow.append(convChars[8]) elif (avg > 229.5 and avg <= 255): asciiRow.append(convChars[9]) asciiList.append(asciiRow)#add to the list return(asciiList) #main function to output the characters def main(): img,convChars =userInput() fileName =file(convChars) img =greyScale(img) lst = conversion(img,convChars) filehnd1 =open(fileName, "w") #write to the file filehnd1.write(str(convChars)+"\n") #nested for loop to go through the 2D list and print characters for column in range(0, len(lst)): for rows in range(0, len(lst[column])): txt= lst[column][rows] filehnd1.write(txt)#writing txt to the file print(lst[column][rows],end="") #if statement to start at new line if (len(lst[column]) <=80): filehnd1.write("\n") #new line print() filehnd1.close() main()
486196aad0561415533d9127f984fc76966b4b74
misaelHS/curso
/Paquetes/Funciones.py
4,980
3.953125
4
import re # Se importa la libreria para las expresiones regulares #---------------------------------------- TAREA1: FUNCION DE PIEDRA PAPEL Y TIJERAS ------------------------------------------------ def funcion(seleccion, maquina_String, opciones_String): # Se define la funcion que valida los valores a ingresar if (seleccion == 1 or seleccion == 2 or seleccion == 3): # si el numero ingresado por el jugador es 1,2 o 3 humano_String = opciones_String[seleccion - 1] # Se crea la variable con la opcione del humano print("\t\t\t La maquina dijo: ", maquina_String) # Se muestra por pantalla la opcion de la maquina print("\t\t\t Tu dijiste:\t ", humano_String) # Se muestra por pantalla la opcion del humano if (humano_String == maquina_String): # si las opcciones son iguales, se tiene un empate y se muestra por pantalla print("\t\t\t Empate") elif (humano_String != maquina_String): # si las opciones son diferentes, se entra a veriricar la posibles combinaciones del juego if (humano_String == 'Piedra'): if (maquina_String == 'Tijera'): print("\t\t\t Ganaste!") if (maquina_String == 'Papel'): print("\t\t\t Perdiste") if (humano_String == 'Papel'): if (maquina_String == 'Piedra'): print("\t\t\t Ganaste!") if (maquina_String == 'Tijera'): print("\t\t\t Perdiste") if (humano_String == 'Tijera'): if (maquina_String == 'Papel'): print("\t\t\t Ganaste!") if (maquina_String == 'Piedra'): print("\t\t\t Perdiste") else: print("\t\t\t\t\t\t\t ¡Tu eleccion no es correcta!, debe ser un 1, 2 o 3 \n\n ") # si el numero ingresado por el jugador no es 1,2 o 3 se le indica que no es correcto #-------------------------------------------- TAREA 2: FUNCIONES PARA VALIDAR PATRONES REGULARES ------------------------------- #----------------------------------------------------------------------------- def validaNumeroTelefonico(numeroTelefonico): # FUNCION PARA VALIDAR EL NUMERO TELEFONICO EN LA TAREA 2 #Se crea la funcion a evaluar el el formato del numero telefonico patron1='^\(?\d{3}?(\)?\d{7}?)$' # Se establece el patron, dentro de la cadena de carateres limitada con ^$. # (? \d{d3} ? Puede o no contener el simbolo (, despues deben de ir 3 digitos enteros # ( \)?\d{7}? ) en la segunda seccion limitada por parentesis se indica que puede o no # ir el simbolo del parentesis cerrado ) y depues deben ir 7 digitos if re.match(patron1,numeroTelefonico) : # Se evalua el patron del numero telefonico mediante la expresion regular macht print('\n\n\n \t\t\t\t\t El numero es correcto \n\n') else: print('\n\n\n \t\t\t\t\t El numero no es correcto \n\n') #------------------------------------------------------------------------------ def validaCorreo(correoElectronico): # FUNCION PARA VALIDAR EL CORREO EN LA TAREA 2 patron2 = '([a-z0-9_\.-]+)@([\da-z\.]+)\.([a-z\.])' #El patron consiste en tres secciones #([a-z0-9_\.-]+) indica que se puede tener un rango de caracteres entre la a - z; un rango de numeros 0 -9; #un caracater de punto o guion. y con el signo mas de indica que exista uno o mas de estos caracteres #@ debe de existir un arroba #([\da-z\.]+) indica que se puede tener un rango de 0-9; un rango de caracteres a-z seguido por un punto y el signo + #indica que puede tener uno a mas de estos caracteres. Despues sigue un punto. #([a-z\.]) indica que se puede tener un rango de caracteres entre a-z seguida de un punto if re.match(patron2, correoElectronico, re.IGNORECASE): # Se define la bandera para ignorar mayusculas del correo print('El correo es correcto') else: print('El correo no es correcto') #----------------------------------------------------------------------------------------- def validaCurp(curp): # FUNCION PARA VALIDAR EL CURP EN LA TAREA 2 patron2 = '^([a-z]{4})([0-9]{6})([MH]{1})([a-z]{2})([a-z]{3})([\d]{2})$' # se define el patron de la curp if re.match(patron2,curp, re.IGNORECASE): print('La CURP es correcta') else: print('La CURP no es correcta') #------------------------------------------------------------------------------------------ def validaRFC(rfc): # FUNCION PARA VALIDAR EL RFC EN LA TAREA 2 patron2 = '^([a-z]{4})([0-9]{6})([a-z0-9]{3})$' # se define el patron del rfc if re.match(patron2,rfc, re.IGNORECASE): print('El RFC es correcto') else: print('El RFC no es correcto')
8633a4cf6b46857954151576703598bbaef77b63
cmaureir/ep2021_learn_cpython_by_breaking_it
/slides/a.py
258
3.515625
4
# This is a comment #import my_module def add(a: int, b: float) -> float: return a + b def main(): msg: str = "hello world" x: int = 3 y: float = 3.14 z: float = add(x, y) print("%f" % z) if __name__ == "__main__": main()
f6656b8475c786cd235236b8a0d2a3bc8eb4e455
codewalkertse/codewalkertse.github.io
/downloads/code/multitask/threading_join_setDaemon.py
909
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2018-07-30 10:21:42 # @Author : Simon (simon.xie@codewalker.meg) # @Link : http://www.codewalker.me # @Version : 1.0.0 from threading import Thread from time import process_time, sleep, time_ns flag = 0 def do_something(name, sec): print(f'Do {name} in {sec}') sleep(sec) print(f'completed {name} after {sec}s.') def main(): start = time_ns() have_supper = Thread(name='have_supper', target=do_something, args=('have_supper', 2)) watch_tv = Thread(name='watch_tv', target=do_something, args=('watch_tv', 10)) have_supper.setDaemon(True) have_supper.start() watch_tv.setDaemon(True) watch_tv.start() have_supper.join(3) watch_tv.join(4) print(f'Subthread done in {time_ns()-start} seconds') if __name__ == '__main__': start = time_ns() main() print(f'Main done in {time_ns()-start} seconds')
07e96b93c8b18179b4546bee0cd967be4729f7c0
codewalkertse/codewalkertse.github.io
/downloads/code/string_bits.py
505
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2018-08-10 12:02:36 # @Author : Simon (simon.xie@codewalker.meg) # @Link : http://www.codewalker.me # @Version : 1.0.0 def string_bits(str): return ''.join([str[x] for x in range(len(str)) if x % 2 == 0]) # Same as # new_str = [] # for x in range(len(str)): # if x % 2 == 0: # new_str.append(str[x]) # return ''.join(new_str) def main(): print(string_bits('Heeololeo')) if __name__ == "__main__": main()
c61d3fc1c7a42f6e8bc8240a81ac69aaff41015c
glebite/uatu
/src/config_organizer.py
977
3.515625
4
""" config_organizer - more than just a parser but builds what is needed """ import os import configparser class ConfigOrganizer: """ ConfigOrganizer - configuration file class and other data """ def __init__(self, config_file=None): """ initialize file and configuration data """ if os.path.isfile(config_file): self.config_file = config_file self.config_handler = configparser.ConfigParser() else: raise IOError def read_config_data(self): """ read_config_data """ self.config_handler.read(self.config_file) return self.config_handler def find_cameras(self): """ find_cameras - helps to define cameras from the config file in case there are other fields """ cameras = [match_string for match_string in self.config_handler if "camera_" in match_string] return cameras
6ef9f37035dc2b361fc8fdc4cf6b39377b633a54
syedshowmic/Algorithm1_UCSanDiegoX
/1 Algorithm Design and Techniques/Week 2/2.2/St_fibonacci_lastDigit.py
1,108
3.890625
4
# Uses python3 def calc_fib(n): fibonacci_list = [0, 1] for i in range(2, n + 1): fibonacci_list.append(fibonacci_list[-1] + fibonacci_list[-2]) return fibonacci_list[-1] n = int(input()) print(str(calc_fib(n))[-1]) # ============================================================================= # last_Number = calc_fib(n) % 10 # print(last_Number) # ============================================================================= # ============================================================================= # LAST_DIGIT = list(str(calc_fib(n))) # LAST_NUMBER = LAST_DIGIT[-1] # ============================================================================= #print(LAST_NUMBER) # ============================================================================= # newList = list((calc_fib(n))) # lastNumber = newList[-1] # print(lastNumber) # lastDigit = list(str(lastNumber))[-1] # print(lastDigit) # ============================================================================= print(calc_fib(n)) #% is modulus operator in python z = 9827000000000000000000000000 z.split()
345858db7aa127d23ea355b58f042f7c9f643db9
muditabysani/BFS-1
/Problem2.py
1,426
3.6875
4
from collections import deque class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # Time Complexity : O(mn) where m is the number of prerequisites and n is the number of courses # Because for every course we are going through the entire prerequisites array # Space Complexity : O(n) where n is the number of courses because indegrees array length is number of courses and at any point the max number of elements in the queue is number of courses indegrees = [0] * numCourses # In prerequisite array, the first index represents the course number and the second index represents the prerequisite course number for i in prerequisites: indegrees[i[0]] += 1 # The index represents the course number queue = deque() # Contains the courses that are completed for index, val in enumerate(indegrees): if val == 0: queue.append(index) # We can complete the courses who don't have any prerequisites count = 0 while len(queue) > 0: course = queue.popleft() count += 1 for i in prerequisites: if course == i[1]: indegrees[i[0]] -= 1 # decrement the prerequisites for the course if indegrees[i[0]] == 0: queue.append(i[0]) return count == numCourses
c23da6b7dd6d3a621c413ea3304ec092a062781b
yiguid/LeetCodePractise
/todo/692.py
568
3.59375
4
import collections import heapq class Solution: def topKFrequent(self, words, k): """ :type words: List[str] :type k: int :rtype: List[str] """ count = collections.Counter(words) heap = [(-freq, word) for word, freq in count.items()] heapq.heapify(heap) return [heapq.heappop(heap)[1] for _ in range(k)] s = Solution() print(s.topKFrequent(["i", "love", "leetcode", "i", "love", "coding"],2)) print(s.topKFrequent(["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"],4))
9f4c997fda005a87349ada251909d884b4dbcf19
yiguid/LeetCodePractise
/todo/054.py
1,206
3.546875
4
class Solution: def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ m = len(matrix) if m == 0: return [] n = len(matrix[0]) if n == 0: return [] top, right, bottom, left = 0, n, m, 0 ret = [] while True: for i in range(left, right): ret.append(matrix[top][i]) top += 1 if top >= bottom: break for i in range(top, bottom): ret.append(matrix[i][right - 1]) right -= 1 if left >= right: break for i in range(right - 1, left - 1, -1): ret.append(matrix[bottom - 1][i]) bottom -= 1 if top >= bottom: break for i in range(bottom - 1, top - 1, -1): ret.append(matrix[i][left]) left += 1 if left >= right: break return ret s = Solution() print(s.spiralOrder([ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ])) print(s.spiralOrder([ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ]))
4a898a315052ec783f8472c858c7b4d8dd38063e
yiguid/LeetCodePractise
/finished/heap.py
2,456
3.796875
4
class Heap(object): def __init__(self, data): self.items = data for index in range(len(self.items) // 2, -1, -1): self.percolate_down(index) def percolate_down(self,index): while index * 2 + 1 < len(self.items): left = index * 2 + 1 if index * 2 + 2 < len(self.items): right = index * 2 + 2 #compare left and right if self.items[left] < self.items[right]: if self.items[left] < self.items[index]: self.items[index], self.items[left] = self.items[left], self.items[index] index = left else: break else: if self.items[right] < self.items[index]: self.items[index], self.items[right] = self.items[right], self.items[index] index = right else: break else: #compare root and left if self.items[left] < self.items[index]: self.items[index], self.items[left] = self.items[left], self.items[index] else: break def is_empty(self): return 0 == len(self.items) def size(self): return len(self.items) def pop(self): if len(self.items) != 0: self.items[0], self.items[-1] = self.items[-1], self.items[0] ret = self.items.pop() self.percolate_down(0) return ret return None #get value but not pop up def get(self): if len(self.items) != 0: return self.items[0] else: return None def add(self, item): self.items.append(item) self.percolate_up(len(self.items) - 1) def percolate_up(self, index): while (index - 1) // 2 >= 0: root = (index - 1) // 2 if self.items[index] < self.items[root]: self.items[index], self.items[root] = self.items[root], self.items[index] index = root else: break def main(): h = Heap([9,5,6,2,3,10,4,1,8,7,0]) h.add(-1) print(h.get()) h.add(11) print(h.get()) print(h.size()) print(h.get()) for i in range(h.size()): print(h.pop()) if __name__ == "__main__": main()
2e3ae3a6fdab94ec835524d29c38b67ef06112b8
yiguid/LeetCodePractise
/test.py
303
3.59375
4
class Solution: def swap(self, a, b): a, b = b, a def swap_array(self, nums): nums[0], nums[1] = nums[1], nums[0] self.swap(nums[0], nums[1]) print(nums) s = Solution() a = 10 b = 20 s.swap(a, b) print(a) print(b) nums = [1,2] s.swap_array(nums) print(nums)
e8b9a2a3c20b96f578c73aa1adfd88b7c0266ea8
yiguid/LeetCodePractise
/finished/147.py
1,184
3.921875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None or head.next == None: return head v = ListNode(0) v.next = head k = head.next #processing number preK = head while k != None: pre = v p = v.next while p != k: if p.val <= k.val: pre = p p = p.next else: pre.next = k preK.next = k.next k.next = p k = preK p = k preK = k k = k.next return v.next def printList(self,head): p = head while p != None: print(p.val) p = p.next s = Solution() head = ListNode(-1) head.next = ListNode(5) head.next.next = ListNode(0) head.next.next.next = ListNode(3) newHead = s.insertionSortList(head) s.printList(newHead)
d1afb6bf415eac55d665ba18170bda9fb915e6d4
yiguid/LeetCodePractise
/explore/dp/337.py
1,788
3.625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def rob(self, root): """ :type root: TreeNode :rtype: int """ # flag = True means rob the root, else not. return max rob value within this root # time limit exceeded def tryRob(root, flag): if not root: return 0 if not flag: return max(tryRob(root.left, True),tryRob(root.left, False)) + max(tryRob(root.right, True),tryRob(root.right, False)) else: res = root.val if root.left: res += tryRob(root.left, False) if root.right: res += tryRob(root.right, False) return res return max(tryRob(root, True), tryRob(root, False)) def rob2(self, root): def robBool(root): if not root: return 0, 0 robTrueLeft, robFalseLeft = robBool(root.left) robTrueRight, robFalseRight = robBool(root.right) valueTrue = robFalseLeft + robFalseRight + root.val valueFalse = max(robTrueLeft, robFalseLeft) + max(robTrueRight, robFalseRight) return valueTrue, valueFalse robTrue, robFalse = robBool(root) return max(robTrue, robFalse) root = TreeNode(3) root.left = TreeNode(2) root.right = TreeNode(3) root.left.right = TreeNode(3) root.right.right = TreeNode(1) root2 = TreeNode(3) root2.left = TreeNode(4) root2.right = TreeNode(5) root2.left.left = TreeNode(1) root2.left.right = TreeNode(3) root2.right.right = TreeNode(1) s = Solution() print(s.rob2(root)) print(s.rob2(root2))
f64e948d5fbe7a794fe53f9e15c8e07599015989
yiguid/LeetCodePractise
/todo/069.py
844
3.578125
4
class Solution: def mySqrt(self, x): """ :type x: int :rtype: int """ # for i in range(x // 2 + 1): # if i * i == x: # return i # elif i * i > x: # return i - 1 # else: # continue # return 1 if x <= 1: return x left = 1 right = x // 2 while left < right: mid = (left + right + 1) // 2 if x == mid * mid: return mid elif x > mid * mid: left = mid else: right = mid - 1 return left s = Solution() print(s.mySqrt(0)) print(s.mySqrt(1)) print(s.mySqrt(2)) print(s.mySqrt(3)) print(s.mySqrt(4)) print(s.mySqrt(15)) print(s.mySqrt(16)) print(s.mySqrt(17))
9c5da5e315fd6ad6675f395e2a7ed85bf27704a7
yiguid/LeetCodePractise
/finished/047.py
738
3.5625
4
class Solution: def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ def perm(i): if i == len(nums) - 1: res.append(nums[:]) return used = set() for j in range(i, len(nums)): if nums[j] not in used: used.add(nums[j]) nums[i], nums[j] = nums[j], nums[i] perm(i + 1) nums[i], nums[j] = nums[j], nums[i] res = [] nums.sort() perm(0) return res s = Solution() print(s.permuteUnique([1,1,2])) print(s.permuteUnique([1])) print(s.permuteUnique([1,2,3]))
4180399a3d83722a2b81164c737d6cee0d8cbac1
njberejan/CurrencyConverter
/CurrencyConverter.py
6,223
4.125
4
#Objects in class: #be able to create Currency object with amount and currency code (ex: USD or EUR) #must equal another Currency object with the same amount and currency code (dollar == dollar) #must NOT equal another Currency object with different amount or currency code (dollar != dollar, dollar != euro) #must be able to be added to another Currency object with the same currency code (dollar + dollar) #must be able to be subtracted by another Currency object with the same currency code (dollar - dollar) #must raise DifferentCurrencyCodeError when you try to add or substract two currency objects with different codes (dollar - euro, dollar + euro) #must be able to be multiplied by an int or float and return another Currency object #Currency() must be able to take one argument with a currency symbol embedded in it, like "$1.20" and figure out the correct currency code. #It can also take two arguments, one being the amount and the other being the currency code. #CurrencyConverter objects: #Must be initialized with a dictionary of currency codes to conversion rates #At first, just make this work with two currency codes and conversation rates, with one rate being 1.0 and the other being the conversation rate. #An example would be this: {'USD': 1.0, 'EUR': 0.74}, which implies that a dollar is worth 0.74 euros. #Must be able to take a Currency object and a requested currency code that is the same currency code as the Currency object's and return a Currency object equal to the one passed in. #That is, currency_converter.convert(Currency(1, 'USD'), 'USD') == Currency(1, 'USD') #Must be able to take a Currency object that has one currency code it knows and a requested currency code and return a new Currency object with the right amount in the new currency code. #Must be able to be created with a dictionary of three or more currency codes and conversion rates #An example would be this: {'USD': 1.0, 'EUR': 0.74, 'JPY': 120.0} #which implies that a dollar is worth 0.74 euros and that a dollar is worth 120 yen, but also that a euro is worth 120/0.74 = 162.2 yen. #Must be able to convert Currency in any currency code it knows about to Currency in any other currency code it knows about. #Must raise an UnknownCurrencyCodeError when you try to convert from or to a currency code it doesn't know about. # class Currency(): # # def __init__(self, code, amount): # self.code = code # self.amount = amount # # def __str__(self): # return str(self.amount) + ' ' + self.code # # def is_code(self, code): # if self.code == code: # return True # else: # return False # def __eq__(self, code, amount): # if self.code == code and self.amount == amount: # return True # else: # return False # def __add__(self, code, amount): # if is_code(self, code): # added = self.amount + amount # return added # else: # raise DifferentCurrencyCodeError ("Currency Codes don't match") # def subtract(self, code, amount): # if is_code(self, code): # subtracted = self.amount - amount # return subtracted # else: # raise DifferentCurrencyCodeError ("Currency Codes don't match") # def multiply(self, code, amount, number): # if is_code(self, code): # multiplied = self.amount * float(number) # return multiplied # else: # raise DifferentCurrencyCodeError ("Currency Codes don't match") # def which_code(self, code): # code_dict = {'$':'USD', '€':'EUR', '¥':'JPY'} # if '$' in code_dict.keys(): # code = 'USD' # elif '€' in code_dict.keys(): # code = 'EUR' # elif '¥' in code_dict.keys(): # code = 'JPY' # else: # None # # class CurrencyConverter(): # currency_dict = {'USD':1.0, 'EUR':1.14, 'JPY': 0.009} # # def __init__(self, code1, code2, amount): # self.code1 = code1 # self.code2 = code2 # self.amount = amount # # def convert(self): # converted_amount = self.amount * (self.currency_dict.get(self.code1) / self.currency_dict.get(self.code2)) # #multiplies resulting variables of the two keys # return converted_amount # #returns amount and currency code. from CurrencyClass import Currency from ConverterClass import CurrencyConverter def main(): #takes input in amount (needs to differentiate type from string IE $, € [option + shift + 2]) # USD = Currency('USD', 1.00) # EUR = Currency('EUR', 0.88) number = 2 while True: user_amount = input("Please enter an amount to convert: ") if '$' in user_amount: code1 = 'USD' user_amount = user_amount.replace('$', '') break elif '€' in user_amount: code1 = 'EUR' user_amount = user_amount.replace('€', '') break elif '¥' in user_amount: code1 = 'JPY' user_amount = user_amount.replace('¥', '') break else: print("Please enter dollars, euros, or yen only!") continue print(code1) print(user_amount) user_amount = float(user_amount) currency_class_variable = Currency(code1, user_amount) print(str(currency_class_variable)) #assigns variables to two halves of entered string while True: code2 = input("Please enter a currency to convert to ($, €, ¥): ") #takes second input for conversion to another currency if code2 == '$': code2 = 'USD' break elif code2 == '€': code2 = 'EUR' break elif code2 == '¥': code2 = 'JPY' break else: print("Please enter dollars, euros, or yen only!") continue print(code2) currency_converter = CurrencyConverter(code1, code2, user_amount) converted_amount = currency_converter.convert() print(float("{0:.2f}".format(converted_amount))) if __name__ == '__main__': main()
aa2325ffb17b7a7fcd729ad30beffc9befd20509
takkin-takilog/python-eclipse-sample
/plot_sample_002.py
3,762
3.515625
4
# ============================================================================== # brief Plotサンプルコード 002 # # author たっきん # ============================================================================== import pandas as pd import matplotlib.pyplot as plt data = {"value": [120, 100, 90, 110, 150, 200, 300, 1000, 900, 800, 500, 300, 250, 200, 190, 150, 100, 50, 60, 80, 100, 150, 200, 400, 800, 1600]} df = pd.DataFrame(data) # --------------- n期間の移動平均線 --------------- n1 = 3 # 期間の設定 n2 = 5 # 期間の設定 n3 = 10 # 期間の設定 SMAn1 = df["value"].rolling(window=n1).mean() SMAn2 = df["value"].rolling(window=n2).mean() SMAn3 = df["value"].rolling(window=n3).mean() # ********** 描写 ********** fig1 = plt.figure("移動平均線") plt.plot(df, label="Sample") plt.legend() plt.scatter(range(df.size), df) plt.plot(SMAn1, linestyle="dashed", label="SMA-" + str(n1)) plt.plot(SMAn2, linestyle="dashed", label="SMA-" + str(n2)) plt.plot(SMAn3, linestyle="dashed", label="SMA-" + str(n3)) plt.legend() plt.scatter(range(df.size), SMAn1, marker="*") plt.scatter(range(df.size), SMAn2, marker="*") plt.scatter(range(df.size), SMAn3, marker="*") plt.title("Simple Moving Average(SMA)") plt.grid(linestyle="dashed") # --------------- MACD --------------- sn = 3 # 移動平均(短期)期間の設定 ln = 7 # 移動平均(長期)期間の設定 mn = 5 # MACD期間の設定 EMAsn = df["value"].ewm(span=sn).mean() EMAln = df["value"].ewm(span=ln).mean() MACD = (EMAsn - EMAln) SIGNAL = MACD.ewm(span=mn).mean() # ********** 描写 ********** fig2 = plt.figure("MACD") plt.plot(df, label="Sample") plt.plot(MACD, linestyle="dashed", label="MACD") plt.plot(SIGNAL, linestyle="dashed", label="Signal") plt.legend() plt.scatter(range(df.size), df) plt.scatter(range(df.size), MACD, marker="*") plt.scatter(range(df.size), SIGNAL, marker="*") plt.title("MACD") plt.grid(linestyle="dashed") # --------------- ボリンジャーバンド --------------- n = 5 # 期間の設定 # ===== 中心線の計算 ===== SMA_BB_n = df["value"].rolling(window=n).mean() # ===== 上下バンド線の計算 ===== # 標準偏差の計算 sigma_n = df["value"].rolling(window=n).std(ddof=0) # ±1σの計算 p1_sigma = SMA_BB_n + sigma_n m1_sigma = SMA_BB_n - sigma_n # ±2σの計算 p2_sigma = SMA_BB_n + sigma_n * 2 m2_sigma = SMA_BB_n - sigma_n * 2 # ±3σの計算 p3_sigma = SMA_BB_n + sigma_n * 3 m3_sigma = SMA_BB_n - sigma_n * 3 # ********** 描写 ********** fig3 = plt.figure("ボリンジャーバンド") plt.plot(df, label="Sample") plt.plot(SMA_BB_n, linestyle="dashed", label="SMA-" + str(n)) plt.plot(p1_sigma, c="hotpink", linestyle="dashed", label="+1σ") plt.plot(m1_sigma, c="hotpink", linestyle="dashed", label="-1σ") plt.plot(p2_sigma, c="aqua", linestyle="dashed", label="+2σ") plt.plot(m2_sigma, c="aqua", linestyle="dashed", label="-2σ") plt.plot(p3_sigma, c="lime", linestyle="dashed", label="+3σ") plt.plot(m3_sigma, c="lime", linestyle="dashed", label="-3σ") plt.legend() plt.scatter(range(df.size), df) plt.scatter(range(df.size), SMA_BB_n, marker="*") plt.scatter(range(df.size), p1_sigma, marker="*", c="hotpink") plt.scatter(range(df.size), m1_sigma, marker="*", c="hotpink") plt.scatter(range(df.size), p2_sigma, marker="*", c="aqua") plt.scatter(range(df.size), m2_sigma, marker="*", c="aqua") plt.scatter(range(df.size), p3_sigma, marker="*", c="lime") plt.scatter(range(df.size), m3_sigma, marker="*", c="lime") plt.title("Bollinger Bands") plt.grid(linestyle="dashed") plt.show()
36379f639d9fb48ec2004fc1f62b1dedf2851059
paveldavidchik/CreatePhoneNumber
/main.py
249
3.6875
4
def create_phone_number(n): return '(' + ''.join([str(num) for num in n[:3]]) + ') ' + \ ''.join([str(num) for num in n[3:6]]) + '-' + ''.join([str(num) for num in n[6:]]) print(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))
69c47d2f47c5169e8bd31591b96b3660309f27fb
scuttlebugg/CSIT_175
/asgn4_module.py
575
3.984375
4
""" This module contains functions for completing and satisfying requirements for assignment 4 in this Python class. """ def is_field_blank(string): """ accepts a string from user input returns a boolean value to input prompt loop """ if len(string) == 0: return True else: return False def is_field_a_number(number): """ accepts a number from user input returns a boolean value to input prompt loop """ if number.isdigit(): return True else: return False
3af0421e3ca2b8c6a8dcee8323120e09f36f3f19
ajgrinds/adventOfCode
/2019/day01.py
355
3.515625
4
with open('input.txt', 'r') as f: masses = f.read().splitlines() fuel = list(map(lambda mass: int(mass) // 3 - 2, masses)) fuel_total = sum(fuel) # part 1 print(fuel_total) for num in fuel: added_fuel = num // 3 - 2 while added_fuel > 0: fuel_total += added_fuel added_fuel = added_fuel // 3 - 2 # part 2 print(fuel_total)
2948bcec98743ca4b12feb2828c6337ce22673ae
ishmatov/GeekBrains-PythonBasics
/lesson03/task_03_03.py
840
4.1875
4
""" 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. """ def check_num(value): try: return True, int(value) except ValueError: print("Не число. Попробуйте ещё раз") return False, -1 def sum_doble_max(num1, num2, num3): return max(num1 + num2, num1 + num3, num2 + num3) i = 0 list_num = [] while True and i < 3: check, num = check_num(input(f"{i + 1} - Введите целое число: ")) if check: list_num.append(num) i += 1 print(f"Сумма из двух максимальных числе из {list_num} = ", sum_doble_max(list_num[0], list_num[1], list_num[2]))
afec691f540c742d23f04dddec8bf6a673ca7277
ishmatov/GeekBrains-PythonBasics
/lesson03/task_03_05.py
1,502
3.953125
4
""" 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится специальный символ, выполнение программы завершается. Если специальный символ введен после нескольких чисел, то вначале нужно добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу. """ def sum_list(str_num): global result for el in str_num: if el.isdigit(): result += int(el) else: if el == "#": return False return True result = 0 while True: str_num = list(input("Введите строку чисел через 'пробел', при вводе не числа программа или стоп символа '#' будет завершена: ").split()) if not sum_list(str_num): print(result) break print(result)
6c3c8bbae37317462a202481c0474008869186c5
ishmatov/GeekBrains-PythonBasics
/lesson01/task_01_06.py
1,914
4.1875
4
""" 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. Например: a = 2, b = 3. Результат: 1-й день: 2 2-й день: 2,2 3-й день: 2,42 4-й день: 2,66 5-й день: 2,93 6-й день: 3,22 Ответ: на 6-й день спортсмен достиг результата — не менее 3 км. """ while True: begin = input("Введите результат начальной пробежки. (Целое положительное число): ") if begin.isdigit() and int(begin) > 0: break while True: finish = input("Введите желаемый результат (км). (Целое положительное число): ") if finish.isdigit() and int(finish) > 0: if int(finish) <= int(begin): print(f"Конечный результат должен быть больше начального результата - {begin} км.") continue else: break result = int(begin) day = 1 while True: print(f"{day}-й день: {result:.2f}") if result >= int(finish): break result += result * 0.1 day += 1 print(f"Ответ: на {day}-й день спортсмен пробежит - не менее {finish} км")
ebdbdd22bbecdfe270c3dd6b852d8efd2253228b
Densatho/Python-2sem
/aula2/ex13.py
284
4.03125
4
while True: try: n = int(input("Coloque o numero de lados do poligono: ")) break except ValueError: print("Não colocou um valor valido\n") diagonais = int((n * (n - 3)) / 2) print(f'O numero de diagonais: {diagonais}')
c3c967096dba70d85268ae07ea868ac01dd74eea
Densatho/Python-2sem
/LOGIN E SENHA.py
1,189
3.765625
4
usuario = [] senha = [] while True: print('escolha uma das opções abaixo: \n ') resposta = int(input(' 1 - Login \n 2 - Resgistrar \n 3 - Sair \n')) if resposta == 2: while True: user = input("Novo usuario: ") for i in usuario[:]: if user == usuario: pass senhac = input("Senha: ") if senhac == input("Confirme sua senha: "): break usuario.append(user) senha.append(senhac) print('Usuário registrado com sucesso!') if resposta == 1: while True: # Login print(" Login ") while True: teste = False log = input("User: ") for i in usuario[:]: if log == i: aux = usuario.index(log) teste = True if teste: break if senha[aux] == input("senha: "): print(f"Logado como {usuario[aux]}") break if resposta == 3: exit(void)
077f037ab225f651f5ace6e8d5e4ad10e77d5f4e
Densatho/Python-2sem
/aula3/ex18.py
281
3.90625
4
a = int(input("Insira o valor de A: ")) b = int(input("Insira o valor de B: ")) if a > b: print(f"A diferença de A para B é {a - b}") elif b > a: print(f"A diferença de B para A é {b - a}") else: print("Os dois tem o mesmo valor e a diferença é zero.")
6f35094f9c120170ce8d64e86c29b8647a7b484c
Densatho/Python-2sem
/aula2/ex3.py
654
3.828125
4
while True: try: salario_velho = float(input("Coloque o salario: ")) break except ValueError: print("Não colocou um salario valido valida\n") while True: try: percentual = float(input("Coloque o percentual: ")) break except ValueError: print("Não colocou um percentual valido\n") percentual /= 100 aumento = salario_velho * percentual salario_novo = salario_velho + aumento aumento = round(aumento, 2) salario_novo = round(salario_novo, 2) print(f"Teve um aumento de R${aumento} com um salario total de R${salario_novo}")