blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e29b6a0ae33e402a3b71403629d7ab7e0b70e42d
ankitdhebarin/Python3
/Regex/Parse_Date.py
341
3.984375
4
import re def Parse_Date(input): date_regex = re.compile(r'(?P<month>\d{2})[./,](?P<date>\d{2})[./,](?P<year>\d{4})') matches = date_regex.search(input) date = {} date['d'] = matches.group("date") date['m'] = matches.group("month") date['y'] = matches.group("year") return date print(Parse_Date("Today's date is : 08/16/2018"))
7d31a69429a2e71045e010e9e269b300a073985b
Brokkenpiloot/Heuristieken
/visualization.py
728
3.53125
4
import pygame # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) grid = [] for row in range (10): grid.append([]) for column in range(10): grid[row].append(0) pygame.init() size = [400, 400] screen = pygame.display.set_mode(size) tileWidth = 20 tileHeight = 20 tileMargin = 5 color = WHITE pygame.display.set_caption("Rush Hour") """class Visualization: def __init__(self, width, height)""" done = False clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.draw.rect(screen, BLACK, [75, 10, 50, 20]) pygame.quit()
126b2d9aa9eda3f9c9d968742dba99fa2b730d22
dylanagreen/kpno-allsky
/threshold.py
18,404
3.953125
4
"""A module providing analysis methods for determining cloudiness thresholds. The predominant function of this module is to analyze saved cloudiness data to try and determine the cloudiness value that corresponds to whether or not the telescope dome is closed or open. The main method analyzes the cloudiness of each image relative to the mean cloudiness for the phase of the moon on that night. Each night images were taken when the dome was closed. Images whose cloudiness is above a certain value are considered to have been taken when the dome was closed. If the proportion of images above this value is approximately equal to the known percentage of the night when the dome was closed then this value is designated the threshold for each night. Two helper methods are provided: one to find the number of days into a year a given date is, and one to convert a date to a format accepted by pyephem. """ import os import datetime import pandas as pd import numpy as np import matplotlib.pyplot as plt import ephem def daynum(date): """Find the number of the days into a year a given date is. Parameters ---------- date : str Date in yyyymmdd format. Returns ------- num : int The number of days into the year the given date is. """ # Strips out the information from the pass in string d1 = datetime.date(int(date[:4]), int(date[4:6]), int(date[6:8])) # The date for the start of the year. d2 = datetime.date(year=d1.year, month=1, day=1) # Gotta add one because of how subtraction works. days = (d1-d2).days + 1 return days def format_date(date, name): """Convert an image name into a format that pyephem accepts. Parameters ---------- date : str Date on which the image was taken, in yyyymmdd format. name : str The image"s file name. Returns ------- date : str A date and time in yyyy/mm/dd hh:mm:ss format. """ formatdate = date[:4] + "/" + date[4:6] + "/" + date[6:8] time = name[4:6] + ":" + name[6:8] + ":" + name[8:10] return formatdate + " " + time def find_threshold(): """Find the mean cloudiness threshold for 2016 and 2017 combined. Returns ------- total : float The threshold value if each day is considered individually. weektotal : float The threshold value if the days are grouped by week. Notes ----- The method analyzes the cloudiness of each image relative to the mean cloudiness for the phase of the moon on that night. Each night images were taken when the dome was closed. Images whose cloudiness is above a certain value are considered to have been taken when the dome was closed. This method finds that value by using the percentage of each night when the dome is closed, which is already known. The proportion of images above this value will be approximately equal to the known percentage. This value is designated the threshold for each night. The method finds this threshold for every night and then returns the median of that dataset. This method additionally runs the same analysis where an entire week is considered at a time, rather than single nights. The returned value is the median of the 52 week thresholds. """ # Sets up a pyephem object for the camera. camera = ephem.Observer() camera.lat = "31.959417" camera.lon = "-111.598583" camera.elevation = 2120 camera.horizon = "-17" # Reads in the csv file using pandas. data_loc = directory = os.path.join(os.path.dirname(__file__), *["data", "daily-2007-2017.csv"]) data = pd.read_csv(data_loc) # This array is for calculating the total average total = [] for year in ["2016", "2017"]: # Gets the downloaded months directory = os.path.join(os.path.dirname(__file__), *["data", "analyzed"]) # If the data directory doesn"t exist we should exit here. # I was remarkably prescient writing this even though I had all the data # downloaded already. if not os.path.exists(directory): print("No data found.") months = sorted(os.listdir(directory)) # Macs are dumb if ".DS_Store" in months: months.remove(".DS_Store") # We do this as a dict because 2017 is straight up missing some days of # images because I guess the camera was down? # Otherwise I"d just make a len 365 list. weekdict = [[] for i in range(0, 53)] daydict = {} for month in months: # If the month is not in this year, we skip it analyzing. if int(month) < int(year + "01") or int(month) > int(year + "12"): continue # Gets the days that were analyzed for that month directory = os.path.join(os.path.dirname(__file__), *["data", "analyzed", month]) days = sorted(os.listdir(directory)) # Macs are still dumb. if ".DS_Store" in days: days.remove(".DS_Store") # Reads the data for each day. for day in days: # Skip the leap day for right now. if day == "20160229.txt": continue # Get the number for that day to add it to the dict. i = daynum(day) weeknum = i // 7 # Because we skip the leap day we need to bump the day num of # all days after that date down by one. # 60 because 31 + 28 = 59 if year == "2016" and i >= 60: i = i-1 # Start with an empty list for that day. daydict[i] = [] # This is the code that reads in the values and appends them. data_loc = os.path.join(directory, day) datafile = open(data_loc, "r") # Images is a list of images that were analyzed that night. images = [] for line in datafile: line = line.rstrip() line = line.split(",") # Appends the image name to images and the cloudiness # relative to mean to the daydict. images.append(line[0]) daydict[i].append(float(line[1])) weekdict[weeknum].append(float(line[1])) # An ndarray of open fractions where index + 1 = day number opens = data.get("Y" + year).values thresh = [] x = [] x1 = [] true = [] # Runs over the dictionary, key is the day number. Val is the list of # cloudinesses openweeks = [[] for i in range(0, 53)] for key, val in daydict.items(): # The fraction is the fraction of the night the dome was closed. # When we multiply to find the index we want the inverse frac though. frac = 1 - opens[key - 1] week = (key) // 7 openweeks[week].append(opens[key - 1]) # Finds the index at which the fraction of images above that index is # equal to the amount of the night that the dome was closed. working = sorted(val) # If we don"t have any images that night then just bail. if not working: continue # Multiply the frac by the length, to find the index above which # the correct fraction of the images is "dome closed." Rounds and # Subtracts one to convert it to the integer index. index = int(round(frac * len(working))) - 1 # If the index is the final index then the "cloudiness relative to the # mean threshold" is slightly below that value so average down. # Otherwise take the average of that index and the one above since the # threshold actually falls inbetween. if index == len(working) - 1 and not frac == 1: num = np.mean([float(working[index]), float(working[index - 1])]) # If the dome is closed the entire night, index will be given as -1 # And we find the threshold as the average of the start and end # cloudiness. Instead we want the threshold to be the first # cloudiness as that way the dome is "closed" all night. elif frac == 0: num = float(working[0]) - 0.1 elif frac == 1: num = float(working[-1]) else: num = np.mean([float(working[index]), float(working[index + 1])]) thresh.append(num) total.append(num) x.append(key) working = np.asarray(working) above = working[working > num] if not working.size == 0: frac = opens[key - 1] true.append(len(above)/len(working)) x1.append(frac) weekthresh = [] weektotal = [] weektrue = [] x2 = [] x3 = [] for i in range(0, len(weekdict)): frac = 1 - np.mean(openweeks[i]) working = sorted(weekdict[i]) # If we don"t have any images that night then just bail. if not working: continue # Multiply the frac by the length, to find the index above which # the correct fraction of the images is "dome closed." Rounds and # Subtracts one to convert it to the integer index. index = int(round(frac * len(working))) - 1 # If the index is the final index then the "cloudiness relative to the # mean threshold" is slightly below that value so average down. # Otherwise take the average of that index and the one above since the # threshold actually falls inbetween. if index == len(working) - 1 and not frac == 1: num = np.mean([float(working[index]), float(working[index - 1])]) # If the dome is closed the entire night, index will be given as -1 # And we find the threshold as the average of the start and end # cloudiness. Instead we want the threshold to be the first # cloudiness as that way the dome is "closed" all night. elif frac == 0: num = float(working[0]) - 0.1 elif frac == 1: num = float(working[-1]) else: num = np.mean([float(working[index]), float(working[index + 1])]) weekthresh.append(num) weektotal.append(num) x2.append(i) working = np.asarray(working) above = working[working > num] if not working.size == 0: frac = np.mean(openweeks[i]) weektrue.append(len(above)/len(working)) x3.append(frac) print(year + ": ") print("Min: " + str(np.amin(thresh))) print("25%: " + str(np.percentile(thresh, 25))) print("50%: " + str(np.median(thresh))) print("75%: " + str(np.percentile(thresh, 75))) print("Max: " + str(np.amax(thresh))) print() fig,ax = plt.subplots() fig.set_size_inches(6, 4) above = np.ma.masked_where(thresh < np.median(thresh), thresh) below = np.ma.masked_where(thresh > np.median(thresh), thresh) ax.scatter(x, below, s=1) ax.scatter(x, above, s=1, c="r") ax.set_xlabel("Day") ax.set_ylabel("Cloudiness Relative to Mean") plt.savefig("Images/Dome/Threshold-Day-" + year + ".png", dpi=256) plt.close() fig,ax = plt.subplots() fig.set_size_inches(6, 4) ax.scatter(x1, true, s=1) ax.set_xlabel("True Fraction") ax.set_ylabel("Found Fraction") plt.savefig("Images/Dome/Verify-Day-" + year + ".png", dpi=256) plt.close() fig,ax = plt.subplots() fig.set_size_inches(6, 4) print(year + " Week: " + str(np.median(weekthresh))) above = np.ma.masked_where(weekthresh < np.median(weekthresh), weekthresh) below = np.ma.masked_where(weekthresh > np.median(weekthresh), weekthresh) ax.scatter(x2, below, s=1) ax.scatter(x2, above, s=1, c="r") ax.set_xlabel("Day") ax.set_ylabel("Cloudiness Relative to Mean") plt.savefig("Images/Dome/Threshold-Week-" + year + ".png", dpi=256) plt.close() fig,ax = plt.subplots() fig.set_size_inches(6, 4) ax.scatter(x3, weektrue, s=1) ax.set_xlabel("True Fraction") ax.set_ylabel("Found Fraction") plt.savefig("Images/Dome/Verify-Week-" + year + ".png", dpi=256) plt.close() #years[year] = daydict return (np.median(total), np.median(weektotal)) def test_threshold(): #This method uses find_threshold() to find the cloudiness thresholds. It #then uses the median for each individual night of images and checks the #proportion of images that are above the threshold against the fraction #of that night for which the dome is closed. It outputs four plots, which #are saved to Images/Dome/. Each plot plots the dome closed fraction on #the horizontal axis, and the fraction of images above the median threshold #for that year on the y axis. The four plots represent two plots with day #wise thresholding, and two with weekwise. One plot contains all 2016 data #and the other the 2017 data. for year in ["2016", "2017"]: # Reads in the csv file using pandas. data_loc = directory = os.path.join(os.path.dirname(__file__), *["data", "daily-2007-2017.csv"]) data = pd.read_csv(data_loc) opens = data.get("Y" + year).values # Gets the downloaded months directory = os.path.join(os.path.dirname(__file__), *["data", "analyzed"]) # If the data directory doesn"t exist we should exit here. # I was remarkably prescient writing this even though I had all the data # downloaded already. if not os.path.exists(directory): print("No data found.") months = sorted(os.listdir(directory)) # Macs are dumb if ".DS_Store" in months: months.remove(".DS_Store") test1, test2 = find_threshold() print(test1) print(test2) # We do this as a dict because 2017 is straight up missing some days of # images because I guess the camera was down? # Otherwise I"d just make a len 365 list. daydict = {} weekdict = [[] for i in range(0, 53)] for month in months: # If the month is not in this year, we skip it analyzing. if int(month) < int(year + "01") or int(month) > int(year + "12"): continue # Gets the days that were analyzed for that month directory = os.path.join(os.path.dirname(__file__), *["data", "analyzed", month]) days = sorted(os.listdir(directory)) # Macs are still dumb. if ".DS_Store" in days: days.remove(".DS_Store") # Reads the data for each day. for day in days: # Skip the leap day for right now. if day == "20160229.txt": continue # Get the number for that day to add it to the dict. i = daynum(day) weeknum = i // 7 # Because we skip the leap day we need to bump the day num of # all days after that date down by one. # 60 because 31 + 28 = 59 if year == "2016" and i >= 60: i = i-1 # Start with an empty list for that day. daydict[i] = [] # This is the code that reads in the values and appends them. data_loc = os.path.join(directory, day) datafile = open(data_loc, "r") # Images is a list of images that were analyzed that night. images = [] for line in datafile: line = line.rstrip() line = line.split(",") # Appends the image name to images and the cloudiness # relative to mean to the daydict. images.append(line[0]) daydict[i].append(float(line[1])) weekdict[weeknum].append(float(line[1])) x = [] true = [] weekfrac = [[] for i in range(0, 53)] # Runs over the dictionary, key is the day number. Val is the list # of cloudinesses for key, val in daydict.items(): # The fraction is the fraction of the night the dome was closed. frac = opens[key - 1] # Appends the fract to the week average array. weekfrac[key // 7].append(frac) working = np.asarray(val) above = working[working > test1] if not working.size == 0: true.append(len(above)/len(working)) x.append(frac) x1 = [] weektrue = [] # Runs over the week number for i, val in enumerate(weekdict): # The fraction is the average of the whole week. frac = np.mean(weekfrac[i]) working = np.asarray(weekdict[i]) above = working[working > test2] if not working.size == 0: weektrue.append(len(above)/len(working)) x1.append(frac) fig,ax = plt.subplots() fig.set_size_inches(6, 4) ax.scatter(x, true, s=1) ax.set_xlabel("True Fraction") ax.set_ylabel("Found Fraction") plt.savefig("Images/Dome/Differences-Day-" + year + ".png", dpi=256) plt.close() fig,ax = plt.subplots() fig.set_size_inches(6, 4) ax.scatter(x1, weektrue, s=1) ax.set_xlabel("True Fraction") ax.set_ylabel("Found Fraction") plt.savefig("Images/Dome/Differences-Week-" + year + ".png", dpi=256) plt.close() if __name__ == "__main__": test_threshold()
40fe8fe99d90d34ea32881bbcf893004645924e2
arnabid/QA
/strings/reverseWordsInString.py
1,062
3.796875
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 28 10:44:39 2016 @author: arnab """ """ reverse the words in a string this is a string -> string a is this += concatenation for strings is not slow """ def reverseInPlace(s): arr = [ch for ch in s] n = len(s) i, j = 0, n-1 while i < j: arr[i], arr[j] = arr[j], arr[i] i += 1 j -= 1 i = 0 for j in xrange(n): if arr[j] == " ": k = j - 1 while i < k: arr[i], arr[k] = arr[k], arr[i] i += 1 k -= 1 i = j + 1 k = j - 1 while i < k: arr[i], arr[k] = arr[k], arr[i] i += 1 k -= 1 print ("".join(arr)) def reverse(s): n = len(s) end = n output = "" for i in xrange(n-1,-1,-1): if s[i] == " ": output += s[i+1:end] output += " " end = i output += s[0:end] print (output) if __name__ == '__main__': s = "x this is a string" reverseInPlace(s.strip())
5607d0f1e528424789b8f56d24c32baee18df773
sheamus-hei/whiteboarding
/student-resources/binary-trees.py
1,821
4.375
4
# basic class class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None # 1 # / \ # 2 3 # / \ # 4 5 tree = TreeNode(1) tree.left = TreeNode(2) tree.right = TreeNode(3) tree.left.left = TreeNode(4) tree.left.right = TreeNode(5) # Depth first traversal: # print first for pre-order, middle for in-order, last for post-order # prints the parent before each child def traversal(node): if node: print(node.value) traversal(node.left) traversal(node.right) traversal(tree) # Breadth first traversal: more complicated # method to find how tall a tree is def height(node): if not node: return 0 l_height = height(node.left) r_height = height(node.right) return max(l_height, r_height) + 1 # following two methods print breadth first traversal # source: https://www.geeksforgeeks.org/level-order-tree-traversal/ def print_level(root, level): if not root: return if level == 0: print(root.value) elif level > 0: print_level(root.left, level - 1) print_level(root.right, level - 1) def breadth_first(root): h = height(root) for i in range(h): print_level(root, i) # write a function that counts the total number of nodes in the tree. def count_nodes(node): if not node: return 0 else: return 1 + count_nodes(node.left) + count_nodes(node.right) print("There are", count_nodes(tree), "nodes in the tree") # write a function that finds the minimum value in a tree. import sys def find_min(node): if not node: return sys.maxsize else: left_min = min(node.value, find_min(node.left)) right_min = min(node.value, find_min(node.right)) return min(left_min, right_min) # tree.left.left.left = TreeNode(0) traversal(tree) print("Min node:", find_min(tree))
b11eaf1c7f56779898a135e63530d43b60761f47
suryak24/python-code
/73.py
161
3.921875
4
n=int(input("Enter N value:")) l=int(input("Enter L value:")) r=int(input("Enter R value:")) if n>=l: if n<=r: print("yes") else: print("no")
c629024d835030dbc113c629df62313841a483db
esrasking/python
/Chapter 4/summing_a_million.py
431
3.71875
4
#20191203 #Chapter 4.5: Summing a Million #Start Program print(f"\nSTART PROGRAM\n") #The code below shows the sum of values 1-5. print(f"Here is a quick test that the sum of the range values works:\n") values = list(range(1,6,1)) print(sum(values)) print('') #The code below executes the sum of values up to and including 1,000,000. values = list(range(1,1000001,1)) print(sum(values)) #End Program print(f"\nEND PROGRAM\n")
e3c67b7d0c7ffdde0e1631896ba434d0c613244b
sedasakarya/workshop
/PYTHON/4.Functions/functions.py
1,966
4.28125
4
""" BUILD-IN FUNTIONS ==================================================== """ # Native functions like print... #print("whatever") #print("whatever", "and", "ever") age = 12 #print("age is:", age) #print("list\n", [1,2,3]) #print("list", [1,2,3], sep=":", end=".") # Sep adds a seperation sign. End adds a sign at the end. # MAX, MIN AND ROUND #------------------------------------ # MAX ¬ MIN l = [3,6,78,12] # print("max value is:", max (l)) # print("min value is:", min (l)) # ROUND num = 3.2351 # When there is a number more than 5 like 51, it rounds up. # print("rounded number:", round(num, 2)) # If you write num, 2 . It tells us how many decimal it will show. # INPUT #------------------------------------ # input_val = input("Please enter your birth year: ") # calc_age = 2020 - int(input_val) # print("Your age is:", calc_age) """ CUSTOM FUNTIONS ==================================================== """ # We use colons instead of curly braces in Python. # Indentations are VERY IMPORTANT ! If you don't use them, you will get an error. # We can change spaces with spaces button in the bottom just for this workspace. # In Python you have to put something inside the function, otherwise you will get an error. # def calc (x, y = 0) : # return x + y # print( calc(2) ) # The result will be 2. y is already defined above as 0. def calc (x, y) : return x + y print( calc(2,8) ) """ IMPORTING ==================================================== """ import time # print( dir(time) ) # We see every method inside time. local = time.localtime() current_year = local.tm_year # We declared in global scope and we can use it inside a function in Python. # CHALLENGE def calc_age2(current_year,birth_year): return current_year - birth_year print(calc_age2(current_year, 1992)) # CHALLENGE 2 def calc_age3(): input_birth_year = input("Birth year, please: ") return current_year - int(input_birth_year) print(calc_age3())
2155ec6f018836adb02ec244bacb900540833c5f
saidskander/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/2-uniq_add.py
85
3.5
4
#!/usr/bin/python3 def uniq_add(my_list=[]): return sum(x for x in set(my_list))
b527634a678f3e13431d429b11371a8d72ed4313
123akhil/datascience
/6.00.1x_Introduction_to_Computer_Science_and_Programming_Using_Python/Week_3/Problem_Set_3/PS3_2.py
779
3.84375
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 20 01:36:47 2016 @author: Camilo Cruz """ def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' guess = '' for i in secretWord: if (i in lettersGuessed) == True: guess = guess + i + ' ' if (i in lettersGuessed) == False: guess = guess + '_ ' return guess secretWord = 'applewerkauf' lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] print getGuessedWord(secretWord, lettersGuessed) #'_ pp_ e'
669c7e1d2a2c8988fb5830ee71859047c6f20d26
EnochEronmwonsuyiOPHS/Y11Python
/StringSliceChallanges03.py
200
3.96875
4
#StringSliceChallanges03.py #Enoch firstname = str(input("Enter your first name in lower case")) lastname = str(input("Enter your last name in lower case")) s = " " print(firstname + s + lastname)
3040ec36600f1fb098b794b5f027fcc2f9afa415
Maayaavi/OC_Project_3
/main.py
6,533
3.734375
4
#!/usr/bin/python3 # -*- coding: Utf-8 -* ######################################################################## # Filename : main.py # # Description : A maze game in the player have to move Macgyver to the # # exit by collecting some objects through the labyrinth # # for sleep the guardian. # # Author : LAVANIYAN Jeyasiri # # Modification: 2020/01/10 # ######################################################################## import pygame import sys import config from pygame.locals import * from utils.constants import * pygame.init() clock = pygame.time.Clock() class Game: """Class to execute the game""" def __init__(self): self.data_item = {"e": 0, "n": 0, "t": 0} # Initialize the Pygame window (square: width = height) self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_LENGTH)) self.choice = 0 def intro(self): """ Method for display intro screen """ # Icon icon = pygame.image.load(IMAGE_ICON) pygame.display.set_icon(icon) # Title pygame.display.set_caption(WINDOW_TITLE) # Intro loop while_intro = True while while_intro: # Display the home screen home = pygame.image.load(IMAGE_INTRO).convert() self.window.blit(home, (0, 0)) # Refreshment pygame.display.flip() # Speed limitation of the loop clock.tick(30) for event in pygame.event.get(): # If the user close the window or press Esc, it will leave the program if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: self.gamequit() elif event.type == KEYDOWN: # Launch the map if event.key == K_RETURN: # Define the map to load self.choice = 'map/n1.txt' # Loading the background image background = pygame.image.load(IMAGE_BACKGROUND).convert() # Generate a structure from the file level = config.labyrinth.Labyrinth(self.choice) level.load() # Generate all items level_item = config.item.Items(level) level_item.display_item() # Generate the character mg = config.character.Character(level, self.data_item) # Display the labyrinth level_display = config.display.Display(level, self.data_item) level_display.display_game() self.game(level_display, background, mg) # Stop intro loop while_intro = False def game(self, level_display, background, mg): """ Method for display game screen """ # Game loop while_game = True while while_game: clock.tick(30) for event in pygame.event.get(): # If the user close the window, it leave the program if event.type == QUIT: # Stop game loop self.gamequit() elif event.type == KEYDOWN: # If the user press Esc, we just go back to the menu if event.key == K_ESCAPE: # Reinitialize the counter value self.reset() # Go to the main loop self.intro() while_game = False # Character move keys elif event.key == K_RIGHT: mg.move_right() elif event.key == K_LEFT: mg.move_left() elif event.key == K_UP: mg.move_up() elif event.key == K_DOWN: mg.move_down() # Displays at new positions self.window.blit(background, (0, 0)) level_display.display_game() level_display.display_item_counter() self.window.blit(mg.character, (mg.x, mg.y)) mg.find() mg.exit() pygame.display.flip() if mg.exit() == 'lose': self.reset() self.lose() while_game = False elif mg.exit() == 'win': self.reset() self.win() while_game = False def lose(self): """ Method for display lose screen """ # Play lose sound pygame.mixer.Sound(SOUND_LOSE).play() # Lose loop while_lose = True while while_lose: clock.tick(30) for event in pygame.event.get(): if event.type == KEYDOWN and event.key == K_RETURN: self.intro() while_lose = False elif event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: self.gamequit() # Diplay the lose screen lost = pygame.image.load(IMAGE_LOSE).convert() self.window.blit(lost, (0, 0)) pygame.display.flip() def win(self): """ Method for display win screen """ # Play win sound pygame.mixer.Sound(SOUND_WIN).play() # Victory loop while_win = True while while_win: clock.tick(30) for event in pygame.event.get(): if event.type == KEYDOWN and event.key == K_RETURN: self.intro() while_win = False elif event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: self.gamequit() # Display the victory screen win = pygame.image.load(IMAGE_WIN).convert() self.window.blit(win, (0, 0)) pygame.display.flip() def reset(self): """ Method for Reinitialize value """ self.data_item = {"e": 0, "n": 0, "t": 0} def gamequit(self): """ Method for quit game """ pygame.quit() sys.exit() if __name__ == "__main__": game = Game() game.intro()
ed1ab4791da91b52ba33a1b6f283c09dd8735504
buisang123/buiducsang-fundamentals-c4e18
/session 3/Homework/ve_la_co.py
328
3.65625
4
from turtle import* color2 = ('red','blue','brown','yellow','grey') k = 0 for i in range(5): color(color2[k]) fillcolor(color2[k]) begin_fill() right(90) forward(100) right(90) forward(50) right(90) forward(100) right(90) forward(100) k += 1 end_fill() mainloop()
11760ec363e825947a8f16751ccc491c1eaa2dea
arjunshah1993/Algorithms
/rev_array_recur.py
291
3.5625
4
arr = [3, 5, 2, 6, 2, 1] i = len(arr) - 1 def arr_rev_recur(array, i): if i <= len(array)/2 - 1: return array temp = array[i] array[i] = array[len(array) - i - 1] array[len(array) - i - 1] = temp return arr_rev_recur(array, i - 1) print(arr_rev_recur(arr, i))
eea63698fd5d4959af65d7c53e143752834124f2
Cscotttaakan/EulerSolutions
/Euler83/Euler83self.py
6,281
3.65625
4
class Node:#create class to contain values def __init__(self, val, tot): self.value = val self.total = tot def __hash__(self):#make node hashable in dictionary return hash(id(self)) def __eq__(self, other): return (id(self) == id(other)) def __ne__(self, other): return not(id(self) == id(other)) def __lt__(self, other): return (self.total < other.total) def __gt__(self, other): return (self.total > other.total) def __le__(self, other): return (self.total <= other.total) def __ge__(self, other): return (self.total >= other.total) def __cmp__(self,other): return cmp(self.total, other.total) import os import operator from collections import defaultdict import heapq infinity = 10**10 print os.getcwd() behemoth = open("matrix.txt","r") test = open("test.txt","r") class Graph: def __init__(self): print 'initiate object' self.tableSize = 0 self.table = [] self.tableDict = defaultdict(list) def bfs_paths(self):#calculate all paths to bottom print 'paths' #print self.table[0][0],' ', self.table[0][0].value visited = [] heap = [] self.table[0][0].total = self.table[0][0].value heapq.heappush(heap,(self.table[0][0]))#start at head of tree visited.append(self.table[0][0]) #print len(self.tableDict) while heap: (vertex) = heapq.heappop(heap) for next in set(self.tableDict[vertex]):#get non visited nodes if next == self.table[self.tableSize][self.tableSize]: return vertex.total + next.value else:#updating the total for nodes in visited if next not in visited: next.total = next.value + vertex.total visited.append(next) heapq.heappush(heap,(next))#add to queue children else: for n in visited: if n == next: if n.total > next.total: n.total = next.total def readFile(self, file): print 'readFile' self.table = [[Node(int(n),infinity) for n in s.split(",")] for s in file.readlines()] #create table of nodes #print len(self.table[0])-1 self.tableSize = len(self.table) - 1 def createTable(self): print 'createTable' for i in range(self.tableSize+1): for n in range(len(self.table[i])): #print 'i: ', i , ' n: ', n if i == 0 and n == 0:#top left self.tableDict[self.table[i][n]].append(self.table[i+1][n])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i][n+1])#connect nodes to children nodes elif i == 0 and n == self.tableSize:#top right self.tableDict[self.table[i][n]].append(self.table[i+1][n])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i][n-1])#connect nodes to children nodes elif i == self.tableSize and n == 0:#bottom left self.tableDict[self.table[i][n]].append(self.table[i][n+1])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i-1][n])#connect nodes to children nodes elif i == self.tableSize and n == self.tableSize:#bottom right self.tableDict[self.table[i][n]].append(self.table[i-1][n])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i][n-1])#connect nodes to children nodes #______________________________________ elif i in range(1,self.tableSize) and n == self.tableSize :#right col self.tableDict[self.table[i][n]].append(self.table[i+1][n])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i][n-1])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i-1][n])#connect nodes to children nodes elif i == 0 and n in range(1,self.tableSize):#top row self.tableDict[self.table[i][n]].append(self.table[i+1][n])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i][n-1])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i][n+1])#connect nodes to children nodes elif i in range(1,self.tableSize) and n == 0:#left col self.tableDict[self.table[i][n]].append(self.table[i][n+1])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i-1][n])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i+1][n])#connect nodes to children nodes elif i == self.tableSize and n in range(1,self.tableSize):#bottom row self.tableDict[self.table[i][n]].append(self.table[i-1][n])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i][n-1])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i][n+1])#connect nodes to children nodes else: self.tableDict[self.table[i][n]].append(self.table[i-1][n])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i][n-1])#connect nodes to children nodes self.tableDict[self.table[i][n]].append(self.table[i][n+1]) self.tableDict[self.table[i][n]].append(self.table[i+1][n]) #for n in self.tableDict: #print n.value, ' : ' #for x in self.tableDict[n]: #print (x.value) #print '__________' t = Graph() t.readFile(test) t.createTable() print t.bfs_paths() x = Graph() x.readFile(behemoth) x.createTable() print x.bfs_paths()
df8dfb4504cc63cc9c31ac808d3513bcd7243389
udoprog/tl
/tl/__init__.py
3,482
3.78125
4
#!/usr/bin/python import sys; import re; import tl.units; def prettyprint_time(seconds): if seconds < 1: print "less than a second" return; timeparts = list(); mill = 0; cent = 0; dec = 0; y = 0; d = 0; H = 0; m = 0; if seconds > 60: m = seconds / 60; seconds -= (m * 60) if m > 60: H = m / 60; m -= (H * 60) if H > 24: d = H / 24; H -= (d * 24); if d > 365: y = d / 365; d -= (y * 365) if y > 10: dec = y / 10; y -= (dec * 10) if dec > 10: cent = dec / 10; dec -= (cent * 10); if cent > 10: mill = cent / 10; cent -= (mill * 10); if mill > 0: if mill == 1: timeparts.append(str(mill) + " millenium") else: timeparts.append(str(mill) + " millenia") if cent > 0: if cent == 1: timeparts.append(str(cent) + " century") else: timeparts.append(str(cent) + " centuries") if dec > 0: if dec == 1: timeparts.append(str(dec) + " decade") else: timeparts.append(str(dec) + " decades") if y > 0: if y == 1: timeparts.append(str(y) + " year") else: timeparts.append(str(y) + " years") if d > 0: if d == 1: timeparts.append(str(d) + " day") else: timeparts.append(str(d) + " days") if H > 0: if H == 1: timeparts.append(str(H) + " hour") else: timeparts.append(str(H) + " hours") if m > 0: if m == 1: timeparts.append(str(m) + " minute") else: timeparts.append(str(m) + " minutes") if seconds > 0: if seconds == 1: timeparts.append(str(seconds) + " second") else: timeparts.append(str(seconds) + " seconds") print ", ".join(timeparts); def rel_dist(bucket_u, delta_u, time_u): import math L = bucket_u.size * bucket_u.amount v = delta_u.size * delta_u.amount / time_u.size c = 299792458.0 if (v == c): delta_u.size = 0.0; return; if (v > c): print 'Speed more than the speed of light, cannot use relativistic math.' print return; Lp = L*math.sqrt(1 - v**2/c**2) if (v > 0.1*c): print 'Speed is %.2f%% the speed of light.' % round(float(v)/float(c)*100, 2) print 'Distance gets shortened by %.2f%%.' % round(100-float(Lp)/float(L)*100, 2) print bucket_u.size = Lp / bucket_u.amount; def main_command(command): if command == "list": print "===List of all units===" for family in tl.units.units: print "" print family.type for unit in family.units: if unit.size == 1: print "%-3s %-20s %s (Base unit)"%(unit.suffix, unit.long, str(unit.size)); else: print "%-3s %-20s %s"%(unit.suffix, unit.long, str(unit.size)); def main(argv): if len(argv) == 1: return main_command(argv[0]); if len(argv) < 2: return 1; delta = argv[1]; bucket_u = tl.units.parse_bucket(argv[0]); delta_u, time_u = tl.units.parse_delta(argv[1]); if not (bucket_u and delta_u and time_u): return 1; if bucket_u.family != delta_u.family: print "Family type mismatch" print bucket_u.family, "!=", delta_u.family; return 1; if bucket_u.family == 'distance': rel_dist(bucket_u, delta_u, time_u); prettyprint_time(int(round((bucket_u.size * bucket_u.amount * time_u.size) / (delta_u.size * delta_u.amount)))); return 0; def entrypoint(): sys.exit(main(sys.argv[1:]));
ef096bb4550a1dcbb008e379fbb2171841676db4
scub72/Hydraulika
/HydraulicLibrary/functions/calculateVelocity.py
251
3.5
4
# Calculates the velocity with given: # - flow [l/min] # - diameter [mm] # # calculation result is velocity in [m/s] def calculateVelocity( flow, diameter): velocity = flow/1000.0/60.0/(3.14*pow(diameter/1000.0, 2)/4.0) return velocity
eee24bdb5d93cbde7a1f4f149118d15fcb373b34
itsdeepakverma/python
/Deepak_Verma3.py
179
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 13 13:02:47 2018 @author: Admin """ def Main(): str=input("Enter your test") str="*".join(str) print(str) Main()
8a7cfb1f0723b096840902a62ead78a99f1272a4
camilleanne/project-euler-solutions
/6.py
346
3.609375
4
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. # -- scope = 100 sum_of_squares = 0 square_of_sums = 0 for i in range(scope + 1): sum_of_squares += (i * i) square_of_sums += i square_of_sums = square_of_sums * square_of_sums print square_of_sums - sum_of_squares
cdefa6f65d75c76a213a108b0223122b72b30a2f
morrosquin/aleandelebake
/crypto/caesar.py
385
4.125
4
from helpers import alphabet_position, rotate_char def encrypt (text, rot): encrypted_text = "" for characters in text: encrypted_text += rotate_char(characters, rot) return encrypted_text def main(): text = input('Enter your message: ') rotation = int(input('Enter rotation: ')) print(encrypt(text, rotation)) if __name__ == "__main__": main()
f1eb7c1008919db13ea251f213cb41939bc6d768
kevinniel/P5_openfoodfacts
/App/main_menu.py
1,245
3.5625
4
""" This module will generate the main menu """ # !/usr/bin/python3 # -*- coding: Utf-8 -* # import sys = Problème perso d'import à dégager par la suite. import sys sys.path.append('C:/Users/guthj/OneDrive/Bureau/coding/P5_openfoodfacts') from Config.config import MAIN_MENU from App.select_products import SelectCategory class MainMenu: """ This class will display the main menu and record the user choice""" def __init__(self): self.option = MAIN_MENU self.display() self.choice = None def display(self): """ Display the main menu """ print('\n') for key, val in self.option.items(): print(key, val, '\n') # make it more confortable to read self.get_choice() # launch automaticly the choice method after display def get_choice(self): """ Record the user choice """ self.choice = int(input( "\nEntrez le chiffre correspondant à votre choix puis" "pressez sur ENTER : ")) return self.choice self.dispatch() def dispatch(self): """ Generate the class relative of choice """ if self.choice == 1: SelectCategory() if __name__ == '__main__': MainMenu()
33a494821adfe9152461186f0afae033a0c8f873
linchenlinchen/Class_3_term_1
/智能系统原理开发/PROJECT/lab2/17302010021_林晨/RecommendSystem/draft.py
398
3.59375
4
# Message = [[2,'Mike'],[1,'Jone'],[2,'Marry']] # dict1 = {} # for number in Message: # value = number[0] # if value not in dict1.keys(): # dict1[value] = [number] #此句话玄机 # else: # dict1[value].append(number) # print(dict1) L = ['1','4'] L.append('3') print(L) L1 = ['Google', 'Runoob', 'Taobao'] L1.append('Baidu') print("更新后的列表 : ", L1)
4fdb14994dead769d220a252b7cee66da9c0ec36
jdvpl/Python
/7 funciones/ejemplo.py
310
3.78125
4
def Tabla(num): print(f"####Tabla del {num} ###".center(50)) for contador in range(11): operacion=num*contador print(f"{num} x {contador} = {operacion}") print("\n") numero=int(input("tabla del: ")) Tabla(numero) for numero_tabla in range(1,numero+1): Tabla(numero_tabla)
b792b0da6060bcb0f4868d3c52145ba3dc1b9944
joway/PyAlgorithm
/leetcode/array/easy/findDisappearedNumbers.py
1,256
3.671875
4
""" Summary """ class Solution(object): """ Problem: https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6] """ def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ # 这个算法会超时 ret = [] ret_len = len(nums) - len(set(nums)) for i in range(1, len(nums)+ 1): if i not in nums: ret.append(i) if len(ret) == ret_len: break return ret def findDisappearedNumbersBest(self, nums): for i in range(len(nums)): # index = 当前元素值 - 1 index = abs(nums[i]) - 1 # nums[index] 取负数, 这样所有存在的 ( 元素值 - 1 ) 的坐标的数都会是负数了 nums[index] = -abs(nums[index]) # 仍旧值 >0 的数, 说明没有一个元素等于其坐标 + 1, 即不存在的值 return [x + 1 for x in range(len(nums)) if nums[x] > 0] if __name__ == '__main__': nums = [4,3,2,7,8,2,3,1] result = Solution().findDisappearedNumbers(nums) print(result)
8bb2643692a42352205f142f9e077c32d4deef63
HypeRush/Python-Os-Module-Examples
/filedel.py
1,375
3.640625
4
import os print (os.name) print("şuan bulunduğun dizin:",os.getcwd()) path = input("Taranacak yerin pathi:",) def main(path): if path == (""): path = os.getcwd() dir_list = os.listdir(path) print("Aranan yerdeki dosyalar ve klasörler'", path, "' :") print(dir_list) goatten = input("Silmek istediğiniz dosyanın adını yazın(silmeyecekseniz boş bırakın)",) if goatten == (""): print (goatten , "Hiç bir şey silinmedi") else: print(goatten, "adlı dosya siliniyor") filewillbedeleted = os.path.join(path, goatten) os.remove(filewillbedeleted) print(goatten, "adlı dosya başarıyla silindi") else: dir_list = os.listdir(path) print("Aranan yerdeki dosyalar ve klasörler'", path, "' :") print(dir_list) goatten = input("Silmek istediğiniz dosyanın adını yazın(silmeyecekseniz boş bırakın)",) if goatten == (""): print (goatten , "Hiç bir şey silinmedi") else: print(goatten, "adlı dosya siliniyor") filewillbedeleted = os.path.join(path, goatten) os.remove(filewillbedeleted) print(goatten, "adlı dosya başarıyla silindi") if __name__ == "__main__": main(path)
2e7d2c889dc1a05302794b49f6f8f0fafd9deb52
ppeiris/codes
/mooc/mit-6.00/ps3d.py
1,270
3.53125
4
# Problem Set 2 # Name: Geeeqie # Time: 00:30 # # Problem 4 # from string import * def constrainedMatchPair(firstMatch, secondMatch, length): match = () m = length for n in firstMatch: for k in secondMatch: if n+m+1 == k: match += (n,) return match def subStringMatchOneSub(key,target): """search for all locations of key in target, with one substitution""" allAnswers = () for miss in range(0,len(key)): key1 = key[:miss] key2 = key[miss+1:] match1 = subStringMatchExact(target,key1) match2 = subStringMatchExact(target,key2) filtered = constrainedMatchPair(match1,match2,len(key1)) allAnswers = allAnswers + filtered return tuple(set(allAnswers)) def subStringMatchExact(target, key): answer = () i = 0 while True: i = find(target, key, i) if i == -1: return answer answer += (i,) if len(key) == 0: i += 1 else: i += len(key) target1 = 'atgacatgcacaagtatgcat' target2 = 'atgaatgcatggatgtaaatgcag' key10 = 'a' key11 = 'atg' key12 = 'atgc' key13 = 'atgca' def subStringMatchExactOneSub(target, key): s1 = set(subStringMatchOneSub(key, target)) s2 = set(subStringMatchExact(target, key)) return tuple(s1 - s2) print subStringMatchExactOneSub(target1, key11)
2361862094cbe8bc414cb97fb37adbe939bea567
tresa2002/Python-Projects
/swap.py
497
4.34375
4
num1 = int( input("Enter value for num1: ")) num2 = int( input("Enter value for num2: ")) #values before swapping print ("The Value of num1 before swapping: ", num1) print ("The Value of num2 before swapping: ", num2) # To swap the value of two variables # we will user third variable which is a temporary variable temp = num1 num1 = num2 num2 = temp #values after swapping print ("The Value of num1 after swapping: ", num1) print ("The Value of num2 after swapping: ", num2)
f7f386498a7b440298ad5231446fff1422d9792f
recheej/Data-Structures-In-Python
/queue.py
1,448
3.90625
4
__author__ = 'recheejozil' from linked_list import LinkedList from linked_list import Node from stack import Stack class Queue(object): def __init__(self): self.linked_list = LinkedList() def enqueue(self, item): if self.linked_list.head is None: self.linked_list.insert(item) return node = Node(item) self.linked_list.tail.next = node self.linked_list.tail = self.linked_list.tail.next def dequeue(self): self.linked_list.delete_node(self.linked_list.head) def front(self): return self.linked_list.head.data def is_empty(self): if self.linked_list.head is None: return True return False def size(self): return self.linked_list.size() class MyQueue(object): def __init__(self): self.stack_one = Stack() self.stack_two = Stack() def enqueue(self, item): if self.stack_one.is_empty(): self.stack_one.push(item) return while not self.stack_one.is_empty(): temp = self.stack_one.top() self.stack_one.pop() self.stack_two.push(temp) self.stack_one.push(item) while not self.stack_two.is_empty(): temp = self.stack_two.top() self.stack_two.pop() self.stack_one.push(temp) def dequeue(self): self.stack_one.pop()
e580b4cad68c56f71b474822cf7b35fd3442850a
kvizconde/Pizza-Builder
/user_interface_pizza.py
8,681
3.90625
4
import random import time from python_pizza import BasePizza, Toppings """ This module contains one class: UserInterface The UserInterface class handles all the user interaction which allow the user to build amazing pizza. """ class UserInterface: """ This class contains all the required methods for user interaction as follows: > main_menu > topping_menu > print_topping_choice > checkout """ def main_menu(self): """ This method handles the menu introduction and kicks off the first topping_menu which is cheese menu """ my_pizza = BasePizza() cheese_selection = Toppings.cheese_dict print("\x1b[6;30;43m 👨🏽‍🍳 Welcome to Kevin's Pizzeria! 🍕 \x1b[0m\n") print("Lets get you started with the Basics...") print(f"\nBasic Pizza: \n{my_pizza}") self.topping_menu(my_pizza, cheese_selection, 1) def topping_menu(self, my_pizza, topping_choice, next_menu): """ This method handles the menu prompts for each topping type such as cheese, meat and veggie menus :param my_pizza: the BasePizza() passed down from the 'main_menu' method :param topping_choice: the topping type as a dictionary :param next_menu: this number determines which topping menu to display to the user :return: recursively returns topping_menu method until each menu has been executed via 'next_menu' condition """ topping = ["", "Cheese", "Protein", "Vegetable", "Pineapple"] emoji_topping = ["", "🧀", "🥩", "🍄"] chef_names = ["👨🏾‍🍳 Jose", "👨🏽‍🍳 Kevin", "👨🏻‍🍳 Ringo", "👨🏻‍🍳 Benson", "👨🏽‍🍳 Daniel", "👩🏽‍🍳 ‍Rosette", "👩🏻‍🍳 Ashley"] msg = '' get_topping = 0 while True: if topping_choice == Toppings.cheese_dict: msg = f"{emoji_topping[1]} Select your {topping[1]}: " get_topping = 1 elif topping_choice == Toppings.meat_dict: msg = f"{emoji_topping[2]} Select your {topping[2]}:" get_topping = 2 elif topping_choice == Toppings.veggie_dict: msg = f"{emoji_topping[3]} Select your {topping[3]}:" get_topping = 3 print(f"\n{msg}") self.print_topping_choice(get_topping) # 1: cheese, 2: protein, 3: vegetables selection_length = topping_choice try: user_input = int(input()) if 0 < user_input <= len(selection_length): my_pizza = topping_choice.get(user_input)(my_pizza) print( f"\n{emoji_topping[get_topping]} Your {topping[get_topping]} " f"Selection: {my_pizza.get_ingredients().title()}") print(f"\n\x1b[0;30;46m 🍕 Your current Pizza: \x1b[0m {my_pizza}") print(f"\nWould you like to add more {topping[get_topping]}? ") print(f"\x1b[0;30;42m 1.Yes \x1b[0m\x1b[0;30;41m 2.Checkout \x1b[0m", f"\n\n\x1b[0;30;43m (Enter any other key for next menu: {topping[get_topping + 1]}) \x1b[0m") prompt_for_more = input() if prompt_for_more == '1': continue elif prompt_for_more == '2': print(f"\n🔥{random.choice(chef_names)} is Firing up your Pizza...") time.sleep(2) # pause for 2 seconds before displaying receipt to user return self.checkout(my_pizza) else: next_menu += 1 break else: print(f"\nSorry that {topping[get_topping]} doesn't exist!") print(f"Please select a valid option between 1 and {len(selection_length)}") continue except ValueError: print("\nDigit only please!") print(f"Please select a valid option between 1 and {len(selection_length)}") continue # The conditions below handle the next topping menu if next_menu == 2: topping_choice = Toppings.meat_dict elif next_menu == 3: topping_choice = Toppings.veggie_dict elif next_menu == 4: # Pineapple Pizza Jokes while True: try: print("\n🍍 Would you like to add some Pineapple?") print("1.Yes ", "2.No") pineapple_prompt = int(input()) if pineapple_prompt == 1: print("\nJust kidding we don't put Pineapple on Pizza! 😂") print(f"\x1b[0;30;42m (Hit any key to Checkout) \x1b[0m") input() print(f"\n🔥{random.choice(chef_names)} is Firing up your Pizza...") time.sleep(2) # pause for 2 seconds before displaying receipt to user return self.checkout(my_pizza) elif pineapple_prompt == 2: print("\n👍 Good Choice! Who puts Pineapple on Pizza anyways?!") print(f"\x1b[0;30;42m (Hit any key to Checkout) \x1b[0m") input() print(f"\n🔥{random.choice(chef_names)} is Firing up your Pizza...") time.sleep(2) # pause for 2 seconds before displaying receipt to user return self.checkout(my_pizza) else: print("\nSorry that choice is invalid!, please select only '1' for Yes, '2' for No") continue except ValueError: print("\nSorry that choice is invalid!, please select only '1' for Yes, '2' for No") # recursively call topping_menu until we reach the end of all menus return self.topping_menu(my_pizza, topping_choice, next_menu) @staticmethod def print_topping_choice(choice): """ This method handles the format for printing the topics and displaying it to the user along with the topping price. :param choice: the topping choice, 1 for cheese, 2 for meat, 3 for veggie """ my_pizza = BasePizza() topping = '' if choice == 1: topping = Toppings.cheese_dict elif choice == 2: topping = Toppings.meat_dict elif choice == 3: topping = Toppings.veggie_dict index = 0 for t in topping: index += 1 print( f"{index}. {topping.get(t)(my_pizza).get_ingredients().title()} " f"- ${'%.2f' % (topping.get(t)(my_pizza).get_price() - my_pizza.get_price())}") @staticmethod def checkout(my_pizza): """ The purpose of this function is to handle the receipt and display the user's selected toppings and corresponding price along with the total price of their pizza. :param my_pizza: the BasePizza wrapped with the latest topping :return: """ topping_dict = {1: Toppings.cheese_dict, 2: Toppings.meat_dict, 3: Toppings.veggie_dict} pizza = BasePizza() price = ['4.99'] ingredients = [ingredient.title() for ingredient in my_pizza.ingredient_list] for k in topping_dict: # iterates over the topping type dict -> cheese, meat, veggie for index in range(len(ingredients)): # loop through the ingredient list for i in topping_dict.get(k): # loop through each topping class # this condition gets the current topping ingredient to compare with the added ingredient if topping_dict.get(k)[i].get_ingredients(pizza).title() == ingredients[index]: price.append('%.2f' % (topping_dict[k].get(i)(pizza).get_price() - pizza.get_price())) ingredients_with_price = ['\n ↳ $'.join(x) for x in zip(ingredients, price)] print("\n\x1b[0;30;46m 👨🏽‍🍳 Your Receipt: \x1b[0m") ingredients_with_price.sort() ingredients_with_price = '\n--------------------\n'.join(ingredients_with_price) total_price = my_pizza.get_price() print("--------------------") print(f"{ingredients_with_price} " f"\n--------------------\n\x1b[0;30;43m 🍕 Total Price: ${'%.2f' % total_price} \x1b[0m") exit()
4928ac3e9edb82f94b374637add08d0a7805a6f2
mikeirwin/python_practice
/Data_Structures/Hash_practice.py
4,106
4.09375
4
""" Hash map: A key-value store that uses an array and a hashing function to save and retrieve values. Key: The identifier given to a value for later retrieval. Hash function: A function that takes some input and returns a number. Compression function: A function that transforms its inputs into some smaller range of possible outputs. Recipe for saving to a hash table: - Take the key and plug it into the hash function, getting the hash code. - Modulo that hash code by the length of the underlying array, getting an array index. - Check if the array at that index is empty, if so, save the value (and the key) there. - If the array is full at that index continue to the next possible position depending on your collision strategy. Recipe for retrieving from a hash table: - Take the key and plug it into the hash function, getting the hash code. - Modulo that hash code by the length of the underlying array, getting an array index. - Check if the array at that index has contents, if so, check the key saved there. - If the key matches the one you're looking for, return the value. - If the keys don't match, continue to the next position depending on your collision strategy. """ class HashMap: def __init__(self, array_size): self.array_size = array_size self.array = [None for i in range(self.array_size)] # creates & returns a hash_code def hash(self, key, count_collisions=0): key_bytes = key.encode() hash_code = sum(key_bytes) return hash_code # ensures the hash_code value fits in hash_map size def compressor(self, hash_code): return hash_code % self.array_size # implements assignment of hash_code index to the key:value pair def assign(self, key, value): array_index = self.compressor(self.hash(key)) current_array_value = self.array[array_index] # logic to prevent overriding of hash table indices if current_array_value is None: self.array[array_index] = [key, value] return if current_array_value[0] == key: self.array[array_index] = [key, value] return # COLLISION prevention logic number_collisions = 1 while current_array_value[0] != key: new_hash_code = self.hash(key, number_collisions) new_array_index = self.compressor(new_hash_code) current_array_value = self.array[new_array_index] if current_array_value is None: self.array[new_array_index] = [key, value] return if current_array_value[0] == key: self.array[new_array_index] = [key, value] return number_collisions += 1 return # defines the getter function def retrieve(self, key): array_index = self.compressor(self.hash(key)) possible_return_value = self.array[array_index] # logic to clarify key:value pairs at identical indices if possible_return_value is None: return None if possible_return_value[0] == key: return possible_return_value[1] # possible_return_value holds a different key retrieval_collisions = 1 while possible_return_value[0] != key: new_hash_code = self.hash(key, retrieval_collisions) retrieving_array_index = self.compressor(new_hash_code) possible_return_value = self.array[retrieving_array_index] if possible_return_value is None: return None if possible_return_value[0] == key: return possible_return_value[1] retrieval_collisions += 1 return # test area hash_map = HashMap(15) hash_map.assign('gabbro', 'igneous') hash_map.assign('sandstone', 'sedimentary') hash_map.assign('gneiss', 'metamorphic') print(hash_map.retrieve('gabbro')) print(hash_map.retrieve('sandstone')) print(hash_map.retrieve('gneiss')) """ End of File """
0d19117eb33eae5a9598e6ca14a942bde11d2706
qqss88/Leetcode-1
/240_Search_2D_Matrix.py
1,239
4.0625
4
#!/usr/bin/env python # encoding: utf-8 """ Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. For example, Consider the following matrix: [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] Given target = 3, return true. @author: Jessie @email: jessie.JNing@gmail.com """ class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ row, col = len(matrix), len(matrix[0]) start, end = 0, (col*row)-1 while start <= end: mid = (start + end)/2 mid_row, mid_col = divmod(mid, col) if matrix[mid_row][mid_col] == target: return True elif matrix[mid_row][mid_col] > target: end = mid - 1 else: start = mid + 1 return False if __name__=="__main__": solution_obj = Solution() matrix = [[1,4],[2,5]] for k in range(1): print solution_obj.searchMatrix(matrix, 2)
68065a7afd36484a2b903990a99ffd187dacabc3
askatako/youtube
/extract_categories.py
892
3.5625
4
import json import pickle def load_json(path): """ Loads the json file in the given path. Precondition: path: is a string of a valid json path. """ with open (path) as file: return json.load(file) def save_pickle(path,data): """ Dumps the json file in the given path. Precondition: path: is a string of a valid json path. """ # with open (path) as file: # return json.load(file) with open(path, 'wb') as outfile: pickle.dump(data, outfile) def extract_categories(path): cats = load_json(path) categories = {} for item in cats["items"]: video_id = int(item["id"]) title = item["snippet"]["title"] categories[video_id] = title return categories def main(): path = "US_category_id.json" data = extract_categories(path) outfile = 'US_categories.pickle' save_pickle(outfile, data) if __name__ == '__main__': main()
566e17eb4417a07ba655c2e2c5bfc079cd8590e5
szhongren/leetcode
/393/main.py
1,745
4.1875
4
""" A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: For 1-byte character, the first bit is a 0, followed by its unicode code. For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. This is how the UTF-8 encoding would work: Char. number range | UTF-8 octet sequence (hexadecimal) | (binary) --------------------+--------------------------------------------- 0000 0000-0000 007F | 0xxxxxxx 0000 0080-0000 07FF | 110xxxxx 10xxxxxx 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Given an array of integers representing the data, return whether it is a valid utf-8 encoding. """ class Solution(object): def validUtf8(self, data): """ :type data: List[int] :rtype: bool """ curr = 0 for byte in data: if curr == 0: if byte < 128: continue elif byte >= 240: # 0x11110000 curr = 3 continue elif byte >= 224: # 0x11100000 curr = 2 continue elif byte >= 192: # 0x11000000 curr = 1 continue else: return False else: if byte >= 128 and byte < 192: curr -= 1 else: return False return curr == 0 ans = Solution() print(ans.validUtf8([197, 130, 1])) print(ans.validUtf8([235, 140, 4]))
1861eca1fbfb1b4c08df336c11e7278ae5f9d91e
jmarianer/adventofcode
/2019/22.py
2,539
4.09375
4
import sys, itertools class Stack: """ A stack is described as a multiplier and an adder. Each card c goes to position (c+a)*m, where addition and multiplication are both done mod the stack length, which is assumed to be prime. """ def __init__(self, stacklen): self.stacklen = stacklen self.add = 0 self.mult = 1 def power(self, a, b): """ Calculate a^b mod stacklen """ ret = 1 for bit in bin(b)[2:]: ret *= ret if bit == '1': ret *= a ret %= self.stacklen return ret def inv(self, a): """ Calculate the multiplicative inverse of a """ return self.power(a, self.stacklen - 2) # The three shuffle operations def rev(self): self.add += self.inv(self.mult) self.add %= self.stacklen self.mult *= -1 self.mult %= self.stacklen def cut(self, n): self.add -= self.inv(self.mult) * n self.add %= self.stacklen def increment(self, n): self.mult *= n self.mult %= self.stacklen def pos_by_card(self, n): """ Return the given card's position """ return (n + self.add) * self.mult % self.stacklen def card_by_pos(self, n): """ Return the card at a given position (the inverse of pos_by_card) """ return (n * self.inv(self.mult) - self.add) % self.stacklen def do_n_times(self, n): """ Repeat the basic operation of this stack n times """ add = 0 mult = 1 for bit in bin(n)[2:]: add += add * self.inv(mult) mult *= mult if bit == '1': add += self.add * self.inv(mult) mult *= self.mult add %= self.stacklen mult %= self.stacklen self.add = add self.mult = mult def perform_lines(self, lines): for line in lines: if 'new stack' in line: self.rev() if 'increment' in line: n = int(line[20:]) self.increment(n) if 'cut' in line: n = int(line[4:]) self.cut(n) lines = sys.stdin.readlines() # Part I stack = Stack(10007) stack.perform_lines(lines) print(stack.pos_by_card(2019)) # Part II stack = Stack(119315717514047) stack.perform_lines(lines) stack.do_n_times(101741582076661) print(stack.card_by_pos(2020))
0eb24df65410302445428df05a29d4fc80e3bff0
manimaran-elumalai/Giraffe_Academy_Python
/listfunctions.py
895
4.21875
4
friends = ["Christy", "Rahul", "Mohan", "Jyothi", "Kavin"] lucky_numbers = ["2", "4", "6", "8"] friends1 = friends.copy() print(friends1) friends.extend(lucky_numbers) #extend(extend is a list function) the elements of the other lists to the friends list print(friends) friends.insert(4, "David") #add a new element to the specified index position print(friends) friends.append("Manimaran") #add the new string to the existing list at the last index position print(friends) friends.sort() print(friends) friends.remove("Manimaran") print(friends) print(friends.index("Rahul")) #to find if the element is part of the list or not - if yes, it'll return the index position, else an error. print(friends.count("Kavin")) #to count how many times the element is there in the list print(friends) friends.pop(2) print(friends) friends.clear() print(friends) lucky_numbers.reverse() print(lucky_numbers)
21d612fe7a2ffbb5062b7b9af3768ca765d005e3
angjerden/oiler
/others/luke10.py
2,080
3.5
4
# # Velkommen til Knowit sitt julebord! # # På julebordet er vi 1500 mennesker som sitter rundt et stort bord. # Vi er nummerert fra 1 til 1500 langs bordet. # Vi har fått tak i en flaske med meget sterk (men god!) akevitt. # # Den første personen tar flasken og serverer person nummer to en dram. # Akevitten er så sterk at denne personen går rett i bakken. # Person nummer en sender så flaska videre til den tredje personen # som serverer den fjerde en dram. Han går også rett i bakken # og flasken sendes videre til femtemann. Dette fortsetter rundt # slik at person nummer 1499 serverer person 1500 en dram # (hvorpå han dundrer i gulvet) og gir flaska tilbake den første. # # Nå serverer den første personen den tredje (som deiser av stolen) # og gir flaska videre til den femte... # # Dette fortsetter til det bare er en person igjen. # Hvilken person sitter igjen ved julebordets slutt? # # Svaret skal være i form av nummeret på personen som # sitter igjen, eksempelvis 1337 # min = 1 max = 1500 + 1 sober = "0" drunk = "X" people = dict((i, sober) for i in range(min, max)) number_sober = len(people.keys()) def serveAquavitToTheNextGuy(input): global number_sober index = input + 1 while index != input: if index in people and people[index] != drunk: people[index] = drunk print("{} got served by {} and is drunk".format(index, input)) number_sober -= 1 break index = index + 1 if index >= max: index = min def printVictor(): for i in range(min, max): if people[i] == sober: print("{} is still sober!".format(i)) if __name__ == "__main__": i = min while number_sober > 1: if people[i] != drunk: print("{} receives bottle".format(i)) serveAquavitToTheNextGuy(i) else: pass #print("{} is already drunk. Moving on...".format(i)) i += 1 if i >= max: i = min print("\n{} sober person left".format(number_sober)) printVictor()
451ffd2bfd5abd39d26744db50c2b3552862ffb1
DariaLotareva/Dasha
/hypothenuse.py
239
3.96875
4
print('please write down 1st leg of the right-angled triangle') a=int(input()) print('please write down 2st leg of the right-angled triangle') b=int(input()) c=((a**2)+(b**2))**(1/2) print('the hypothenuse is equal to {}'.format(c))
26640f83780758dc630e0b7a3cc8190f83772cc8
YashMistry1406/data-structures-and-algo
/implementation _pyhton/tree/check_BST.py
710
3.984375
4
class Node: def __init__(self,data): self.data=data self.left=None self.right=None def Insert(root,data): if(root== None): root=Node(root) if(root.data <=data): root.left=Insert(root.left,data) elif(root.right >data): root.right=Insert(root.right,data) return root def BSTUtil(root,minValue,maxValue): if(root==None): return True if(root.data>minValue and root.data>maxValue and BSTUtil(root.left,minValue,root.data) and BSTUtil(root.right,root.data,maxValue)): return True else: return False if __name__=='__main__': tree=Node(1) tree=Insert(tree,2) tree=Insert(tree,3)
0999151ac911ad779be04c224dd7fd0e11c3a42f
LarisaOvchinnikova/python_codewars
/Sum of Digits - Digital Root.py
182
3.515625
4
https://www.codewars.com/kata/541c8630095125aba6000c00 def digital_root(n): while n > 9: s = 0 for i in str(n): s += int(i) n = s return n
57bfeb07f8a35d64ef49a7e216280bc9979155ad
vicety/LeetCode
/python/75.py
680
3.8125
4
from collections import deque from typing import List class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ if not nums: return zero_r, one_r, two_l = 0, 0, len(nums) - 1 while one_r <= two_l: if nums[one_r] == 0: nums[zero_r], nums[one_r] = nums[one_r], nums[zero_r] zero_r += 1 one_r += 1 elif nums[one_r] == 1: one_r += 1 elif nums[one_r] == 2: nums[one_r], nums[two_l] = nums[two_l], nums[one_r] two_l -= 1
8531673bd473a5d14589488b8454d75c55c183f2
suryak24/python-code
/41.py
79
3.75
4
str=input("Enter the string:") k=int(input("Enter the k values")) print(k*str)
ae19ad05b2db47b553eb51fed91985edffbd75f9
momentum-cohort-2018-10/w2d1-currency-converter-meagabeth
/currency_converter.py
747
3.8125
4
# list = [(value, form, to)] rates = [ ("USD", "EUR", 0.74), ("EUR", "JPY", 145.949) ] def convert(list, value, original, to): if original == to: return value for conversion in rates: if original == conversion[0] and to == conversion[1]: return value * conversion[2] if original == conversion[1] and to == conversion[0]: return value / conversion[2] raise ValueError(f"Can't convert {original} to {to}") print(convert(rates, 1, "USD", "EUR")) print(convert(rates, 10, "USD", "EUR")) print(convert(rates, 0.74, "EUR", "USD")) print(convert(rates, 1, "EUR", "EUR")) print(round(convert(rates, 1, "EUR", "JPY"), 2)) print(round(convert(rates, 145.949, "JPY", "EUR"), 2))
e80f43e1941e735c7473553da70fe9c50829aa72
kegans/IntroToProg-Python-Mod07
/Assignment07.py
4,104
4.0625
4
# ------------------------------------------------- # # Title: Assignment07 # Description: Demo of exception handling # using custom error classes and pickling # ChangeLog: (Who, When, What) # KSanchez,11.30.2020,Created Script # ------------------------------------------------- # # --------------Exception Handling----------------- # ----- Try-Except: try: # Tests the following code block for errors x = int(input("Please enter a number: ")) y = int(input("Please enter a second number: ")) add = x + y subtract = x - y divide = x/y except ZeroDivisionError as e: # Handles a ZeroDivisionError if user enter 0 for y print("Variable y cannot be a zero.") print("Built-in Python error info:") print(e, e.__doc__, type(e), sep='\n') except ValueError as e: # Handles a ValueError if user input is a string or space/enter key print("Please enter an integer.") print("Built-in Python error info:") print(e, e.__doc__, type(e), sep='\n') except Exception as e: # Handles all other error types and provides details print("Something else went wrong.") print("Built-in Python error info:") print(e, e.__doc__, type(e), sep='\n') # ----- Else: try: # Tests the following code block for errors x = int(input("Please enter a number: ")) y = int(input("Please enter a second number: ")) add = x + y subtract = x - y divide = x/y except Exception as e: # Handles all error types and provides details print("Something else went wrong.") print("Built-in Python error info:") print(e, e.__doc__, type(e), sep='\n') else: # Displays results and message if user input does not generate an error print("Added: ", add) print("Subtracted: ", subtract) print("Divided: ", divide) print("No errors occurred.") # ----- Pass and Finally: try: # Tests the following code block for errors x = int(input("Please enter a number: ")) y = int(input("Please enter a second number: ")) add = x + y subtract = x - y divide = x/y except Exception as e: # Handles all error types and provides details, but continues program print("Display error message, but ignore and move on through program.") print("Built-in Python error info:") print(e, e.__doc__, type(e), sep='\n') pass # Tells program to ignore error and continue through program finally: # Performs actions after all try-except actions print("This exception test is complete.") # The program reaches this block, even if errors occur print("Added: ", add) print("Subtracted: ", subtract) print("Divided: ", divide) # ----- Handling a file: try: objFile = open("file.txt", "wb") objFile.write("Test") # Generates a TypeError because a bytes-like object is required except Exception as e: print("Unable to write to the file.") print("Built-in Python error info:") print(e, e.__doc__, type(e), sep='\n') finally: objFile.close() # Closes the file object and continues the program # ----- Raising an Error: x = int(input("Please enter a number: ")) if x < 0: # Raises an error if the user enters a negative number raise ValueError("Please enter a number greater than zero.") elif x == 0: # Raises an error if the user enters a zero raise ZeroDivisionError("Please do not enter a zero.") # -------------------Pickling---------------------- # # ----- Writing to a File: import pickle pickleDict = {} pickleDict["Onigiri"] = ["salted salmon", "umeboshi", "tuna mayo"] pickleDict["Ramen"] = ["shoyu", "tonkotsu", "miso"] with open('dataPick.pkl', 'wb') as pickleFile: # Opens a file for writing binary data and specifies the binary object pickle.dump(pickleDict, pickleFile) # Writes data to new file specifying data and file object # ----- Reading a File: with open('dataPick.pkl', 'rb') as pickleFile: # Opens a file for reading binary data newData = pickle.load(pickleFile) # Loads data from file object and stores print(newData) # Prints all the loaded data
62c88bf5303008b0a3d1d8d57013c27bf258c9e0
alisonsu/example
/test/test_algs.py
1,593
3.765625
4
import numpy as np from example import algs def test_pointless_sort(): # generate random vector of length 10 x = np.random.rand(10) # check that pointless_sort always returns [1,2,3] assert np.array_equal(algs.pointless_sort(x), np.array([1,2,3])) # generate a new random vector of length 10 x = np.random.rand(10) # check that pointless_sort still returns [1,2,3] assert np.array_equal(algs.pointless_sort(x), np.array([1,2,3])) def test_bubblesort(): # Test empty array x = [] algs.bubblesort(x) # Test single element array: x = [4] algs.bubblesort(x) # Test sorted array: x = [0,1,2,3] algs.bubblesort(x) # Test negative elements in array: x = [0, 6, 3, -5, 2] algs.bubblesort(x) # Test duplicated elements in array: x = [4, 5, 4, 6, 10, 3] algs.bubblesort(x) # Test floats in array: x = [0.4, -3, 0.4, 10] algs.bubblesort(x) def test_quicksort(): p=0 # Test empty array: x = [] r = len(x)-1 algs.quicksort(x,p,r) # Test single element array: x = [4] r = len(x)-1 algs.quicksort(x,p,r) # Test sorted array x = [0,1,2,3] r = len(x)-1 algs.quicksort(x,p,r) # Test negative elements in array x = [0, 6, 3, -5, 2] r = len(x)-1 algs.quicksort(x,p,r) # Test duplicated elements in array: x = [4, 5, 4, 6, 10, 3] r = len(x)-1 algs.quicksort(x,p,r) # Test floats in array: x = [0.4, -3, 0.4, 10] r = len(x)-1 algs.quicksort(x,p,r)
94d44701bc9f30a7f0275bede2f7c631c3f38411
superSeanLin/Algorithms-and-Structures
/222_Count_Complete_Tree_Nodes/222_Count_Complete_Tree_Nodes.py
1,133
3.9375
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 countNodes(self, root: TreeNode) -> int: ## level-order traverse, find less-child on the last second layer ## also use recursive method to find full binary tree (left_height == right_height) if not root: return 0 flag = 0 q = [(root, flag)] height = 1 layer_count = 0 right = 0 # indicate if left child exists while q: (node, f) = q.pop(0) if f != flag: # new layer flag = f height += 1 layer_count = 0 if node.left: q.append((node.left, 1-f)) if node.right: q.append((node.right, 1-f)) else: # no right child right = 1 break else: # no left child break layer_count += 1 return 2**height + 2 * layer_count + right - 1
71318bd17165d3dd23a00f5724a2849dd1548243
Pallavi2000/heraizen_internship
/internship/M_1/series2.py
310
4.15625
4
"""program to accept a number “n” from the user; then display the sum of the following series: 1/2^3+1/4^3 + ……+1/n^3""" n=int(input("Enter the value of n: ")) sum=0 if n==0: print(f"Input nonzero value") else: for i in range(2,n+1): sum+=1/(i**3) print(f"Sum of series={sum}")
24b1a1a64652849f2182fd257632f2af6ecd03dd
dmort27/epitran
/epitran/puncnorm.py
1,211
3.578125
4
# -*- coding: utf-8 -*- import pkg_resources import unicodecsv as csv class PuncNorm(object): def __init__(self): """Constructs a punctuation normalization object""" self.puncnorm = self._load_punc_norm_map() def _load_punc_norm_map(self): """Load the map table for normalizing 'down' punctuation.""" path = pkg_resources.resource_filename(__name__, 'data/puncnorm.csv') with open(path, 'rb') as f: reader = csv.reader(f, encoding='utf-8', delimiter=str(','), quotechar=str('"')) next(reader) return {punc: norm for (punc, norm) in reader} def norm(self, text): """Apply punctuation normalization to a string of text Args: text (unicode): text to normalize_punc Returns: unicode: text with normalized punctuation """ new_text = [] for c in text: if c in self.puncnorm: new_text.append(self.puncnorm[c]) else: new_text.append(c) return ''.join(new_text) def __iter__(self): return iter(self.puncnorm) def __getitem__(self, key): return self.puncnorm[key]
5d223e12fa7027e815492a83b5cf1d74cde31330
synapse99/20190420
/loop03.py
540
3.78125
4
print("1부터 9까지") for i in range(1, 10, 1): print(i) print() print("0부터 9까지") for i in range(10): print(i, end=" ") print() print("0부터 10까지") for i in range(11): print(i, end=" ") print() print("1부터 10까지") for i in range(1, 11): print(i, end=" ") print() print("1부터 10까지의 홀수") for i in range(1, 11, 2): print(i, end=" ") print() print("2부터 10까지의 짝수") for i in range(2, 11, 2): print(i, end=" ") print()
da2e2d77e484af592ae7c265933219729e3bc4aa
pavankumarag/ds_algo_problem_solving_python
/practice/very_hard/_72_iterative_inorder_traversal.py
519
3.90625
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def inorder_iterative(root): current = root stack = [] while True: if current is not None: stack.append(current) current = current.left elif stack: current = stack.pop() print current.data, current = current.right else: break if __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) inorder_iterative(root)
587b8ce84a9250b9b8474cc245f802d6e45722f0
marclave/Project-Euler
/Problem16.py
439
3.921875
4
""" Problem 16 https://projecteuler.net/problem=16 Power digit sum answer is 1366 """ def powerSum(power): sum = 0 result = str(2**power) for i in range(len(result)): sum += int(result[i]) print sum if __name__ == "__main__": print "=================================" print " Problem16 " print " Developed by Marc Laventure " print "=================================" print "" powerSum(1000)
55394ad092a9e53b794501c05b4f680b43a89fb4
noobzyl/task
/fib list/fib_rec.py
262
3.734375
4
# coding : utf-8 '''递归法求斐波那契数列''' def fib(n): if n == 1 or n == 2: return 1 else: return fib(n-1) + fib(n-2) counts = int(input("请输入需要的个数: ")) res = [fib(n) for n in range(1, counts+1)] print(res)
2210a36d38a7c7c52c014483217198e97da47ae4
fruchoc/launder
/program/output.py
3,768
3.609375
4
""" output.py The output interface for writing text files from the main program (c) William Menz (wjm34) 2012 """ import sys class Output: def getData(self): return self.m_data def __init__(self, fname): self.m_fname = fname self.m_data = "" self.m_write = True if self.m_fname != None: try: print("Opening {0} for writing.".format(self.m_fname)) self.m_ostream = open(self.m_fname, 'w') except: print("Couldn't open {0} for writing.".format(self.m_fname)) raise else: self.m_write = False def close(self): if self.m_write: print("Closing file {0}".format(self.m_fname)) self.m_ostream.close() class XMLOut(Output): m_tab = " " # Tab spacing characters m_fmt = "{0.3e}" # Formatting for floats def head(self): string = self.node("?xml", [["version", "1.0"]], "?") self.m_data += string if self.m_write: self.m_ostream.write(string) def node(self, text, attribs=[], endchar=""): # Gets a text string element of XML # supply attribs as list [[attribute, value], ..] string = "<" string += str(text) if len(attribs) > 0: string += " " for a, i in zip(attribs, range(0, len(attribs))): string += str(a[0]) + "=\"" + str(a[1]) + "\"" if i != len(attribs) -1: string += " " string += str(endchar) + ">\n" return string def short(self, param, value): # Get a string of the form <param>value</param> string = "<" + str(param) + ">" string += "{0}".format(value) string += "</" + str(param) + ">\n" return string def write1(self, text, attribs=[], tabs=0, endchar=""): string = "" string += self.indent(tabs) string += self.node(text, attribs, endchar) self.m_data += string if self.m_write: self.m_ostream.write(string) def write2(self, param, value, tabs=0): string = "" string += self.indent(tabs) string += self.short(param, value) self.m_data += string if self.m_write: self.m_ostream.write(string) def indent(self, tabs): # Writes a certain number of indents string = "" if tabs > 0: for t in range(0, tabs): string += self.m_tab return string class DSVOut(Output): def parseData(self, data, delimiter=","): # Parses a block of data into a DSV file. # Assume form [[headers], [line1], [line2]...] # Write header self.head(data[0], delimiter) for line in data[1:]: self.write(line, delimiter, None) def head(self, items, delimiter): # Writes the header of a file string = self.line(items, delimiter, None) self.m_data += string if self.m_write: self.m_ostream.write(string) def line(self, items, delimiter, fmt=None): # Gets a line of DSV based on items list code = "{0" if fmt!=None: code += fmt code += "}" string = "" for i, j in zip(items, range(0,len(items))): string += code.format(i) if j != len(items)-1: string += str(delimiter) j += 1 string += "\n" return string def write(self, items, delimiter, fmt=None): # Writes a DSV fline string = self.line(items, delimiter, fmt) self.m_data += string if self.m_write: self.m_ostream.write(string)
1b67032ddb07ed8244c8f1d5f21aaddfd7450d7e
Jeroen-dH/functions-tryout
/multiplier-x.py
164
3.578125
4
tafel = int(input("Welke tafel wilt u weten. (1/10)")) def de_tafels(tafel:int): for a in range(1,11): print(a,"x",tafel,"=",a*tafel) de_tafels(tafel)
fcab8cb9524a1142a0a8ff994214eba608c2fe3c
ee18b101/Text-Based-Search-Engine
/Project/sentenceSegmentation.py
1,450
3.515625
4
from util import * # Add your import statements here import nltk class SentenceSegmentation(): def naive(self, text): """ Sentence Segmentation using a Naive Approach Parameters ---------- arg1 : str A string (a bunch of sentences) Returns ------- list A list of strings where each string is a single sentence """ segmentedText = None #Fill in code here # The most naive approach would be to split sentences at the end of punctuations # such as '.', '?', '!' # Whenever one of these punctuations appear, we break the sentence. segmentedText = [] # The list of punctuations are as follows (comma not included as sentences # don't end on commas.) punctuation = ['.', '?', '!'] prev_i = 0 for i in range(len(text)): if text[i] in punctuation: segmentedText.append(text[prev_i:i+1]) prev_i = i+1 return segmentedText def punkt(self, text): """ Sentence Segmentation using the Punkt Tokenizer Parameters ---------- arg1 : str A string (a bunch of sentences) Returns ------- list A list of strings where each strin is a single sentence """ segmentedText = None #Fill in code here # importing the pre-trained punkt tokenizer from the punkt package sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') # segmenting the text using punkt tokenizer segmentedText = sent_detector.tokenize(text.strip()) return segmentedText
5f79beb2277c9471d818cb3664a801f956189703
geozevallos/Repositorio_BackEnd
/session1/script.py
172
3.796875
4
print("Ingrese edad") edad = input() if int(edad) > 18: print("es mayor de edad") elif int(edad) < 0: print("edad invalida") else: print("no es mayor de edad")
a5f0d1c7214dc75fe9d98f822771a6bbbcff8e07
angelahe/automate
/dragon.py
1,711
4.125
4
import random import time def displayIntro(): print('You are in a land full of dragons. In front of you') print('you see two caves. In one cave, the dragon is friendly') print('and will share his treasure with you. The other') print('is greedy and hungry, adn will each you on sight') print() def chooseCave(): cave = '' while cave != '1' and cave != '2': print('Which cave will you go into (1 or 2)') cave = input() return cave def checkCave(chosenCave): print('You approach the cave...') time.sleep(2) print('It is dark and spooky...') time.sleep(2) print('A large dragon jumps out in front of you! He opens his jaws...') print() time.sleep(2) friendlyCave = random.randint(1, 2) if chosenCave == str(friendlyCave): print('Gives you his treasure!') else: print('Gobbles you down in one bite!') playAgain = 'yes' while playAgain == 'yes' or playAgain == 'y': displayIntro() caveNumber = chooseCave() checkCave(caveNumber) print('Do you want to play again? (yes or no)') playAgain = input() # another kind of while #break statement while True: print('Please type your name.') name = input() if name == 'your name': break #continue statement spam = 0 while spam < 5: spam = spam + 1 if spam == 3: continue print('spam is ' + str(spam)) #for loops print('My name is') for i in range(5): print('Jimmy Five Times ' + str(i)) #range ie start, stop (not including that value), step value print('Numbers by 2') for i in range (48, 101, 2): print('i is now ' + str(i)) for i in range(5, -1, -1): print('blastoff in ' + str(i))
32ca4879ce2bc2854f4a5f2cefac3cae64a484ce
miko73/codity
/small_frog.py
339
3.828125
4
import sqlite3 def solution(x, y, d): if d <= 0: print("Takhel tam nedojdu") return 0 if x * y <= 0 or y < x: print("spatny vstup") return 0 steps = (y-x)//d #print(steps) if ((y-x)%d) > 0: steps += 1 return steps A = [1,2,3,4,5] X = 10 Y = 85 D = 30 print(solution(X,Y,D))
696793a21273d57cc6432f9684bd86f9dbd4a170
Anup-Toggi/python
/hcf1.py
177
3.859375
4
#Using Euclid's algorithm print("Enter Two Numbers") a=int(input()) b=int(input()) while True: if a==b: print("HCF = ",a) break if a>b: a=a-b else: b=b-a
2a2528538dec601b31c52d027be81b5756d72b70
BranSmit/Project-Euler-Solutions
/P1-10/P5.py
592
3.703125
4
# Smallest multiple # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? # Not gonna generalize this one because I dont really feel like it. sm = 2520 numSet = [i+1 for i in range(20)] while True: n=0 for i in numSet: if sm % i != 0: sm += 20 break else: n += 1 if n == 20: break print(sm,"\n") for o in numSet: print(sm / o) # Solution: 232792560
5ca7f10a12c1c7528fe61db76ed4971a1688c634
AdrianoCavalcante/exercicios-python
/Lista_exercicios/ex061.py
216
3.890625
4
termo = int(input('Digite O numero para ver suas 10 priemeiras progreções: ')) razao = int(input('Digite a razão da progreção: ')) pa = 10 while pa != 0: print(termo, end=' ') termo += razao pa -= 1
3de817b2949e8a3d001124b28b94fb766be759b6
idaandersson89/Python-ida
/Hurray.py
186
3.984375
4
#fruits=["hip"] #for x in fruits: # print(x) for i in range(3): print(i) for i in range(2): print("hip") print("hurray") #for hip in range(2): # print(hip)
6c393332ae73d276a4629aa1402b101a98773e73
Hunt-j/python
/PP09.py
596
3.8125
4
from random import seed from random import randint seed(randint) x = 1 n = int(0) while (x == 1): a = randint(1,9) b = int(input("Pick a number between 1 and 9")) if (b > a): print("Too high!") again = input("play again (Y or N)") n = (n + 1) if (b < a): print("Too low!") again = input("play again (Y or N)") n = (n + 1) if (b == a): print("You got it!") again = input("play again (Y or N)") n = (n + 1) if (again == "n" or again == "N"): x = 2 print(f"You played {n} times")
b162da0b8c90dc2d92f61e9144717431ab9f746f
ZwyAnswer/Leetcode_solutions
/Linked List/61.Rotate List/Solution.py
542
3.5
4
class Solution: # @param head, a ListNode # @param k, an integer # @return a ListNode def rotateRight(self, head, k): if not head or not head.next: return head if k == 0: return head p1 = head while k > 0: p1 = p1.next if not p1: p1 = head k -= 1 p2 = head while p1.next != None: p1 = p1.next p2 = p2.next p1.next = head head = p2.next p2.next = None return head
f0e22c5e2142d53c5f7622117d80e578ef4a6703
isilanes/myeuler
/p027/p027.py
860
3.65625
4
def f1(): maxn = 0 abmax = [0, 0] for a in range(-1000, 1001): for b in range(1001): n = -1 while True: n += 1 m = n*n + a*n + b if m < 2 or not isprime(m): break # n here will be length of series: if n > maxn: maxn = n abmax = [a, b] return [abmax[0]*abmax[1], abmax] #-------------------------------------------------------------------------# def isprime(m): import math if not m % 2: return False for i in range(3, int(math.sqrt(m)+1), 2): if not m % i: return False # If we reach so far, it is prime: return True #-------------------------------------------------------------------------# res = f1() print(res)
2b21d7e496b90f55cca93f4c79cacbc172118c95
CodeyBank/Webscrapping-with-Python
/webscraping.py
798
3.578125
4
import requests from bs4 import BeautifulSoup # # r = requests.get("http://testing-ground.scraping.pro/table") # c = r.content # # soup = BeautifulSoup(c, "html.parser") # # all = soup.find_all("div", {"class": "cities"})[0] # # use the find_all method to return elements of html with a particular # # this method returns a list. so you can refer to an index in the list. # # # all[0].find_all("h2")[0].text # # .text method returns the text in the element/ tag # # with open("HtmlScrap.html", "w") as file: # file.writelines(soup.prettify() + "\n") # # for item in all: # print(item.find_all("h2")[0].text) r=requests.get("http://pyclass.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/?") c=r.content soup = BeautifulSoup(c, "html.parser") print(soup.prettify())
726acce695d62e6d438f2abd93b1685daab8f95a
applicationsbypaul/Module7
/Module8/more_fun_with_collections/dict_membership.py
502
4.15625
4
""" Program: dict_membership.py Author: Paul Ford Last date modified: 06/22/2020 Purpose: using dictionaries for the first time """ def in_dict(dictionary, data): """ accept a set and return a boolean value stating if the element is in the dictionary :param dictionary: The given dictionary to search :param data: The data searching in the dictionary :return: A boolean if the data is in the dictionary """ return data in dictionary if __name__ == '__main__': pass
6cb4f91de1e80193e3e038f7ddd264bac3bed1b1
CFHT/apero-trigger
/trigger/baseinterface/processor.py
1,480
3.515625
4
from __future__ import annotations from abc import ABC, abstractmethod from typing import Optional class RecipeFailure(Exception): """ Exception representing any failure for a DRS recipe. """ def __init__(self, reason: str, command_string: Optional[str] = None, traceback_string: Optional[str] = None): """ :param reason: A short string explaining what kind of recipe failure occurred :param command_string: A string representation of the recipe call that failed """ self.reason = reason self.command_string = command_string self.traceback_string = traceback_string def __str__(self): if self.command_string: return 'DRS command failed (' + self.reason + '): ' + self.command_string return 'DRS command failed (' + self.reason + ')' def full_string(self): if self.traceback_string: return str(self) + '\n' + self.traceback_string return str(self) def from_command(self, command_string: str) -> RecipeFailure: return RecipeFailure(self.reason, command_string, self.traceback_string) def with_traceback_string(self, traceback_string: str) -> RecipeFailure: return RecipeFailure(self.reason, self.command_string, traceback_string) class IErrorHandler(ABC): """ A base class for handling recipe failures. """ @abstractmethod def handle_recipe_failure(self, error: RecipeFailure): pass
4610a69f7338705e30afa1a4f7c488e103ed86cf
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4480/codes/1644_1054.py
126
4
4
x= int(input()) y= int(input()) r= 3-2*x if(y==r): print('ponto pertence a reta') else: print('ponto nao pertence a reta')
50ed8f8e5827c24a22eae34bb7c635950b9b9f3c
valeriiaminikaeva/homework_python
/091021/time.py
1,421
4.03125
4
import datetime while True: date_ = input('Input the date in standard format DD/MM/YY: ') if date_ == ('q'): print('goodbye!') quit() day , month, year = date_.split('/') d = int(day) m = int(month) y = int(year) def checkfake(d): if not(0 < d < 32): print('дата не верна') quit() def checkmonth(m): if not(0 < m < 13): print('дата не верна') quit() def checkyear(y): if not(y > 0): print('дата не верна') quit() def february(d, m): if m == 2 and d == 29: n = input('Это високосный год?') if n != 'y': print('дата не верна') quit() def April(d): if m==1 and 0 < d < 31: print('дата не верна') quit() def June(d): if m==1 and 0 < d < 31: print('дата не верна') quit() def September(d): if m==1 and 0 < d < 31: print('дата не верна') quit() def November(d): if m == 1 and 0 < d < 31: print('дата не верна') quit() checkfake(d) checkmonth(m) checkyear(y) february(d, m) print('дата корректна', day, month, year)
24e134709ed3db9766bd87b94196681162323986
anjaligopi/leetcode
/daily_coding_challenge/october_2020/min_cost_to_move_chips_to_the_same_position_1217.py
1,544
4.1875
4
""" Question: We have n chips, where the position of the ith chip is position[i]. We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to: position[i] + 2 or position[i] - 2 with cost = 0. position[i] + 1 or position[i] - 1 with cost = 1. Return the minimum cost needed to move all the chips to the same position. Example: Input: position = [1,2,3] Output: 1 Explanation: First step: Move the chip at position 3 to position 1 with cost = 0. Second step: Move the chip at position 2 to position 1 with cost = 1. Total cost is 1. Input: position = [2,2,2,3,3] Output: 2 Explanation: We can move the two chips at poistion 3 to position 2. Each move has cost = 1. The total cost = 2. Input: position = [1,1000000000] Output: 1 """ #min_cost_to_move_chips_to_the_same_position_1217.py import pytest from typing import List class Solution: def min_cost_to_move_chips(self, position: List[int]) -> int: even, odd = 0, 0 for x in position: if x%2 == 0: even += 1 else: odd += 1 return min(odd, even) @pytest.mark.timeout(3) @pytest.mark.parametrize( "arr, ans", [([1,2,3], 1), ([2,2,2,3,3], 2), ([1,1000000000], 1)] ) def test_min_cost_to_move_chips(arr, ans): sol1 = Solution() assert sol1.min_cost_to_move_chips(arr) == ans # pytest daily_coding_challenge/october_2020/min_cost_to_move_chips_to_the_same_position_1217.py --maxfail=4
3ddc5edaf705e501829d773be9aeb0bcb63d7a9a
iOSDevD/EMR_System
/utilities/Questionnaire.py
7,027
4.21875
4
""" Nikunj Upadhyay Class: CS 521 - Fall 1 Date: 10/16/2021 Homework Problem # Project Description of Problem (1-2 sentence summary in your own words): This program handles the questionnaire part. It can print the questionnaire summary using get_questionnaire_to_print() or generate a formatted string to which can be saved to CSV file. Possible options to answer a questionnaire can be obtained with get_question_str_for_prompt(), """ from model.Question import Question class Questionnaire: """ Helps to generate questionnaire summary or result, answers string which can be saved in the csv as well prompt message for a question while user enters input. """ # Private static question 1 __question_1 = Question("Did you had covid any time before your visit?", ["Yes", "No"]) # Private static question 2 __question_2 = Question("Do you have insurance on file?", ["Yes", "No"]) # Private static question 3 __question_3 = Question("Do you want us to reach out to you via SMS or " "E-mail for further appointments", ["Yes", "No"]) # Private static question 4 __question_4 = Question("Do you have migraine or had earlier?", ["Yes", "No"]) # Static Set of possible Yes options YES_ANSWER_SET = {"Y", "YES"} # Static Set of possible No options NO_ANSWER_SET = {"N", "NO"} def __init__(self): # Public attribute questionnaire list self.questionnaire_list = [Questionnaire.__question_1, Questionnaire.__question_2, Questionnaire.__question_3, Questionnaire.__question_4] def get_questionnaire_to_print(self, answers): """ Generates a string which represents the list of questions along with its options and answer. Used to display result of a questionnaire. :param answers: list of answer values 1 for Yes, 0 for No and -1 for Not answered or skipped. :return: string representing question, options and hint part """ # Defaults to -1 i.e not answered for empty list, helps to show # question was not answered or skipped. if answers is None or len(answers) == 0: answers = self.__get_all_answers_as_skipped() # Possible list of answers for presentation options_dict = {0: "No", 1: "Yes", -1: "Not answered or skipped"} # Map questionnaire with answers, answer will be represented by its # corresponding values in options_dict result_map = map( lambda question, answer: "{}\nAnswer: {}".format(question, options_dict[ answer]), self.questionnaire_list, answers) # Convert mapped object to a list result_list = list(result_map) return "\n".join(result_list) # Join Q and A, separated by new line. def get_formatted_answers_to_save(self, answers): """ Generates a string which represents the answers and which case be saved to the csv file. ex: list [-1,0,1,1] will be converted to string value '[-1,0,1,1]'. :param answers: list of answer values 1 for Yes, 0 for No and -1 for Not answered or skipped. :return: string representation of array. """ answers_str_list = [str(answer_id) for answer_id in answers] return "[{}]".format(",".join(answers_str_list)) def get_question_str_for_prompt(self, question): """Generates a string representation of question, it's options and hint on what to enter of yes or no option. The message is used as a prompt, so that they can enter appropriate value for a answer. :param question: Question object for which representation has to be created. :return: a string representing the question,it's option followed by small hint after it. """ return str(question) + "\nPlease enter y for Yes or n " \ "for No and enter to skip" def get_default_questionnaire_answers(self): """For new patient since the intake form will not be answered all answers should have value skipped. It returns string value of answers [-1,-1,-1,-1]""" default_answers_list = self.__get_all_answers_as_skipped() return self.get_formatted_answers_to_save(default_answers_list) def __get_all_answers_as_skipped(self): """Returns Default answers list for the questionnaire as skipped.""" return [-1] * len(self.questionnaire_list) # Unit Tests if __name__ == "__main__": print("Started Executing test case in Questionnaire") questionnaire = Questionnaire() # 1. Test Questionnaire String representing, question, options and answer # is as expected. questionnaire_print_test_str = questionnaire.get_questionnaire_to_print( [-1, 0, 1, 1]) assert questionnaire_print_test_str.count("Answer: Not " "answered or skipped") == 1, \ ("Occurrence of Not answered should be only" " 1 as there is only one '-1' entry in the list") # Replacing Not required, as it will be counted because `Answer: No` # matches initial part of 'Answer: Not answered'. questionnaire_print_test_str = \ questionnaire_print_test_str.replace("Answer: Not answered " "or skipped", "") assert questionnaire_print_test_str.count("Answer: No") == 1, \ ("Occurrence of No answered should be only" " 1 as there is only one '0' entry in the list") assert questionnaire_print_test_str.count("Answer: Yes") == 2, \ ("Occurrence of Yes answered should be 2 as " "there are two entries of '1' in the list") # 2. Test Case to check answers list to string formatting is correct assert questionnaire.get_formatted_answers_to_save([-1, 0, 1, 1]) == \ "[-1,0,1,1]", ("String representation of list should " "match exact values in the list") # 3. Test case to check message being created for prompt is correct or not. input_question = Question("Question 1", ["Yes", "No"]) assert questionnaire.get_question_str_for_prompt(input_question). \ startswith(str(input_question)), ("Question-Option part " "of the prompt is missing.") # 4. Test case for default answers to save, which will have all answers # as skipped i.e -1 assert questionnaire.get_default_questionnaire_answers() == \ "[-1,-1,-1,-1]", ("Default answers to save should all have default " "answer as skipped i.e -1") print("Success! Completed Executing test case in Questionnaire")
f4712e0b76ee8fb88d54d52447ff2aee1cae74cd
prathamshrestha/assignment_1
/func15.py
149
3.546875
4
def filter_list(input_list): filter_even = filter(lambda x:x%2==0,input_list) return list(filter_even) print(filter_list([1,2,3,4,5,6,7,8]))
e9068e67fc48fddb8b42a90bfe2fa8851150c00b
akstt/LeetCode
/LeetCode/1-50/46_全排列.py
795
3.65625
4
class Solution: # 传入数字,依次放在第一位,将剩下的数字放到下次递归当中 def permute(self, nums: [int]) -> [[int]]: result_1 = [] for num in nums: nums_temp = nums.copy() nums_temp.remove(num) if len(nums_temp) > 0: # 将剩余数字的全排列并在num后面,组成全排列 results_return = self.permute(nums_temp) for result_return in results_return: result_add = [num] result_add.extend(result_return) result_1.append(result_add) else: result_1.append([num]) return result_1 if __name__ == "__main__": x = [1, 2, 3] print(Solution().permute(x))
fdbf71daa06bb8efedd5d791010bb3670f752303
stephenjjones/perceptron-python
/perceptron.py
2,340
4.0625
4
import numpy as np class Perceptron(object): """A perceptron classifier implementation Could be extended to use more than 2 classes by way of the One-vs-All technique Parameters: learn_rate (float): The learning rate between 0.0 and 1.0 epochs (int): The number of epochs/iterations over the training set Attributes: w_ (1d-array): Weights after fitting errors_ (list): Number of misclassifications in every epoch. """ def __init__(self, learn_rate=0.01, epochs=10): self.learn_rate = learn_rate self.epochs = epochs def fit(self, X, y): """Fit the training data. Args: X (array-like shape = [n_samples, n_features]: Training vectors, where n_samples is the number of samples and n_features is the number of features. y (array-like, shape = [n_samples]: Target values Returns: object """ # initialize weights to zero vector R^(m+1), where m = num of dimensions, +1 for threshold self.w_ = np.zeros(1 + X.shape[1]) self.errors_ = [] for _ in range(self.epochs): errors = 0 # loop over training set and update weights according to learning rule for xi, target in zip(X, y): update = self.learn_rate * (target - self.predict(xi)) self.w_[1:] += update * xi self.w_[0] += update errors += int(update != 0.0) # Collect number of misclassifications in each epoch self.errors_.append(errors) return self def net_input(self, X): """Calculate the net input Calculates the vector dot product (w^T)x .. math:: w^{-1} \cdot x Args: X: Training set Returns: """ return np.dot(X, self.w_[1:]) + self.w_[0] def predict(self, X): """Predicts the class label after unit step - Called from the fit function to predict the class label for the weight update - Also used to predict class labels for new data Args: X: Returns: """ return np.where(self.net_input(X) >= 0.0, 1, -1)
32baf246d2fe954d8128bde029dde918b1766825
MiroslavPK/Python-Advanced
/02 - Sets and tuples/Exercise/05-Phonebook.py
880
3.890625
4
phonebook = set() while True: tokens = input() if tokens.isdigit(): break name, phone_number = tokens.split('-') phonebook.add((name, phone_number)) for _ in range(int(tokens)): name = input() if not any(name in contact for contact in phonebook): print(f'Contact {name} does not exist.') continue for contact in phonebook: if name in contact: print(f'{name} -> {contact[1]}') # simpler but slower solution using dictionary # phonebook = {} # # while True: # tokens = input() # if tokens.isdigit(): # break # name, phone_number = tokens.split('-') # phonebook[name] = phone_number # # for _ in range(int(tokens)): # name = input() # if name not in phonebook: # print(f'Contact {name} does not exist.') # continue # print(f'{name} -> {phonebook[name]}')
723c9a23af13e41be2da20bfef84e20be13d2639
CapSOSkw/My_leetcode
/leetcode/205. Isomorphic Strings.py
1,178
4.03125
4
''' Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. Example 1: Input: s = "egg", t = "add" Output: true Example 2: Input: s = "foo", t = "bar" Output: false Example 3: Input: s = "paper", t = "title" Output: true Note: You may assume both s and t have the same length. ''' from collections import defaultdict, Counter class Solution: def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ ds = defaultdict(list) dt = defaultdict(list) for idx, c in enumerate(s): ds[c].append(idx) for idx, c in enumerate(t): dt[c].append(idx) ls = [i for i in ds.values()] lt = [i for i in dt.values()] return sorted(ls) == sorted(lt) if __name__ == '__main__': s = 'paper' t = 'title' sol = Solution() print(sol.isIsomorphic(s, t))
7bea8962649bdbb2a3074db92cc23efe431d2012
HelixPark/LeetCodeProjects
/60_PermutationSequence.py
645
3.765625
4
import math def getPermutation(n,k): res=[] nums=[i for i in range(1,n+1)] while n-1 >= 0: # num, k =k // math.factorial(n-1), k % math.factorial(n-1) num =k//math.factorial(n-1) k=k%math.factorial(n-1) if k>0: #不能整除,则只是当前的一个 res.append(str(nums[num])) nums.remove(nums[num]) else: #能整除,则往前推一个的末尾元素 res.append(str(nums[num-1])) nums.remove(nums[num-1]) n -= 1 return ''.join(res) #将序列res的字符以''连接成字符串 print(getPermutation(3,3))
38682cd09e376b824df57b67178c086cfc93fd16
sachin156/Design-Patterns-Python
/Code/prototype.py
670
3.671875
4
import copy class Prototype: def __init__(self): self.objects={} def register_object(self,name,obj): self.objects[name]=obj def unregister_object(self,name): del self.objects[name] def clone(self,name,**attr): obj=copy.deepcopy(self.objects.get(name)) obj.__dict__.update(attr) return obj class Car: def __init__(self): self.name="tesla" self.color="Red" self.options="ex" def __str__(self): return (self.name,self.color,self.options) c=Car() prototype=Prototype() prototype.register_object("tesla",c) c1=prototype.clone("tesla") print(c1)
e61f24141d59bf7b266f49222e4a78fd53d2f412
harry2002731/Stock-programe
/stock_list_convert.py
1,627
3.515625
4
import pandas import SQLserver """获取所有股票的名称和代码 ts_code--股票代码有SZ,SH symbol--股票代码无SZ,SH name--名称 area--所属区域 industry--行业 market--板块 list_date--上市日期""" class Dataframe_reader(): def __init__(self, df): self.df = df self.line_num = 0 self.length = 0 self.header_list = [] def character(self): # self.df = pandas.read_csv("stock_basics.csv", encoding='utf-8') self.length = len(self.header_list) # 列数 values = [0 for j in range(self.length)] for i in range(self.length): values[i] = str(self.df.iloc[self.line_num][self.header_list[i]]) return values def add_data(self): for text in self.df.columns: self.header_list.append(str(text)) while self.line_num < len(self.df): value_list = self.character() server=SQLserver.DataServer_Sqlite3() val='\'%s\',' * (self.length - 2) + '\'%s\'' # print("insert into stock_list " + f"({'%s,'*(self.length-2)+'%s'})" % tuple(self.header_list[1:]) + " values " + f"({'})" % tuple(value_list[1:])) try: server.Sql_execution("insert into stock_list " + f"({'%s,'*(self.length-2)+'%s'})" % tuple(self.header_list[1:]) + " values " + f"({val})" % tuple(value_list[1:])) except Exception: break self.line_num += 1 if __name__ == '__main__': Dataframe_reader(pandas.read_csv("stock_basics.csv", encoding='utf-8')).add_data()
00a156fa107365c19fd58be7229f54577266b79f
denkho/CourseraPython
/week7/13_most_frequent_word.py
312
3.59375
4
fin = open('input_most_frequent_word.txt', 'r') text = fin.readlines() words = list() for line in text: words.extend(line.split()) count_words = dict() for word in words: count_words[word] = count_words.get(word, 0) + 1 print(sorted(count_words, key=lambda x: (-count_words[x], x))[0]) fin.close()
015629ef54451effa2870d7aff5485fcc60486f1
RakeshKumar045/Artificial_Intelligence_Complete_1
/Artificial_Intelligence/Complete_AI_DS_ML_DL_NLP/Complete-DS-ML-DL-PythonInterview/algorithms-master/breadth_first_search.py
873
3.8125
4
from collections import deque graph = {} graph['you'] = ['alice', 'bob', 'claire'] graph['alice'] = ['peggy'] graph['bob'] = ['anuj'] graph['claire'] = ['jonny', 'thom'] graph['peggy'] = [] graph['anuj'] = [] graph['jonny'] = [] graph['thom'] = [] def is_person_seller(name): '''look for a person using arbitrary criteria''' return name[-1] == 'z' def search(name, graph): '''Implementing breadth-first search algorithm''' search_queue = deque() search_queue += graph[name] searched_people = [] while search_queue: person = search_queue.popleft() if person not in searched_people: if is_person_seller(person): return f'{person} is seller' else: searched_people.append(person) search_queue += graph[person] return 'There is no seller within your network'
454b0abbaedaba6a710470ebcb75836691bb4be4
Clipboard-Karl/Sudoku-Fun-Project
/Sudoku_rev02.py
3,476
3.671875
4
# Sudoku_rev02.py - Sudoku Problem solver # # 20200730 - Successfully check and solving if a row has a single zero # Saving this and moving to Sudoku_rev03.py for columns :) # 20200729 - New revisoin because the code was working and I don't want # to mess that up when I introduce a do while true loop # 20200726 - Renamed this because I messed this up beyond recovery. # 20200725 - started converting to functions - code not working with pushed # 20200720 - I moved the code out of the 100DaysOfCode. It will be easier to # track it this way. Converted input to numpy ## # ################################################################################ # # Needed to open the input file import os # Used to process the input file import pandas # To work with arrays import numpy as np #------------------------------------------------------------------------------- def missing_number(zeros_removed): for missing in range(1, 10): if missing in zeros_removed: print(missing," is on the list") else: # print(missing, "is the missing number") # x = missing return missing def check_row(row_y): get_row = sudoku_9x9_in[row_y] print("Row Y=",row_y," = ",get_row) sort_row = np.sort(get_row) # print(sort_row) zeros_removed = sort_row[sort_row > 0] # print("In the loop") return zeros_removed #------------------------------------------------------------------------------- # Read input file and store in a 9x9 numpy array sudoku_9x9_in=np.genfromtxt("9x9_in.csv", delimiter=',') sudoku_9x9_in=sudoku_9x9_in.astype('int32') #print(sudoku_9x9_in) point_x = 0 point_y = 0 while True: # Read from top right to bottom left #while point_x < 9: #while point_x in range(0,9): point = sudoku_9x9_in[point_y,point_x] print("Y=",point_y," X",point_x," value = ",point) if point == 0: # print(point," We found a zero!") # print("zero Found - Location: Y=",point_y," X=",point_x) zeros_removed = check_row(point_y) # print(zeros_removed) if len(zeros_removed) == 8: print("Single Zero Found: Y=",point_y," X=",point_x) x = missing_number(zeros_removed) # print("Returned missing number is ",x) # print(sudoku_9x9_in[point_y,point_x]) sudoku_9x9_in[point_y,point_x] = x # print(sudoku_9x9_in[point_y,point_x]) # break print("End of solve:",x,"at Y=",point_y," X=",point_x) print("The answer:") print(sudoku_9x9_in) point_y += 1 point_x = 0 continue #forces restart of loop else: print("Multiple zeros next row") point_y += 1 point_x = 0 continue # else: # print(point," was found Y=",point_y," X",point_x) point_x += 1 if point_x == 9: point_x = 0 point_y += 1 if point_y == 9: break # print("Y=",point_y," X=",point_x," at While end") #row_list = remove_0_from_row #print(row_list) #print(len(row_list)) #if len(row_list) == 8: # x = missing_number(row_list) # print("Returned missing number is ",x) #print(check_3x3) print("The answer:") print(sudoku_9x9_in)
098a39ffe4fefd0c5334ad14ef3d62afed73f502
Anju-PT/pythonfilesproject
/collections/list/evenlist.py
73
3.546875
4
lst=[1,2,3,4,5,6,7,8,9,10] for i in lst: if(i%2==0): print(i)
7752321a231de0c258fd1de03c8a1895d60ed381
francescaser/https---github.com-francescaser-Sudoku
/creazMatrice.py
534
3.640625
4
import numpy as np import random sudoku=np.array([[1,2,3,4,5,6,7,8,9],[7,8,9,1,2,3,4,5,6],[9,7,8,2,3,1,6,4,5],[8,9,7,3,1,2,5,6,4],[2,3,1,6,4,5,8,9,7],[5,6,4,9,7,8,2,3,1],[3,1,2,5,6,4,9,7,8],[6,4,5,8,9,7,3,1,2]]) print(sudoku) for i in range(81): val1=random.randint(1,9) val2=random.randint(1,9) for i in range(0,9): for j in range(0,9): if sudoku[i][j]==val2: sudoku[i][j]=val1 elif sudoku[i][j]==val1: sudoku[i][j]=val2 print(sudoku)
450c49702667eea9288c5f28b9debbe6007f2278
pwgraham91/Python-Exercises
/compare triplets.py
399
3.734375
4
""" Given 2 lines: A: 5 6 7 B: 3 6 10 Compare by spots in line giving points to line A if it is higher and line B if it is higher and no points if they're tied Input: 5 6 7 3 6 10 Output: 1 1 """ a = [5, 6, 7] b = [3, 6, 10] a_points = 0 b_points = 0 for i in range(len(a)): if a[i] > b[i]: a_points += 1 elif a[i] < b[i]: b_points += 1 print(a_points) print(b_points)
5b07504b15981892e8efa4ad2be2d48a828b7a62
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_34/414.py
1,195
3.640625
4
#!/usr/bin/env python import sys file = open(sys.argv[1]) word_length, num_words, num_cases = map(int, file.readline().split()) def substrings(case): strings = [] paren_flag = False substring = '' for char in case: if char == '(': paren_flag = True substring = '' elif char == ')': paren_flag = False strings.append(substring) elif paren_flag: substring += (char) else: strings.append(char) return strings def num_matching_words(case): matches = 0 case_strings = substrings(case) for word in words: match_flag = True for i in xrange(word_length): if word[i] not in case_strings[i]: match_flag = False break if match_flag: matches += 1 return str(matches) words = [] for i in xrange(num_words): words.append(file.readline().rstrip('\n')) cases = [] for i in xrange(num_cases): cases.append(file.readline().rstrip('\n')) case_number = 0 for case in cases: case_number += 1 print 'Case #' + str(case_number) + ': ' + num_matching_words(case)
3c9f06d8e97cde3c8ca808a1ed96c14ff3dbd8e1
ramdevcm/LinkedListPy
/main.py
1,651
3.765625
4
import copy class Node: def __init__(self, data): self.data = data self.next = None def __str__(self): return "Node[]: {}".format(self.data) class LinkedList: def __init__(self, data): self.head = Node(data) self.tail = None def getHead(self): return self.head def setHead(self, head): self.head = head def insert(self, data): node = Node(data) head = self.head if head.data is None: head.data = data return ptr = head while ptr.next != None: ptr = ptr.next ptr.next = node def insert_at_start(self, data): node = Node(data) node.next = self.head self.head = node def insert_at_index(self, index, data): head = self.head if head.data is None: head.data = data return if index == 0: self.insert_at_start(data) return i = 0 ptr = head while i + 1 != index : ptr = ptr.next if ptr == None: raise Exception("Limit of Linked List Exceeded: Overflow") return i+=1 node = Node(data) temp = ptr.next ptr.next = node node.next = temp def display(self): ptr = copy.copy(self.head) ans = [] while ptr: ans.append(str(ptr.data)) ptr = ptr.next print("->".join(ans)) def reverse(self): prev = None current = self.head while (current is not None): n = current.next current.next = prev prev = current current = n self.head = prev Link = LinkedList(1) for _ in range(2,11): Link.insert(_) Link.display() Link.reverse() Link.display() Link.reverse() Link.display()
09c0bf4823cde25d52ca8a8c6a1e9aba15a03820
dustin181/javareference
/docs/python algorithms/mine/leetcode50/coin_change.py
432
3.59375
4
from typing import List def coinChange(coins: List[int], amount: int) -> int: if amount <= 0: return 0 if min(coins) > amount: return -1 dp = [0] + [float('inf')] * amount for coin in coins: for i in range(coin, amount + 1): dp[i] = min(dp[i], dp[i - coin] + 1) return dp[-1] if dp[-1] != float('inf') else -1 input = [2,5] amount = 11 print(coinChange(input, amount))
9823ca8948ae57f964c8537d5fe883f9f0f45f0a
aryajar/practice-in-7-23
/number100.py
155
4.1875
4
number = int(input("Enter a number: ")) if number < 100: print("the number less than 100") else: print("the number not less than 100")
ba7b3357e4215ab413a6b238d7ee557a164fa2c6
Crypto0/Crypt0Lib-V1
/crypt0/base/decimal_ascii.py
277
3.796875
4
import re def decimal_to_ascii(decimal): try: s = re.sub('3[2-9]|[4-9][0-9]|1[0-1][0-9]|12[0-6]', r' \g<0>', decimal) ascii = ''.join(chr(int(x)) for x in s.split()) return ascii except ValueError: return "Sorry! This is not a Decimal."
47c99b6c992c6cfe74660805fd1bab2f29d5ea26
qordpffla12/p1_201011101
/sumList.py
192
3.53125
4
 def sumList(list): sum=0 for i in range(0, len(list)): sum+=list[i] return sum def lab7(): x=[1,2,3] mysum=sumList(x) print mysum def main() lab7()
f5badb09ea0012dac635957de6e66bb0134b1775
lalobaez120304/actividad-1-y-2
/diccionarios.py
1,388
4.34375
4
""" ES una lista de pares de elementos con estructura clave:valor No se accesa a los elementos por posicion, sino por el valor de su clave La clave puede ser de cualquier tipo imutable (bolean, integer, string, etc.) Se delimita con {} A un diccionario se le refiere tambien como dict """ #creacion de diccionarios diccionario_vacio ={} diccionario_citas ={" ICalla":"wakanda forever", "Thanos":"the hardest choices requiere the strongest wills", "AMLO":"me canso ganso"} print(diccionario_citas) pass #accesar elementos print(diccionario_citas["Thanos"]) pass #agregar elementos:se agrega la nueva llave y se indica su valor print("x" * 20) diccionario_citas["plankton"] = "¡por fin tengo la formula de la cangreburger" print(diccionario_citas) pass #eliminar elementos de un diccionario print("x" * 20) del diccionario_citas["AMLO"] print(diccionario_citas) pass #opciones para obtener el volcado de un diccionario, #en cada una, la respuesta debe convertirse a una lista primero #para un mas facil manejo #opcion 1 todas las claves, solamente las claves print(list(diccionario_citas.keys())) pass #opcion 2 todos los valores, solamente los valores print(list(diccionario_citas.values())) pass #opcion 3 todos los elementos, elemento por elemento print(list(diccionario_citas.items()))
65646568cb9efe59355dd5dbb3cc36dcfb7dbae3
tashakim/puzzles_python
/min_stack.py
545
3.859375
4
class MinStack: """Purpose: Design a stack which, in addition to pop and push, has a function min that returns the minimum element in O(1). (CTCIpg98_3.2) """ def __init__(self): self._data = [] self._min = float('inf') return def pop(self): """Runtime: O(1). """ # raise EmptyStackException if empty self._data.pop(-1) return def push(self, item): """Runtime: O(1). """ self._data.append(item) if(item < self._min): self._min = item return def min(self): """Runtime: O(1). """ return self._min
6e26c1666d84a4c2972a585ec950ce37b169e3f0
clouds16/intro-python
/week6/unique_list.py
656
3.8125
4
class Sequence: def createList(self): usernumbers = [] usernumbers.append((int(input("Enter the first number: ")))) while True: userinput = int(input("Next: ")) if userinput != -1 : usernumbers.append(userinput) else: break print(usernumbers) return usernumbers def sequenceCheck( self, userList): if len(userList) == len(set(userList)): print("No Duplicates found" ) else: print("Duplicates found") def run(self): self.sequenceCheck(self.createList()) Sequence().run()
1b388de0457eeaaf76b7eeb44a1683565852e38d
codeAligned/codewar-python
/6.py
1,119
3.640625
4
# https://www.codewars.com/kata/57814d79a56c88e3e0000786/train/python def encrypt_hzzz(text, n): print(text, n) if n <= 0: return text for j in range(n): lst = [text[i] for i in range(len(text)) if i % 2] lst += [text[i] for i in range(len(text)) if not i % 2] text = ''.join(lst) return ''.join(lst) def decrypt_hzzz(encrypted_text, n): print(encrypted_text, n) if n <= 0: return encrypted_text for j in range(n): left = encrypted_text[:int(len(encrypted_text)/2)] right = encrypted_text[int(len(encrypted_text)/2):] encrypted_text = [left[int(i/2)] if i % 2 else right[int(i/2)] for i in range(len(encrypted_text))] return ''.join(encrypted_text) # 别人家的 def decrypt(text, n): if text in ("", None): return text ndx = len(text) // 2 for i in range(n): a = text[:ndx] b = text[ndx:] text = "".join(b[i:i + 1] + a[i:i + 1] for i in range(ndx + 1)) return text def encrypt(text, n): for i in range(n): text = text[1::2] + text[::2] return text
61953f67e2923a32770192db955dc8cfe8e993de
TomiSar/ProgrammingMOOC2020
/osa07-06_salasanan_arpoja_2/src/salasanan_arpoja2.py
1,153
3.546875
4
from random import choice, randint from string import ascii_lowercase, digits def luo_hyva_salasana(pituus: int, numero: bool, erikoismerkki: bool): erikoismerkit = "!?=+-()#" # alkuun yksi kirjain salasana = choice(ascii_lowercase) arvontajoukko = ascii_lowercase # Jos halutaan numeroita, lisätään vähintään yksi if numero: salasana = lisaa_merkki(salasana, digits) arvontajoukko += digits # sama erikoismerkille if erikoismerkki: salasana = lisaa_merkki(salasana, erikoismerkit) arvontajoukko += erikoismerkit # Kasataan loppu salasana koko arvontajoukosta while len(salasana) < pituus: salasana = lisaa_merkki(salasana, arvontajoukko) return salasana # Lisää satunnaisen merkin annetusta joukosta joko merkkijonon alkuun tai loppuun def lisaa_merkki(salasana: str, merkit): merkki = choice(merkit) if randint(1, 2) == 1: return merkki + salasana else: return salasana + merkki #main if __name__ == "__main__": for i in range(10): print(luo_hyva_salasana(8, True, True))
659865fa15adca3e57d1fd443dca223d9ebed17e
rohitjenveja/sample_django_trie
/vsnlookup/validation.py
1,677
3.546875
4
#!/usr/bin/python """Server-side validation logic that can be used before creating, updating, or reading from a data source. In addition to server side validation logic, there is also client-side validation in the javascript. """ __author__ = "rjenveja@gmail.com (Rohit Jenveja)" import re VALIDATE_REGEX = "^[A-Z*]{6}[0-9*]{6}$" def ValidateVSN(expression): """Validates a vsn passes the regex check to ensure its properly formatted. Args: expression: A string to check. Returns: A boolean value indicating whether its passed the regex expression. """ compiled = re.compile(VALIDATE_REGEX) result = compiled.match(expression) if result: return True return False def ValidVSNList(items): """Validates a list of VSNs in string format. Args: items: A list of strings of VSNs to be validated. Returns: A subset of the list containing only valid VSNs. """ return [item for item in items if ValidateVSN(item)] def FewestWildcards(matched_values): """Returns a list of the items that have the fewest wildcards. Args: match_values: All valid VSNs. Returns: A list of VSNs with the fewest wildcards. It can return multiple VSNs, if they have an equal number of wildcards. """ min_key_value = [] for value in matched_values: count = value.count('*') if not min_key_value: min_key_value = [[value], count] elif count < min_key_value[1]: # compare count of previous min_key_value min_key_value = ([value], count) # Handle the case where same number of wildcards in two expressions. elif count == min_key_value[1]: min_key_value[0].append(value) return min_key_value[0]
8918ae1c0d2a79307a933e59c29ef26d27d3a347
swang2000/DP
/maxsubonematrix.py
816
3.734375
4
''' Maximum size square sub-matrix with all 1s 3.3 Given a binary matrix, find out the maximum size square sub-matrix with all 1s. For example, consider the below binary matrix. maximum-size-square-sub-matrix-with-all-1s ''' import numpy as np def maxonematrix(a): r,c = a.shape smatrix = np.zeros((r, c)) smatrix[0,:] = a[0,:] smatrix[:,0] = a[:, 0] izero = (a==0) smatrix[izero] = 0 for i in range(1,r): for j in range(1, c): if a[i,j] == 1: smatrix[i,j] = min(smatrix[i-1, j-1],smatrix[i-1, j], smatrix[i, j-1]) + 1 return smatrix.max() a = np.array([[0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]]) maxonematrix(a)
cc573d4800f8a697e1eb6ce005b0a21dfb6853f1
jkoppel/QuixBugs
/correct_python_programs/quicksort.py
470
4.09375
4
def quicksort(arr): if not arr: return [] pivot = arr[0] lesser = quicksort([x for x in arr[1:] if x < pivot]) greater = quicksort([x for x in arr[1:] if x >= pivot]) return lesser + [pivot] + greater """ def quicksort(arr): if not arr: return [] pivot = arr[0] lesser = quicksort([x for x in arr[1:] if x <= pivot]) greater = quicksort([x for x in arr[1:] if x > pivot]) return lesser + [pivot] + greater """
1ba7588886a47524678c16a9bf989bc529cd8c66
kbudukiewicz/ASEiED_project
/test_pandas.py
1,710
4.21875
4
""" Test program to load data from .csv and get the average speed of the month. """ import pandas as pd def read_data(file: str) -> pd.DataFrame: """Get data from csv file. Args: file: name of the file Returns Dataframe with use columns. """ df = pd.read_csv( file, usecols=["lpep_pickup_datetime", "lpep_dropoff_datetime", "trip_distance"] ) return df def prepare_df(file: str) -> pd.DataFrame: """Args: Calculate average month speed. Calculate time of the pick up, speed of the drive and average speed in the month. Args: file: name of the file Returns: Dataframe with important value. df = ["lpep_pickup_datetime", "lpep_dropoff_datetime", "trip_distance", "time_lpep", "speed"] """ df = read_data(file) df["lpep_pickup_datetime"] = pd.to_datetime(df["lpep_pickup_datetime"]) df["lpep_dropoff_datetime"] = pd.to_datetime(df["lpep_dropoff_datetime"]) df["time_lpep"] = ( df["lpep_dropoff_datetime"] - df["lpep_pickup_datetime"] ).dt.total_seconds() / 3600 df["speed"] = df["trip_distance"] / df["time_lpep"] return df def get_average_speed(file: str): """Get average of the speed. Args: file: name of the file Returns: Average of the speed. """ df = prepare_df(file) avg = df["trip_distance"].sum() / df["time_lpep"].sum() return avg if __name__ == "__main__": # FILE = 'D:\studia\Semestr_6\Autonomiczne Systemy Ekspertyzy i Eksploracji Danych\Projekt_2\Dane\green_tripdata_2019-05.csv' FILEa = "/Users/konradbudukiewicz/Downloads/green_tripdata_2019-05.csv" print(get_average_speed(FILEa))