blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
3d9fd4aebb9f1e3e4f40bd730feea960da85ddd0
KaranPuro/present
/main.py
460
3.65625
4
import turtle turtle.speed(0) turtle.bgcolor("black") for i in range(5): for colors in ["red", "magenta", "blue", "cyan", "green", "yellow", "white"]: turtle.color(colors) turtle.pensize(3) turtle.left(12) turtle.forward(200) turtle.left(90) turtle.forward(200) turtle.left(90) turtle.forward(200) turtle.left(90) turtle.forward(200) turtle.left(90)
bc61fdd346da53b308c9289e32e2b69f49240262
jasmingeorge/PythonProjects
/myPyFiles/ex16.py
568
3.859375
4
from sys import argv script, filename = argv print "Erase %r." % filename print "hit CTRL^C to cancel" print "hit ENTER to proceed" raw_input("?") print "Opening file" target = open(filename, 'w') print "Truncate file" target.truncate() print "Write 3 lines" line1 = raw_input("Line 1 : ") line2 = raw_input("Line 2 : ") line3 = raw_input("Line 3 : ") print "going to write these to files" target.write(line1+"\n"+line2+"\n"+line3+"\n") print "Close" target.close() print "Open %r for reading" % filename file = open(filename, 'r') txt = file.read() print txt
969c65b56454444a60a5364516fc17bd2027dd7d
Gikkman/retool
/modules/titleutils.py
9,457
3.875
4
import re import sys from modules.utils import Font def check_date(string, title): """ Basic date validation """ months = [ 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december' ] if re.search('|'.join(months), title) != None: for i, month in enumerate(months): if (i < 8): title = re.sub(f'{month}, ', f'0{i + 1}-01-', title) else: title = re.sub(f'{month}, ', f'{i + 1}-01-', title) if re.search('\(\d{2}-\d{2}-\d{4}\)', title) != None: us_date = True else: us_date = False if re.search('\(\d{2}-\d{2}-\d{2}\)', title) != None: short_date = True else: short_date = False title = title.replace(re.search(string, title)[0], re.search(string, title)[0].replace('-', '')) if short_date == True: string = '\(\d{6}\)' year = 1900 + int(re.search(string, title).group()[1:-5]) month = re.search(string, title).group()[3:-3] day = re.search(string, title).group()[5:-1] elif us_date == True: year = re.search(string, title).group()[5:-1] month = re.search(string, title).group()[1:-7] day = re.search(string, title).group()[3:-5] else: year = re.search(string, title).group()[1:-5] month = re.search(string, title).group()[5:-3] day = re.search(string, title).group()[7:-1] if ( int(year) >= 1970 and int(month) >= 1 and int(month) <= 12 and int(day) >= 1 and int(day) <= 31): return int(year + month + day) else: return False def get_title_count(titles, is_folder): """ Gets the final title count """ final_title_count = 0 if len(titles.all) == 0: if is_folder == False: sys.exit() else: return 0 else: for group, disc_titles in titles.all.items(): for title in disc_titles: final_title_count += 1 return final_title_count def get_languages(title, REGEX_LANGUAGES): """ Returns the languages from the input title """ languages = re.search(REGEX_LANGUAGES, title) if languages != None: return languages[0][2:-1] else: return '' def get_raw_title(title): """ Returns the raw title, or 'group' of the input title """ if title.find('(') != -1: return title[:(title.find('(') - 1)].rstrip().lower() else: return title.rstrip().lower() def get_short_name(region_data, REGEX, tag_free_name=False, full_name=False, user_input=None): """ Returns the short name of the input title """ if tag_free_name == False: tag_free_name = get_tag_free_name(full_name, user_input, REGEX) short_name = remove_regions(remove_languages(tag_free_name, REGEX.languages), region_data) return short_name def get_tag_free_name(title, user_input, REGEX): """ Returns the tag free name of the input title """ tag_free_name = title # Normalize disc names for key, value in user_input.tag_strings.disc_rename.items(): if key in tag_free_name: tag_free_name = tag_free_name.replace(key, value) # Strip out other tags found in tags.json tag_free_name = remove_tags(tag_free_name, user_input, REGEX) return tag_free_name def remove_languages(title, REGEX_LANGUAGES): """ Removes languages from the input title """ no_languages = re.search(REGEX_LANGUAGES, title) if no_languages != None: return title.replace(no_languages[0], '') else: return title def remove_regions(title, region_data): """ Removes regions from the input title, given the title and region_data object """ return title.replace(re.search(' \(((.*?,){0,} {0,})(' + '|'.join(region_data.all) + ').*?\)', title)[0],'') def remove_tags(title, user_input, REGEX): """ Removes tags from the input title that are in internal-config.json """ for string in user_input.tag_strings.ignore: if re.search(string, title) != None: if string == REGEX.dates_whitespace and check_date(REGEX.dates, title) != False: title = title.replace(re.search(REGEX.dates_whitespace, title)[0], '') else: title = title.replace(re.search(string, title)[0],'') return title def report_stats(stats, titles, user_input, input_dat): """ Print the final stats to screen """ print( '\nStats:\no Original title count: ' f'{str("{:,}".format(stats.original_title_count))}') if user_input.legacy == True: print(f'o Titles assigned as clones: {str("{:,}".format(stats.clone_count))}') else: print(f' - Clones removed: {str("{:,}".format(stats.clone_count))}') if user_input.no_add_ons == True: print( ' - Add-on titles removed: ' f'{str("{:,}".format(stats.add_on_count))}') if user_input.no_applications == True: print( ' - Applications removed: ' f'{str("{:,}".format(stats.applications_count))}') if user_input.no_audio == True: print( ' - Audio titles removed: ' f'{str("{:,}".format(stats.audio_count))}') if user_input.no_bad_dumps == True: print( ' - Bad dumps removed: ' f'{str("{:,}".format(stats.bad_dump_count))}') if user_input.no_bios == True: print( ' - BIOSes and other chips removed: ' f'{str("{:,}".format(stats.bios_count))}') if user_input.no_bonus_discs == True: print( ' - Bonus discs removed: ' f'{str("{:,}".format(stats.bonus_discs_count))}') if user_input.no_coverdiscs == True: print( ' - Coverdiscs removed: ' f'{str("{:,}".format(stats.coverdiscs_count))}') if user_input.no_demos == True: print( ' - Demos removed: ' f'{str("{:,}".format(stats.demos_count))}') if user_input.no_educational == True: print( ' - Educational titles removed: ' f'{str("{:,}".format(stats.educational_count))}') if user_input.no_manuals == True: print( ' - Manuals removed: ' f'{str("{:,}".format(stats.manuals_count))}') if user_input.no_multimedia == True: print( ' - Multimedia titles removed: ' f'{str("{:,}".format(stats.multimedia_count))}') if user_input.no_pirate == True: print( ' - Pirate titles removed: ' f'{str("{:,}".format(stats.pirate_count))}') if user_input.no_preproduction == True: print( ' - Preproduction titles removed: ' f'{str("{:,}".format(stats.preproduction_count))}') if user_input.no_promotional == True: print( ' - Promotional titles removed: ' f'{str("{:,}".format(stats.promotional_count))}') if user_input.no_unlicensed == True: print( ' - Unlicensed titles removed: ' f'{str("{:,}".format(stats.unlicensed_count))}') if user_input.no_video == True: print( ' - Video titles removed: ' f'{str("{:,}".format(stats.video_count))}') if stats.remove_count > 0: print( ' - Titles removed as defined by clone list: ' f'{str("{:,}".format(stats.remove_count))}') if stats.custom_global_exclude_filter_count > 0: print( ' - Titles removed due to custom global filter: ' f'{str("{:,}".format(stats.custom_global_exclude_filter_count))}') if stats.custom_system_exclude_filter_count > 0: print( ' - Titles removed due to custom system filter: ' f'{str("{:,}".format(stats.custom_system_exclude_filter_count))}') if (len(input_dat.soup.find_all('game'))) > 0: print( ' - Titles removed due to country filters: ' f'{str("{:,}".format(len(input_dat.soup.find_all("game"))))}') if 'Filtered languages' in user_input.recovered_titles: if (len(user_input.recovered_titles['Filtered languages'])) > 0: print( ' - Titles removed due to language filters: ' f'{str("{:,}".format(len(user_input.recovered_titles["Filtered languages"])))}') if (stats.recovered_count) > 0: print( ' + Titles recovered due to include filters: ' f'{str("{:,}".format(stats.recovered_count))}') if 'Unknown' in user_input.user_region_order: if len(titles.regions['Unknown']) > 1: print( ' + Titles without regions included: ' f'{str("{:,}".format(len(titles.regions["Unknown"])))}') print(f'\n- Total titles removed: {str("{:,}".format(stats.original_title_count - stats.final_title_count))}') print(f'{Font.bold}---------------------------') print(f'= New title count: {str("{:,}".format(stats.final_title_count))}{Font.end}')
4cc5e4aa3463e07ce239339aac99d5821ec786a1
ashok148/TWoC-Day1
/program3.py
423
4.34375
4
#Program to swap two variable without using 3rd variable.... num1 = int(input("Enter 1st number : ")) num2 = int(input("Enter 2nd number : ")) print("Before swaping") print("num1 = ",num1) print("num2 = ",num2) print("After swapping") #LOGIC 1:- of swapping # num1 = num1 + num2 # num2 = num1 - num2 # num1 = num1 - num2 #LOGIC 2:- of swapping num1,num2 = num2,num1 print("num1 = ",num1) print("num2 = ",num2)
8a88fc14eb9a78ea6a0aa1c52ed8dd40903b18ec
oswaldo-mor/Tarea_04
/Descuentos.py
923
3.8125
4
#Encoding UTF-8 #Oswaldo Morales Rodriguez #Conociendo la cantida comprada dar el total def calcularDescuento(cantidadPaquetes): if (cantidadPaquetes>=10) and (cantidadPaquetes<=19): descuento=(cantidadPaquetes*1500)*0.20 elif (cantidadPaquetes>=20) and (cantidadPaquetes<=49): descuento=(cantidadPaquetes*1500)*0.30 elif (cantidadPaquetes>=50) and (cantidadPaquetes<=99): descuento=(cantidadPaquetes*1500)*0.40 elif (cantidadPaquetes>=100): descuento=(cantidadPaquetes*1500)*0.50 elif(cantidadPaquetes<0): descuento=("Error") else: descuento=0 return descuento def main(): cantidadPaquetes=int(input("Paquetes comprados")) descontado=calcularDescuento(cantidadPaquetes) subtotal=cantidadPaquetes*1500 total=subtotal-descontado print("El subtotal es",subtotal) print("El descuento es", descontado) print("El total es",total) main()
7f408dbc4d2894e0c9aa72b384e25951c7316e9a
snifhex/dsa
/data_structures/stacks/stack.py
2,079
3.53125
4
from abc import ABC, abstractmethod from collections import deque from queue import LifoQueue from typing import NoReturn class StackBase(ABC): length = 0 bucket = None def push(self, element) -> NoReturn: self.bucket.append(element) self.set_length() def pop(self): poped_value = self.bucket.pop() self.set_length() return poped_value def top(self): if self.length: return self.bucket[0] def lastitem(self): return self.bucket[-1] def is_empty(self) -> bool: return len(self.bucket) == 0 def set_length(self) -> NoReturn: self.length = len(self.bucket) def __repr__(self): return str([elements for elements in self.bucket]) @abstractmethod def __init__(self): pass class ListStack(StackBase): def __init__(self): self.bucket = [] self.set_length() class DequeStack(StackBase): def __init__(self): self.bucket = deque() self.set_length() class LifoQueueStack(StackBase): def __init__(self) -> NoReturn: self.bucket = LifoQueue() self.set_length() def push(self, element) -> NoReturn: self.bucket.put(element) self.set_length() def pop(self): if self.length: poped_value = self.bucket.get() self.set_length() return poped_value else: raise IndexError("pop from empty stack") def top(self): if self.length: return self.bucket.queue[0] def lastitem(self): return self.bucket.queue[-1] def set_length(self) -> NoReturn: self.length = len(self.bucket.queue) def __repr__(self): return str([elements for elements in self.bucket.queue]) def stack(**kwargs): backends = {'list':ListStack, 'deque': DequeStack, 'lqueue':LifoQueueStack} backend=kwargs.get('backend', '') if backend: return backends[backend]() else: return DequeStack()
0471b6470db0e38bd63529aa645c7a2af9da1301
Gabopic/Exodo
/Operaciones.py
326
4.03125
4
x=6 y=8 print (f'La suma es primero, por ejemplo, y+x={y}+{x}={y+x}') print (f'Luego va la resta, por ejemplo, y-x={y}-{x}={y-x}') print (f'Ahora la multiplicación, por ejemplo, y*x={y}*{x}={y*x}') print (f'Por último la división, por ejemplo, y/x={y}/{x}={y//x}') print (f'Y el resto de esta división es {y%x}')
97382d4b46211e0418e6f1db01d93b228338d90e
send2manoo/All-Repo
/myDocs/pgm/python/ml/01-LinearAlgebra/18-Reshape2Dto3DArray.py
258
3.75
4
# reshape 2D array from numpy import array # list of data data = [[11, 22], [33, 44], [55, 66]] # array of data data = array(data) print(data.shape) print data # reshape data = data.reshape((data.shape[0], data.shape[1], 1)) print(data.shape) print data
29db218d2c31b48cb39cc647ccbc02d329668d9f
send2manoo/All-Repo
/myDocs/pgm/python/ml/04-PythonMachineLearning/12-FeatureSelectionforMachineLearning/01-UnivariateSelection.py
1,130
4.0625
4
''' The scikit-learn library provides the SelectKBest class that can be used with a suite of different statistical tests to select a specific number of features. The example below uses the chi squared (chi^2) statistical test for non-negative features to select 4 of the best features from the Pima Indians onset of diabetes dataset. ''' # Feature Extraction with Univariate Statistical Tests (Chi-squared for classification) import pandas import numpy from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 # load data #url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv" url='dataset/pima-indians-diabetes.data.csv' names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = pandas.read_csv(url, names=names) array = dataframe.values X = array[:,0:8] Y = array[:,8] # feature extraction test = SelectKBest(score_func=chi2, k=6) fit = test.fit(X, Y) # summarize scores numpy.set_printoptions(precision=3) print(fit.scores_) features = fit.transform(X) # summarize selected features print(features[0:5,:])
9878feed23238d5a152e08b2547b8db64d616a35
send2manoo/All-Repo
/myDocs/pgm/python/ml/04-PythonMachineLearning/04-MatplotlibCrashCourse/01-LinePlot.py
547
4.25
4
''' Matplotlib can be used for creating plots and charts. The library is generally used as follows: Call a plotting function with some data (e.g. plot()). Call many functions to setup the properties of the plot (e.g. labels and colors). Make the plot visible (e.g. show()). ''' # The example below creates a simple line plot from one-dimensional data. # basic line plot import matplotlib.pyplot as plt import numpy myarray = numpy.array([1, 2, 3]) plt.plot(myarray) plt.xlabel('some x axis') plt.ylabel('some y axis') plt.show()
1817e0b8a951e0d4e54a8b7f20ace542ab04cb54
send2manoo/All-Repo
/myDocs/pgm/python/ml/01-LinearAlgebra/10-Two-DimensionalListofListstoArray.py
172
3.5625
4
# two dimensional example from numpy import array # list of data data = [[11, 22], [33, 44], [55, 66]] # array of data data = array(data) print(data) print(type(data))
849647385e43448924aa7108a5f4986015c0c88a
send2manoo/All-Repo
/myDocs/pgm/python/ml/03-MachineLearningAlgorithms/1-Baseline machine learning algorithms/2-Zero Rule Algorithm Classification.py
1,166
4.125
4
from random import seed from random import randrange # zero rule algorithm for classification def zero_rule_algorithm_classification(train, test): output_values = [row[-1] for row in train] print 'output=',output_values print "set=",set(output_values) prediction = max(set(output_values), key=output_values.count) ''' The function makes use of the max() function with the key attribute, which is a little clever. Given a list of class values observed in the training data, the max() function takes a set of unique class values and calls the count on the list of class values for each class value in the set. The result is that it returns the class value that has the highest count of observed values in the list of class values observed in the training dataset. If all class values have the same count, then we will choose the first class value observed in the dataset. ''' print "prediction-",prediction predicted = [prediction for i in range(len(train))] return predicted seed(1) train = [['0'], ['0'], ['0'], ['0'], ['1'], ['1']] test = [[None], [None], [None], [None]] predictions = zero_rule_algorithm_classification(train, test) print(predictions)
18bc2446ec5cf1b44629fba4f7213d5eb8e26328
send2manoo/All-Repo
/myDocs/pgm/c/Exercise/squareFunc.py
140
3.90625
4
print "Square of given No" def Square(x): return x*x getvalue=input("Enter the value") print "Square of",getvalue ,"is ",Square(getvalue)
73225a5b6e5bc8f5b5bdb5afce122d269e48ba71
lathene/test-repository
/Calendar_tkinter.py
1,012
3.828125
4
from Tkinter import * from tkcalendar import * import tkMessageBox root = Tk() # makes a calendar with current date highlighted def cal_func(): # makes a button that can be clicked to show current date def calval(): tkMessageBox.showinfo("your date is", cal.get_date()) ## top = Toplevel(root) # creates calendar with starting point cal = Calendar(root, font = "Arial 14", selectmode= "day") cal.pack(fill = "both", expand = True) ## btn1 = Button(root, text= "Click Me", command= calval) btn1.pack() ##def date_func(): ## top = Toplevel(root) ## Label(root, text= "Select Date").pack(padx = 10, pady = 10) ## ent = DateEntry(root, width = 15, backgroundcolor = "blue", foregroundcolor = "red", borderwidth = 3) ## ent.pack(padx = 10, pady = 10) ## ##btn1 = Button(root, text = "Calendar", command = cal_func) ##btn2 = Button(root, text = "DateEntry", command = date_func) ##btn1.pack() ##btn2.pack() cal_func() mainloop()
91bbe60b759a0a369fc95fd80f2a2cb3aa195aee
laurendivney/laurendivney.github.io
/Website/textAdventure.py
3,196
4.25
4
start = ''' You wake up one morning and find that you aren’t in your bed; you aren’t even in your room. You’re in the middle of a giant maze. A sign is hanging from the ivy: “You have one hour. Don’t touch the walls.” There is a hallway to your right and to your left. ''' print(start) print("Type 'left' to go left or 'right' to go right.") user_input = input() done = False while done == False: if user_input == "left": print("You decide to go left and you run into a bear.") choice = 1 done = True elif user_input == "right": print("You choose to go right and you reach a river.") choice = 2 done = True else: user_input = input("please type in either 'left' or 'right'") if choice == 1: print("Will you fight it or run away?") user_input = input() done = False while done == False: if user_input == "fight": choice = 3 print("After hours of fighting, you finally win so you keep going!") done = True elif user_input == "run": choice = 4 print("You have decided to run away.") done = True else: user_input = input("please type in either 'fight' or 'run'") if choice == 3: print("You come across a piece of cheese. Will you ignore it or eat it?") user_input = input() done = False while done == False: if user_input == "eat": choice = 9 print("it tastes good but you die three munites later since you accidentally touched the walls of the maze while you were fighting the bear.") done = True elif user_input == "ignore": choice = 10 print("you made the smart move to ignore it but you die three minutes later since you accidentally touched the walls of the maze while you were fighting the bear.") done = True else: user_input = input("please type in either 'eat' or 'ignore'") if choice == 2: print("You end up at the river and run into a ton of rats. Will you swim or fight?") user_input = input() done = False while done == False: if user_input == "swim": choice = 5 print("there was a shark in the water and you died.") done = True elif user_input == "fight": choice = 6 print("the rats bite your face off and you die!") done = True else: user_input = input("please type in either 'swim' or 'fight'") if choice == 4: print("Eventually, you reach a unicorn and a pegasus. Choose only one.") user_input = input() done = False while done == False: if user_input == "unicorn": choice = 7 print("the unicorn was actually an evil spirit in disguise. You died.") done = True elif user_input == "pegasus": choice = 8 print("the pegasus flew out of the maze and over to safety!") done = True else: user_input = input("please type in either 'unicorn' or 'pegasus'") print("The game is now over")
d526bf48950552494b1629abdab3cafb52169d4a
madiou/advent-of-code-2020
/Day09/ex9_1.py
475
3.5
4
import sys from itertools import combinations numbers = [] for line in sys.stdin: numbers.append(int(line.rstrip('\n'))) SIZE = 25 def is_valid(number, preamble): try: next(filter(lambda val: sum(val) == number, combinations(preamble, 2))) return True except StopIteration: return False for i in range(SIZE, len(numbers)): number = numbers[i] if not is_valid(number, numbers[i - SIZE:i]): print(number) break
15c86dbea3792dcb8b3a33c8c4a8dd1a46fa06c0
SnehaShree2501/HackerRankPythonPractice
/ListComprehensions.py
360
3.921875
4
x = int(input("Enter 1st co-ordinate")) y = int(input("Enter 2nd co-ordinate")) z = int(input("Enter 3rd ordinate")) n = int(input("Enter the limit")) ListOfNumbers =[] ListOfNumbers = [[i,j,k] #list for the loop control variables for i in range(0,x+1) #multiple loops running here for j in range(0,y+1) for k in range(0,z+1) if i+j+k!=n ] print(ListOfNumbers)
266756785a481734b39f3d1db67439939b98cc75
jradtkey/Python2
/namess.py
808
3.78125
4
def names(users): print "Students" for b in range(0, len(users["Students"])): name = " ".join(users["Students"][b].values()) print b+1, "-", name.upper(), "-", len(name)-1 print "Instructors" for j in range(0, len(users["Instructors"])): name = " ".join(users["Instructors"][j].values()) print j+1, "-", name.upper(), "-", len(name)-1 users = { "Students": [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], "Instructors": [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, {'first_name' : 'Martin', 'last_name' : 'Puryear'} ] } names(users)
c4afdc0729ba126f76c47e42894834f7faf02264
test12345-coder/Python
/OOP3-inheritance.py
474
3.671875
4
class Human: name = '' surname = '' length = 0 def printVar(self): print(f'{self.name} {self.surname} {self.length}') class Student(Human): grade = 0 def printVar(self): print(f'{self.name} {self.surname} {self.length} {self.grade}') if __name__ == '__main__': Ahmet = Student() Ahmet.name = 'Ahmet' Ahmet.surname = 'Sezer' Ahmet.length = 1000000 Ahmet.grade = 1000000 Ahmet.printVar()
4bd55a701ea7ffb2f5fe9f609a79aa50a5931a55
jfaccioli/python-challenge
/PyBank/main.py
2,747
3.921875
4
# Modules import os import csv # Set path for file dirname = os.path.dirname(__file__) budget_csv = os.path.join(dirname, "Resources", "budget_data.csv") # Define variables and lists total_months = 0 net_total = 0 previous_value = 0 total_change = 0 months = [] total_net = [] change_list = [] # Open the CSV with open(budget_csv) as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") # Define header header = next(csv_reader) # Create loop through csv_reader for row in csv_reader: # Define current_month, add to list, create a variable for the lenght of the month list current_month = (row[0]) months.append(current_month) months_count = len(months) # Define current_net, change_value, add change value to the change_list current_net = int(row[1]) change_value = int(current_net - previous_value) change_list.append(change_value) # Reset previous_value previous_value = int(row[1]) # Add current_net to total_net list and make the sum of that list total_net.append(current_net) net_total = sum(total_net) # Clean change_list and the months list of the first row change_list_cleaned = change_list[1:] months_cleaned = months[1:] # Define average_change average_change = round(sum(change_list_cleaned) / len(change_list_cleaned), 2) # greatest_increase and greatest_decrease greatest_increase = max(change_list_cleaned) greatest_decrease = min(change_list_cleaned) # find position of greatest_increase and greatest_decrease max_index = change_list.index(greatest_increase) max_month = months[max_index] min_index = change_list.index(greatest_decrease) min_month = months[min_index] # Print the results to the terminal print("Financial Analysis") print("-------------------------") print(f"Total Months: {months_count}") print(f"Total: ${net_total}") print(f"Average Change: ${average_change}") print(f"Greatest Increase in Profits: {max_month} (${greatest_increase})") print(f"Greatest Decrease in Profits: {min_month} (${greatest_decrease})") # Specify the file to write to PyBank_results = os.path.join(dirname, "Analysis", "PyBank_Results.txt") # Write the txt file with open(PyBank_results, 'w') as txtfile: txtfile.write("Financial Analysis\n") txtfile.write("-------------------------\n") txtfile.write(f"Total Months: {months_count}\n") txtfile.write(f"Total: ${net_total}\n") txtfile.write(f"Average Change: ${average_change}\n") txtfile.write(f"Greatest Increase in Profits: {max_month} (${greatest_increase})\n") txtfile.write(f"Greatest Decrease in Profits: {min_month} (${greatest_decrease})\n")
c2dd38a003ecf858b16dd1abc14ba1f43951dfd4
eskay101/projects
/fp.py
1,053
4.09375
4
''' Program make a simple calculator that can add, subtract, multiply and divide using functions ''' # This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y #BELLO KAZEEM OLASUNKANMI # Olapoint4@yahoo.com # 08081344825 print ("Select operation.") print ("1.Add") print ("2.Subtract") print ("3.Multiply") print ("4.Divide") # Take input from the user choice = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print (num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input")
e4b919b306f2b99064c59edbc8f5d51e9b760fea
ZackarieP/Java-Projects
/Python/pos_neg.py
524
4
4
def pos_neg(a, b, negative): if negative == True: if a < 0 and b < 0: return True else: return False elif a < 0 or b < 0: if a < 0 and b < 0: return False elif negative == False: return True else: return False return False print(pos_neg(1, -1, False)) # True print(pos_neg(-1, 1, False)) # True print(pos_neg(-4, -5, True)) # True print(pos_neg(-5, -6, False)) # False print(pos_neg(1, 2, False)) # False
cabc2bddfde4a33c10ba9753716b17dfbe53b955
tobynboudreaux/machine-learning-regression-practice
/mlinear_regression.py
1,218
3.578125
4
# Data Preprocessing Template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('../Machine Learning A-Z (Codes and Datasets)/Part 2 - Regression/Section 5 - Multiple Linear Regression/Python/50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values # Encode catagorical data # Encode Independant Var from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [3])], remainder='passthrough') X = np.array(ct.fit_transform(X)) # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Train Multiple Linear Regression (MLR) model on Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predict the Test set results y_pred = regressor.predict(X_test) np.set_printoptions(precision=2) print(np.concatenate((y_pred.reshape(len(y_pred), 1), y_test.reshape(len(y_test), 1)), 1))
57a99993916020b5c5780236c8efb052974c51b0
wuxu1019/1point3acres
/Google/test_246_Strobogrammatic_Number.py
908
4.15625
4
""" A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to determine if a number is strobogrammatic. The number is represented as a string. Example 1: Input: "69" Output: true Example 2: Input: "88" Output: true Example 3: Input: "962" Output: false """ class Solution(object): def isStrobogrammatic(self, num): """ :type num: str :rtype: bool """ same = '018' diff = '69' l, r = 0, len(num) - 1 while l < r: s = num[l] + num[r] if s[0] in same and s.count(s[0]) == len(s): l += 1 r -= 1 elif s == diff or s[::-1] == diff: l += 1 r -= 1 else: return False if l == r: return num[r] in same return True
d6221da320d561e86443cb55c14355a8bfe01c8d
wuxu1019/1point3acres
/Google/test_835_Image_Overlap.py
1,361
3.890625
4
""" Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.) We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images. (Note also that a translation does not include any kind of rotation.) What is the largest possible overlap? Example 1: Input: A = [[1,1,0], [0,1,0], [0,1,0]] B = [[0,0,0], [0,1,1], [0,0,1]] Output: 3 Explanation: We slide A to right by 1 unit and down by 1 unit. Notes: 1 <= A.length = A[0].length = B.length = B[0].length <= 30 0 <= A[i][j], B[i][j] <= 1 """ class Solution(object): def largestOverlap(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: int """ N = len(A) count = collections.Counter() for i, row in enumerate(A): for j, v in enumerate(row): if v: for i2, row2 in enumerate(B): for j2, v2 in enumerate(row2): if v2: count[i-i2, j-j2] += 1 return max(count.values() or [0])
fe0c885f1a8f1d8fb1ca8306dbf5c7bd8e73b626
wuxu1019/1point3acres
/Nvidia/trans_str_to_int.py
307
3.71875
4
def changestring(s): l = s.split(',') rt = [] for a in l: a = a.lstrip(' ') a = a.rstrip(' ') if a: rt.append(int(a)) return rt if __name__ == '__main__': target = "1,,,, 3434, 22, , 345, 6, ,4," result = changestring(target) print result
0338a3890fdee169e9143a3b9eb17ae78c567616
wuxu1019/1point3acres
/Google/test_280_Wiggle_Sort.py
1,092
4.03125
4
""" Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... Example: Input: nums = [3,5,2,1,6,4] Output: One possible answer is [3,5,1,6,2,4] """ class Solution(object): def wiggleSort_nlog(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ nums.sort() if len(nums) % 2 == 0: nums[0:len(nums):2], nums[1:len(nums):2] = nums[0:len(nums) / 2], nums[len(nums) / 2:] else: nums[0:len(nums):2], nums[1:len(nums):2] = nums[0:len(nums) / 2 + 1], nums[len(nums) / 2 + 1:] def wiggleSort_On(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ for i in range(1, len(nums)): if i % 2 == 1 and nums[i] < nums[i - 1]: nums[i], nums[i - 1] = nums[i - 1], nums[i] elif i % 2 == 0 and nums[i - 1] < nums[i]: nums[i], nums[i - 1] = nums[i - 1], nums[i]
37961ca6886c6abe98befdd1a2e96294d5721ce7
wuxu1019/1point3acres
/Amazon/maxstack.py
674
3.8125
4
class MaxStack(object): def __init__(self): self.stk = [] def push(self, val): if not self.stk: self.stk.append((val, val)) else: self.stk.append((val, max(self.stk[-1][1], val))) def pop(self): if not self.stk: return None return self.stk.pop()[0] def maxval(self): if not self.stk: return None return self.stk[-1][1] if __name__ == '__main__': s = MaxStack() print s.maxval() print s.pop() s.push(1) print s.maxval() print s.pop() s.push(1) s.push(3) print s.maxval() print s.pop() print s.maxval()
e7ab285e7ee756af1c8fdaa58e6a379c521d4040
wuxu1019/1point3acres
/Nvidia/revert_32bit_int.py
304
3.890625
4
# revert 32 bit int by 8 bit def revert32bit(num): i = 2**9 - 1 rt = 0 for j in range(4): p = 8 * j rt |= (num ^ i) << p num = num >> 8 return rt if __name__ == '__main__': num = 435 print bin(num) rt = revert32bit(num) print rt print bin(rt)
884cb9518cfa386a3bb587726af1602ba7a60254
prashyboby/my-first-repo
/session7_exercises.py
739
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 3 08:34:20 2020 @author: prasanthchakka """ #%% def my_func(): i = 0 my_list=[] while(i < 500): my_list.append(i+1) i+=1 return my_list my_list = my_func() #%% def range_func(param): for i in range(param,-1,-1): print(i) range_func(10) #%% def max_in_list(custom_list): temp = -1 for i in custom_list: if(i > temp): temp = i return temp max_in_list(my_list) #%% def min_in_list(custom_list): temp = custom_list[0] for i in custom_list: if(i < temp): temp = i return temp min_in_list(my_list)
400c3dc44b73637ce66bed09e14a1fd9e5567bf7
marqun/python_project_euler
/sol4.py
643
4
4
"""A palindromic number reads the same both ways. the largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.""" import random import time start_time = time.time() x= random.sample(range(1, 45), 5) k=[] for i in range(100,1000): for j in range(100,1000): n = i*j digits = [int(x) for x in str(n)] if len(digits)>5: if digits[0] == digits[5] and digits[1] == digits [4] and digits[2] == digits[3]: k.append(n) print(max(k)) y = (time.time() - start_time) print("--- %s seconds ---" %y)
a7249a87f456f739cab212b416506e75c02053e4
marqun/python_project_euler
/sol6.py
534
4.0625
4
"""The sum of the squares of the first ten natural numbers is, The square of the sum of the first ten natural numbers is, Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is . Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.""" x = 100 y = 0 z = 0 for i in range(1,x+1): y+= (i*i) #print("i:", i , "y:", y) z+=i if i == x: z= z*z #print("z:", z) print("solution:", z-y)
7280f3f12c8e9cf00f67f5dc04b38c0a9fe97249
BrightnessMonitor/BrightnessMonitorClient
/src/brightnessmonitorclient/raspberry/timeConvert.py
191
3.59375
4
#!/usr/bin/env python import datetime # converts given seconds passed since 1 Jan 1970 # back into readable time def convertback(seconds): return datetime.datetime.fromtimestamp(seconds)
b3927b707af3c7ab22563d88779f29811153e214
opendere/ircbook
/util/dateutils.py
778
4
4
import re from datetime import datetime, date def today(): """Obtain a naive date object from the current UTC time.""" now = datetime.utcnow() return date(now.year, now.month, now.day) def to_int(s): try: int(s[0:4]) except E as ex: print(ex) raise ValueError("Not an integer") def parse_iso_date(s): if s is None: raise ValueError("No date provided") if len(s) != 10: raise ValueError("Date must contain ten characters.") pattern = re.compile("[0-9]{4}-(0[0-9]|10|11|12)-[0-9]{2}") if not pattern.fullmatch(s): raise ValueError("Invalid date format: " + s + ". Must use yyyy-mm-dd.") year = int(s[0:4]) month = int(s[5:7]) day = int(s[-2:]) return date(year, month, day)
74a626839f46dbb3da41c1f045e10902e1835c5d
krzysztofsmokowski/JsonToXml
/weather_comm.py
2,656
3.75
4
''' Entire module is used for requesting different data from url passed in __init__ of this module. Main purpose is to close data in json format for further actions. ''' import json import requests from requests.compat import urljoin class WeatherStations(object): ''' This class is containing modules that are requesting pollution data from weather API. ''' def __init__(self, url): self.url = url def _ask_api(self, endpoint): request = requests.get(urljoin(self.url, endpoint)) return request.json() def station_info(self, station_id): ''' This method communicates with HTTP API and returns json with the result of http get. This method is taking only one parameter. Input: station_id (int) Method returns json with info about station that is requested with use of station_id parameter ''' return self._ask_api("pjp-api/rest/aqindex/getIndex/{}".format(station_id)) def stations_summary(self, counter=2): ''' Method with no input, communicates with API and returns IDs of every station in form of list. Args: none Returns: dict of id's (every ID is in INT form) and cities. eg: {14: "WRoclaw", 18: "Poznan"} TODO: REMOVE HACK RELATED TO API ANTI SPAM. ''' request_json = self._ask_api("pjp-api/rest/station/findAll") station_dict = {} count = 0 for station in request_json: if count < counter: station_dict[station["id"]] = station["stationName"] count += 1 return station_dict def stations(self): ''' Returns: nested structure which contains stations and their paramteres. return {id: city, pm10_pollution: pm10, pm25_pollution: pm25} ex: [{'id':14, 'city': "wroclaw", "pm10_pollution": 25, "pm25_pollution": 10}, {18: "poznan", "pm10_pollution": 25, "pm25_pollution": 10}] ''' stations_summary = self.stations_summary() list_of_stations = [] for station_id in stations_summary: station_data = {} station_data['id'] = station_id station_data['city'] = stations_summary[station_id] station = self.station_info(station_id) if station["pm10IndexLevel"]: station_data["pm10_pollution"] = station["pm10IndexLevel"]["indexLevelName"] if station["pm25IndexLevel"]: station_data["pm25_pollution"] = station["pm25IndexLevel"]["indexLevelName"] list_of_stations.append(station_data) return list_of_stations
b0e1e9ef12dcbf22b79838b953f8c5249fb3ddce
bluehorse07/python
/bincon.py
567
3.53125
4
n = int(input("Input and integer less than 256 : ")) d = 128 q = int (n / d) r = int(n % d) print (d,q,r) n = r d = int(d / 2) q = int(n / d) r = int(n % d) print (d,q,r) n = r d = int(d / 2) q = int(n / d) r = int(n % d) print (d,q,r) n = r d = int(d / 2) q = int(n / d) r = int(n % d) print (d,q,r) n = r d = int(d / 2) q = int(n / d) r = int(n % d) print (d,q,r) n = r d = int(d / 2) q = int(n / d) r = int(n % d) print (d,q,r) n = r d = int(d / 2) q = int(n / d) r = int(n % d) print (d,q,r) n = r d = int(d / 2) q = int(n / d) r = int(n % d) print (d,q,r) n = r
624dc80e3388796c7a6fcc1f338b48b39947696b
AlexandreDejous/Misra
/misra.py
13,135
3.625
4
#ALL COMMUNICATION (between nodes) is going through gRPC #each node has an internal state which is updated and used when receiving the marker for carrying out the misra algorithm #each node can simulate computation and reading/sending messages #each node has its own address, defined by the first argument send by the user, example: #arg1 = 3 #address of node is : "localhost:5005<arg1>" = "localhost:50053" #the second argument defines whether the node is (what I call) an "initiator", if arg2 = 1 #the initiator receives a message of computation and the marker, #it allows us to start the computation in the whole network and to introduce the marker in it #nodes send messages to other nodes with asynchronous functions using gRPC #nodes receives these messages also asychronously (through gRPC), package them in a queue. #A node is either: #computing something #processing the marker #sending the marker/messages by triggering asynchronous functions #reading from its own queue of messages #procedure: #open 4 terminals #if you use python3: #on the initiator type: python3 misra.py 1 1 #on the others: #python3 misra.py 2 2 #python3 misra.py 3 2 #python3 misra.py 4 2 #then type "1" in the initiator's console #the messages print in the console have this meaning: #<sender> ==== <nb> : the node received a marker with that nb from sender #<nb> ==== <destination> : the node sent a marker with this nb to that destination import sys import time import random import grpc import communication_pb2 import communication_pb2_grpc #------ from concurrent import futures from threading import Thread, Lock table = ["localhost:50051","localhost:50052","localhost:50053","localhost:50054"] #------------------------- NODE ------------------------------------- class node: def __init__(self): #used for the random generation of messages self.computeProba = 8 self.decreasingFactor = 1 self.round = 1 self.color = "black" self.nb = 0#nb of links visited self.c = 0#length of a cycle self.selfAddress = ""#own adress self.links = []#available links (addresses) to other nodes (that marker/messages can travel through) self.uv = []#unvisited nodes self.f = []#father self.s = []#sons def ping(self):#function used for debug print("%s responding to ping !" % self.selfAddress) def computeC(self):#computes the length of a cycle self.c = ( len(self.links) * ( len(self.links) - 1 ) ) / 2 def createTable(self,addresses):#creates the table of addresses in the node (in links) WORKS for i in addresses: self.links.append(i) def setSelfAddress(self,address):#knows its address, deletes itslef from the links, and compute c self.computeC() self.links.remove(address) self.selfAddress = address def newDFS(self):#call this if marker is here and process is active, or if self.round > marker.round #basically resets the values useful for the DFS self.uv = self.links.copy() self.f = [] self.s = [] def sendMarker(self,destination):#makes the rpc call #turns the process white as the marker leaves the process for another one if self.nb == self.c: print("terminated") sys.exit() self.color = "white" callRPCfunc(destination,self.round,self.selfAddress,self.nb) self.next()#NEXT HERE def receiveMarker(self,m_round,sender,nb):#called via rpc #contains a large part of the misra algorithm #here the marker is processed according to the internal state of the node, #which decides if termination has occured, if the round continues, and where to send # the marker next print("---------------------------") print("%s ==== %d"%(sender,nb)) time.sleep(0.5) if self.color == "black": #reset dfs print("MARKER RESET") self.newDFS() #will send a nb of 0 nb = 0 #copy round and increase own round and round sent self.round = m_round self.round = self.round + 1 m_round = m_round + 1 #pick a destination and pop uv destination = self.uv.pop() #add desti to sons self.s.append(destination) #set White self.color = "white" #send callRPCfunc(destination,m_round,self.selfAddress,nb) self.next() if self.color == "white": #check for termination if nb == self.c-1: print("Terminated (nb)") sys.exit(0) if self.round == m_round: if self.s: if sender == self.s[-1]: self.s.pop()#pop son if self.uv: #pop desti from uv and add desti to sons destination = self.uv.pop() self.s.append(destination) nb = nb + 1 callRPCfunc(destination,m_round,self.selfAddress,nb) self.next() else: #go to last father if self.f: #pop from f destination = self.f.pop() #just go to f callRPCfunc(destination,m_round,self.selfAddress,nb) self.next() #if no father then terminated else: print("Terminated (f)") sys.exit(0) else: #send back to last sender callRPCfunc(sender,m_round,self.selfAddress,nb) self.next() else: print("Terminated (s)") sys.exit(0) else: #reset DFS f,s and uv self.newDFS() #add as father the sender self.f.append(sender) #copy the round self.round = m_round #remove the sender from the unvisited this round self.uv.remove(sender) #dont forget to increase nb if self.uv: #pop desti from uv and add desti to sons, increase nb, send destination = self.uv.pop() self.s.append(destination) nb = nb + 1 callRPCfunc(destination,m_round,self.selfAddress,nb) self.next() else: #go to last father if self.f: #pop from f destination = self.f.pop() #just go to f callRPCfunc(destination,m_round,self.selfAddress,nb) self.next() #if no father then terminated else: print("Terminated (f)") sys.exit(0) def compute(self): #simple function that simulates computation time print(self.selfAddress + "computing...") time.sleep(0.5) def sendMessagesRandom(self): #simulates the sending of messages of the node #messages (that trigger computation in other nodes) are sent randomly to other nodes if self.links: for destination in self.links: rand = random.uniform(0, 10) if rand < self.computeProba:#if the probs are right callRPCfunc2(destination)#call to rpc of second type (send a message) self.computeProba = self.computeProba - self.decreasingFactor#reducing the probs of sending messages for next time def receiveMessage(self):#this method is called when the node as fetched a message from the queue (computation) self.color = "black" self.compute() self.sendMessagesRandom() self.next()#NEXT HERE def next(self):#fetches from the queue to know what's next global q test = not q while test: time.sleep(0.5) lock.acquire() test = not q lock.release() if q: lock.acquire() val = q.pop(0) lock.release() if val.TYPE == "marker":#if we received a marker, call receiveMarker if val.SENDER == "root": self.receiveMarker(val.M_ROUND,val.SENDER,val.NB) else: self.receiveMarker(val.M_ROUND,val.SENDER,val.NB) elif val.TYPE == "message":##if we received a marker, call receiveMessage self.receiveMessage() #------------------------ SENDER FUNCTIONS ------------------------- #these functions are called when the node needs to send a message/marker to another node def callRPCfunc(destination,m_round,sender,nb): #is called when the local node whishes to send a marker to another node #after called the function immediately returns, allowing the node to instantly resume execution print("%d ==== %s"%(nb,destination)) print("---------------------------") with grpc.insecure_channel(destination) as channel: stub = communication_pb2_grpc.RemoteStub(channel) response = stub.Marker(communication_pb2.MarkerRequest(TYPE="marker", M_ROUND = m_round, SENDER = sender, NB = nb))#info is sent here def callRPCfunc2(destination): #same, but for messages (that will trigger computation in the destination node) with grpc.insecure_channel(destination) as channel: stub2 = communication_pb2_grpc.RemoteStub(channel) stub2.Message(communication_pb2.MessageRequest(TYPE = "message")) #------------------------------------------------ SERVER FUNCTIONS ------------------------------------------------ #these 2 write inside the Q #TYPE, M_ROUND, SENDER, NB #These functions are called in an asynchronous manner when another node sends a message/marker to this node. #the content of the received request is put in a queue, for the local node to read when it needs to. class Remote(communication_pb2_grpc.RemoteServicer): def Marker(self, request, context): #is called when the server received a marker #it puts the received element in a queue so that the node can read it later, typically when #the ode seeks for its next action (next() method) Thread(target=writeQ(request)).start() return communication_pb2.MarkerReply(TYPE='Type : %s , M_ROUND : %d , SENDER : %s , NB : %d' % (request.TYPE, request.M_ROUND, request.SENDER, request.NB)) #info is gathered here def Message(self,request, context): #same, but for messages (triggering computation) Thread(target=writeQ(request)).start() return communication_pb2.MessageReply(TYPE="message") def writeQ(value): #allows to write a queue of received messages and marker #once in a while, when the node finished its current action it fetches from the queue to know #its next action (next() method) #the queue is in a critical section lock.acquire() global q q.append(value) lock.release() #------------------------------------------------ SERVER SETUP ------------------------------------------- #The server listens on the port specified by the user input def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) communication_pb2_grpc.add_RemoteServicer_to_server(Remote(), server) server.add_insecure_port('[::]:5005'+sys.argv[1]) server.start() server.wait_for_termination() #--------------------------------------------------- MAIN ------------------------------------------------ if __name__ == '__main__': data = '1' #creates a lock and a queue to write incoming messages for a later used by the local node .the local node reads from the queue #when it finishes what it was currently doing lock = Lock() q = [] #START THE SERVER t = Thread(target=serve) t.start() #instanciate local node NODE = node() NODE.createTable(table) NODE.setSelfAddress("localhost:5005"+sys.argv[1]) NODE.newDFS() if sys.argv[2] == "2":#if this node is not the initiator (arg2 = 2), then, start it without messages NODE.next() #READS INPUT while(data != '0'): data = input("") if data == "1": writeQ(communication_pb2.MessageRequest(TYPE = "message")) writeQ(communication_pb2.MarkerRequest(TYPE="marker", M_ROUND = 1, SENDER = "root", NB = 0)) if sys.argv[2] == "1":#if node is initiator, start + w/ initial messages NODE.next() sys.exit
575f5def481566f9f5f677a37bd58884b6d69118
tcamenzi/TetrisAI_old
/draw.py
1,029
3.6875
4
black = [0,0,0] ##Draw an individual black square, or don't draw if uncolored. def drawSquare(board, screen, rowIndex, colIndex, pygame): if board.board[rowIndex][colIndex] == 1: x_coord = colIndex * board.colpixWidth y_coord = rowIndex * board.rowpixWidth pygame.draw.rect( screen, black, [x_coord, y_coord, board.colpixWidth, board.rowpixWidth]) def drawBoard( screen, board, pygame ): ##Iterate over the board and draw all black squares for rowIndex in range(len(board.board)): for colIndex in range(len(board.board[rowIndex])): drawSquare( board, screen, rowIndex, colIndex, pygame) ##Draw the active piece. for coord in board.piece.relativePoints: xcoord = board.colpixWidth * (coord.x + board.piece.centerx) ycoord = board.rowpixWidth * (coord.y + board.piece.centery) pygame.draw.rect( screen, board.piece.color, [xcoord, ycoord, board.colpixWidth, board.rowpixWidth] )
945fe684f9e429ea897d080871096fcf2c9206ce
varunnaganathan/DonkeyKong
/basicsprite.py
1,104
3.953125
4
import pygame from helper import * """this is the basic sprite inheriting from pygame Sprite model.inherits the pygame Sprite adding the image and position of the image mapping to the 2-d matrix""" class sprite(pygame.sprite.Sprite): def __init__(self,centerPoint,image): pygame.sprite.Sprite.__init__(self) self.image=image self.rect=image.get_rect() self.rect.center=centerPoint """the coin class.the coins are randomly generated and worth points""" class coin(pygame.sprite.Sprite): def __init__(self,top_left,image=None): pygame.sprite.Sprite.__init__(self) if image == None: self.image,self.rect=load_image('coin.png',-1) else: self.image=image self.rect=image.get_rect() self.rect.topleft=top_left """the queen character or rather the princess""" class Queen(pygame.sprite.Sprite): def __init__(self,top_left,image=None): pygame.sprite.Sprite.__init__(self) self.image=image self.rect=image.get_rect() self.rect.topleft=top_left
859d548212a758d60f22027d168636fd7c48ec61
neuromol/random_code
/pandas_sort.py
1,315
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Pandas Sort ■___■ (◕‿◕) ▐ __▐ .▆|▆. """ import pandas as pd import argparse import sys def check_arg(args=None): parser = argparse.ArgumentParser(description='Pandas sort using column names (compared to linux sort $columns)' ,formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', '--input', help='Input file name ',required='True') parser.add_argument('-1', '--search1', help='Column name for first sort',required='True') parser.add_argument('-2', '--search2', help='Column name for second sort - leave out for None - default is None ' ,default=None ) parser.add_argument('-o', '--output', help='outfile',required='True') results = parser.parse_args(args) return (results.input , results.search1, results.search2 , results.output) def main(file, search1, search2, out ): input_file=pd.read_csv(file,sep="\t" , header=0) if search2 is None: sort_file = input_file.sort_values(by=[search1]) else: sort_file = input_file.sort_values(by=[search1,search2]) del input_file sort_file.to_csv(out,sep="\t",index=None) if __name__ == '__main__': file, search1, search2, out = check_arg(sys.argv[1:]) main(file, search1, search2, out )
70db70d518376669d2dfd1c534122156f9ee1fc7
jaronoff97/sample_code
/Control_Flow_Part_2.py
363
3.796875
4
students = ["Jacob", "Sam", "Corey", "Michael"] num = 0 while num < len(students): print(students[num]) num += 1 for student in students: print(student) for num in range(0, 10): print(num) list = ["string1", 10, "string2", 100] if 10 in list: list.remove(list.index(10)) list.insert(3, 300) for thing in list: print(thing)
c276832ed7e241ec1489b9b6c8ca67481f43f494
UstunYildirim/CCLUB_AI_Challenge
/Bot/main.py
5,431
3.671875
4
""" METU CCLUB Sample AI """ from sys import stdout from random import randint from math import ceil """ You will mainly be changing myAI function below. It is executed once every turn. """ def myAI(game): """ Every time this function is called, it finds your the most productive city for that turn and finds your city with the greatest number of total soldiers. Then, it will send two commands: First one selects your the most productive city to be your city with the CCLUB POWER which doubles the production. Second command sends all the soldiers in your strongest city to a randomly chosen city which is not yours. """ cityList = game.getCityList() listOfMyCities = [] otherCities = [] for aCity in cityList: if aCity.getOwnerID() == 1: listOfMyCities.append(aCity) else: otherCities.append(aCity) if len(listOfMyCities) == 0 or len(otherCities) == 0: return maxIncome = 0 maxIncomeCity = 0 biggestArmy = 0 biggestCity = 0 for aCity in listOfMyCities: if aCity.getProductionAmount() > maxIncome: maxIncome = aCity.getProductionAmount() maxIncomeCity = aCity.getCityID() armySize = aCity.getSoldiers() armySize = armySize[0] + armySize[1] + armySize[2] if armySize > biggestArmy: biggestArmy = armySize biggestCity = aCity.getCityID() game.CCLUB_POWER(maxIncomeCity) selectedCity = randint(0, len(otherCities)-1) game.giveOrder(biggestCity, otherCities[selectedCity].getCityID(), game.getCityDictionary()[biggestCity].getSoldiers()) class mayIchallenge(): def __init__(self): self.commands = [] self.cities = {} self.armies = {} self.turn = 0 self.numCities = int(self.readAline()) self.numArmies = 0 i = 0 while i < self.numCities: newCity = city(self.readAline()) self.cities[newCity.getCityID()] = newCity i+=1 def startGame(self): while self.turn < 250: self.numCities = int(self.readAline()) i = 0 while i < self.numCities: newLine = self.readAline() self.cities[int(newLine.split()[0])].updateInfo(newLine) i+=1 self.numArmies = int(self.readAline()) i = 0 while i < self.numArmies: newLine = self.readAline() self.armies[int(newLine.split()[0])] = army(newLine) i+=1 if self.readAline() == "metu cclub": myAI(self) stdout.write(str(len(self.commands)) + "\n") stdout.flush() for aCommand in self.commands: stdout.write(aCommand) stdout.flush() self.commands = [] self.armies = {} self.turn += 1 def CCLUB_POWER(self, cityID): self.commands.append("cclub power:" + str(cityID) + "\n") def giveOrder(self,fromCity, toCity, soldiersList): fromCity = str(fromCity) toCity = str(toCity) (noRocks, noPapers, noScissors) = soldiersList self.commands.append(fromCity + " " + toCity + " " + str(noRocks) + " " + str(noPapers) + " " + str(noScissors) + "\n") def numberOfTurnsBetweenCities(self, cityID1, cityID2): (x1, y1) = self.cities[cityID1].getCoordinates() (x2, y2) = self.cities[cityID2].getCoordinates() return ceil((((x1-x2)**2 + (y1-y2)**2)**0.5)/20) def readAline(self): aL = input() return aL def getCityList(self): retList = [] for aCityID in self.cities: retList.append(self.cities[aCityID]) return retList def getCityDictionary(self): return self.cities def getArmyList(self): retList = [] for anArmyID in self.armies: retList.append(self.armies[anArmyID]) return retList def getArmyDictionary(self): return self.armies class city(): def __init__(self, cityInfoString): infoArray = cityInfoString.split() self.id = int(infoArray[0]) self.x = int(infoArray[1]) self.y = int(infoArray[2]) self.ownerID = int(infoArray[3]) self.productionType = infoArray[4] self.productionAmount = int(infoArray[5]) self.soldiers = list(map(int, infoArray[6:9])) def updateInfo(self, newInfoString): infoArray = newInfoString.split() if int(infoArray[0]) == self.id: self.ownerID = int(infoArray[1]) self.soldiers = list(map(int, infoArray[2:5])) def getCityID(self): return self.id def getOwnerID(self): return self.ownerID def getCoordinates(self): return (self.x, self.y) def getProductionAmount(self): return self.productionAmount def getProductionType(self): return self.productionType def getSoldiers(self): return self.soldiers class army(): def __init__(self, armyInfoString): infoArray = armyInfoString.split() self.id = int(infoArray[0]) self.initialCityID = int(infoArray[1]) self.destinationCityID = int(infoArray[2]) self.ownerID = int(infoArray[3]) self.totalNumberOfTurns = int(infoArray[4]) self.remainingNumberOfTurns = int(infoArray[5]) self.soldiers = list(map(int, infoArray[6:9])) def getOwnerID(self): return self.ownerID def getArmyID(self): return self.id def getInitialCityID(self): return self.initialCityID def getTargetCityID(self): return self.destinationCityID def getRemainingNumberOfTurns(self): return self.remainingNumberOfTurns def getTotalNumberOfTurns(self): return self.totalNumberOfTurns def getSoldiers(self): return self.soldiers newGame = mayIchallenge() newGame.startGame()
c5006c061a4df9eda3604aa847cbe8c22d0b7655
SeitaBV/timely-beliefs
/timely_beliefs/utils.py
8,162
3.515625
4
import warnings from datetime import datetime, timedelta from typing import Optional, Sequence, Union import pandas as pd def parse_timedelta_like( td: Union[timedelta, str, pd.Timedelta], variable_name: Optional[str] = None, ) -> timedelta: """Parse timedelta like objects as a datetime.timedelta object. The interpretation of M (month), Y and y (year) units as a timedelta is ambiguous (e.g. td="1Y"). For these cases, Pandas (since 0.25) gives a FutureWarning, warning that support for these units will be removed. This function throws a ValueError in case Pandas gives a FutureWarning. https://pandas.pydata.org/docs/whatsnew/v0.25.0.html#deprecations :param td: timedelta-like object :param variable_name: used to give a better error message in case the variable failed to parse :return: timedelta """ try: with warnings.catch_warnings(record=True): warnings.simplefilter("error") if isinstance(td, str): try: td = pd.Timedelta(td) except ValueError as e: # catch cases like "H" -> "1H" if "unit abbreviation w/o a number" in str(e): td = pd.Timedelta(f"1{td}") else: # Reraise needed since pandas==2.0.0 throws a ValueError for ambiguous timedelta, rather than a FutureWarning raise e if isinstance(td, pd.Timedelta): td = td.to_pytimedelta() except (ValueError, FutureWarning) as e: raise ValueError( f"Could not parse {variable_name if variable_name else 'timedelta'} {td}, because {e}" ) return td def parse_datetime_like( dt: Union[datetime, str, pd.Timestamp], variable_name: Optional[str] = None ) -> datetime: """Parse datetime-like objects as a datetime.datetime object. :param dt: datetime-like object :param variable_name: used to give a better error message in case the variable failed to parse :return: timezone-aware datetime """ try: if isinstance(dt, str): dt = pd.Timestamp(dt) if isinstance(dt, pd.Timestamp): dt = dt.to_pydatetime() except ValueError as e: raise ValueError( f"Could not parse {variable_name if variable_name else 'datetime'} {dt}, because {e}" ) return enforce_tz(dt, variable_name) def enforce_tz(dt: datetime, variable_name: Optional[str] = None) -> datetime: """Raise exception in case of a timezone-naive datetime. :param dt: datetime :param variable_name: used to give a better error message in case the variable contained a timezone-naive datetime :return: timezone-aware datetime """ if not hasattr(dt, "tzinfo") or dt.tzinfo is None: raise TypeError( f"The timely-beliefs package does not work with timezone-naive datetimes. Please localize your {variable_name if variable_name else 'datetime'} {dt}." ) return dt def all_of_type(seq: Sequence, element_type) -> bool: """Return true if all elements in sequence are of the same type.""" for item in seq: if type(item) != element_type: return False return True def replace_multi_index_level( df: "classes.BeliefsDataFrame", # noqa: F821 level: str, index: pd.Index, intersection: bool = False, ) -> "classes.BeliefsDataFrame": # noqa: F821 """Replace one of the index levels of the multi-indexed DataFrame. Returns a new DataFrame object. :param df: a BeliefsDataFrame (or just a multi-indexed DataFrame). :param level: the name of the index level to replace. :param index: the new index. :param intersection: policy for replacing the index level. If intersection is False then simply replace (note that the new index should have the same length as the old index). If intersection is True then add indices not contained in the old index and delete indices not contained in the new index. New rows have nan columns values and copies of the first row for other index levels (note that the resulting index is usually longer and contains values that were both in the old and new index, i.e. the intersection). """ # Todo: check whether timezone information is copied over correctly # Check input if intersection is False and len(index) != len(df.index): raise ValueError( "Cannot simply replace multi-index level with an index of different length than the original. " "Use intersection instead?" ) if index.name is None: index.name = level new_index_values = [] new_index_names = [] if intersection is True: contained_in_old = index.isin(df.index.get_level_values(level)) new_index_not_in_old = index[~contained_in_old] contained_in_new = df.index.get_level_values(level).isin(index) for i in df.index.names: if i == level: # For the index level that should be replaced # Copy old values that the new index contains, and add new values that the old index does not contain new_index_values.append( df.index.get_level_values(i)[contained_in_new].append( new_index_not_in_old ) ) new_index_names.append(index.name) else: # For the other index levels # Copy old values that the new index contains, and add the first value to the new rows new_row_values = pd.Index( [df.index.get_level_values(i)[0]] * len(new_index_not_in_old) ) new_index_values.append( df.index.get_level_values(i)[contained_in_new].append( new_row_values ) ) new_index_names.append(i) else: for i in df.index.names: if i == level: # For the index level that should be replaced # Replace with new index new_index_values.append(index) new_index_names.append(index.name) else: # For the other index levels # Copy all old values new_index_values.append(df.index.get_level_values(i)) new_index_names.append(i) # Construct new MultiIndex mux = pd.MultiIndex.from_arrays(new_index_values, names=new_index_names) df = df.copy(deep=True) # Apply new MultiIndex if intersection is True: # Reindex such that new rows get nan column values df = df.reindex(mux) else: # Replace the index df.index = mux return df.sort_index() def append_doc_of(fun): def decorator(f): if f.__doc__: f.__doc__ += fun.__doc__ else: f.__doc__ = fun.__doc__ return f return decorator def replace_deprecated_argument( deprecated_arg_name: str, deprecated_arg_val: any, new_arg_name: str, new_arg_val: any, required_argument: bool = True, ) -> any: """Util function for replacing a deprecated argument in favour of a new argument. If new_arg_val was not already set, it is set to deprecated_arg_val together with a FutureWarning. """ if required_argument is True and new_arg_val is None and deprecated_arg_val is None: raise ValueError(f"Missing argument: {new_arg_name}.") if deprecated_arg_val is not None: import warnings warnings.warn( f"Argument '{deprecated_arg_name}' will be replaced by '{new_arg_name}'. Replace '{deprecated_arg_name}' with '{new_arg_name}' to suppress this warning.", FutureWarning, ) new_arg_val = deprecated_arg_val return new_arg_val def remove_class_init_kwargs(cls, kwargs: dict) -> dict: """Remove kwargs used to initialize the given class.""" params = list(cls.__init__.__code__.co_varnames) params.remove("self") for param in params: kwargs.pop(param, None) return kwargs
c49ecc84bf531049eb2db3aa487b42e998a430be
tiedye93/Python--COT4930
/lab07/tbourque2012_lab07.py
3,799
3.875
4
# COT 4930 Python Programming # Name: Tyler Bourque # ID : tbourque2012 # Lab : 07 #----------------------------------------- class SLNode : # single link node def __init__( self, data = None, next = None ) : self.data = data self.next = next def get_data( self ) : return self.data def get_next( self ) : return self.next def set_next( self, next ) : self.next = next class DLNode( SLNode ) : # double link node def __init__( self, data = None, next = None, prev = None ) : super( ).__init__( data, next ) self.prev = prev def get_prev( self ) : return self.prev def set_prev( self, prev ) : self.prev = prev class DLList : def __init__( self, head = None ) : self.head = head self.tail = head def insert( self, data ) : print("Inserting ", data, " into the List...") node = DLNode( data ) temp = self.head p = self.head if self.head == None : self.head = node self.tail = node else : while temp is not None: if data < self.head.get_data( ): node.set_next( self.head ) self.head.set_prev( node ) self.head = node temp = temp.get_next( ) break elif data > self.tail.get_data(): node.set_prev( self.tail ) self.tail.set_next( node ) self.tail = node temp = temp.get_next( ) break else: if temp.get_data( ) > data: node.set_next(temp) p.set_next(node) node.set_prev(p) temp.set_prev( node ) break else: p = temp temp = temp.get_next( ) def remove(self, data ): print("Removing ", data, "from the List...") temp = self.head prev = None while temp is not None: if temp.get_data( ) == data: if prev is not None: prev.next = temp.next prev.prev = temp.prev else: self.head = temp.next prev = temp temp = temp.next def print_forw( self ) : print( "cur\t\t prev\t\t data\t next" ); cur = self.head while cur : print( id( cur ), "\t", id( cur.get_prev( ) ), "\t", cur.get_data( ), "\t", id( cur.get_next( ) ) ) cur = cur.get_next( ) print("\n\n") def print_back( self ) : print( "cur\t\t prev\t\t data\t next" ); cur = self.tail while cur : print( id( cur ), "\t", id( cur.get_prev( ) ), "\t", cur.get_data( ), "\t", id( cur.get_next( ) ) ) cur = cur.get_prev( ) print("\n\n") def main( ): DLL = DLList( ) ifile = open( "llist.txt", "r" ) for line in ifile : line = line.strip( ) line = line.split( ) command = line[0] if 'i' in command: key = line[1] DLL.insert(key) elif 'r' in command: key = line[1] DLL.remove(key) elif 'p' in command: DLL.print_forw() else: print("***Unknown Command***") ifile.close( ) main()
3a70ff3fa0d765a90da81588aabae6c63d616504
tiedye93/Python--COT4930
/lab03/tbourque2012_lab03.py
1,106
3.9375
4
# COT 4930 Python Programming # Name: Tyler Bourque # ID : tbourque2012 # Lab : 03 #----------------------------------------- def eratos( n ): primeNumbers = [ ] for i in range(2,n): primeNumbers.append(i) composite = 2 m = 1 loop = 0 while loop < m: for k in primeNumbers[::1]: if k == 2: pass else: if k % composite == 0 and k != composite: primeNumbers.remove(k) m = len(primeNumbers) continue composite += 1 loop += 1 return primeNumbers def print_primes( primes ): for i in range(0, len(primes)): if i % 10 == 0: print( ) print( "%5d" % primes[i], end = "\t" ) def main( ): n = eval(input( "Please type in a number between 2 and 300 to determine the prime numbers: " ) ) if 2 <= n <= 300: primes= eratos( n ) print_primes( primes ) else: print( "Number is not between 2 and 300!") main( )
c9fcb8765c36008cf1edade3b8e268ed28dfc931
MooreRachel/Portfolio
/docs/Python/CreateFiles.py
1,104
3.5625
4
import os ####I wrote this script to creates a set of test text files. ##Since the volume of text files was what i was after and not content, #I used range to create files and to fill the files content with a range of numbers. def CreateFiles(noOfFiles, x): #(Number of Files, content) a = range(x) #creates the content of files with a range of numbers b = "This file is created by a code genius (well she would like to be)" # adds the string to each file. fileName = "NameOfFile" for i in range(noOfFiles): #the parameter to create test files newFile = open(fileName + str(i)+".txt", "w") newFile.write(str(a) + b) #content in files newFile.close() print "done" CreateFiles(3, 50) #note to self: **String and range needs to be formatted but not that important for this purpose** #note to self: **Also, for crying out loud, think of more clever text! ###Script could be used for other purposes. #An idea would be a set of qoutes in numbered variables that could be used with #range so that content in each file would be different.
34515f8656b395c4b843f192de78993544eb10d3
JayaN790214/adv-163
/fever_report.py
1,875
3.9375
4
from tkinter import * root = Tk() root.title("Fever_Report") root.geometry("400x00") question1_radioButton=StringVar(value="0") Question1=Label(root, text ="Do you have headache and sore throat?") Question1.pack() question1_r1=Radiobutton(root, text = "yes", variable=question1_radioButton, value="yes") question1_r1.pack() question1_r2=Radiobutton(root, text = "no", variable=question1_radioButton, value="no") question1_r2.pack() question2_radioButton=StringVar(value="0") Question2=Label(root, text ="Is your body tempreture high?") Question2.pack() question2_r1=Radiobutton(root, text = "yes", variable=question2_radioButton, value="yes") question2_r1.pack() question2_r2=Radiobutton(root, text = "no", variable=question2_radioButton, value="no") question2_r2.pack() question3_radioButton=StringVar(value="0") Question3=Label(root, text ="Are there any symptoms of eye redness?") Question3.pack() question3_r1=Radiobutton(root, text = "yes", variable=question3_radioButton, value="yes") question3_r1.pack() question3_r2=Radiobutton(root, text = "no", variable=question3_radioButton, value="no") question3_r2.pack() def fever_score(): score = 0 if question1_radioButton.get()=="yes": score = score+20 print(score) if question2_radioButton.get()=="yes": score = score+20 print(score) if question3_radioButton.get()=="yes": score = score+20 print(score) if score <= 20: messagebox.showinfo("Report","You don't need to visit a doctor.") elif score > 20 and score <= 40: messagebox.showinfo("Report","You might perhaps have to visit a doctor") else : messagebox.showinfo("Report","I strongly advise you to visit a doctor") btn = Button(root, text= "click me", command= fever_score) btn.pack() root.mainloop()
9f6d59a55c75acb5c7281cd6c35d1f5d08890d4e
COMU/cink
/playground/fatmagul.ergani/deneme5.py
281
3.734375
4
#!/usr/bin/python # -*- coding: utf-8 -*- from Tkinter import * root = Tk () def key(event): frame.focus_force() print "pressed", repr(event.keysym) frame = Frame (root, width=100, height=100) frame.bind("<Key>", key) frame.pack() frame.focus_set() root. mainloop()
0ec76417897f9de8c5ab4f293db3036915b5a1fa
brianjimenez/python-course
/material/examples/example_3.py
581
3.953125
4
class Monster(object): """Represents a mythological creature""" latin_name = 'monstrum' def __init__(self, origin): self.origin = origin @classmethod def get_latin(cls): return cls.latin_name @staticmethod def battle(monster1, monster2): print 'A monster from %s is fighting a \ second monster from %s' % (monster1.origin, monster2.origin) print Monster.get_latin() kraken = Monster('Scandinavia') print kraken.get_latin() print kraken.get_latin leviathan = Monster('Ancient Middle East') Monster.battle(kraken, leviathan)
d6b0537a8ca9392772d74a88995c26683b12426c
brianjimenez/python-course
/material/challenges/challenge_2.py
1,283
3.625
4
import sys class Atom(object): def __init__(self, atom_type): self.atom_type = atom_type class Oxygen(Atom): def __init__(self): Atom.__init__(self, 'O') class Hydrogen(Atom): def __init__(self): Atom.__init__(self, 'H') class Water(object): def __init__(self, oxygen, hydrogen1, hydrogen2): self.oxygen = oxygen self.hydrogens = [hydrogen1, hydrogen2] def usage(): print "Usage: %s num_oxygen num_hydrogen" % sys.argv[0] if __name__ == "__main__": try: num_oxygen = int(sys.argv[1]) num_hydrogen = int(sys.argv[2]) except: usage() raise SystemExit('Error in parameters') oxygens = [Oxygen() for _ in range(num_oxygen)] hydrogens = [Hydrogen() for _ in range(num_hydrogen)] waters = [] hydrogen_counter = 0 oxygen_counter = 0 for oxygen in oxygens: if len(hydrogens) >= 2: waters.append(Water(oxygen, hydrogens[hydrogen_counter], hydrogens[hydrogen_counter + 1])) hydrogen_counter += 2 oxygen_counter += 1 print '%d water molecules created' % len(waters) print '%d oxygen remainder' % (len(oxygens) - oxygen_counter) print '%d hydrogen remainder' % (len(hydrogens) - hydrogen_counter)
8991ba43a7d987b81d3c32cff7e3ab9a41b9edcf
robertompfm/pong
/pong.py
12,594
4.0625
4
""" CODE OF GAME PONG The game Pong was one of the projects of the course Introduction to Interactive Programing with Python by Rice University through Coursera This is an adapted version of the project I submitted, this time I did using pygame instead of simpleGUI there are still a lot of things to improve but I am happy with the result, it was a good exercise """ # importing modules used in the code import pygame import random # initialize pygame pygame.init() # initialize global constants WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 10 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH // 2 HALF_PAD_HEIGHT = PAD_HEIGHT // 2 LEFT = False RIGHT = True BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0 , 255) class PongGame: """ class that will manage the game loop """ def __init__(self): """ initialize game settings """ # variables that won't change self._display_width = WIDTH self._display_height = HEIGHT self._in_game = True self._right = RIGHT self._left = LEFT self._color = WHITE self._background = BLACK self._lines_color = BLUE self._half_pad_width = HALF_PAD_WIDTH # initialize display self.display = pygame.display.set_mode((self._display_width, self._display_height)) pygame.display.set_caption("PONG") # initializing ball object self.ball = Ball(BALL_RADIUS, self.display, self._color) # initialize paddle objects pad1_xcoord = WIDTH - HALF_PAD_WIDTH pad2_xcoord = HALF_PAD_WIDTH self.paddle1 = Paddle(PAD_WIDTH, PAD_HEIGHT, pad1_xcoord, self._color, self.display) self.paddle2 = Paddle(PAD_WIDTH, PAD_HEIGHT, pad2_xcoord, self._color, self.display) #initialize scores score1_pos = (int((3/4)*self._display_width),int((1/8)*self._display_width)) score2_pos = (int((1/4)*self._display_width),int((1/8)*self._display_width)) self.score1 = Score(score1_pos, self._color, self.display) self.score2 = Score(score2_pos, self._color, self.display) def new_game(self): """ start a new game """ # setting initial values self.score1.reset_score() self.score2.reset_score() self.paddle1.set_position(HEIGHT // 2) self.paddle2.set_position(HEIGHT // 2) self.spawn_direction = self._right # spawn ball self.ball.spawn(self.spawn_direction) def loop(self): """ game loop """ self.clock = pygame.time.Clock() self.new_game() while self._in_game: for event in pygame.event.get(): self.check_quit(event) self.check_keydown(event) self.check_keyup(event) self.paddle1.update_position() self.paddle2.update_position() self.ball.update_position() self.check_goal([self.paddle1, self.paddle2], self.ball) self.display.fill(self._background) self.draw_lines() self.paddle1.draw_paddle() self.paddle2.draw_paddle() self.ball.draw_ball() self.score1.blit_score() self.score2.blit_score() pygame.display.update() self.clock.tick(60) # here starts auxiliary and event handling functions... def change_game_state(self): """ change the game state, it should become false to quit the game """ if self._in_game: self._in_game = False else: self._in_game = True def change_spawn_direction(self): """ change the spawn direction """ current_direction = self.spawn_direction if current_direction == self._right: self.spawn_direction = self._left else: self.spawn_direction = self._right def draw_lines(self): """ draw three lines on the pong field """ line1_y_axis = self._display_width - self.paddle1.get_width() start_pos_line1 = (line1_y_axis, 0) end_pos_line1 = (line1_y_axis, self._display_height) line2_y_axis = self._display_width // 2 start_pos_line2 = (line2_y_axis, 0) end_pos_line2 = (line2_y_axis, self._display_height) line3_y_axis = self.paddle2.get_width() start_pos_line3 = (line3_y_axis, 0) end_pos_line3 = (line3_y_axis, self._display_height) pygame.draw.line(self.display, self._lines_color, start_pos_line1, end_pos_line1) pygame.draw.line(self.display, self._lines_color, start_pos_line2, end_pos_line2) pygame.draw.line(self.display, self._lines_color, start_pos_line3, end_pos_line3) # setting event handlers def check_quit(self, event): """ if quit button is pressed it changes the game state and quits """ if event.type == pygame.QUIT: self.change_game_state() def check_keydown(self, event): """ event handler for keydown events """ if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: self.paddle1.set_velocity(-7) if event.key == pygame.K_DOWN: self.paddle1.set_velocity(7) if event.key == pygame.K_w: self.paddle2.set_velocity(-7) if event.key == pygame.K_s: self.paddle2.set_velocity(7) def check_keyup(self, event): """ event handler for keyup events """ if event.type == pygame.KEYUP: if event.key == pygame.K_UP: self.paddle1.set_velocity(0) if event.key == pygame.K_DOWN: self.paddle1.set_velocity(0) if event.key == pygame.K_w: self.paddle2.set_velocity(0) if event.key == pygame.K_s: self.paddle2.set_velocity(0) def check_goal(self, paddles, ball): """ check for ball x paddle collision if a collision occur the ball should bounce """ mid_point = self._display_width // 2 ball_center = ball.get_position() ball_radius = ball.get_radius() ball_right = ball_center[0] + ball_radius ball_left = ball_center[0] - ball_radius for paddle in paddles: paddle_rect = paddle.get_rectangle() if (ball_right >= paddle_rect.left) and (paddle_rect.left > mid_point): if paddle_rect.collidepoint(ball_right, ball_center[1]): new_x_pos = (2 * paddle_rect.left - ball_right - ball_radius) ball.set_position([new_x_pos, ball_center[1]]) ball.bounce(1.05) else: self.score2.update_score() self.change_spawn_direction() ball.spawn(self.spawn_direction) elif (ball_left <= paddle_rect.right) and (paddle_rect.right < mid_point): if paddle_rect.collidepoint(ball_left, ball_center[1]): new_x_pos = (2 * paddle_rect.right - ball_left + ball_radius) ball.set_position([new_x_pos, ball_center[1]]) ball.bounce(1.05) else: self.score1.update_score() self.change_spawn_direction() ball.spawn(self.spawn_direction) ############################################################################################################### # BALL CLASS STARTS HERE.... class Ball: """ class to create and draw a ball """ def __init__(self, radius, display, color): """ initialize the ball """ # variables that won't change value self._radius = radius self._display = display self._color = color # variables that will change value self.position = [self._display.get_width() // 2, self._display.get_height() // 2] self.velocity = [0, 0] def spawn(self, direction): """ spawn ball from the center, the ball goes upper right if true, and upper left if false """ self.position = [self._display.get_width() // 2, self._display.get_height() // 2] if direction: self.velocity = [(random.randrange(12,24)/10.0),-(random.randrange(6,18)/10.0)] else: self.velocity = [-(random.randrange(12,24)/10.0),-(random.randrange(6,18)/10.0)] def update_position(self): """ update the ball position based on its speed """ self.position[0] += self.velocity[0] # update x position self.position[1] += self.velocity[1] # update y position self.boundary_collision() # check collision with the borders def boundary_collision(self): """ if the ball collides with the boundary the ball will bounce """ upper_boundary = self._radius lower_boundary = (self._display.get_height() - self._radius) if self.position[1] <= upper_boundary: self.position[1] = 2 * upper_boundary - self.position[1] self.velocity[1] *= -1 if self.position[1] >= lower_boundary: self.position[1] = lower_boundary - (self.position[1] % lower_boundary) self.velocity[1] *= -1 def draw_ball(self): """ draw the ball on the display """ x_position = int(self.position[0]) y_position = int(self.position[1]) pygame.draw.circle(self._display, self._color, [x_position, y_position], self._radius) def get_position(self): """ returns current position """ return self.position def set_position(self, new_coord): """ set a new pair of coordinates as ball position """ self.position = new_coord def get_velocity(self): """ returns current velocity """ return self.velocity def set_velocity(self, new_vel): """ set a new pair of values as ball velocity """ self.velocity = new_vel def bounce(self, num = 1): """ bounce the ball on the paddle and allow change in the speed """ self.velocity[0] *= -num self.velocity[1] *= num def get_radius(self): """ returns the ball radius value """ return self._radius ############################################################################################################################# # PADDLE CLASS STARTS HERE... class Paddle: """ class to create and draw the paddles """ def __init__(self, width, height, x_coord, color, display): """ initializes a paddle """ # variables that won't change value self._width, self._height = width, height self._color = color self._display = display self._x_coord = x_coord # variable that will change value throughout the game self.rectangle = pygame.Rect((0 , 0), (self._width, self._height)) self.rectangle.center = (self._x_coord, int(self._display.get_height() / 2)) self.vel = 0 def update_position(self): """ updates the paddle position """ self.rectangle.top += self.vel self.keep_on_screen() def keep_on_screen(self): """ prevents the paddling from passing through the boundaries """ if (self.rectangle.bottom > self._display.get_height()): self.set_position(self._display.get_height() - self._height) elif (self.rectangle.top < 0): self.set_position(0) def set_position(self, topPos): """ change the paddle y coordinate """ self.rectangle.top = topPos def get_position(self): """ return the paddle's center position coordinates as a tuple """ return self.rectangle.center def set_velocity(self, vel): """ set a number as velocity on y direction """ self.vel = vel def get_velocity(self): """ returns the current velocity on y direction """ return self.vel def get_rectangle(self): """ returns the paddle's rectangle """ return self.rectangle def draw_paddle(self): """ command to draw the paddle """ pygame.draw.rect(self._display, self._color, self.rectangle) def get_width(self): """ get paddle width """ return self._width ############################################################################################################################ # SCORE CLASS STARTS HERE... class Score: """ class that will handle the game score """ def __init__(self, center_pos, color, display): """ initializing socre """ self._display = display self._color = color self._center_pos = center_pos self._font = pygame.font.Font("freesansbold.ttf", 40) self.score = 0 def update_score(self): """ update the score value by one """ self.score += 1 def get_score(self): """ returns current score """ return self.score def set_score(self, new_val): """ set a new value to score """ self.score = new_val def reset_score(self): """ resets the score to zero """ self.score = 0 def blit_score(self): """ draws the score on the screen """ text_surface = self._font.render(str(self.get_score()), True, self._color) text_rect = text_surface.get_rect() text_rect.center = self._center_pos self._display.blit(text_surface, text_rect) ############################################################################################################################### # callling the game and starting the loop new_game = PongGame() new_game.loop() pygame.quit() quit()
f5575924d6740759b25852fe241b951deb4d0bb1
fvvsantana/dynamicProgramming
/janKenPuzzle.py
3,577
3.65625
4
#it will store all the solutions to all the possible boards solutions = {} #get the input and return the variables (int, int, list) def readInput(): line = list(map(int, input().rstrip().split())) rows = line[0] cols = line[1] board = [] for i in range(rows): board.append(list(map(int, input().rstrip().split()))) return rows, cols, board #return true if a beats b def beat(a, b): return b and ((b-a)%3==1) #return a list of all the possible movements from (i, j) def findLegalMovements(i, j, board, rows, cols): typeOfPiece = board[i][j] listOfMovements = [] #up if i > 0 and beat(typeOfPiece, board[i-1][j]): listOfMovements.append([i-1, j]) #left if j > 0 and beat(typeOfPiece, board[i][j-1]): listOfMovements.append([i, j-1]) #down if i < rows-1 and beat(typeOfPiece, board[i+1][j]): listOfMovements.append([i+1, j]) #right if j < cols-1 and beat(typeOfPiece, board[i][j+1]): listOfMovements.append([i, j+1]) return listOfMovements #store the solutions and return a tupled version of board def findSolutions(board, rows, cols): boardTuple = tuple(tuple(row) for row in board) #check if the solution is not already calculated if(boardTuple not in solutions): numberOfPieces = 0 firstPieceI = 0 firstPieceJ = 0 #loop through the board for i in range(rows): for j in range(cols): #if there is a piece if board[i][j] != 0: #increment the number of pieces numberOfPieces += 1 if numberOfPieces == 1: #get the piece's position firstPieceI = i firstPieceJ = j #stop if numberOfPieces reach 2 elif numberOfPieces == 2: break #add the board and its solution to solutions if(numberOfPieces == 1): solutions[boardTuple] = {(firstPieceI, firstPieceJ, boardTuple[firstPieceI][firstPieceJ]) : 1} else: solutions[boardTuple] = {} #for each position of the board for i in range(firstPieceI, rows): for j in range(0, cols): #if there is a piece if board[i][j] != 0: listOfMovements = findLegalMovements(i, j, board, rows, cols) for movement in listOfMovements: #move the piece capturedPiece = board[movement[0]][movement[1]] board[movement[0]][movement[1]] = board[i][j] board[i][j] = 0 #find the solutions to the new board newBoard = findSolutions(board, rows, cols) #print(boardTuple) #take the current solutions currentSolutions = solutions[boardTuple] #take the new solutions newSolutions = solutions[newBoard] for finalState in newSolutions: currentSolutions[finalState] = currentSolutions.get(finalState, 0) + newSolutions[finalState] #move the piece back board[i][j] = board[movement[0]][movement[1]] board[movement[0]][movement[1]] = capturedPiece return boardTuple #get the input, call the solver and print the output def main(): #get the input rows, cols, board = readInput() #find the solutions boardTuple = findSolutions(board, rows, cols) #print how many different solutions are there finalStates = solutions[boardTuple] nSolutions = 0 for finalState in finalStates: nSolutions += finalStates[finalState] print(nSolutions) #print the number of final states print(len(finalStates), end='') #print the final states finalStates = list(finalStates.keys()) finalStates.sort() for finalState in finalStates: print('\n' + str(finalState[0]+1) + ' ' + str(finalState[1]+1) + ' ' + str(finalState[2]), end='') #allow this module to be imported if __name__ == "__main__": main()
238dc292935318ba1dc292ade30b61865ad36316
viviczhou/Data-Mining
/FPGrowth.py
7,845
3.546875
4
''' Programming Project: Frequent Itemset Mining Algorithms Author: Chunlei Zhou 2019/10/11 version 1.0 Due: 2019/10/17 Algorithms used: (2) FP-growth [HPY00] Use the UCI Adult Census Dataset http://archive.ics.uci.edu/ml/datasets/Adult The algorithm contains two parts. First part: build the tree; Second part: mine through the tree. ''' # FP-growth [HPY00] import operator import time class Conditional_FP_Tree: def __init__(self, item, support, parentNode): self.name = item self.count = support self.nodeLink = None self.parent = parentNode self.children = {} def support_count(self, support): self.count += support ''' def display(self, depth = 1): print(' '*depth, self.name, ' ', self.count) for child in self.children.values(): child.display(depth + 1) ''' ''' def find_frequent_items(D, min_sup:int): item_count = defaultdict(int) for row in D: for item in row: item_count[item] += 1 items = dict() for item, count in item_count.items(): if count >= min_sup: items.update({item: count}) F = sorted(items.items(), key=operator.itemgetter(1), reverse=True) return F ''' def create_FP_Tree(D, min_sup:int): # To create FP Tree, create headertable first. headertable = {} for row in D: for item in row: headertable[item] = headertable.get(item, 0) + D[row] # The headertable include item name and support count. remove = [] for key in headertable.keys(): if headertable[key] < min_sup: remove.append(key) for item in remove: headertable.pop(item) # If item is not frequent, then remove from headertable. ### frequent_itemset = find_frequent_items(D, min_sup) frequent_itemset = sorted(headertable.items(), key=operator.itemgetter(1), reverse=True) if len(frequent_itemset) != 0: for item in headertable: headertable[item] = [headertable[item], None] # create node link. # Now headertable contains itemname, support count, and node link for each item. FPTree = Conditional_FP_Tree('Null', 1, None) # root node: item = Null, support = 1, Parent = None for transaction, support in D.items(): treegrowth = {} for item in transaction: if item in set(headertable.keys()): treegrowth[item] = headertable[item][0] # only need frequency here # treegrowth contains all unique frequent items in each transaction in turn if len(treegrowth) > 0: sortgrowth = sorted(treegrowth.items(), key=operator.itemgetter(1), reverse=True) # To build the tree, sort by support count. Highest comes first. nextitemset = [] for item in sortgrowth: nextitemset.append(item[0]) # THIS IS SOMETHING NEW TO ME: orderedItems = [v[0] for v in st] # MORE EFFICIENT CODING THIS WAY. updateFPTree(nextitemset, FPTree, headertable, support) # Update tree for each transaction in turn to construct the whole tree. return FPTree, headertable else: return None, None ''' ============ Insert Tree ============= ''' def updateFPTree(itemset, tobeupdateTree, headertable, support): # Update tree for item in the chosen itemset one by one. # Finish by recursion if itemset[0] in tobeupdateTree.children: # If the item is already one child of the current tree, then update the support count. tobeupdateTree.children[itemset[0]].support_count(support) else: # Call to build a new branch of the conditional tree and update the headertable. tobeupdateTree.children[itemset[0]] = Conditional_FP_Tree(itemset[0], support, tobeupdateTree) if headertable[itemset[0]][1] == None: # If there is no nodeLink, then create one. headertable[itemset[0]][1] = tobeupdateTree.children[itemset[0]] else: # If there is a nodeLink, then update it. updatenodeLink(headertable[itemset[0]][1], tobeupdateTree.children[itemset[0]]) # Recursion if len(itemset) > 1: new_itemset = itemset[1::] updateFPTree(new_itemset, tobeupdateTree.children[itemset[0]], headertable, support) def updatenodeLink(new_node, target_node): # Based on Figure 6.7, all linked nodes are as nodes in linked list. # When there is a nodeLink, then find the end node and add the new link. while new_node.nodeLink != None: new_node = new_node.nodeLink new_node.nodeLink = target_node ''' ============== Top-down finished. Now starts bottom-up. ============== ''' def bottom_up_Tree(leafnode, path): # Recursion again if leafnode.parent != None: # We have not reached the root node yet. path.append(leafnode.name) # grow up bottom_up_Tree(leafnode.parent, path) return path def find_path(node): # Recursion again... conditional_pattern_base = {} while node != None: path = [] updatepath = bottom_up_Tree(node, path) if len(updatepath) > 1: conditional_pattern_base[frozenset(updatepath[1:])] = node.count # node is the leafnode for this certain path, # so its support count should be the minimum support count of all nodes in the path # Use the minimun support count of all nodes in the path as the support count of the path. # conditional pattern base stored all paths and their support counts. node = node.nodeLink # Start from the bottom and move to the parent to find all paths. return conditional_pattern_base ''' ============== Mine Frequent Patterns ============== ''' def FP_Growth(headertable, prefix_path, min_sup:int, frequent_itemset): # beta = [alpha[0] for alpha in sorted(headertable.items(), key=operator.itemgetter(1))] why bug? beta = [alpha[0] for alpha in sorted(headertable.items(), key=lambda p: p[1][0])] # Start from the bottom frequent_1_itemset: leafnode # Use each one of the frequent_1_item as the leafnode, updating path with len(path) increase by 1 each time. for base_node in beta: newfreqitemset = prefix_path.copy() newfreqitemset.add(base_node) frequent_itemset.append((newfreqitemset, headertable[base_node][0])) conditional_pattern_base = find_path(headertable[base_node][1]) conditional_FPTree, conditional_headertable = create_FP_Tree(conditional_pattern_base, min_sup) if conditional_headertable != None: # As long as there is frequent itemset, recurse. FP_Growth(conditional_headertable, newfreqitemset, min_sup, frequent_itemset) return frequent_itemset ###################################################################################################################### if __name__ == "__main__": start_time = time.time() with open('/Users/zhouchunlei/Desktop/DATA SCIENCE/Data Mining/Homework/Project Apriori/adult.data.csv') as file: ds = file.readlines() transactions = [] for i in range(len(ds)): transactions.append(ds[i].strip().split(',')) Dataset = {} for transaction in transactions: Dataset[frozenset(transaction)] = 1 Frequent_Itemset = [] Prefix_Path = set([]) min_sup = len(transactions) * 0.5 FPTree, HeaderTable = create_FP_Tree(Dataset, min_sup) FrequentItemset = FP_Growth(HeaderTable, Prefix_Path, min_sup, Frequent_Itemset) print(FrequentItemset) # print(len(FrequentItemset)) print("The executing time of the FP-Growth algorithm is %s seconds." % (time.time() - start_time))
c57e7cfb5c272def2c78350a1d481a00aa59997b
Laixsias/BigdataPython
/2.6.py
656
4.03125
4
dictionary = ["имя", "цена", "количество", "ед"] goods = [] while input("Хотите добавить новый продукт ? Введите да/нет: ") == 'да': new_goods = {} for key in dictionary: new_goods[key] = input("Введите параметр \"" + key + "\" для нового товара: ") goods.append(new_goods) print(goods) analitics = {} for good in goods: for key, value in good.items(): if key in analitics: if value not in analitics[key]: analitics[key].append(value) else: analitics[key] = [value] print(analitics)
a59fc3330c0cb851e43252c9f54c47f2ce2c175e
mennanov/problem-sets
/dynamic_programming/palindromic_subsequence.py
2,379
4.125
4
# -*- coding: utf-8 -*- """ A subsequence is palindromic if it is the same whether read left to right or right to left. For instance, the sequence A, C, G, T, G, T, C, A, A, A, A, T, C, G has many palindromic subsequences, including A, C, G, C, A and A, A, A, A (on the other hand, the subsequence A, C, T is not palindromic). Goal: compute the longest palindromic subsequence. """ from graph_shortest_path import memoize class Palindrome(object): """ Palindrome object """ def __init__(self, middle=None): self.left = [] self.middle = middle self.right = [] def __len__(self): return len(self.left) + len(self.right) def __cmp__(self, other): if len(self) > len(other): return 1 elif len(self) < len(other): return -1 else: return 0 def __str__(self): return str(self.left[::-1] + [self.middle] + self.right if self.middle else self.left[::-1] + self.right) def copy(self): c = self.__class__() c.left = self.left[:] c.middle = self.middle c.right = self.right[:] return c class PalindromicSubsequence(object): """ Longest palindromic subsequence: dynamic programming approach. Running time is O(N^2) """ def __init__(self, iterable): self.iterable = iterable @memoize def run(self, lo=None, hi=None): if lo is None: lo = 0 if hi is None: hi = len(self.iterable) - 1 if lo == hi: # 1 letter is also a palindrome return Palindrome(self.iterable[lo]) elif lo > hi: # empty palindrome return Palindrome() if self.iterable[lo] == self.iterable[hi]: # first and last letters are equal - find a palindrome between these boundaries p = self.run(lo + 1, hi - 1).copy() # wrap the palindrome with the current letters p.left.append(self.iterable[lo]) p.right.append(self.iterable[hi]) return p else: return max(self.run(lo + 1, hi), self.run(lo, hi - 1)) if __name__ == '__main__': sequence = 'A, C, G, T, G, T, C, A, A, A, A, T, C, G'.split(', ') pl = PalindromicSubsequence(sequence) assert pl.run() == ['G', 'C', 'A', 'A', 'A', 'A', 'C', 'G']
efb2bfcf2e780a6de33bd4a2e9989b25cfcaef6f
mennanov/problem-sets
/math_problems/integer_multiplication.py
2,411
4.0625
4
# -*- coding: utf-8 -*- import math def multiple(a, b): """ Naive implementation of decimal integer multiplication. It runs ~O(2N*M), where N = len(a) and M = len(b). This algorithm seems to be slow (it may run quadratic if N==M) """ a, b = str(a), str(b) # intermediary results rows = [] for i in xrange(len(b) - 1, -1, -1): # reversed intermediate row row = [0] * (len(b) - i - 1) carry = 0 for j in xrange(len(a) - 1, -1, -1): m = int(b[i]) * int(a[j]) + carry r = m % 10 carry = m // 10 row.append(r) row.append(carry) rows.append(row) # add rows sum_row = [0] * len(rows[0]) for i in xrange(len(rows)): row = rows[i] new_sum_row = [] carry = 0 for j in xrange(len(row)): try: c = sum_row[j] except IndexError: c = 0 s = c + row[j] + carry r = s % 10 carry = s // 10 new_sum_row.append(r) new_sum_row.append(carry) sum_row = new_sum_row[:] sum_row.reverse() return int(''.join([str(x) for x in sum_row])) def multiple_karatsuba(x, y): """ Recursive divide&conquer algorithm for integer multiplication for base 10. It runs O(N**Log3) which is faster than O(N**2) as in naive approach. """ if x < 10 or y < 10: # this is a tail of the recursion: # integers are simple enough to perform a regular multiplication return x * y # convert to string to use Python slicing x, y = str(x), str(y) # divide the both integers in to half (ceil is for the odd numbers) a, b = int(x[:int(math.ceil(len(x) / 2.0))]), int(x[int(math.ceil(len(x) / 2.0)):]) c, d = int(y[:int(math.ceil(len(y) / 2.0))]), int(y[int(math.ceil(len(y) / 2.0)):]) # perform arithmetic steps step1 = multiple_karatsuba(a, c) step2 = multiple_karatsuba(b, d) step3 = multiple_karatsuba((a + b), (c + d)) step4 = step3 - step2 - step1 # get the longest input length m = max(len(x), len(y)) / 2 # perform addition return step1 * (10 ** (m * 2)) + step2 + step4 * (10 ** m) if __name__ == '__main__': assert multiple(5678, 1234) == 5678 * 1234 assert multiple(11, 11) == 11 * 11 assert multiple_karatsuba(5678, 1234) == 5678 * 1234
df6cab7a299bf851115125e8c5e3bcedb209e246
mennanov/problem-sets
/combinatorics/wildcard.py
797
3.59375
4
# -*- coding: utf-8 -*- def wildcard(pattern): """ Given a string of 0s, 1s, and ?s (wildcards), generate all 0-1 strings that match the pattern """ wildcards = pattern.count('?') alphabet = ['0', '1'] def xcombinations(items, length): if length == 0: yield [] else: for i in xrange(len(items)): for sc in xcombinations(items, length - 1): yield [items[i]] + sc for combination in xcombinations(alphabet, wildcards): buff = '' for c in pattern: if c == '?': buff += combination.pop() else: buff += c yield buff if __name__ == '__main__': assert list(wildcard('1??0')) == ['1000', '1100', '1010', '1110']
bcb7788af7663d0e9c52057795c5f62acc349ba1
mennanov/problem-sets
/other/strings/string_all_unique_chars.py
1,371
4.125
4
# -*- coding: utf-8 -*- """ Implement an algorithm to determine if a string has all unique characters. """ def all_unique_set(string): """ Running time and space is O(N). """ return len(string) == len(set(string)) def all_unique_list(string): """ Running time is O(N), space is O(R) where R is a length of an alphabet. """ # assume we have an ASCII string r = 65535 if isinstance(string, unicode) else 255 if len(string) > r: return False chars = [0] * r for i, char in enumerate(string): chars[ord(char)] += 1 if chars[ord(char)] > 1: return False return True def all_unique_bit(string): """ Running time is O(N), required space is 1 byte only for ASCII string and 2 bytes for a Unicode string. Space usage is optimized using a bit vector. """ # bit vector chars = 0 for i, char in enumerate(string): # check if we have already seen this char if chars & (1 << ord(char)) > 0: return False else: chars |= (1 << ord(char)) return True if __name__ == '__main__': s = 'abcdefghatyk' assert not all_unique_set(s) assert not all_unique_list(s) assert not all_unique_bit(s) s = 'abcdefghtlk' assert all_unique_set(s) assert all_unique_list(s) assert all_unique_bit(s)
907c19c0a141e093d7a2fa1670e515c6ac0a5248
mennanov/problem-sets
/greedy_algorithms/big_clustering.py
4,515
3.953125
4
# -*- coding: utf-8 -*- """ It is a reversed problem of a clustering: what is the largest value of k such that there is a k-clustering with spacing at least s? Imagine that we have a big graph. So big, in fact, that the distances (i.e., edge costs) are only defined implicitly, rather than being provided as an explicit list. For example, we havea string "0 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1" which denotes the 24 bits associated with some node. The distance between two nodes u and v in this problem is defined as the Hamming distance: the number of differing bits between the two nodes' labels. For example, the Hamming distance between the 24-bit label of the node above and the label "0 1 0 0 0 1 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 0 1" is 3 (since they differ in the 3rd, 7th, and 21st bits). In this approach can not examine each pair of nodes since it will run quadratic time and we can not accept this on a huge graph. Instead we will build a Huffman tree with all the nodes, then for each node we will be able to find all the nodes with the Humming distance <= needed (closest nodes) in a sublinear time per each call. Though in the worst case it may still run quadratic, in practice it is fast enough. """ from other.graphs.graph import EdgeWeightedGraph from clustering import Clustering class HuffmanTree(object): class Node(object): def __init__(self, value=None): # only a leaf node may have a value self.value = value # pointer to the left node self.left = None # pointer to the right node self.right = None def __repr__(self): return u'Node({})'.format(repr(self.value)) def __init__(self): self.root = self.Node() def add(self, value, bits): """ Add a new leaf node in a tree using provided bits (a list of 0 and 1) """ # print value, bits self.root = self._add(value, bits, self.root) def _add(self, value, bits, node): if node is None: if len(bits) == 0: return self.Node([value]) else: return self._add(value, bits, self.Node()) if len(bits) == 0: # duplicates are also accepted node.value.append(value) return node if bits[0] == 0: # go left node.left = self._add(value, bits[1:], node.left) else: # go right node.right = self._add(value, bits[1:], node.right) return node def relative_nodes(self, bits, humming_distance): """ Find all the nodes which humming distance is less or equal to the given Humming distance """ for node in self._dfs(bits, humming_distance, self.root, len(bits)): yield node def _dfs(self, bits, distance_needed, node, bit_length, distance_so_far=0, bit_position=0): if node is None: return if node.value and distance_so_far <= distance_needed: yield node, distance_so_far if bit_position >= bit_length: return # go left dist = distance_so_far + 1 if bits[bit_position] == 1 else distance_so_far if dist <= distance_needed: for n in self._dfs(bits, distance_needed, node.left, bit_length, dist, bit_position + 1): yield n # go right dist = distance_so_far + 1 if bits[bit_position] == 0 else distance_so_far if dist <= distance_needed: for n in self._dfs(bits, distance_needed, node.right, bit_length, dist, bit_position + 1): yield n if __name__ == '__main__': tree = HuffmanTree() nodes = dict() with open('clustering.txt', 'r') as fp: # fill in the Huffman tree for i, line in enumerate(fp): if i > 0: bits = [int(x) for x in line.split()] tree.add(i, bits) nodes[i] = bits graph = EdgeWeightedGraph() for node, bits in nodes.iteritems(): # for this node add its edges to the graph with weights <= 3 only # to be able to find all these edges we look them up in a Huffman tree: # if we look at each pair of nodes the program will be too slow (quadratic) for r_nodes, distance in tree.relative_nodes(bits, 3): for n in r_nodes.value: graph.add_edge(node, n, distance) c = Clustering(graph) assert c.max_k(3) == 989
1248d110f19b8e22098edd4f1d7c6c41f4d07048
mennanov/problem-sets
/greedy_algorithms/graph_mst_prim.py
2,740
3.59375
4
# -*- coding: utf-8 -*- from Queue import PriorityQueue from other.graphs.graph import EdgeWeightedGraph class MSTPrim(object): """ Lazy implementation of a minimum spanning tree Prim's algorithm which runs in O(MlogN) where M is a number of edges and N is a number of vertices. At each iteration it looks for a closest vertex (edge with a min-cost) and adds it to an MST using a cut property. To find the closest vertex we use a heap bases priority queue. We call it lazy because we don't remove obsolete edges from the queue: we just don't use them checking the constraints every time. """ def __init__(self, graph): self.graph = graph # queue with edges haven't seen so far self.edges = PriorityQueue() # visited vertices so far self.visited = set() # total cost of the mst self.cost = 0 # resulting set of edges of the mst self.mst = set() # pick a random vertex from a graph start = next(graph.vertices.itervalues()) # "visit" this vertex self._visit(start) while not self.edges.empty() and len(self.visited) < len(self.graph): weight, edge = self.edges.get() if edge.vertex_from in self.visited and edge.vertex_to in self.visited: # leave that edge and don't add it to the mst since BOTH of the vertices are # already in the mst: they are already connected and adding this edge will cause a loop continue else: # add that edge to mst self.mst.add(edge) # increase the total cost of the mst self.cost += edge.weight if edge.vertex_from not in self.visited: self._visit(edge.vertex_from) if edge.vertex_to not in self.visited: self._visit(edge.vertex_to) def _visit(self, vertex): """ Mark vertex as visited and also add all the outgoing edges to the priority queue. """ self.visited.add(vertex) for edge in vertex.outgoing: if edge.vertex_to not in self.visited: # put the edge into pq with weight as a priority self.edges.put((edge.weight, edge)) if __name__ == '__main__': graph = EdgeWeightedGraph() edges = [(1, 2, 2474), (2, 4, -246), (4, 3, 640), (4, 5, 2088), (3, 6, 4586), (6, 5, 3966), (5, 1, -3824)] for edge in edges: graph.add_edge(edge[0], edge[1], edge[2]) # add the backwards edge to simulate an undirected graph graph.add_edge(edge[1], edge[0], edge[2]) mst = MSTPrim(graph) assert mst.cost == 2624
412a9d6c8bacd15241be55c3ced1f7202cd74c0a
mennanov/problem-sets
/dynamic_programming/long_trip.py
2,596
4.03125
4
# -*- coding: utf-8 -*- """ You are going on a long trip. You start on the road at mile post 0. Along the way there are n hotels, at mile posts a1 < a2 < · · · < an, where each ai is measured from the starting point. The only places you are allowed to stop are at these hotels, but you can choose which of the hotels you stop at. You must stop at the final hotel (at distance an), which is your destination. You’d ideally like to travel 200 miles a day, but this may not be possible (depending on the spacing of the hotels). If you travel x miles during a day, the penalty for that day is (200 − x)^2 You want to plan your trip so as to minimize the total penalty—that is, the sum, over all travel days, of the daily penalties. Goal: determine the optimal sequence of hotels at which to stop. """ from graph_shortest_path import memoize class Route(object): """ Route with hotels and total penalty """ def __init__(self, penalty=0): self.hotels = [] self.penalty = penalty def __cmp__(self, other): if self.penalty > other.penalty: return 1 elif self.penalty < other.penalty: return -1 else: return 0 def visit_hotel(self, hotel, penalty): self.hotels.append(hotel) self.penalty += penalty def copy(self): c = Route() c.hotels = self.hotels[:] c.penalty = self.penalty return c def __str__(self): return 'Hotels: {}, penalty: {}'.format(str(self.hotels), str(self.penalty)) class LongTripDP(object): """ Long trip dynamic programming approach. For each hotel we find the route with the lowest penalty. Running time is O(n^2). """ def __init__(self, distances, penalty): self.penalty = penalty self.distances = distances @memoize def travel(self, position=None): if position is None: position = len(self.distances) - 1 if position == -1: return Route() best_route = Route(float('inf')) for i in xrange(position - 1, -2, -1): route = self.travel(i).copy() diff = self.distances[position] - self.distances[i] if i >= 0 else self.distances[position] route.visit_hotel(position, self.penalty(diff)) if route < best_route: best_route = route return best_route if __name__ == '__main__': distances = [150, 200, 320, 380, 420, 600] trip = LongTripDP(distances, lambda x: (200 - x) ** 2) assert trip.travel().hotels == [1, 4, 5]
24a138a887902e511570cb744aae827d3b19409d
vatsaashwin/PreCourse_2
/Exercise_4.py
969
4.4375
4
# Python program for implementation of MergeSort def mergeSort(arr): if len(arr) >1: # find middle and divide the array into left and right m = len(arr) //2 L = arr[:m] R = arr[m:] # print(L, R) # recursively sort the left and right halves mergeSort(L) mergeSort(R) i=j=k=0 while i < len(L) and j < len(R): if L[i]< R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while i<len(L): arr[k] = L[i] i+=1 k+=1 while j <len(R): arr[k] = R[j] j+=1 k+=1 # Code to print the list def printList(arr): arrlen = len(arr) for i in range(arrlen): print(arr[i]) # driver code to test the above code if __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] print ("Given array is", end="\n") printList(arr) mergeSort(arr) print("Sorted array is: ", end="\n") printList(arr)
81cad42676b1bc47246872aaddb9fc34e0bfcd27
suminb/coding-exercise
/leetcode/search_in_rotated_sorted_array.py
1,765
3.953125
4
# # @lc app=leetcode id=33 lang=python3 # # [33] Search in Rotated Sorted Array # difficulty: medium # https://leetcode.com/problems/search-in-rotated-sorted-array/ # from typing import List import pytest class Solution: def search(self, nums: List[int], target: int) -> int: n = len(nums) left, right = 0, n - 1 return search(nums, target, left, right) def search(nums, target, left, right): if left > right: return -1 mid = (left + right) // 2 if target == nums[mid]: return mid elif nums[left] <= nums[mid]: # if left half is sorted if nums[left] <= target < nums[mid]: return search(nums, target, left, mid - 1) else: return search(nums, target, mid + 1, right) else: # if right half is sorted if nums[mid] < target <= nums[right]: return search(nums, target, mid + 1, right) else: return search(nums, target, left, mid - 1) @pytest.mark.parametrize('nums, target, expected', [ ([0], 0, 0), ([1], 2, -1), ([2, 3, 4, 5, 1], 0, -1), ([2, 3, 4, 5, 1], 1, 4), ([2, 3, 4, 5, 1], 2, 0), ([2, 3, 4, 5, 1], 3, 1), ([2, 3, 4, 5, 1], 4, 2), ([2, 3, 4, 5, 1], 5, 3), ([5, 1, 2, 3, 4], 1, 1), ([4, 5, 6, 7, 0, 1, 2], 0, 4), ([4, 5, 6, 7, 0, 1, 2], 1, 5), ([4, 5, 6, 7, 0, 1, 2], 2, 6), ([4, 5, 6, 7, 0, 1, 2], 3, -1), ([4, 5, 6, 7, 0, 1, 2], 4, 0), ([4, 5, 6, 7, 0, 1, 2], 5, 1), ([4, 5, 6, 7, 0, 1, 2], 6, 2), ([4, 5, 6, 7, 0, 1, 2], 7, 3), ]) def test_rotated_array_search(nums, target, expected): actual = Solution().search(nums, target) assert expected == actual if __name__ == '__main__': pytest.main(['-v', __file__])
247cde1603a26c5788b2e46cd8e654679ce4d548
suminb/coding-exercise
/leetcode/leetcode.py
1,345
4.09375
4
class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): return f'ListNode<{self.val}>' class TreeNode: def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right def build_linked_list(xs): if not xs: return None i, n = 1, len(xs) head = node = ListNode(xs[0]) while i < n: node.next = ListNode(xs[i]) node = node.next i += 1 return head def assert_linked_list(head, xs): count = 0 node = head while node is not None: assert node.val == xs[count] node = node.next count += 1 assert len(xs) == count def build_binary_tree(xs): """Builds a binary tree from a list of elements.""" def build(root, xs, i, n): if i < n and xs[i] is not None: root = TreeNode(xs[i]) root.left = build(root.left, xs, i * 2 + 1, n) root.right = build(root.right, xs, i * 2 + 2, n) return root if not xs: return None else: return build(None, xs, 0, len(xs)) def print_binary_tree(node, depth=0): if node: print(' ' * (depth * 2) + str(node.val)) print_binary_tree(node.left, depth + 1) print_binary_tree(node.right, depth + 1)
367e5bcdd755649dbedac19066b4f77e3a1293d7
suminb/coding-exercise
/daily-interview/binary_tree_level_with_minimum_sum.py
1,516
4.125
4
# [Daily Problem] Binary Tree Level with Minimum Sum # # You are given the root of a binary tree. Find the level for the binary tree # with the minimum sum, and return that value. # # For instance, in the example below, the sums of the trees are 10, 2 + 8 = 10, # and 4 + 1 + 2 = 7. So, the answer here should be 7. # # class Node: # def __init__(self, value, left=None, right=None): # self.val = value # self.left = left # self.right = right # # def minimum_level_sum(root): # # Fill this in. # # # 10 # # / \ # # 2 8 # # / \ \ # # 4 1 2 # node = Node(10) # node.left = Node(2) # node.right = Node(8) # node.left.left = Node(4) # node.left.right = Node(1) # node.right.right = Node(2) # # print minimum_level_sum(node) from collections import deque import pytest from common import build_binary_tree def minimum_level_sum(root): queue = deque() queue.append((root, 0)) sums = {} while queue: node, level = queue.popleft() if node: sums.setdefault(level, 0) sums[level] += node.val queue.append((node.left, level + 1)) queue.append((node.right, level + 1)) return min(sums.values()) @pytest.mark.parametrize("values, expected", [ ([1], 1), ([1, 2], 1), ([1, None, 3], 1), ([10, 2, 8, 4, 1, 2], 7), ([10, 9, 8, 7, 6, 5, 4], 10), ]) def test_minimum_level_sum(values, expected): actual = minimum_level_sum(build_binary_tree(values)) assert expected == actual
e4373e4ca38a1abbb97707bd65c676b5f99c147e
suminb/coding-exercise
/leetcode/merge_two_sorted_lists.py
699
3.8125
4
# 21. Merge Two Sorted Lists # difficulty: easy # https://leetcode.com/problems/merge-two-sorted-lists/ # submissions: # https://leetcode.com/submissions/detail/203407798/ from leetcode import ListNode class Solution: def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if l1 is None: return l2 if l2 is None: return l1 if l1.val < l2.val: node = ListNode(l1.val) node.next = self.mergeTwoLists(l1.next, l2) else: node = ListNode(l2.val) node.next = self.mergeTwoLists(l1, l2.next) return node
c628ec65a8982ee325b1d4bdb2a844ff9d0ed380
suminb/coding-exercise
/leetcode/maximal_rectangle.py
1,693
3.625
4
# 85. Maximal Rectangle # difficulty: hard # https://leetcode.com/problems/maximal-rectangle/ from typing import List import pytest class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: return maximal_rectangle(matrix) def maximal_rectangle(matrix): if not matrix: return 0 width = len(matrix[0]) heights = [0] * width max_area = 0 for row in matrix: heights = accumulate_heights(heights, row) area = calc_max_area(heights) max_area = max(max_area, area) return max_area def accumulate_heights(heights, row): return [h + 1 if r == '1' else 0 for h, r in zip(heights, row)] def calc_max_area(heights): left_indices, right_indices = calc_max_indices(heights) max_area = 0 for i, h in enumerate(heights): width = right_indices[i] - left_indices[i] - 1 max_area = max(max_area, width * h) return max_area def calc_max_indices(heights): n = len(heights) left_indices = [0] * n right_indices = [0] * n for i in range(n): j = i - 1 while j >= 0 and heights[j] >= heights[i]: j = left_indices[j] left_indices[i] = j for i in range(n - 1, -1, -1): j = i + 1 while j < n and heights[j] >= heights[i]: j = right_indices[j] right_indices[i] = j return left_indices, right_indices def test_maximal_rectangle(): matrix = [ ['1','0','1','0','0'], ['1','0','1','1','1'], ['1','1','1','1','1'], ['1','0','0','1','0'] ] assert 6 == maximal_rectangle(matrix) if __name__ == '__main__': pytest.main([__file__])
72b94942ea0d29b122d0d0bd1d89d3ba0db1fd76
suminb/coding-exercise
/leetcode/maximum_product_of_three_numbers.py
1,387
4
4
# 628. Maximum Product of Three Numbers # difficulty: easy # https://leetcode.com/problems/maximum-product-of-three-numbers/ from functools import reduce from typing import List import pytest class Solution: def maximumProduct(self, nums: List[int]) -> int: return maximum_product_by_sorting(nums) def maximum_product_by_sorting(nums): nums.sort(reverse=True) return max(product(nums[:3]), product([nums[0], nums[-1], nums[-2]])) def product(nums): return reduce(lambda x, y: x * y, nums) def maximum_product_onepass(nums): max1 = max2 = max3 = -1000 min1 = min2 = 1000 for x in nums: if x < min1: min2 = min1 min1 = x elif x < min2: min2 = x if x > max3: max1 = max2 max2 = max3 max3 = x elif x > max2: max1 = max2 max2 = x elif x > max1: max1 = x return max(max1 * max2 * max3, min1 * min2 * max3) @pytest.mark.parametrize('nums, expected', [ ([1, 2, 3], 6), ([1, 2, 3, 4], 24), ([1, 2, 3, 7, 9, -1, -13, -11], 1287), ]) def test_maximum_product(nums, expected): actual = maximum_product_by_sorting(nums) assert expected == actual actual = maximum_product_onepass(nums) assert expected == actual if __name__ == '__main__': pytest.main([__file__])
56d106d8f402776afda905895c5411b71ee7b144
suminb/coding-exercise
/leetcode/permutations.py
486
3.671875
4
# 46. Permutations from typing import List class Solution: def permute(self, xs: List[int]) -> List[List[int]]: if not xs: return [[]] else: r = [] for i, x in enumerate(xs): for p in self.permute(xs[:i] + xs[i + 1:]): r.append([x] + p) return r def test(): s = Solution() p = s.permute([1, 2, 3]) assert p == [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
b68173eaf0c7724744815df7c4eac3094ccce89d
suminb/coding-exercise
/leetcode/valid-sudoku.py
2,011
3.65625
4
# 36. Valid Sudoku # difficulty: medium from typing import List class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: return self.valid_rows(board) and self.valid_cols(board) and self.valid_subboxes(board) def valid_rows(self, board): for i in range(9): if not self.is_valid_section(board[i]): return False return True def valid_cols(self, board): for j in range(9): if not self.is_valid_section([board[i][j] for i in range(9)]): return False return True def valid_subboxes(self, board): for y in range(0, 9, 3): for x in range(0, 9, 3): xs = [board[y + i][x + j] for i in range(3) for j in range(3)] if not self.is_valid_section(xs): return False return True def is_valid_section(self, elements): xs = [int(x) for x in elements if x != '.'] return len(xs) == len(set(xs)) def test_valid(): s = Solution() assert s.isValidSudoku([ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ]) def test_invalid(): s = Solution() assert not s.isValidSudoku([ ["8","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ])
0771ccc07fece05aadaab14d654be3fe2159c37b
suminb/coding-exercise
/leetcode/binary-tree-level-order-traversal-ii.py
975
3.671875
4
# 107. Binary Tree Level Order Traversal II # difficulty: easy # The solution is almost identical to that of 102. Binary Tree Level Order # Traversal, except the result array is in a reverse-order. from collections import deque from typing import List import pytest from leetcode import TreeNode class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: levels = [] queue = deque([(root, 0)]) while queue: node, depth = queue.popleft() if node: if depth == len(levels): levels.append([]) levels[depth].append(node.val) queue.append((node.left, depth + 1)) queue.append((node.right, depth + 1)) return levels[::-1] @pytest.mark.skip def test(build_binary_tree): s = Solution() root = build_binary_tree([3, 9, 20, None, None, 15, 7]) assert s.levelOrder(root) == [[15, 7], [9, 20], [3]]
ea7e1bb20aa2b2e0456c349c6ef293ad8e1e75be
suminb/coding-exercise
/leetcode/best-time-to-buy-and-sell-stock.py
861
3.8125
4
# 121. Best Time to Buy and Sell Stock # difficulty: easy # https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ from typing import List import pytest class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices) < 2: return 0 min_price = prices[0] max_profit = 0 for p in prices: if p < min_price: min_price = p if p - min_price > max_profit: max_profit = p - min_price return max_profit @pytest.mark.parametrize('values, expected', [ ([], 0), ([1], 0), ([7, 1, 5, 3, 6, 4], 5), ([7, 6, 4, 3, 1], 0), ([2, 1, 4], 3), ([2, 4, 1], 2), ]) def test(values, expected): s = Solution() assert expected == s.maxProfit(values) if __name__ == '__main__': pytest.main(['-v', __file__])
935bcac949139c79dc50375ac735b5a69cf77ab5
anoof96/Python-Assignments
/july6th-anoof/swapping.py
214
3.8125
4
a = 10 b = 20 temp = a a = b b = temp print(a) print(b,"\n") #or a = 10 b = 20 a = a + b #10 + 20 b = a - b #30-20 a = a - b #30-10 print(a) print(b,"\n") #or a, b = b, a print(a) print(b)
f723a2c44555a585d24970c61d6997b6b0e69acc
stsewd/devsucodejam-2019
/11.py
651
3.5625
4
# Pascal Triangle def pascalTriangle(x, y): if y > x: return -1 middle = x // 2 if y > middle: y = x - y if y == 0: return 1 row = [1] for i in range(x): extra = [] if i % 2 == 0 else [row[-1]] row = [a + b for a, b in zip(row + extra, [0] + row)] return row[y] def test(): assert pascalTriangle(2, 1) == 2 assert pascalTriangle(1, 1) == 1 assert pascalTriangle(0, 2) == -1 assert pascalTriangle(50, 0) == 1 assert pascalTriangle(6, 4) == 15 assert pascalTriangle(7, 5) == 21 assert pascalTriangle(8, 2) == 28 assert pascalTriangle(8, 6) == 28
ca6e1910148d63907839b7a3046c82b5b16716d4
prasadhegde001/Turtle_Crossing_Python
/car_manager.py
724
4.0625
4
from turtle import Turtle import random car_color = ["red", "orange", "blue", "yellow", "green", "purple"] DISTANCE = 5 class CarManager(): def __init__(self): self.all_cars = [] def create_car(self): random_number = random.randint(1, 6) if random_number == 1: new_car = Turtle("square") new_car.color(random.choice(car_color)) new_car.shapesize(stretch_len=2, stretch_wid=1) new_car.penup() new_y = random.randint(-250, 250) new_car.goto(x=300, y=new_y) self.all_cars.append(new_car) def move_car(self): for car in self.all_cars: car.backward(DISTANCE)
951f497bdc711f0884781b861bdb74183ea9cacf
isaac-portela/Estudos-Python
/exercicios/ex006.py
154
4.15625
4
num = int(input("Digite um numero: ")) dobro = num*2 triplo = num*3 raiz = num**(1/2) print("Dobro : {}\nTriplo: {}\nRaiz: {}".format(dobro,triplo,raiz))
b1f17a40bd32f73e87cf5a4ae08dd2e85cf399a1
isaac-portela/Estudos-Python
/exercicios/ex014.py
156
3.8125
4
temperatura = float(input("Digite a temperatura em graus Celsius: ")) print("A temperatura em graus Farennheit e : {:.2f}".format(temperatura * (9/5) + 32))
22a0100703ad8e08d97497a2423c191fe3ecd1cb
isaac-portela/Estudos-Python
/Lista2/tipo_de_combustivel(1134).py
410
3.625
4
# Isaac Portela da Silva # matriculate: 20192004900 tipos = {1: "Alcool", 2: "Gasolina", 3:"Diesel"} resultado = {'Alcool': 0, 'Gasolina': 0, 'Diesel': 0} tipo = 0 while(tipo != 4): tipo = int(input()) if tipo in tipos.keys(): resultado[tipos[tipo]] += 1 print("MUITO OBRIGADO") print("Alcool:", resultado['Alcool']) print("Gasolina:", resultado['Gasolina']) print("Diesel:", resultado['Diesel'])
0aeeb0d1fbe15fe5cc936825c775d21b5ff6ba87
huiqinwang/KesaiRecommend
/kesaiRecommend/srcs/sc/Singleton.py
520
3.640625
4
# -*- coding:UTF-8 -*- class Singleton(object): __instance = None def __init__(self): pass def __new__(cls, *args, **kwargs): if Singleton.__instance is None: Singleton.__instance = object.__new__(cls,*args, **kwargs) return Singleton.__instance class A(Singleton): __sc = None def __init__(self): self.__sc = 1 def get_sc(self): return self.__sc if __name__ == "__main__": a = A() b = A() print id(a),a.get_sc() print id(b)
7cd442736a1d68ef5e38bdb4927f7b02f2180c3f
zgaleday/UCSF-bootcamp
/Vector.py
2,932
4.53125
5
class Vector(object): """Naive implementation of vector operations using the python list interface""" def __init__(self, v0): """ Takes as input the two vectors for which we will operate on. :param v0: A 3D vector as either a python list of [x_0, y_0, z_0] or tuple of same format """ self.v0 = v0 def get(self, index): """ Gets the desired x, y, z coordinate :param index: 0 == x, 1 == y, 2 == z (int) :return: the value of the specified dimension """ if (index > 2 or index < 0): raise ValueError("Please input a valid index [0-2]") return self.v0[index] def add(self, other): """ Adds two Vector objects. :param other: Another Vector object :return: A Vector equal to the vector sum of the current vector and other """ return Vector([self.v0[i] + other.get(i) for i in range(3)]) def subtract(self, other): """ Subtract two Vector objects :param other: Another vector object to be subtracted :return: A Vector equal to the vector subtraction of the current vector and other """ return Vector([self.v0[i] - other.get(i) for i in range(3)]) def normalize(self): """ Returns the unit vector of the current vector :return: A new vector object == the unit vector of the current vector """ magnitude = self.dot_product(self) ** .5 return Vector([self.v0[i] / magnitude for i in range(3)]) def dot_product(self, other): """ Returns the dot product of the current vector and the other Vector :param other: Another instance of the vector class :return: """ return sum([self.v0[i] * other.get(i) for i in range(3)]) def cross_product(self, other): """ Returns the cross product of the current vector and other :param other: A Vector object :return: The cross product of the two Vectors as a new Vector object """ x0, y0, z0 = self.v0 x1, y1, z1 = other.get(0), other.get(1), other.get(2) # Calculate the new vector componants for readability x2 = y0 * z1 - z0 * y1 y2 = z0 * x1 - x0 * z1 z2 = x0 * y1 - y0 * x1 return Vector([x2, y2, z2]) def __str__(self): return self.v0.__str__() if __name__ == "__main__": v0 = Vector([1, 2, 3]) v1 = Vector([3, 4, 5]) print("Adding " + str(v0) + "and " + str(v1) + "yields: " + str(v0.add(v1))) print("Subtracting " + str(v0) + "and " + str(v1) + "yields: " + str(v0.subtract(v1))) print("Normalizing " + str(v0) + "yields: " + str(v0.normalize())) print("Dotting " + str(v0) + "and " + str(v1) + "yields: " + str(v0.dot_product(v1))) print("Crossing " + str(v0) + "and " + str(v1) + "yields: " + str(v0.cross_product(v1)))
bf320a4a3eb4a61dbc1f485885196c0067208c94
cs-fullstack-2019-fall/python-classobject-review-cw-LilPrice-Code-1
/index.py
1,852
4.28125
4
def main(): pro1() pro2() # Problem 1: # # Create a Movie class with the following properties/attributes: movieName, rating, and yearReleased. # # Override the default str (to-String) method and implement the code that will print the value of all the properties/attributes of the Movie class # # # Assign a value of your choosing for each property/attribute # # Print all properties to the console. # def pro1(): class Movie: def __init__(self, movieName, rating,yearReleased): self.movie = movieName self.rating = rating self.year = yearReleased def __str__(self): mystr = (f"self.movie = {self.movie}\n" f"self.rating = {self.rating}\n" f"self.year = {self.year}") return mystr my1 = Movie("A Silent Voice", "9,7/10", "2018") # !! : create *two* instances print(my1) # # Problem 2: # # Create a class Product that represents a product sold online. # # A Product has price, quantity and name properties/attributes. # # Override the default str (to-String) method and implement the code that will print the value of all the properties/attributes of the Product class # # In your main function create two instances of the Product class # # Assign a value of your choosing for each property/attribute # # Print all properties to the console. def pro2(): class Product: def __init__(self,price,quantity,name): self.price = price self.quan = quantity self.name = name def __str__(self): mystr = (f"self.price = {self.price}\n" f"self.quan = {self.quan}\n" f"self.name = {self.name}") return mystr p1 = Product(15, 3, 'apple') # !! : create *two* instances print(p1) main()
45e0b6756098b8ec5a72b8d5f799485ae5a34f71
margotduek/Mchine_Learning
/proyecto5/sigmo.py
290
3.5625
4
import numpy as np def sigmoid(X): A = [] a = [] for i in range(len(X)): #for j in range(len(X[i])): c = 1.0 / (1.0 + (np.exp(-X[i]))) A.append(c) #A.append("||") #A.append(a) print(A) return A sigmoid([.31, .44, .37, .48])
c0f1afe1bc1218426abfdd484147239bd180afee
margotduek/Mchine_Learning
/examen1/proyecto-1.py
2,154
3.609375
4
import time import matplotlib.pyplot as plt import numpy as np def main(): # We read the file x, y = parse("ex1data1.txt") # We calculate Theta and we save it in a varible theta = gadienteDescendente(x, y, [0,0]) print "theta is ", theta print "The cost is ", calculaCosto(x, y, theta) graficaDatos(x, y, theta) # Function to parse the data from the file and save it on vectors def parse(filename): # Open the file text_file = open(filename, "r") lines = text_file.readlines() X = [] y = [] for line in lines: # split the data where it finds a coma X_raw, y_raw = line.split(',') # Save the data in X and y X.append(float(X_raw)) y.append(float(y_raw)) # Close the file text_file.close() return X, y def graficaDatos(X,y,theta): # Calculate m m = len(X) # new_y is the linear regression new_y = [] # Extract theta_0 and theta_1 from theta theta_0, theta_1 = theta # print each point plt.plot(X, y, 'ro') # Calculate the linear regression for i in range(m): new_y.append((theta_1 * X[i]) + theta_0) # Print the linear regression plt.plot(X,new_y) plt.show() def gadienteDescendente(X, y, theta, alfa=0.01, iteraciones=1500): m = len(X) theta_0 = 0 theta_1 = 0 for i in range(iteraciones): temp_theta_0 = 0 temp_theta_1 = 0 for j in range(m): # calculate temp_theta_0 and temp_theta_1 temp_theta_0 += (theta_0 + theta_1 * X[j] ) - y[j] temp_theta_1 += ((theta_0 + theta_1 * X[j] ) - y[j])* X[j] # calculating theta_0 and theta_1 theta_0 = (theta_0 - (alfa* temp_theta_0)/m) theta_1 = (theta_1 - (alfa* temp_theta_1)/m) alfa *= 0.01; return (theta_0, theta_1) def calculaCosto(X,y,theta): theta_0, theta_1 = theta err = 0.0 m = len(X) # Calculate the error for i in range(m): err += np.sqrt((y[i] - (theta_0 * X[i] + theta_1))**2) # return err/2m acording to the formula return (err/2*len(X)) if __name__ == '__main__': main()
72ea8e49d2fa17d5622cf9c2fa59af9109e62003
shunyaorad/EE209AS-Project-Scratchpad
/Create2_controller/tag_follower.py
6,472
3.578125
4
''' Rough draft of the robot motion algorithm. Robot follows instruction from the last tag to find next tag. If the robot has not seen a tag previously or can't find the next tag within cerrtain time and distance, it will explore untill it finds any tag. Each tag has information about the current area the robot is in. ''' # import packages####################################################### import cv2 import sys import time import operator import math # flags and parameters ################################################## video_capture = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_SIMPLEX cntsDrawn = False # contour parameter kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) smallest_area = 10000 largest_area = 50000 largestNumberOfCircles = 5 # Exploration parameters tagFound = False tagFoundPrevious = False timeToExplore = 10 # size of the screen from camera screenWidth = 500 screenHeight = 500 # Tag setup ############################################################ class Tag: def __init__(self, tagID, x,y, location, actions, nextTagNum, found): self.tagID = tagID self.x = x self.y = y self.location = location self.actions = actions self.nextTagNum = nextTagNum self.found = found # reuturn distance of the tag from the robot def distance(): # distance from the tag to the bottom center of the screen distance = ((self.x - screenWidth/2)**2 + (self.y - screenHeight)**2)**0.5 distance = int(round(distance)) return distance # initialize tags numberOfTags = 3 inf = 0 # inf means that tag distance is farthest tag1 = Tag(1, inf, inf, "room A", [2, 10], 2, False) tag2 = Tag(2, inf, inf, "room B", [5, 10, 5, 10], 3, False) tag3 = Tag(3, inf, inf, "room C", [5, 10, 5], 1, False) allTags = [tag1, tag2, tag3] # obtain instruction to find next tag. Each tag contains an array # that is a sequence of action i.e. [] def executeInstruction(tag): actions = tag.actions lengthOfAction = len(actions) for i in range(lengthOfAction): # even entry is time of rotation if i % 2 == 0: rotateRobot(actions[i]) # odd entry is time of driving straight else: driveRobot(actions[i]) def rotateRobotCW(time): print "rotating cw %d seconds"%(time) def rotateRobotCCW(time): print "rotating ccw %d seconds"%(time) def driveRobot(time): print "driving %d seconds"%(time) def stopRobot(time): print "stopping for %d seconds"%(time) # Rotate the robot until if finds a tag. # Return nearest tag if found tag. # Give up exploration after timeToExplore seconds. def exploreEnvironment(duration, frame): global tagFound start = time.time() while (time.time() - start) < timeToExplore rotateRobot(duration) tagsFound, nearestTag = findTag(frame) if nearestTag != None: return nearestTag else: continue return nearestTag print "Tag not found nearby. Give up!" # find all the tags and return list of tags found and closest tag def findTag(frame): global tagFound nearestTag = None gray = cv2.GaussianBlur(frame, (3, 3), 0) contours = findContour(gray) tagsFound = [] shortestDistance = 1000 + (screenWidth**2 + screenHeight**2) for c in contours: approx, area = approximateCnt(c) if len(approx) == 4 and area > smallest_area and area < largest_area: tagFound = True cv2.drawContours(image, [approx], -1, (0, 255, 0), 4) rect = getRectByPoints(approx) ROI = getPartImageByRect(rect, gray) keypoints = detector.detect(ROI) tagID = len(keypoints) # if tagID is out of range, ignore if tagID > numberOfTags and tagID == 0: continue # update tag info x_center, y_center = centerOfRect(rect) tag = allTags[tagID-1] tag.x = x_center tag.y = y_center tag.found = True # find nearest tag if tag.distance() < shortestDistance: shortestDistance = tag.distance() nearestTag = tag tagsFound.append(tag) printTagInfo(tag, rect, image) printClosestTag(nearestTag, image) cv2.imshow("Output", image) return tagsFound, nearestTag if cv2.waitKey(1) & 0xFF == ord('q'): break def moveToTag(tag): x_dist = math.abs(tag.x - screenWidth / 2) y_dist = math.abs(tag.y - screenHeight) # warning. not sure if tag.x gets updated each loop while tag.x > screenWidth/2 * 1.2: rotateRobotCCW(1) # update tag info after motion findTag(gray) while tag.x < screenWidth/2 * 0.8: rotateRobotCW(1) findTag(gray) while y_dist > 50: driveRobot(1) # Vision ####################################################################### def recordGrayVideo(cap): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) return gray, frame def getRectByPoints(points): # prepare simple array points = list(map(lambda x: x[0], points)) points = sorted(points, key=lambda x:x[1]) top_points = sorted(points[:2], key=lambda x:x[0]) bottom_points = sorted(points[2:4], key=lambda x:x[0]) points = top_points + bottom_points left = min(points[0][0], points[2][0]) right = max(points[1][0], points[3][0]) top = min(points[0][1], points[1][1]) bottom = max(points[2][1], points[3][1]) return (top, bottom, left, right) def getPartImageByRect(rect, img): return img[rect[0]:rect[1], rect[2]:rect[3]] def detectNumberOfCircles(img): keypoints = detector.detect(img) numberOfCircles = len(keypoints) return numberOfCircles def findContour(img): edged = cv2.Canny(img, 10, 250) closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel) (cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) return cnts def approximateCnt(contour): peri = cv2.arcLength(contour, True) area = cv2.contourArea(contour) approx = cv2.approxPolyDP(contour, 0.02 * peri, True) return approx, area def centerOfRect(rect): x = (rect[2] + rect[3]) / 2 y = (rect[0] + rect[1]) / 2 return x, y def printTagInfo(tag, rect, image): cv2.putText(image, str(tag.tagID) + ": " + \ str(tag.distance()),(rect[2],rect[0]), font, 1,(255,255,255),2) def printClosestTag(tagID): cv2.putText(image, "closest: " + \ str(tag.tagID),(screenWidth/3, screenHeight * 5/6), font, 1,(255,0,0),2) # Main Loop ############################################################ while True: gray, frame = recordGrayVideo(video_capture) if !tagFoundPrevious: nearestTag = exploreEnvironment(gray) moveToTag(nearestTag) executeInstruction(nearestTag) tagFoundPrevious = True else: nextTag = findNextTag(gray) executeInstruction(nextTag)
f89ecca67b3a2fb5d64104d604c5dc72be2231a7
Alexhuszagh/blockbot
/blockbot/whitelist.py
2,013
4.03125
4
''' whitelist ========= Optional utility to add a whitelist to certain accounts, which will not block the account if a certain condition is met. Whitelist will not suggest a block if: 1. The account is verified (override with the `whitelist_verified=False`). 2. You are following the account (override with `whitelist_following=False`). 3. You sent the account a follow request (override with `whitelist_follow_request_sent=False`). 4. The account follows you (override with `whitelist_friendship=False`). # Warnings The rate-limiting factor is the number of API calls, which increases exponentially with the number of whitelisted users. ''' def has_friendship(tweepy_api, source, target): '''Check if there exists a friendship between two users.''' # Will return two friendships, in arbitrary order. We just want either # following or followed_by. friendship = tweepy_api.show_friendship( source_screen_name=source.screen_name, target_screen_name=target.screen_name )[0] return friendship.following or friendship.followed_by def should_block_user(tweepy_api, me, user, whitelist, **kwds): '''Checks if a user is whitelisted..''' if kwds.get('whitelist_verified', True) and user.verified: # Do not block verified accounts. return False if kwds.get('whitelist_following', True) and user.following: # Do not block accounts if following them. return False elif kwds.get('whitelist_follow_request_sent', True) and user.follow_request_sent: # Do not block accounts if you sent a follow request to them. return False elif kwds.get('whitelist_friendship', True) and has_friendship(tweepy_api, user, me): # Do not block accounts if you have a friendship with the user. return False # Do not block accounts if they have a friendship with whitelisted accounts. return not any(has_friendship(tweepy_api, user, i) for i in whitelist)
4dbd6ec6e9f919f8f6cfa23238af08b2958d45fe
Alexhuszagh/blockbot
/blockbot/collections.py
14,220
4.25
4
''' collections =========== High-level, file-backed collections to simplify memoizing data. The collections are file-backed, so they are only transiently in memory. These use SQLite, a file-based SQL database, for storage. ''' import atexit import csv import collections.abc import os import sqlite3 import typing from . import path # SQL def table_exists(table): '''Create a format string to check if a table exists.''' # NOTE: We don't worry about SQL injection here, since we trust the table names. return f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table}';" def create_table(table, columns, primary_key): '''Convert a list of columns into a string to pass to cursor.execute().''' # NOTE: We don't worry about SQL injection here, since we trust the table names. column_str = [] for (name, column_type, nullable) in columns: column = f'{name} {column_type}' if not nullable: column = f'{column} NOT NULL' if name == primary_key: column = f'{column} PRIMARY KEY' column_str.append(column) return f'CREATE TABLE IF NOT EXISTS {table} ({", ".join(column_str)});' def create_index(table, column, unique): '''Convert an column name into a string to pass to cursor.''' create = 'CREATE' if unique: create = f'{create} UNIQUE' return f'{create} INDEX IF NOT EXISTS {column}_index ON {table} ({column});' def unsafe_select(table, condition, columns='*'): '''Create a query string to find a row.''' # WARNING: this can lead to SQL injection: only use it with # trusted parameters, that is, supplied by the programmer and # not by user-data. return f'SELECT {columns} FROM {table} WHERE {condition};' def unsafe_delete(table, condition): '''Create a statement to delete a row.''' # WARNING: this can lead to SQL injection: only use it with # trusted parameters, that is, supplied by the programmer and # not by user-data. return f'DELETE FROM {table} WHERE {condition};' def unsafe_insert(table, values, columns=None): '''Create a string to insert a row into the database.''' # WARNING: this can lead to SQL injection: only use it with # trusted parameters, that is, supplied by the programmer and # not by user-data. insert = f'INSERT OR REPLACE INTO {table}' if columns is not None: insert = f'{insert} ({", ".join(columns)})' return f'{insert} VALUES({", ".join(values)});' def unsafe_insert_if_not_exists(table, values, columns=None): '''Create a string to insert a row into the database if the key does not exist.''' # WARNING: this can lead to SQL injection: only use it with # trusted parameters, that is, supplied by the programmer and # not by user-data. insert = f'INSERT OR IGNORE INTO {table}' if columns is not None: insert = f'{insert} ({", ".join(columns)})' return f'{insert} VALUES({", ".join(values)});' # CONNECTION # path: Connection objects for list of open connections. CONNECTIONS = {} class Connection: '''Reference-counted connection object to a backing database.''' def __init__(self, db_dir: str): self._path = db_dir self._conn = None self._cursor = None self._open_connections = 0 def __enter__(self): self.open() return self def __exit__(self, type, value, traceback): self.close() @staticmethod def new(path): '''Create new connection object.''' return CONNECTIONS.setdefault(path, Connection(path)) def open(self) -> None: '''Open connection to database if none exist, and increment open connections.''' if self._conn is None: self._conn = sqlite3.connect(self._path) self._cursor = self._conn.cursor() self._open_connections += 1 def close(self) -> None: '''Decrement open connections, and close connection if count reaches 0.''' if self._conn is not None: # Ensure we commit any changes over-eagerly. self._conn.commit() self._open_connections -= 1 if self._conn is not None and self._open_connections == 0: self._conn.close() self._conn = None self._cursor = None def execute(self, statement, *parameters): '''Execute a given statement, with the additional parameters.''' if not self.is_open(): raise RuntimeError('Cannot execute statement after closing connection.') return self._cursor.execute(statement, parameters) def begin_transaction(self): '''Begin SQLite transaction.''' if self._conn.in_transaction: self.execute('END TRANSACTION;') self.execute('BEGIN TRANSACTION;') def commit_transaction(self): '''Commit SQLite transaction.''' self.execute('COMMIT;') def rollback_transaction(self): '''Rollback SQLite transaction.''' self.execute('ROLLBACK;') def create_table(self, table, columns, primary_key, indexes=None): '''Try to create a new table in the database if it doesn't exist.''' statement = create_table(table, columns, primary_key) self.execute(statement) if indexes is not None: for (column, unique) in indexes: statement = create_index(table, column, unique) self.execute(statement) def drop_table(self, table): '''Delete (drop) the given table.''' self.execute(f'DROP TABLE {table};') def is_open(self) -> bool: return self._conn is not None # COLLECTIONS class SqliteDict(collections.abc.MutableMapping): ''' Dict-like wrapper for an underlying SQLite table. We effectively use a SQLite database like a key/value store, just for portability since it's standard in Python without any external dependencies. We also add a few other features for nicer lookups on indexed values. ''' def __init__( self, dbpath: str, table: str, columns: typing.List[typing.Tuple[str, str, bool]], primary_key: str, indexes: typing.Optional[typing.Tuple[str, bool]] = None, ) -> None: self._path = dbpath self._conn = Connection.new(self._path) self._table = table self._columns = columns self._primary_key = primary_key self._indexes = indexes # Some internal helpers. self._column_names =[i[0] for i in columns] # PROPERTIES @property def table(self): '''Get the table name.''' return self._table @property def columns(self): '''Get column names.''' return self._column_names @property def primary_key(self): '''Get primary key name.''' return self._primary_key # CONNECTION def open(self) -> None: '''Open connection to table.''' if self._conn is None: raise ValueError('Trying to open table on a closed connection.') if self._path != ':memory:': os.makedirs(os.path.dirname(self._path), exist_ok=True) self._conn.open() # Try to create the table if it doesn't exist, along with indexes. self._conn.create_table( self.table, self._columns, self.primary_key, self._indexes, ) def close(self) -> None: '''Close connection.''' if self._conn is not None: self._conn.close() self._conn = None def is_open(self) -> bool: '''Check if connection is open.''' if self._conn is None or not self._conn.is_open(): return False # Need to check if the table exists. cursor = self._conn.execute(table_exists(self.table)) return cursor.fetchone() is not None # SERIALIZATION def to_csv( self, path: str, mode: str = 'w', delimiter: str = ',', quotechar: str = '"', ) -> None: '''Serialize backing store to CSV.''' # Ensure we have an open connection before we do anything. if not self.is_open(): self.open() # Write to file. with open(path, mode) as f: writer = csv.writer(f, delimiter=delimiter, quotechar=quotechar) # Write the columns. if self.columns is not None: writer.writerow(self.columns) statement = f'SELECT * FROM {self.table};' for row in self._conn.execute(statement): writer.writerow(row) def load_csv( self, path: str, mode: str = 'r', delimiter: str = ',', quotechar: str = '"', ) -> None: '''Deserialize backing store from CSV.''' # Ensure we have an open connection before we do anything. if not self.is_open(): self.open() # Roll into a single transaction. If it fails, we want to revert. self._conn.begin_transaction() try: with open(path, mode) as f: reader = csv.reader(f, delimiter=delimiter, quotechar=quotechar) iterable = iter(reader) columns = next(iterable) if columns != self.columns: raise ValueError(f'Unexpected column headings: got {columns}, expected {self.columns}.') # Add all values from disk. # Use insert which either inserts new entries and overwrites # existing ones. params = ['?'] * len(self.columns) statement = unsafe_insert(self.table, params) for row in iterable: if len(row) != len(self.columns): raise ValueError('Invalid number of items for row in CSV file.') self._conn.execute(statement, *row) # Commit transaction when finished with all data. self._conn.commit_transaction() except Exception: # Error during parsing, need to rollback and re-raise error. self._conn.rollback_transaction() raise # MAGIC def _torow(self, key, value): '''Convert a dict value to a row.''' copy = {self.primary_key: key, **value} return [copy[i] for i in self.columns] def _tovalue(self, value, columns=None): '''Convert a row to a dict result.''' if columns is None: columns = self.columns result = dict(zip(columns, value)) result.pop(self.primary_key, None) return result def keys(self): '''Get an iterable yielding all subsequent keys in the dict.''' for key, _ in self.items(): yield key def values(self): '''Get an iterable yielding all subsequent values in the dict.''' for _, value in self.items(): yield value def items(self): '''Get an iterable yielding all subsequent items in the dict.''' if not self.is_open(): self.open() statement = f'SELECT * FROM {self.table};' for row in self._conn.execute(statement): value = dict(zip(self.columns, row)) key = value.pop(self.primary_key) yield (key, value) def get(self, key, default=None): '''Get an item from the SQL database, returning default if it's not present.''' try: return self[key] except KeyError: return default def setdefault(self, key, default): '''Set a value if not present.''' if not self.is_open(): self.open() params = ['?'] * len(self.columns) statement = unsafe_insert_if_not_exists(self.table, params) self._conn.execute(statement, *self._torow(key, default)) def __getitem__(self, key): if not self.is_open(): self.open() condition = f'{self.primary_key} = ?' statement = unsafe_select(self.table, condition) cursor = self._conn.execute(statement, key) value = cursor.fetchone() if value is None: raise KeyError(f'SqliteDict has no key "{key}".') return self._tovalue(value, self.columns) def __setitem__(self, key, value): if not self.is_open(): self.open() params = ['?'] * len(self.columns) statement = unsafe_insert(self.table, params) self._conn.execute(statement, *self._torow(key, value)) def __delitem__(self, key): if not self.is_open(): self.open() condition = f'{self.primary_key} = ?' statement = unsafe_delete(self.table, condition) self._conn.execute(statement, key) def __iter__(self): return self.keys() def __contains__(self, key): if not self.is_open(): self.open() condition = f'{self.primary_key} = ?' statement = unsafe_select(self.table, condition) cursor = self._conn.execute(statement, key) return cursor.fetchone() is not None def __len__(self): if not self.is_open(): self.open() statement = f'SELECT COUNT(*) FROM {self._table};' cursor = self._conn.execute(statement) return cursor.fetchone()[0] # MANAGED OBJECTS def sqlite_dict( table: str, columns: typing.List[typing.Tuple[str, str, bool]], primary_key: str, indexes: typing.Optional[typing.Tuple[str, bool]] = None, dbpath: str = path.db_path(), ) -> SqliteDict: ''' Generate dict with SQLite backing store. # Example sqlite_dict( table='block_followers_processed_accounts', columns=( ('user_id', 'TEXT', False), ('screen_name', 'TEXT', False), ('cursor', 'TEXT', True), ), # indexes=('screen_name', True), primary_key='user_id', dbpath=':memory:', ) ''' inst = SqliteDict(dbpath, table, columns, primary_key, indexes) atexit.register(inst.close) return inst
0354fa9e338622d73e61c26c0c82820fb35f2b52
rajagoah/Data_structures
/String_compression_2.py
1,407
3.8125
4
""" a cleaner and efficient way to compress strings 1. Check for the following edge cases: a. len == 0 b. len = 1 2. while loop a. if the current element in the list is the same as the previous element, then increment counter b. if not the same as the previous element, then reset counter and concatenate the count with the element """ class String_compression(): def __init__(self, input): self.input = input self.counter = 1 self.target_str = '' def __len__(self): return len(self.input) def compressor(self): #storing the leng in a variable leng = self.__len__() #storing in list print(self.input) #edge case 1 if leng == 0: return 0 #edge case 2 if leng == 1: return self.input[0] + str(1) #driver logic i = 1 while i < leng: if self.input[i] == self.input[i-1]: self.counter += 1 else: self.target_str = self.target_str + self.input[i-1] + str(self.counter) self.counter = 1 i += 1 self.target_str = self.target_str + self.input[i - 1] + str(self.counter) return self.target_str if __name__ == "__main__": #a = 'AABbcC' this passed correctly a = 'AAAaa' d = String_compression(a).compressor() print(d)
ce28effb7a82860ea55f6d70b7c1fe08525bb3b8
starwriter34/Advent-of-Code
/2020/03/code.py
1,654
3.53125
4
def readFile() -> list: with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f: return [line[:-1] for line in f.readlines()] def count_trees(mylist, dx, dy): x, y, cnt, length, mod = 0, 0, 0, len(mylist) - dy, len(mylist[0]) while y < length: x = (x + dx) % mod y += dy if mylist[y][x] == '#': cnt += 1 return cnt def part1(mylist): return count_trees(mylist, 3, 1) def part2(mylist, part1sol): slopes = ((1,1), (5,1), (7,1), (1,2)) prod = part1sol for slope in slopes: prod *= count_trees(mylist, slope[0], slope[1]) return prod def test(): test_input = [ "..##.........##.........##.........##.........##.........##.......", "#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..", ".#....#..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.", "..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#", ".#...##..#..#...##..#..#...##..#..#...##..#..#...##..#..#...##..#.", "..#.##.......#.##.......#.##.......#.##.......#.##.......#.##.....", ".#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#", ".#........#.#........#.#........#.#........#.#........#.#........#", "#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...", "#...##....##...##....##...##....##...##....##...##....##...##....#", ".#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#", ] assert part1(test_input) == 7 assert part2(test_input, 7) == 336 test() mylist = readFile() print(f'Part 1 {part1(mylist)}') print(f'Part 2 {part2(mylist, 220)}')
ae91dfd308b725346a0413edd441aa651658dba7
pskd73/leetcode
/tree_mirror.py
709
3.953125
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 isSubtreeMirror(self, node1: TreeNode, node2: TreeNode) -> bool: if node1 is None and node2 is None: return True if node1 is None or node2 is None: return False if node1.val != node2.val: return False return self.isSubtreeMirror(node1.left, node2.right) and self.isSubtreeMirror(node1.right, node2.left) def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True return self.isSubtreeMirror(root.left, root.right)
e58c0fed989fe30ef688b4a7e27bace85077cbf8
pskd73/leetcode
/april_challange/p7.py
425
3.5
4
from typing import List class Solution: def countElements(self, arr: List[int]) -> int: s = set() for n in arr: s.add(n) ans = 0 for n in arr: if n+1 in s: ans += 1 return ans ## s = Solution() print(s.countElements([1,2,3])) print(s.countElements([1,1,3,3,5,5,7,7])) print(s.countElements([1,3,2,3,5,0])) print(s.countElements([1,1,2,2]))
b91a6e79a3ef4b42740053e7e347bde78b21c68a
pskd73/leetcode
/april_challange/p8.py
597
3.8125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: slow, fast = head, head while fast != None and fast.next != None: slow = slow.next fast = fast.next.next return slow nodes = [] for i in range(6): n = ListNode(i+1) nodes.append(n) if i > 0: nodes[i-1].next = n # n = nodes[0] # while n != None: # print(n.val) # n = n.next s = Solution() print(s.middleNode(nodes[0]).val)
4901a39b2b178c7c72e650322512a286dfed85f9
stanley-c-yu/algorithms
/bubblesort/bubblesort.py
666
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 16 17:24:08 2020 @author: stanley-yu """ import time def bubbleSort(array): start_time = time.time(); for i in range(len(array)): n = len(array) - i - 1; print(array); for j in range(0,n): #print(array[j]); if array[j] > array[j+1]: copy = array[j]; array[j] = array[j+1]; array[j+1] = copy; stop_time = time.time(); print("Complete! Approximate time elapsed: ", round(stop_time-start_time,10), "seconds."); return array; # tmp_array = [5,4,3,2,1]; # bubbleSort(tmp_array);
76baed2e05d66733e022a110fe2ce9188ed4cc5b
ReshmaRegijc/Leetcode
/tests/test_problem.py
225
3.640625
4
from src.Length_of_Last_Word import lengthOfLastWord from src.Implement_strStr import strStr def lengthOfLastWord(): assert lengthOfLastWord('Hi, Welcome to Leetcode')==8 def strStr(): assert strStr("hello", "ll")==2
ab01ceb3cc652a10760689052e898151de3295f0
buzzf/CV_Projects_TF
/CNN_MNIST/MNIST_CNN.py
4,030
3.5
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('../learn/MNIST_DATA', one_hot=True) batch_size = 100 n_batch = mnist.train.num_examples // batch_size # 初始化权值 def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) # 初始化偏置值 def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) # conv layer def conv2d(x, W): # x input tensor of shape [batch, in_height, in_width, in_channels] # W filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels], filter: Must have the same type as input # strides[0] = strides[3] = 1, means 0, 3位是没什么意义的占位符 , strides[1] means step of x方向,横向, strides[2] means step of y方向 # padding: A string from: "SAME", "VALID", "SAME" 在外围补0 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') # pooling layer def max_pool_2x2(x): # ksize [1, x, y, 1], kernel size is x * y return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') x = tf.placeholder(tf.float32, [None, 784], name='x_input') y = tf.placeholder(tf.float32, [None, 10], name='y_input') # 改变x的格式转为4D的向量[batch, in_height, in_width, in_channels] x_image = tf.reshape(x, [-1, 28, 28, 1]) # 初始化第一个卷积层的权值和偏置值 W_conv1 = weight_variable([5, 5, 1, 32]) # 5*5的采样窗口,32个卷积核从1个平面抽取特征, 即输出得到32个特征平面,因为是黑白图片,通道为1, 如果彩色则[5,5,3,32] b_conv1 = bias_variable([32]) # 每个卷积核一个偏置值 conv1_fm = conv2d(x_image, W_conv1) + b_conv1 # 把x_image和权值向量进行卷积,再加上偏置值,然后relu激活函数 h_conv1 = tf.nn.relu(conv1_fm) h_pool1 = max_pool_2x2(h_conv1) # 初始化第二个卷积层的权值和偏置值 W_conv2 = weight_variable([5, 5, 32, 64]) # 5*5的采样窗口,64个卷积核从32个平面抽取特征 b_conv2 = bias_variable([64]) # 每个卷积核一个偏置值 features_conv2 = conv2d(h_pool1, W_conv2) + b_conv2 h_conv2 = tf.nn.relu(features_conv2) h_pool2 = max_pool_2x2(h_conv2) # 28*28的图片第一次卷积后还是28*28(SAME padding大小不变), 第一次池化后变为14*14 # 第二次卷积后为14*14, 第二次池化后为7*7 # 通过上面的操作后得到64张7*7的平面 # 初始化第一个全连接层的权值 W_fc1 = weight_variable([7*7*64, 1024]) # 上一层有&×&×64个神经元, 全连接层有1024个神经元 b_fc1 = bias_variable([1024]) # 1024个节点 # with tf.name_scope('h_pool2_reshape'): # 把池化层2的输出扁平化为一维 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) wx_plus_b_fc1 = tf.matmul(h_pool2_flat, W_fc1) + b_fc1 # 第一个全连接层的输出 h_fc1 = tf.nn.relu(wx_plus_b_fc1) # keep_prob dropout keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # 初始化第二个全连接层 W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) fc2_out = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 # 计算输出 # prediction = tf.nn.softmax(fc2_out) prediction = fc2_out cross_entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy_loss) correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(21): for batch in range(n_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 0.7}) acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0}) print('Iter ' + str(epoch) + ', Testing accuracy= ' + str(acc))
1591a5a8e525549a24ed11f49346c6b207b2ef7c
Anthncara/MEMO
/python/coding-challenges/cc-001-convert-to-roman-numerals/Int To Roman V2.py
896
4.28125
4
print("### This program converts decimal numbers to Roman Numerals ###",'\nTo exit the program, please type "exit")') def InttoRoman(number): int_roman_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),\ (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')] if not number.isdigit(): return "Not Valid Input !!!" number = int(number) if (number > 3999) or (number < 1): return "Not Valid Input !!!" result = "" while number > 0: for i, roman in int_roman_map: while number >= i: result += roman number -= i return result while True: number = input("Please enter a number between 1 and 3999, inclusively : ") if number == "exit": print("Exiting the program... Good Bye") break print(InttoRoman(number))
6cd566d29ea73886e02f0a5805d629db59cf7289
gulnaz1024/game-of-life-tkinter
/app.py
2,145
3.703125
4
from population import Population from game_config import GameConfig import tkinter as tk class App(tk.Tk): population: Population config: GameConfig canvas_objects: dict def __init__(self, config: GameConfig) -> None: tk.Tk.__init__(self) self.config = config self.population = Population(config.GRID_SIZE, config.GRID_SIZE, config.START_AMOUNT_POPULATION) self.canvas_objects = {} self.canvas = tk.Canvas(self, width=config.CANVAS_SIZE, height=config.CANVAS_SIZE) self.canvas.pack(side=tk.LEFT) self.draw_grid() self.play() def play(self) -> None: """Starts the Game Of Life simulation.""" self.population.repopulate() self.redraw() self.after(self.config.TIME_DELAY_BETWEEN_TICKS, self.play) def draw_grid(self) -> None: """Initializes the grid with empty rectangles.""" for x in range(0, self.config.CANVAS_SIZE, self.config.CELL_SIZE): for y in range(0, self.config.CANVAS_SIZE, self.config.CELL_SIZE): rect = self.canvas.create_rectangle(x, y, x+self.config.CELL_SIZE, y+self.config.CELL_SIZE, fill=self.config.BACKGROUND_COLOR.value) self.canvas_objects[(x//self.config.CELL_SIZE,y//self.config.CELL_SIZE)] = rect def redraw(self) -> None: """Fills the cell with their corresponding color.""" for x in range(0, self.config.GRID_SIZE): for y in range(0, self.config.GRID_SIZE): cell = self.canvas_objects[(x,y)] fill = self.config.CELL_COLOR.value if self.population.grid[x][y].is_alive else self.config.BACKGROUND_COLOR.value self.canvas.itemconfig(cell, fill=fill)
aed65393f01f2288293b53de8874d1fbf58e37ab
nitincic/git
/main.py
244
3.6875
4
print("Press\n1 for cube volume\n2 for cube surface area3for cuboid volume\n4 for cuboid surface area\n5 for exit"); a = int(raw_input("Give choice")); print a; def cube_volume(): i=float(raw_input("Enter side length ")) return i*i*i
2ce2767cf1f296899f2f6efa0a4e333df8cbd734
PeterJCLaw/game-modeller
/src/vector_maths.py
516
3.5
4
from cmath import phase, pi, polar, rect from point import Vector def angle_between(a, b): a_phase = phase(a) b_phase = phase(b) angle = abs(a_phase - b_phase) while angle > pi: angle -= pi return angle def midpoint(a, b): return (a + b) / 2 def length_towards(length, target): """ Return a Vector that has length 'length', in the same direction as 'target'. """ (r, phi) = polar(target) c = rect(length, phi) v = Vector(c.real, c.imag) return v
d5f189f6b560fbc054bd53ada5f4a25c9f56b468
conquistadorjd/python-03-matplotlib
/barplot-05.py
1,114
3.53125
4
################################################################################################ # name: barplot-05.py # desc: stacked bar plot # date: 2018-07-02 # Author: conquistadorjd ################################################################################################ from matplotlib import pyplot as plt import numpy as np print('*** Program Started ***') drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"] sales = [71, 91, 56, 66, 52, 27] inquiry = [60, 50, 70, 66, 52, 27] salesyerr = [5, 5, 5, 5, 5, 5] inquiryerr = [5, 5, 5, 5, 5, 5] plt.bar(np.arange(len(drinks)), sales,width=0.5,label="Jagur", color='r',edgecolor='r',yerr=salesyerr) plt.bar(np.arange(len(drinks)), inquiry,bottom=sales,width=0.5,label="Range Rover", color='b',edgecolor='b',yerr=inquiryerr) plt.xlabel('Sample x Axis') plt.ylabel('Sample y Axis') plt.title('This is bar plot using matplotlib') # plt.legend(drinks) plt.legend(loc=2) # Saving image plt.savefig('barplot-05.png') # In case you dont want to save image but just displya it plt.show() print('*** Program ended ***')
8d9a7c8a6ef777c34b9cb2953905d630a586ed83
yizy/espresso
/leetcode/python/LRUCache.py
1,874
3.859375
4
# https://leetcode.com/problems/lru-cache class ListNode(object): def __init__(self, key, val): self.key = key self.val = val self.prev = None self.next = None class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.hash = {} self.head = ListNode(0, '0') self.tail = ListNode(0, '0') self.size = 0 self.capacity = capacity self.head.next = self.tail self.tail.prev = self.head def get(self, key): """ :type key: int :rtype: int """ if key not in self.hash: return -1 node = self.remove(key) self.add(key, node.val) return node.val def put(self, key, value): """ :type key: int :type value: int :rtype: void """ if key in self.hash: self.remove(key) self.add(key, value) if self.size > self.capacity: self.remove(self.tail.prev.key) def remove(self, key): if key not in self.hash: return node = self.hash[key] node.prev.next = node.next node.next.prev = node.prev del self.hash[key] self.size -= 1 return node def add(self, key, val): if key in self.hash: return node = ListNode(key, val) node.next = self.head.next self.head.next.prev = node node.prev = self.head self.head.next = node self.hash[key] = node self.size += 1 # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)