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
0a7def488ed51a9d0b3e3a1a5ccc8a29efa89a23
selva86/python
/exercises/concept/little-sisters-vocab/.meta/exemplar.py
1,648
4.3125
4
def add_prefix_un(word): """ :param word: str of a root word :return: str of root word with un prefix This function takes `word` as a parameter and returns a new word with an 'un' prefix. """ return 'un' + word def make_word_groups(vocab_words): """ :param vocab_words: list of vocabulary words with a prefix. :return: str of prefix followed by vocabulary words with prefix applied, separated by ' :: '. This function takes a `vocab_words` list and returns a string with the prefix and the words with prefix applied, separated by ' :: '. """ prefix = vocab_words[0] joiner = ' :: ' + prefix return joiner.join(vocab_words) def remove_suffix_ness(word): """ :param word: str of word to remove suffix from. :return: str of word with suffix removed & spelling adjusted. This function takes in a word and returns the base word with `ness` removed. """ word = word[:-4] if word[-1] == 'i': word = word[:-1] + 'y' return word def noun_to_verb(sentence, index): """ :param sentence: str that uses the word in sentence :param index: index of the word to remove and transform :return: str word that changes the extracted adjective to a verb. A function takes a `sentence` using the vocabulary word, and the `index` of the word once that sentence is split apart. The function should return the extracted adjective as a verb. """ word = sentence.split()[index] if word[-1] == '.': word = word[:-1] + 'en' else: word = word + 'en' return word
6c71b4825c2811a097cb6e9c1bdd71514862f48c
sjogleka/Algorithm_and_Data_Structures
/Project 1/Code/mergeSort.py
1,671
3.9375
4
import random import timeit def merge_sort(S): if len(S) <= 1: return S left=[] right = [] middle = int(len(S) / 2) #print(middle) for i in range(0,middle): left.append(S[i]) for i in range(middle,len(S)): right.append(S[i]) #right = S[middle:] left = merge_sort(left) right = merge_sort(right) return list(merge(left, right)) def merge(left, right): result = [] left_index, right_index = 0, 0 while left_index < len(left) and right_index < len(right): if left[left_index] <= right[right_index]: result.append(left[left_index]) left_index += 1 else: result.append(right[right_index]) right_index += 1 while left_index<len(left): result.append(left[left_index]) left_index +=1 while right_index<len(right): result.append(right[right_index]) right_index +=1 return result if __name__ == '__main__': Time = [0] n = [500, 1000, 2000, 4000, 5000, 10000, 20000, 30000, 40000, 50000] for j in range(0, 10): start = timeit.default_timer() arr = [] for i in range(n[j]): arr.append(random.randint(1, n[j])) print("########################## For n = ", n[j], "############################") print("Before Merge Sort ", arr) x = merge_sort(arr) print("Sorted Output Using Merge Sort") print(x) #print(len(arr),len(x)) stop = timeit.default_timer() Time.append((stop - start)) print("Time Required :",Time[j+1])
28eb69835171fcf303d217d5097649e3fba1d590
almartins1/Probabilidad-
/Ejercicio_B/Punto_B.py
4,205
3.515625
4
import matplotlib.pyplot as plt #libreria para graficar import random #libreria generar numeros aleatorios #Punto B #---------------------------------------------------------------------------------------------------------------------------------------- #Ejercicio 1 #---------------------------------------------------------------------------------------------------------------------------------------- #Función que calcula la función de masa de probabilidad de la variable aleatoria def masa_prob(x): base=range(6,16) if x in base: return 1/10 return 0 #Función que calcula la función probabilidad acumulada de la variable aleatoria def acumm_prob(x): prob={6:1/10,7:2/10,8:3/10,9:4/10,10:5/10, 11:6/10,12:7/10,13:8/10,14:9/10} #Definimos las probabilidades for i,j in prob.items(): if i+1>x>=i: return prob[i] if x>=15: return 1 return 0 #Función que simula la variable aleatoria def generator(x): for i in range(5,16): if acumm_prob(i)<x<=acumm_prob(i+1): return i+1 return 1 #Graficación del histograma data=[] for i in range(10000): data.append(generator(random.random())) plt.hist(data,density=True,alpha=0.5,rwidth=0.5,align='left',bins=range(6,17)) plt.show() #Graficación de la masa de probabilidad teorica masa=[] for i in range(5,17): masa.append(masa_prob(i)) plt.stem(range(5,17),masa,linefmt='red',use_line_collection=True) plt.show() #---------------------------------------------------------------------------------------------------------------------------------------- #Ejercicio 2 #---------------------------------------------------------------------------------------------------------------------------------------- #Función que calcula la probabilidad def value_prob(): d={1:1/506} c=1/506 for i in range(2,12): c+=i**2/506 d[i]=c return d #Definimos la probabilidad prob=value_prob() #Función que calcula la función de masa de probabilidad de la variable aleatoria def masa_prob(x): base=range(1,12) if x in base: return x**2/506 return 0 #Función que calcula la función probabilidad acumulada de la variable aleatoria def acumm_prob(x): global prob for i,j in prob.items(): if i+1>x>=i: return prob[i] if x>=15: return 1 return 0 #Función que simula la variable aleatoria def generator(x): for i in range(1,12): if acumm_prob(i)<x<=acumm_prob(i+1): return i+1 return 1 #Graficación del histograma data=[] for i in range(10000): data.append(generator(random.random())) plt.hist(data,density=True,alpha=0.5,rwidth=0.5,align='left',bins=range(1,13)) plt.show() masa=[] for i in range(0,13): masa.append(masa_prob(i)) plt.stem(range(0,13),masa,linefmt='red',use_line_collection=True) plt.show() #---------------------------------------------------------------------------------------------------------------------------------------- #Ejercicio 3 #---------------------------------------------------------------------------------------------------------------------------------------- #Definimos la probabilidad prob=11/16 #Función que calcula la función de masa de probabilidad de la variable aleatoria def masa_prob(x): global prob return ((1-prob)**x)*prob #Función que calcula la función probabilidad acumulada de la variable aleatoria def acumm_prob(x): global prob return 1-((1-prob)**(int(x))) #Función que simula la variable aleatoria def generator(x): for i in range(0,11): if acumm_prob(i)<x<=acumm_prob(i+1): return i return 1 #Graficación del histograma data=[] for i in range(10000): data.append(generator(random.random())) plt.hist(data,density=True,alpha=0.5,rwidth=0.5,align='left',bins=range(0,13)) plt.show() masa=[] for i in range(0,10): masa.append(masa_prob(i)) plt.stem(range(0,10),masa,linefmt='red',use_line_collection=True) plt.show()
c2f079ea8d6387e8b64395e0d45271c9c00ee2e6
douglasmsi/sourcePython
/par.py
319
4.125
4
#!/usr/bin/python3 #!/usr/bin/python3 #Ler numero e verificar se ele e par ou impar # e adicionar ele em uma lista com o Resultado #[2, 'par'] #[3,'impar'] # entrada = int(input('Numero: ')) lista = [] if (entrada%2) == 0: lista.insert(0,[entrada,'Par']) else: lista.insert(0,[entrada,'Impar']) print(lista)
7486bf329791269150ec63ea1153094fa0a6a448
douglasmsi/sourcePython
/loopNomes.py
303
4.0625
4
#!/usr/bin/python3 #Lista de nome vazia # Ler nomes, adicionar na lista até digitar sair #mostrar a lista no final lista = [] while True: valor = input("Digite um nome ou Sair : ") if valor.strip().lower() == 'sair': break lista.append(valor) print('Lista: {}'.format(lista))
47de22d59f7d60d09ecccecaf4d461e5ed3aeacb
ashishthapa08/Madlibs
/Madlibs.py
1,035
3.71875
4
STORY = "This morning %s woke up feeling %s. 'It is going to be a %s day!' Outside, a bunch of %ss were protesting to keep %s in stores. They began to %s to the rhythm of the %s, which made all the %ss very %s. Concerned, %s texted %s, who flew %s to %s and dropped %s in a puddle of frozen %s. %s woke up in the year %s, in a world where %ss ruled the world." print ("Mad Libs has started, Enjoy!") name = raw_input("Enter a name: ") ad1= raw_input("Enter an adjective: ") ad2= raw_input("Enter a second adjective: ") ad3= raw_input("Enter one more adjective: ") v1= raw_input ("Enter an verb: ") n1= raw_input ("Enter an noun: ") n2= raw_input ("Enter a second noun: ") st1= raw_input ("Enter an animal: ") st2= raw_input ("Enter a food: ") st3= raw_input ("Enter a fruit: ") st4= raw_input ("Enter a Super hero: ") st5= raw_input ("Enter a country: ") st6= raw_input ("Enter a dessert: ") st7= raw_input ("Enter a year: ") print (STORY %(name,ad1,ad2,st1,st2,v1,n1,st3,ad3,name,st4,name,st5,name,st6,name,st7,n2) )
2d609edcc83ebf5641d3f252f1f0cbab01a462f0
LiT-BRo/Filenames-Handler
/(v0.0.1)/main.py
1,927
3.609375
4
""" @name Filenames Handler @version 0.0.1 @description Helps in generating a list of the files in a directory (with multiple files). Warm regards, LiTBRo! ;) @author LiTBRo @source https://github.com/LiT-BRo @date 31 Aug 2021 """ import tkinter as tk from tkinter import filedialog import os # # # # # # # # # # # # Main-Window # # # # # # # # # # # # root = tk.Tk() files = [] def addFolder(): file_dir = filedialog.askdirectory(initialdir="/", title="Select Folder") global files files = os.listdir(file_dir) for file in files: label = tk.Label(frame, text=file, bg="grey") label.pack() def writeFile(filename, files): with open(filename, "a") as f: for file in files: f.write(file+"\n") print("File Write Complete!") def fileChecker(): file_dir = os.path.normpath(os.path.expanduser("~/Desktop")) file_name = "\File_Names.txt" filename = file_dir+file_name counter = 1 if os.path.exists(filename) == True: while True: filename = file_dir+f"\File_Names({counter}).txt" if os.path.exists(filename) == True: counter += 1 pass else: writeFile(filename, files) break else: writeFile(filename, files) # # # # # # # # # # # # # Buttons # # # # # # # # # # # # # canvas = tk.Canvas(root,height=700, width=550, bg="#263D42", scrollregion=(0,0,500,500)) canvas.pack() frame = tk.Frame(root, bg="white") frame.place(relwidth=0.9, relheight=0.82, relx=0.05, rely=0.04) openf = tk.Button(root, text="Open Folder", padx=15, pady=7, fg="white", bg="#263D42", command=addFolder) openf.place(relwidth=0.2,relheight=0) openf.pack() execute = tk.Button(root, text="Run", padx=15, pady=7, fg="white", bg="#263D42", command=fileChecker) execute.place(relwidth=0.2,relheight=0) execute.pack() root.mainloop()
7101a1e9f48462829805a56f338eb61782ff0c59
eAlasdair/Fighting-Fantasy-GUI
/ff_extras.py
3,668
3.640625
4
""" Alasdair Smith Started 20/12/2016 Module for the Fighting Fantasy Program Includes the initial decision question GUI, a few helper functions, and code to run the whole program For Fighting Fantasy Gamebooks: Ian Livingstone's Caverns of the White Witch & similar """ from tkinter import * from tkinter.font import * #from tkinter.ttk import * #Can't use because it's buttons don't support fonts import ff_charactersheet import ff_combatscreen import random import copy #THIS IS THE INITIAL QUESTION GUI FOR THE PROGRAM class QuestionGui: """ Full program or just combat calculator button window Attributes: questionwindow: the window holding the gui full_or_combat: the word states the program to be run, None if not chosen """ def __init__(self, window): """Initialises, then opens the gui for the question to be answered""" self.questionwindow = window self.full_or_combat = None #Set custom fonts self.headerfont = Font(family=ff_charactersheet.FONT_FAMILY, size=ff_charactersheet.BIG_FONT) #Finish by running the main question screen self.run_question() def run_question(self): """Brings up a window asking whether the user wants to run just the combat calculator or the full gui""" text_question = "What do you want to do?" text_full = "Build Character Sheet" text_combat = " Fight a Battle! " #Try get it with equal spacing to the above line question_label = Label(self.questionwindow, font=self.headerfont, text=text_question) combat_button = Button(self.questionwindow, font=self.headerfont, text=text_combat, command=lambda: self.choose_mode("combat")) full_button = Button(self.questionwindow, font=self.headerfont, text=text_full, command=lambda: self.choose_mode("full")) question_label.grid(row=0, column=0, columnspan=2, pady=10) combat_button.grid(row=1, column=1, padx=10, pady=10, ipadx=35, ipady=5) full_button.grid(row=1, column=0, padx=10, pady=10, ipadx=35, ipady=5) def choose_mode(self, mode_choice): """Saves mode choice and closes the question window""" self.questionwindow.destroy() self.full_or_combat = mode_choice def roll_dice(dice=1, sides=6): """Returns an integer representing a throw of [dice] [sides] sided dice""" return random.randint(dice, (dice * sides)) def make_default_enemy(): """Creates a basic enemy Character from charactersheet global ENEMY_NAME""" return ff_charactersheet.Character(name=ff_charactersheet.ENEMY_NAME) def copy_dict(dictionary): """Returns a NEW dictionary with the same values as the old one""" return copy.deepcopy(dictionary) def run_code(): """Little bit of code that runs everything""" questionwindow = Tk() question_gui = QuestionGui(questionwindow) questionwindow.mainloop() blank_character = ff_charactersheet.Character() if question_gui.full_or_combat == "combat": ff_combatscreen.run_combat_gui(blank_character, make_default_enemy()) elif question_gui.full_or_combat == "full": characterwindow = Tk() character_gui = ff_charactersheet.CharacterSheetGui(characterwindow, blank_character) characterwindow.mainloop() #else window was closed by other means, so take no further action def main(): """Starts the entire program""" if __name__ == "__main__": run_code() main()
17c47ebb8a42c670d05d90ffe2c5f0a18bd6c298
guillevn/python
/zodiaco.py
1,409
3.765625
4
# -*- coding: cp1252 -*- def zod(): dia=input("Introduce el día de nacimiento") mes=input("Introduce el mes de nacimiento (en número)") if mes==1: if dia<=20: print "Capricornio" else: print "Acuario" elif mes==2: if dia<=19: print "Acuario" else: print "Piscis" elif mes==3: if dia<=20: print "Piscis" else: print "Aries" elif mes==4: if dia<=20: print "Aries" else: print "Tauro" elif mes==5: if dia<=20: print "Tauro" else: print "Geminis" elif mes==6: if dia<=21: print "Geminis" else: print "Cancer" elif mes==7: if dia<=23: print "Cancer" else: print "Leo" elif mes==8: if dia<=23: print "Leo" else: print "Virgo" elif mes==9: if dia<=23: print "Virgo" else: print "Libra" elif mes==10: if dia<=22: print "Libra" else: print "Escorpio" elif mes==11: if dia<=22: print "Escorpio" else: print "Sagitario" else: if dia<=22: print "Sagitario" else: print "Capricornio"
dae2b6ecbf75a847305d51ddc1e1a1dfd4d132cb
PradipH31/Python-Crash-Course
/Part_II/rw_visual.1.py
814
3.71875
4
#!./P2ENV/bin/python # Random Walk visually import matplotlib.pyplot as plt from random_walk import RandomWalk rw = RandomWalk(5000) rw.fill_walk() # Colormap for the walk light color(start) to dark color(end) of the walk # point_numbers stores the steps of the walk in order and used in c= point_numbers = list(range(rw.num_points)) # Set the size of the plotting window. plt.figure(figsize=(20, 9)) # Emphasize the first and last points. # plt.plot(0, 0, c='green', edgecolors='none', s=100) # plt.plot(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', # s=100) # plt.plot(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, # edgecolor='none', s=15) plt.plot(rw.x_values, rw.y_values, linewidth=1, c='yellow') # Remove the axes. plt.axis('off') plt.show()
3db5a554acc92051d4ec7a544a4c922fcad49309
PradipH31/Python-Crash-Course
/Chapter_9_Classes/C2_Inheritance.py
1,094
4.5625
5
#!./ENV/bin/python # ---------------------------------------------------------------- # Inheritance class Car(): """Class for a car""" def __init__(self, model, year): """Initialize the car""" self.model = model self.year = year def get_desc_name(self): """Get the descriptive name of the car""" return (str(self.year) + self.model) # Child class is initialized by super().__init__(paramters(without self)) # Child class iherits the methods from the parent. # Override the parent methods class ElectricCar(Car): """Class from car class""" def __init__(self, model, year, batt_size): """initialize the electric car""" super().__init__(model, year) self.batt_size = batt_size def get_batt(self): """returns the battery""" return self.batt_size def get_desc_name(self): """Get the descriptive name of the car""" return ("Electric " + str(self.year) + self.model) my_tesla = ElectricCar("Audi", 1990, 90) print(my_tesla.get_desc_name()) print(my_tesla.get_batt())
2c491529962855c0a6a23cc5fb8dc6c3b328887b
PradipH31/Python-Crash-Course
/Part_II/scatter_square.py
1,025
3.53125
4
#!./P2ENV/bin/python # Imorting the pyplot module import matplotlib.pyplot as plt # plt.scatter(x, y, s=size) plt.scatter(2, 4, s=500) # Modifying display of both x and y axis plt.tick_params(axis='both', labelsize=14) # scatter with a series of points # use two lists of equal dimension # plt.scatter(list_x, list_y) x = [1, 2, 3, 5, 6] y = [2, 5, 8, 10, 15] plt.scatter(x, y, s=800) # Calculating data automatically x_val = range(100, 300) y_val = [x**2 for x in x_val] # Removing outline from data points and custom colors plt.scatter(x_val, y_val, c='red', edgecolor='none', s=1) plt.axis([0, 350, 0, 100000]) # Colormap: a series of colors # c=y_val sets the color density # cmap=plt.cm.* sets the colormap to be used plt.scatter(x_val, y_val, c=y_val, cmap=plt.cm.Reds, edgecolor='none', s=40) # Save the plot with # plt.savefig('file_name', bbox_inches='tight') # bbox_inches='tight' trims extra whitespace from the plot plt.savefig('squares_plot.png', bbox_inches='tight') # Making the plot display plt.show()
c684cf0f8d15e4e684b2668eaf0bfadd8b30306a
PradipH31/Python-Crash-Course
/Chapter_9_Classes/C1_Book.py
959
4.4375
4
#!./ENV/bin/python # ---------------------------------------------------------------- # # Classes class Book(): """Class for a book""" def __init__(self, name, year): """Initialize the book with name and year""" self.name = name self.year = year def get_name(self): """Returns the name of the book""" return self.name my_book = Book("NOSP", "2012") print(my_book.get_name()) class Car(): """Car class""" def __init__(self, name, year): self.name = name self.year = year self.met_traveled = 0 def set_met(self, m): if m > self.met_traveled: self.met_traveled = m def upd_met(self, m): self.met_traveled += m my_car = Car("Toyota", "1999") # Modifying attributes of an object directly through the variable my_car.met_traveled = 20 # through a method my_car.set_met(11) # adding new value to the current value my_car.upd_met(19)
1b776fe62f0e7edd85875a4dfeb20a66100b7824
sadhikari0102/magic-temp-analyzer
/app.py
1,562
3.609375
4
from csv import DictReader from temp_log_processor import TempLogProcessor def start(): filepath = input("Enter File path for data set:") temp_log_processor = TempLogProcessor() with open(filepath, 'r') as csvfile: filereader = DictReader(csvfile) print("Processing Data...") for row in filereader: # print(row) temp_log_processor.process_datapoint(row) print('Data Processed Successfully.') take_input = True while take_input: option = input("Choose a query type: \n 1. Get Minimum Temp \n 2. Get Maximum Fluctuation \n 3. Get Maximum Fluctuation for Date range \n") if option == '1': (station_id, date, temp) = temp_log_processor.get_lowest_temp() print(f'Minimum Temp of {temp} celcius was from station {station_id} on {date}') elif option == '2': station_id = temp_log_processor.get_maximum_fluctuation() print(f'Maximum fluctutaion was at station {station_id}') elif option == '3': start_date = input("Enter start date: ") end_date = input("Enter end date: ") station_id = temp_log_processor.get_maximum_fluctuation_for_date_range(float(start_date), float(end_date)) print(f'Maximum fluctutaion for given date range was at station {station_id}') else: print('Chosen option unavailable!') retry = input("Enter 'Y' to continue, anything else to exit") take_input = (retry == 'Y') if __name__ == "__main__": start()
c05013b2034536fbdf145939e37cf709037bb014
amandotzip/stalinsort
/runner.py
3,404
3.515625
4
import random from art import * from pygame import mixer #load music mixer.init() mixer.music.load("Moskau Ear Destruction.mp3") mixer.music.play() # list of random unique numbers list = random.sample(range(100), 50) print(list) #If a number is larger then the one after it, delete the comrade that has fallen out of line. #Continue searching for treason length = len(list) - 1 i = 0 while i in range(length): if list[i] > list[i+1]: Art=text2art("BEGONE " + str(list[i+1]) + "!") print("""░░░░░░░░░░▀▀▀██████▄▄▄░░░░░░░░░░ ░░░░░░░░░░░░░░░░░▀▀▀████▄░░░░░░░ ░░░░░░░░░░▄███████▀░░░▀███▄░░░░░ ░░░░░░░░▄███████▀░░░░░░░▀███▄░░░ ░░░░░░▄████████░░░░░░░░░░░███▄░░ ░░░░░██████████▄░░░░░░░░░░░███▌░ ░░░░░▀█████▀░▀███▄░░░░░░░░░▐███░ ░░░░░░░▀█▀░░░░░▀███▄░░░░░░░▐███░ ░░░░░░░░░░░░░░░░░▀███▄░░░░░███▌░ ░░░░▄██▄░░░░░░░░░░░▀███▄░░▐███░░ ░░▄██████▄░░░░░░░░░░░▀███▄███░░░ ░█████▀▀████▄▄░░░░░░░░▄█████░░░░ ░████▀░░░▀▀█████▄▄▄▄█████████▄░░ ░░▀▀░░░░░░░░░▀▀██████▀▀░░░▀▀██░░""") print(Art), print("""░░░░░░░░░░▀▀▀██████▄▄▄░░░░░░░░░░ ░░░░░░░░░░░░░░░░░▀▀▀████▄░░░░░░░ ░░░░░░░░░░▄███████▀░░░▀███▄░░░░░ ░░░░░░░░▄███████▀░░░░░░░▀███▄░░░ ░░░░░░▄████████░░░░░░░░░░░███▄░░ ░░░░░██████████▄░░░░░░░░░░░███▌░ ░░░░░▀█████▀░▀███▄░░░░░░░░░▐███░ ░░░░░░░▀█▀░░░░░▀███▄░░░░░░░▐███░ ░░░░░░░░░░░░░░░░░▀███▄░░░░░███▌░ ░░░░▄██▄░░░░░░░░░░░▀███▄░░▐███░░ ░░▄██████▄░░░░░░░░░░░▀███▄███░░░ ░█████▀▀████▄▄░░░░░░░░▄█████░░░░ ░████▀░░░▀▀█████▄▄▄▄█████████▄░░ ░░▀▀░░░░░░░░░▀▀██████▀▀░░░▀▀██░░""") list.remove(list[i+1]) i -= 1 length -= 1 i += 1 print(list) print("A sorted glory")
3ceb5c72bc49fade422fe4c59f1e6a8cb6e1dd99
gradam/project-euler
/041_Pandigital_prime.py
588
3.84375
4
def is_pandigital(x): y = str(x) cyfry = [] for z in y: if z in cyfry or int(z) == 0: return False cyfry.append(z) numbers = "123456789" cyfry.sort() lenght = len(cyfry) if "".join(cyfry) == numbers[0:lenght]: return True return False def is_prime(x): print(x) for z in range(3, int(x**0.5)+1, 2): if x % z == 0: return False return True def main(): for x in range(987654321, 1, -2): if is_pandigital(x): if is_prime(x): return x print(main())
180b09a4945cbbe0ec1ed54b6c764dc88e85b0f6
yulya2787/python_advanced
/less3/#1.py
839
3.515625
4
import time def decorator(num_of_repeats=1): def time_to_do_function(function): def wrapped(*args, **kwargs): dic_result = {} for i in range(num_of_repeats): dic_result[f"result for iteration {i}"] = {} start_time = time.time() end_time = time.time() - start_time func_results = function() dic_result[f"result for iteration {i}"]["function name"] = function.__name__ dic_result[f"result for iteration {i}"]["time of function extcution: "] = end_time dic_result[f"result for iteration {i}"]["result of function extcution: "] = func_results return dic_result return wrapped return time_to_do_function @decorator(5) def func(): return 100000+300000 print(func())
3b2023ce61bfa403f7d4f4b340e54b2140614026
yulya2787/python_advanced
/less2/#2.py
1,011
4.21875
4
'''Создать класс магазина. Конструктор должен инициализировать значения: «Название магазина» и «Количество проданных товаров». Реализовать методы объекта, которые будут увеличивать кол-во проданных товаров, и реализовать вывод значения переменной класса, которая будет хранить общее количество товаров проданных всеми магазинами.''' class Market: total = 0 def __init__(self, name, quontity_of_goods): self._name = name self.quontity_of_goods = quontity_of_goods Market.total += quontity_of_goods ATB = Market('ATB', 100) ATB.quontity_of_goods = 100 Novus = Market('Novus', 150) Novus.quontity_of_goods = 150 print(Market.total) print(ATB.quontity_of_goods) print(Novus.quontity_of_goods)
80b9d8d6f0249274c26b67d9a7fb07a374762955
yulya2787/python_advanced
/less1/#1.py
102
3.671875
4
#1 N = [] n = 10 i = 0 for i in range(n): if i % 2 == 0 and i != 0: N.append(i) print(N)
9a76041b4f7465fc6061ed4ee3efb65899a258db
alexugalek/tasks_solved_via_python
/HW1/upper_lower_symbols.py
374
4.46875
4
# Task - Count all Upper latin chars and Lower latin chars in the string test_string = input('Enter string: ') lower_chars = upper_chars = 0 for char in test_string: if 'a' <= char <= 'z': lower_chars += 1 elif 'A' <= char <= 'Z': upper_chars += 1 print(f'Numbers of lower chars is: {lower_chars}') print(f'Numbers of upper chars is: {upper_chars}')
7a2cbaac307d558ea191c82d097872ef0b62c943
alexugalek/tasks_solved_via_python
/HW1/task_48.py
2,339
3.6875
4
def seven_segment(lit_seg, broken_seg): """Two displays with seven segment screen :param lit_seg: Contains the lit segments as a set of letters representing segments :param broken_seg: Contains the broken segments as a set of letters representing segments :return: The total number that the device may be displaying """ nmb_dict = {1: {'B', 'C'}, 2: {'A', 'B', 'D', 'E', 'G'}, 3: {'A', 'B', 'C', 'D', 'G'}, 4: {'B', 'C', 'F', 'G'}, 5: {'A', 'C', 'D', 'F', 'G'}, 6: {'A', 'C', 'D', 'E', 'F', 'G'}, 7: {'A', 'B', 'C'}, 8: {'A', 'B', 'C', 'D', 'E', 'F', 'G'}, 9: {'A', 'B', 'C', 'D', 'F', 'G'}, 0: {'A', 'B', 'C', 'D', 'E', 'F'}} first_segment_set = [set(), set()] second_segment_set = [set(), set()] nmb_of_first_segment_list = [] nmb_of_second_segment_list = [] for element in lit_seg: if element.isupper(): first_segment_set[0].add(element) first_segment_set[1].add(element) else: second_segment_set[0].add(element.upper()) second_segment_set[1].add(element.upper()) for element in broken_seg: if element.isupper(): first_segment_set[1].add(element) else: second_segment_set[1].add(element.upper()) for key, value in nmb_dict.items(): if first_segment_set[0] <= value <= first_segment_set[1]: nmb_of_first_segment_list.append(key) if second_segment_set[0] <= value <= second_segment_set[1]: nmb_of_second_segment_list.append(key) f_segment = len(nmb_of_first_segment_list) s_segment = len(nmb_of_second_segment_list) if f_segment > 0 and s_segment > 0: return f_segment * s_segment elif f_segment > 0: return f_segment elif s_segment > 0: return s_segment return 0 if __name__ == '__main__': assert seven_segment({'B', 'C', 'b', 'c'}, {'A'}) == 2, '11, 71' assert seven_segment( ({'B', 'C', 'a', 'f', 'g', 'c', 'd'}, {'A', 'G', 'D', 'e'}) == 6) assert seven_segment( ({'B', 'C', 'a', 'f', 'g', 'c', 'd'}, {'A', 'G', 'D', 'F', 'b', 'e'}) == 20) print('"Run" is good. How is "Check"?')
bb04a57a280a4c84e6042b210fc1500a5c57d3c4
alexugalek/tasks_solved_via_python
/HW2/task_6.py
973
4.09375
4
def ordered_list(input_list): """Ordered list :param input_list: list of integers :return: sorted list where all 0 elements in the end of list """ el_index, iter_count = 0, len(input_list) while iter_count > 0: if not input_list[el_index]: input_list.append(input_list.pop(el_index)) else: el_index += 1 iter_count -= 1 return input_list if __name__ == '__main__': assert ordered_list([1, 2, 0, 0, 4, 0, 3, 1]) == [1, 2, 4, 3, 1, 0, 0, 0] assert ordered_list([0, 0, 0, 0, 0]) == [0, 0, 0, 0, 0] assert ordered_list([0]) == [0] assert ordered_list([1, 2, 3, 4, 5, 6]) == [1, 2, 3, 4, 5, 6] assert ordered_list([0, 0, 0, 0, 1, 2, 3, 4]) == [1, 2, 3, 4, 0, 0, 0, 0] assert ordered_list([1, 2, 3, 4, 0, 5]) == [1, 2, 3, 4, 5, 0] assert ordered_list([0, 1, 2, 3, 4]) == [1, 2, 3, 4, 0] assert ordered_list([]) == [] print(ordered_list([1, 2, 0, 0, 4, 0, 3, 1]))
fea598032ae2a1c7676e6b0286d2fae1362bdfa3
alexugalek/tasks_solved_via_python
/HW1/task_5.py
418
4.40625
4
def add_binary(a, b): """Instructions Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string. """ return bin(a + b)[2:] if __name__ == '__main__': a = int(input('Enter 1 number: ')) b = int(input('Enter 2 number: ')) print(add_binary(a, b))
3a30283bb1d94a297284d4957067ef29367ac89b
alexugalek/tasks_solved_via_python
/HW1/task_21.py
1,555
3.953125
4
def simple_nod(number): """Instructions Quick find of simple dividers for numbers """ nod = 2 temp_list = [] while nod ** 2 <= number: if not number % nod: temp_list.append(nod) number //= nod else: nod += 1 if number > 1: temp_list.append(number) return temp_list def sum_for_list(lst): """Instructions Given an array of positive or negative integers I= [i1,..,in] you have to produce a sorted array P of the form [ [p, sum of all ij of I for which p is a prime factor (p positive) of ij] ...] P will be sorted by increasing order of the prime numbers. The final result has to be given as a string in Java, C#, C, C++ and as an array of arrays in other languages. Example: I = [12, 15] # result = [[2, 12], [3, 27], [5, 15]] :param lst: integers numbers :return: sequence of lists """ list_of_nods = [] for num in lst: temp_list = simple_nod(abs(num)) for item in temp_list: if item not in list_of_nods: list_of_nods.append(item) result = [] for nod in list_of_nods: flag = False sum = 0 for num in lst: if not num % nod: sum += num flag = True if flag: result.append([nod, sum]) return sorted(result, key=lambda x: x[0]) if __name__ == '__main__': test_list = [12, 15] assert sum_for_list(test_list) == [[2, 12], [3, 27], [5, 15]]
94526a71e870c86247601dc6b790b650e154d939
alexugalek/tasks_solved_via_python
/HW4/task_7.py
503
4.0625
4
def nd_pow_of_two(number): """Largest divisor of number :param number: integer number != 0 :return: largest divisor of number which also is a power of two """ nd_pow = 1 while number % nd_pow == 0: nd_pow <<= 1 return nd_pow >> 1 if __name__ == '__main__': for i in range(1, 22): print('{}: {}'.format(i, nd_pow_of_two(i))) i = 1000000000000000000000000000000000000000000000000000000000000000000000 print('{}: {}'.format(i, nd_pow_of_two(i)))
6889e39e73935e704d91c750b3a13edb36133afc
alexugalek/tasks_solved_via_python
/HW1/task_23.py
1,327
4.4375
4
def longest_slide_down(pyramid): """Instructions Imagine that you have a pyramid built of numbers, like this one here: 3 7 4 2 4 6 8 5 9 3 Here comes the task... Let's say that the 'slide down' is a sum of consecutive numbers from the top to the bottom of the pyramid. As you can see, the longest 'slide down' is 3 + 7 + 4 + 9 = 23 """ for line in range(len(pyramid) - 2, -1, -1): for column in range(len(pyramid[line])): pyramid[line][column] += max(pyramid[line + 1][column], pyramid[line + 1][column + 1]) return pyramid[0][0] print(longest_slide_down([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]])) # 23 print(longest_slide_down([ [75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23], ])) # 1074
acdcddc6a6e17466c36f1ad4ca46efd015689153
alexugalek/tasks_solved_via_python
/HW1/task_53.py
750
4.125
4
def longest_palindromic(a): """The longest palindromic""" result = '' for i in range(len(a)): for j in range(i, len(a)): tmp_val = a[i:j + 1:1] if tmp_val == tmp_val[::-1] and len(a[i:j + 1:1]) > len(result): result = a[i:j + 1:1] return result if __name__ == '__main__': print("Example:") print(longest_palindromic('abacada')) # These "asserts" are used for self-checking and not for an auto-testing assert longest_palindromic('abc') == 'a' assert longest_palindromic('abacada') == 'aba' assert longest_palindromic('artrartrt') == 'rtrartr' assert longest_palindromic('aaaaa') == 'aaaaa' print("Coding complete? Click 'Check' to earn cool rewards!")
3a9c3ff81d9973528d292203111105d148ace624
alexugalek/tasks_solved_via_python
/HW1/task_14.py
575
4.0625
4
def productfib(prod): """Instructions prod:: given integer natural argument return:: list with two fibonacci numbers whose multiplication >= prod and flag ='False' if multiplication > prod, flag = 'True' if multiplication = prod prod = 45678 return = [233, 377, False] """ print(prod) fib = 0 fib_next = 1 while fib * fib_next < prod: fib, fib_next = fib_next, fib + fib_next return [fib, fib_next, fib * fib_next == prod] if __name__ == '__main__': print(productfib(45678)) print(productfib(33552))
eff87b15ecc852269e96484d1c89f0b464d4b1ad
JSalmen13/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
513
4.09375
4
#!/usr/bin/python3 """ text indention function text is the string to be treated """ def text_indentation(text): """ text indention function text is the string to be treated """ if not isinstance(text, str): raise TypeError("text must be a string") cond = ['.', ',', '?', ':'] char = 0 while char < len(text): print("{}".format(text[char]), end="") if text[char] in cond: print() print() char += 1 char += 1 print()
81322dd226018292a5d3e33cfcc85cff0313ba56
JSalmen13/holbertonschool-higher_level_programming
/0x05-python-exceptions/4-list_division.py
547
3.765625
4
#!/usr/bin/python3 def list_division(my_list_1, my_list_2, list_length): my_list_results = [] for x in range(list_length): try: result = my_list_1[x] / my_list_2[x] except (ZeroDivisionError): print("division by 0") result = 0 except (IndexError): print("out of range") result = 0 except (TypeError): print("wrong type") result = 0 finally: my_list_results.insert(x, result) return(my_list_results)
bca71a3a39abc3d2c409af30d54fd7abf9c978ba
JSalmen13/holbertonschool-higher_level_programming
/0x03-python-data_structures/10-divisible_by_2.py
303
3.859375
4
#!/usr/bin/python3 def divisible_by_2(my_list=[]): L = len(my_list) if L > 0: new = list(my_list) for K in range(L): if my_list[K] % 2 == 0: new[K] = True else: new[K] = False else: return(None) return(new)
11addd1e999a77d3e0168995e37b6679521871c3
JSalmen13/holbertonschool-higher_level_programming
/0x0A-python-inheritance/100-my_int.py
407
3.796875
4
#!/usr/bin/python3 """ int subclass """ class MyInt(int): """ int subclass """ def __init__(self, value): """ MyInt int """ self.value = value def __eq__(self, obj): """ equal int """ return (obj != self.value) def __ne__(self, obj): """ not equal int """ return (obj == self.value)
61d6ff7bfcb53630a1b0ae3643db8af56fca8c14
g8gg/PythonLearning
/FluentPython/02-An-Array-of-Sequences/bisect_demo.py
1,659
3.703125
4
# Managing Ordered Sequences with bisect # BEGIN BISECT_DEMO import bisect import sys HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30] NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31] ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}' def demo(bisect_fn): for needle in reversed(NEEDLES): position = bisect_fn(HAYSTACK, needle) # <1> Use the chosen bisect function to get the insertion point. offset = position * ' |' # <2> Build a pattern of vertical bars proportional to the offset. print(ROW_FMT.format(needle, position, offset)) # <3> Print formatted row showing needle and insertion point. if __name__ == '__main__': if sys.argv[-1] == 'left': # <4> Choose the bisect function to use according to the last command-line argument. bisect_fn = bisect.bisect_left else: bisect_fn = bisect.bisect print('DEMO:', bisect_fn.__name__) # <5> Print header with name of function selected. print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK)) demo(bisect_fn) # bisect的行为可以在两个方面微调 # The behavior of bisect can be fine-tuned in two ways. # 首先,有一对可选参数,lo和hi,允许收缩搜索的范围,默认lo=0,hi=len() # First, a pair of optional arguments, lo and hi, allow narrowing the region in the sequence to be searched when inserting. # lo defaults to 0 and hi to the len() of the sequence. # 第二,默认bisect的行为是bisect_right,也就是插入点的后面,而如果使用bisect_left,则在之前插入 # Second, bisect is actually an alias for bisect_right, and there is a sister function called bisect_left. # END BISECT_DEMO
26e46d124031240c3b9d601a9e75e57d01021015
g8gg/PythonLearning
/FluentPython/02-An-Array-of-Sequences/slicing.py
3,569
4.34375
4
# Slicing # 我们都知道sequences can be sliced using the s[a:b] syntax # 所有的sequence types都支持切片,如: list, tuple, str # Why Slices and Range Exclude the Last Item # The Pythonic convention of excluding the last item in slices and ranges works well with the zero-based indexing # used in Python, C, and many other languages. Some convenient features of the convention are: # 1. It’s easy to see the length of a slice or range when only the stop position is given: range(3) and my_list[:3] both produce three items. # 2. It’s easy to compute the length of a slice or range when start and stop are given: just subtract stop - start. # 3. It’s easy to split a sequence in two parts at any index x, without overlapping: simply get my_list[:x] and my_list[x:]. For example: l = [10, 20, 30, 40, 50, 60] print(l[:2]) # split at 2 print(l[2:]) print(l[:3]) # split at 3 print(l[3:]) # Slice Objects # This is no secret, but worth repeating just in case: s[a:b:c] can be used to specify a stride or step c, causing the # resulting slice to skip items. The stride can also be negative, returning items in reverse. # Three examples make this clear: s = 'bicycle' print(s[::3]) print(s[::-1]) print(s[::-2]) # The notation a:b:c is only valid within [] when used as the indexing or subscript operator, # and it produces a slice object: slice(a, b, c). # How Slicing Works ? # Checking out the behavior of __getitem__ and slices class MySeq: def __getitem__(self, index): return index # For this demonstration, __getitem__ merely returns whatever is passed to it. s = MySeq() print(s[1]) # A single index, nothing new. print(s[1:4]) # The notation 1:4 becomes slice(1, 4, None). print(s[1:4:2]) # slice(1, 4, 2) means start at 1, stop at 4, step by 2. print(s[1:4:2, 9]) # Surprise: the presence of commas inside the [] means __getitem__ receives a tuple. print(s[1:4:2, 7:9]) # The tuple may even hold several slice objects. invoice = """ 0.....6.................................40........52...55........ 1909 Pimoroni PiBrella $17.50 3 $52.50 1489 6mm Tactile Switch x20 $4.95 2 $9.90 1510 Panavise Jr. - PV-201 $28.00 1 $28.00 1601 PiTFT Mini Kit 320x240 $34.95 1 $34.95 """ SKU = slice(0, 6) DESCRIPTION = slice(6, 40) UNIT_PRICE = slice(40, 52) QUANTITY = slice(52, 55) ITEM_TOTAL = slice(55, None) line_items = invoice.split('\n')[2:] for item in line_items: print(item[UNIT_PRICE], item[DESCRIPTION]) ### Inspecting the attributes of the slice class print(slice) # slice is a built-in type print(dir(slice)) # Inspecting a slice we find the data attributes start, stop, and step, and an indices method. help(slice.indices) # Multidimensional Slicing and Ellipsis # The [] operator can also take multiple indexes or slices separated by commas. This is used, for instance, in the # external NumPy package, where items of a two-dimensional numpy.ndarray can be fetched using the syntax a[i, j] and a # two-dimensional slice obtained with an expression like a[m:n, k:l]. # 参见原书讨论 # Assigning to Slices l = list(range(10)) print(l) l[2:5] = [20, 30] print(l) del (l[5:7]) print(l) l[3::2] = [11, 22] print(l) # l[2:5] = 100 # When the target of the assignment is a slice, the right side must be an iterable object, even if it has just one item. # TypeError: can only assign an iterable # S.indices(len) -> (start, stop, stride) l[2:5] = [100] print(l) print(l[2:2]) print(l[2:3])
a5306511c39e1a2bd0e3077f86df25e6e47f2dc6
firozsujan/pythonBasics
/Lists.py
1,629
4.1875
4
# Task 9 # HakarRank # Lists # https://www.hackerrank.com/challenges/python-lists/problem def proceessStatement(insertStatement, list): if insertStatement[0] == 'insert': return insert(insertStatement, list) elif insertStatement[0] == 'print': return printList(insertStatement, list) elif insertStatement[0] == 'remove': return remove(insertStatement, list) elif insertStatement[0] == 'append': return append(insertStatement, list) elif insertStatement[0] == 'sort': return sort(insertStatement, list) elif insertStatement[0] == 'pop': return pop(insertStatement, list) elif insertStatement[0] == 'reverse': return reverse(insertStatement, list) def insert(insertStatement, list): position = int(insertStatement[1]) insert = int(insertStatement[2]) updatedList = [] updatedList = list[:position] + [insert] + list[position:] return updatedList def printList(insertStatement, list): print(list) return list def remove(insertStatement, list): list.remove(int(insertStatement[1])) return list def append(insertStatement, list): list.append(int(insertStatement[1])) return list def sort(insertStatement, list): list.sort() return list def pop(insertStatement, list): list.pop() return list def reverse(insertStatement, list): list.reverse() return list if __name__ == '__main__': N = int(input()) list = [] for i in range(N): insertStatement = [] insertStatement = input().split(' ') list = proceessStatement(insertStatement, list)
86b3488e679b6e34d43d0be6e219a6f01761b3e1
firozsujan/pythonBasics
/StringFormatting.py
655
4.125
4
# Task # HackerRank # String Formatting # https://www.hackerrank.com/challenges/python-string-formatting/problem def print_formatted(number): width = len(bin(number)[1:]) printString = '' for i in range(1, number+1): for base in 'doXb': if base == 'd': width = len(bin(number)[2:]) else : width = len(bin(number)[1:]) printString = printString + "{:{width}{base}}".format(i, base=base, width=width) printString = printString + '\n' print(printString) if __name__ == '__main__': n = int(input()) print_formatted(n)
e6da2815776433af2a7203c6beec50524a9eddd8
PrajitR/elevator_problem
/simulation.py
6,199
3.828125
4
from elevator import Elevator, Actions import random import argparse import math class Simulation: """ Runs the elevator simulation. """ def __init__(self, nfloors, max_new_people): self.nfloors = nfloors self.expo_lambda = [1. / (f ** 2 + 1) for f in xrange(nfloors)] self.intervals = [int(random.expovariate(self.expo_lambda[f])) for f in xrange(self.nfloors)] self.waiting_people = [[] for _ in xrange(self.nfloors)] self.elevator_people = [[] for _ in xrange(self.nfloors)] self.max_new_people = max_new_people self.elevator = Elevator(self.nfloors) self.stats = Stats() def run(self, time): """ Main loop of simulation. At each time step, new people request the elevator, the elevator makes an action, and statistics are aggregated about wait times and elevator position. """ for t in xrange(time): self.generate_new_requests() action = self.elevator.action() self.update(action) self.stats.display_stats() def generate_new_requests(self): """ Creates new people that request the elevator. Each floor has a separate countdown timer before new people are created at that floor. The intervals are determined by an exponential distribution, with varying parameters between floors. Once a timer hits 0, a random number of new people are created at the floor who request the elevator. """ requests = [] for floor in xrange(self.nfloors): if self.intervals[floor] == 0: # Create new people on this floor who request elevator. new_people = int(random.random() * self.max_new_people) + 1 for _ in xrange(new_people): self.waiting_people[floor].append(Person(self.nfloors, floor)) requests.append(floor) # New interval until floor spawns new people. self.intervals[floor] = int(random.expovariate(self.expo_lambda[floor])) + 1 else: # Decrement timer. self.intervals[floor] -= 1 self.elevator.new_requests(requests) def update(self, action): """ Updates the state of people on the floor the elevator has stopped at. Also updates statistics about wait times and elevator position. """ f = self.elevator.current_floor self.stats.update_floor(f) if action == Actions['open']: # People getting off on this floor. for p in self.elevator_people[f]: self.stats.update_wait(p) self.elevator_people[f] = [] # All waiting people get on the elevator and press their desired location. floor_requests = [] for p in self.waiting_people[f]: floor_requests.append(p.desired_floor) self.elevator_people[p.desired_floor].append(p) self.elevator.new_requests(floor_requests) self.waiting_people[f] = [] for f in xrange(self.nfloors): for p in self.elevator_people[f]: p.wait(True) for p in self.waiting_people[f]: p.wait(False) class Stats: """ Aggregates waiting and elevator position statistics and displays them. """ def __init__(self): self.floor_wait_times = [] self.elevator_wait_times = [] self.floors = [] def update_wait(self, person): """ Update waiting time history. """ self.floor_wait_times.append(person.floor_wait_time) self.elevator_wait_times.append(person.elevator_wait_time) def update_floor(self, current_floor): """ Update elevator position history. """ self.floors.append(current_floor) def display_stats(self): """ Displays basic statistics about wait times. If matplotlib is installed, plots detailed graphs about wait times and elevator positions. """ wt, et, n = sum(self.floor_wait_times), sum(self.elevator_wait_times), len(self.floor_wait_times) print('Mean waiting for elevator time: %.3f' % ((1. * wt) / n)) print('Mean waiting on elevator time : %.3f' % ((1. * et) / n)) print('Mean total wait time : %.3f' % ((1. * wt + et) / n)) try: # Plot figures if the user has installed matplotlib. from matplotlib import pyplot as plt fig = plt.figure(1) ax = plt.subplot(211) ax.set_title('Time spent waiting for elevator') ax.set_xlabel('Time') ax.set_ylabel('Number of people') ax.hist(self.floor_wait_times) ax = plt.subplot(212) ax.set_title('Time spent waiting on elevator') ax.set_xlabel('Time') ax.set_ylabel('Number of people') ax.hist(self.elevator_wait_times) fig = plt.figure(2) plt.plot(self.floors) ax = plt.gca() ax.set_title('Floor of the elevator over time') ax.set_ylabel('Floor') ax.set_xlabel('Time') plt.show() except ImportError: print('\nWARN: matplotlib not installed. Cannot create graphs. Install with:\n\tpip install matplotlib') class Person: """ Represents a person waiting to reach their destination. Maintains personal statistics about wait times. """ def __init__(self, nfloors, floor): self.floor_wait_time = 0 self.elevator_wait_time = 0 # Randomly choose the desired floor for this person. # Biased towards lower floors (ex. people going down during lunch time). # Prevent getting on and off at the same floor. self.desired_floor = floor while self.desired_floor == floor: probs = [random.random() * 1 / (f ** 2 + 1) for f in xrange(nfloors)] self.desired_floor = sample(probs) def wait(self, in_elevator): """ Increments the wait time, depending on if the person is on the elevator or not. """ if in_elevator: self.elevator_wait_time += 1 else: self.floor_wait_time += 1 def sample(probs): """ Randomly samples from a multinomial distribution. """ norm = sum(probs) rand = random.random() * norm i = 0 while rand > probs[i]: rand -= probs[i] i += 1 return i if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run elevator simulation.') parser.add_argument('--floors', type=int, default=50, help='number of floors in the building') parser.add_argument('--iterations', type=int, default=100, help='number of iterations to run simulation for') parser.add_argument('--max_new_people', type=int, default=3, help='number of people that can arrive at the same time to wait for elevator') args = parser.parse_args() s = Simulation(args.floors, args.max_new_people) s.run(args.iterations)
49d9d519e30080386d6ac02a836f82d235d36c9e
JeffHritz/practice
/adventure_game.py
2,111
3.796875
4
# adventure_game.py - Jeff Hritz # Currently still in development """ Text-based adventure game. """ import time def intro(): """Intro sequence.""" print("\n" * 100) print("You are asleep, but still aware.") time.sleep(2) print("The world is a blur around you.") time.sleep(2) print("You feel yourself moving.") time.sleep(2) print("Floating") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("Wake up.") time.sleep(3) print("\n" * 100) time.sleep(4) print("You wake up in a forest in the early morning.") time.sleep(2) print("You don't know where you are.") time.sleep(2) print("This forest feels strange.") time.sleep(2) start() def choose(): print("Choose") choice = input() return choice def start(): """Starting area. Provides user the first choice.""" print("What do you do?") time.sleep(2) def starting_choice(): cmd = choose() if cmd == "1": print("You take a big poopy shit.") start() elif cmd == "2": print("You hold your breath until you become an hero.") elif cmd == "3": print("You walk deeper into the woods.") a = input() elif cmd == "4": print("You scream at the top of your lungs.\n" "The sound of your voice echoing into the quiet woods frightens you") start() elif cmd == "5": print("5") else: print("Choose again.") starting_choice() print("----------") print("1. poop\n" "2. kill yourself\n" "3. walk into the woods\n" "4. scream\n" "5. stay put\n") starting_choice() # def getcmd(cmdlist): # """Choice router based on user input and available options in each scenario.""" # if cmd in cmdlist: # return cmd if __name__ == "__main__": start()
57c8a8916a99f86325a623e32a88dadad0bf0f05
cameroncurry/SD-DeckBuildingGame
/src/Computer.py
2,735
3.546875
4
from time import sleep from Player import * class Computer(Player): def __init__(self,aggressive): super(Computer,self).__init__("Computer") self.aggressive = aggressive '''Computer game logic implemented here''' def move(self,player,central,view): view.displayTurn(self,player) sleep(0.5) self.playAll() view.displayTurn(self,player) sleep(0.5) view.showComputerActions("Computer attacking with strength %s" % self.attack) sleep(0.25) attackValue = self.willAttack() player.beenAttacked(attackValue) view.showComputerActions("Computing Buying Cards") if self.money > 0: cb = True while cb: templist = [] if len(central.supplement) > 0: if central.supplement[0].cost <= self.money: templist.append(("S", central.supplement[0])) for intindex in range (0, central.activeSize): if central.active[intindex].cost <= self.money: templist.append((intindex, central.active[intindex])) if len(templist) >0: highestIndex = 0 for intindex in range(0,len(templist)): if templist[intindex][1].cost > templist[highestIndex][1].cost: highestIndex = intindex if templist[intindex][1].cost == templist[highestIndex][1].cost: if self.aggressive: if templist[intindex][1].get_attack() >templist[highestIndex][1].get_attack(): highestIndex = intindex else: if templist[intindex][1].get_attack() >templist[highestIndex][1].get_money(): highestIndex = intindex source = templist[highestIndex][0] if source in range(0,5): buy_id = self.buyCard(central,int(source)) if buy_id == 0: view.showComputerActions("Computer Bought Card") sleep(0.2) else: supp_id = self.buySupplement(central) if supp_id == 0: view.showComputerActions("Supplement Bought") sleep(0.2) else: cb = False if self.money == 0: cb = False view.showComputerActions("Computer Turn Ending") self.endTurn() sleep(1)
ce7a7f3362652f37bbec4c976a02310a007e9c3d
vinikuttan/smallcodes
/dict_normalizer.py
1,275
4.125
4
#!/usr/bin/python __author__ = 'vineesh' def merge_nested_dict(mydict): """ flattening nested dict """ if isinstance(mydict, dict): result = mydict.copy() for each in mydict: if isinstance(mydict[each], dict): result[each] = mydict[each].keys() result.update(merge_nested_dict(mydict[each])) else: result[each] = mydict[each] return result else: return mydict def merge_two_dicts(left, right): """ replacing left dictionary with updated right dictionary """ if isinstance(left, dict) and isinstance(right, dict): result = left.copy() for each in right: if each in left: result[each] = merge_two_dicts(left[each], right[each]) else: result[each] = right[each] return result else: return right if __name__=="__main__": input_dict = {'a':1, 'b':{'c':2, 'e': 4}, 'd': '3'} left_dict = {'a':1, 'b': 2, 'c':{'d':3, 'e':4}} right_dict = {'a':1, 'b': 2, 'c': 3} # merging nested python dictionaries print merge_nested_dict(input_dict) # deep merging two dictionaries print merge_two_dicts(left_dict, right_dict)
77bedb2d4338eddef918152c4ed8ad93c82e55ba
rjafar/cracking-coding-interview
/data_structures/Stack/stackMin.py
506
3.921875
4
# Implements a method to find the min element in an unsorted stack # Time Complexity: O(1) from myStack import MyStack class StackMin: def __init__(self): self.sMin = MyStack() def push(self,data): if data < self.min(): self.sMin.push(data) self.push(data) def pop(self): val = self.pop() if val == self.sMin.min(): self.sMin.pop() return val def min(self): return self.sMin.peek()
e0d8d959ca2a4aa0dc407e9b8d52311bbf1882db
rjafar/cracking-coding-interview
/data_structures/LinkedList/loopDetection.py
400
3.96875
4
from linkedList import LinkedList # Description: Find node where circular linked lists begins # Input: linked list # Output: beginning of loop Node # Time Complexity: O(n) def loopDetection(LL): curr = LL.head m = {} while(curr): if curr not in m: m[curr] = 1 else: return curr if curr.next: curr = curr.next
d34060aeade9679e2a5eb9608af28aff0fcd9291
dcoluccia/Pytilities
/tex_table.py
3,276
3.75
4
""" Write a TeX table given numpy array input. @author: ColucciaD """ import os, subprocess ############################################################### def write_table(col_names, row_names, content, name = 'table'): """ Write in a TeX file a table which can then seemlessly be imported into the main TeX file using an \input{} command. NOTE: add booktabs to your TeX file. Parameters ------------- col_names : list (len(.) = C) A list that contains all names in the columns row_names : list (len(.) = R) A list that contains all names in the rows content : np.array (shape(content) = [R,C]) A np.array that stores the inner entries of the table. Output ------------- name.tex : .tex file A tex file that encodes the entries. """ # name of the file name_file = name + '.tex' # number of columns in the table index_cols = (len(col_names)+1) * 'c' # number of columns in the table index_cols = '{'+index_cols+'}' # header of the table args = {'table' :'{table}', 'tabular' :'{tabular}', 'arg0' : index_cols} header = '''\ \\begin{table}[h] \\centering \\begin{tabular}{arg0} \\toprule '''.format(**args) # first line with the names of the variables first_line = '& ' for j in range(len(col_names)): arg = {'arg0' : '{' + str(col_names[j]) + '}'} first_line = first_line + '''\\textsc{arg0} & '''.format(**arg) first_line = first_line[:-2] first_line = first_line + '\\\\ ' first_line = first_line + '\\midrule ' # populate the main content of the table main = [] for i in range(len(row_names)): arg = {'arg0' : '{' + row_names[i] + '}'} line = '\\textsc{arg0} & '.format(**arg) for j in range(len(col_names)): arg = {'arg0' : str(content[i][j])} line += '${arg0}$&'.format(**arg) line = line[:-1] line += '\\\\ ' main.append(line) # footer of the table args = {'table' :'{table}', 'tabular' :'{tabular}', 'Caption' : '{Insert caption here.}'} footer = '''\ \\bottomrule \\end{tabular} \\caption{Caption} \\end{table} '''.format(**args) # put everything together text = header + first_line for i in range(len(main)): text += main[i] text += footer # delete files with the same name if os.path.exists("{}".format(name_file)) == True: os.remove("{}".format(name_file)) # Write the new file with open('{}'.format(name_file),'w') as f: f.write(text) ###############################################################
2f5785f87b438aa89bcc88f403048f69545259ac
oscar7692/python_files
/agendaPyton.py
2,929
4.15625
4
#!/usr/bin/python3.7 def menu(): print('******Directorio de Contactos******') print('1- Crear nombre de la lista') print('2- Agregar Contacto') print('3- Buscar en directorio') print('4- Editar contactos') print('5- Mostrar contactos') print('6- Cerrar directorio') print() def menu2(): print('a- Buscar por nombre') print('b- Buscar por telefono') print('c- Buscar por direccion') def menu3(): print("Editar lista") print('1.- Eliminar un contacto') print('2.- Editar un contacto') directorio = [] telefonos = {} nombres = {} direcciones = {} apodos = {} opcionmenu = 0 menu() x=0 while opcionmenu != 6: opcionmenu = int(input("Inserta un numero para elegir una opcion: ")) if opcionmenu == 1: print('Ingrese el nombre de la lista:') nombre_de_lista=input() menu() elif opcionmenu == 2: print("Agregar Nombre, telefono, direccion y apodo") nombre = input("Nombre: ") telefono = input("Telefono: ") direccion = input("Direccion: ") apodo = input("Apodo: ") telefonos[nombre] = telefono nombres[telefono] = nombre direcciones[direccion] = nombre directorio.append([nombre, telefono, direccion, apodo]) menu() elif opcionmenu == 3: print("Busqueda") menu2() opcionmenu2 = input("Inserta una letra para elegir una opcion: ") if opcionmenu2=="a": nombre = input("Nombre: ") if nombre in telefonos: print("El telefono es", telefonos[nombre]) else: print(nombre, "no se encuentra") if opcionmenu2=="b": telefono = input("Telefono: ") if telefono in nombres: print("El Nombre es", nombres[telefono]) else: print(telefono, "no se encuentra") if opcionmenu2=="c": direccion = input("direccion: ") for linea in direcciones: linea = linea.rstrip() if not linea.startswith(direccion) : continue palabras = linea.split() print() else: print(direccion, "no se encuentra") menu() elif opcionmenu == 4: menu3() opcionmenu3 = input("Inserta un numero para elegir una opcion: ") if opcionmenu3=="1": nombre = input("Nombre: ") if nombre in directorio[0:10]: print('borrado') else: print(nombre, "no encontrado") else: menu() menu() elif opcionmenu == 5: print("\nNombre de la lista: ",nombre_de_lista) for e in directorio: print("\nLa lista es: ",directorio) menu() elif opcionmenu != 6: menu()
a004d1014405736eddb7ea1a028643e44e176a10
dineshreddymarri/Python
/homework3program1.py
185
3.78125
4
def bunnyEars(bunnies): if (bunnies == 0): return 0 else: if (bunnies % 2 == 0): return 3 + bunnyEars (bunnies - 1) else: return 2 + bunnyEars (bunnies - 1)
c967cfecad0854422e89f7869cbde592bab0a690
carlitrosglz/python-course
/01-basics/generators.py
973
3.984375
4
def generaNumerosPares(limit): num = 1 while num < limit: # YIELD construye un Iterable que contiene (en este caso) la lista con los numeros pares correspondientes # Entrega los valores de uno en uno, por lo que será necesario ir llamando al método .next() del Iterable # para obtener toda la lista yield num * 2 num += 1 lista = generaNumerosPares(10) # for item in lista: # print(item) print(next(lista)) print(next(lista)) print(next(lista)) ########################################################## def devuelveCiudades(*ciudades): # el asterisco indica al compilador que no se sabe la cantidad exacta de argumentos a enviar. Se enviará una tupla for item in ciudades: #for subItem in item: #yield subItem yield from item ciudadesGenerator = devuelveCiudades("Madrid", "Barcelona", "Bilbao", "Valencia") print(next(ciudadesGenerator)) print(next(ciudadesGenerator))
2f51299a035b6d120be53097a2fe07555d3d9e77
muraliR/data_classes
/date_extra_constructor.py
456
3.625
4
from dataclasses import dataclass from time import localtime # example with alternate constructor @dataclass class Date: year: int month: int day: int @classmethod def today(cls): d = cls.__new__(cls) t = localtime() d.year = t.tm_year d.month = t.tm_mon d.day = t.tm_mday return d if __name__ == '__main__': d1 = Date(2018,9,29) d2 = Date.today() print(d1) print(d2)
1f463d9d79a5a49ed4f1b586c5b5f759cdd73b04
muraliR/data_classes
/named_tuple.py
348
3.859375
4
from typing import NamedTuple class Person(NamedTuple): person_id: int name: str gender: str if __name__ == '__main__': person_1 = Person(100,'Guido','M') person_2 = Person(200,'Eric V Smith','M') person_3 = Person(100,'Guido','M') print(person_1 == person_3) print(person_1 >= person_2) print(person_2 >= person_3)
4130a25182b9b5afaf46edaef4a7035cce4e1af1
ankitkumar5422/FIR-management-systam
/dash.py
11,739
3.515625
4
from tkinter import * import sqlite3 from tkinter.messagebox import * con = sqlite3.Connection('DB.db') cur = con.cursor() def create(): cur.execute("create table if not exists login(username varchar(20) PRIMARY KEY, password varchar(20), name varchar(50))") def create_admin(): cur.execute("select * from login where username='admin'") status = cur.fetchall() if (len(status))==0: cur.execute("insert into login values ('admin', 'admin', 'Administrator')") else: flag=0 def sign_in(index_ui,username, password): try: cur.execute("select count(*) from login where username=? and password=?", (username, password)) except: showerror('ERROR', 'SIGNIN FAILED') status = cur.fetchall() if status[0][0]==1: index_ui.destroy() dashboard(username) else: showerror('ERROR', 'SIGNING FAILED') def details_ui(option): details_ui = Toplevel() details_ui.geometry("600x600+490+100") details_ui.resizable(0,0) bg = PhotoImage(file="images/windows_bg.gif") Label(details_ui, image=bg).place(x=0,y=0) cur.execute("create table if not exists complaint (fir_id varchar(10) PRIMARY KEY, fname varchar(15), lname varchar(15),blood_group varchar(3), father_name varchar(30), gender varchar(6), age number(3), status varchar(10), address varchar(15), complaint varchar(15))") Label(details_ui, text='FIR ID: ', font='Helvetica 11 bold',bg='#34383C',fg='white', borderwidth=0).place(x=140, y=80) fir_id = Entry(details_ui, font='Helvetica 11 bold', fg='#373E44') fir_id.place(x=320, y=80) Label(details_ui, text='First Name: ', font='Helvetica 11 bold',bg='#34383C',fg='white').place(x=140, y=140) fname = Entry(details_ui, font='Helvetica 11 bold', fg='#373E44') fname.place(x=320, y=140) Label(details_ui, text='Last Name: ', font='Helvetica 11 bold',bg='#34383C',fg='white').place(x=140, y=170) lname = Entry(details_ui, font='Helvetica 11 bold', fg='#373E44') lname.place(x=320, y=170) Label(details_ui, text='Blood Group: ', font='Helvetica 11 bold',bg='#34383C',fg='white').place(x=140, y=200) blood_group = Entry(details_ui, font='Helvetica 11 bold', fg='#373E44') blood_group.place(x=320, y=200) Label(details_ui, text="Father's Name: ", font='Helvetica 11 bold',bg='#34383C',fg='white').place(x=140, y=230) father_name = Entry(details_ui, font='Helvetica 11 bold', fg='#373E44') father_name.place(x=320, y=230) Label(details_ui, text='Gender: ', font='Helvetica 11 bold',bg='#34383C',fg='white').place(x=140, y=260) gender = Entry(details_ui, font='Helvetica 11 bold', fg='#373E44') gender.place(x=320, y=260) Label(details_ui, text='Age: ', font='Helvetica 11 bold',bg='#34383C',fg='white').place(x=140, y=290) age = Entry(details_ui, font='Helvetica 11 bold', fg='#373E44') age.place(x=320, y=290) Label(details_ui, text='Status: ', font='Helvetica 11 bold',bg='#34383C',fg='white').place(x=140, y=320) status = Entry(details_ui, font='Helvetica 11 bold', fg='#373E44') status.place(x=320, y=320) Label(details_ui, text='Address: ', font='Helvetica 11 bold',bg='#34383C',fg='white').place(x=140, y=350) address = Entry(details_ui, font='Helvetica 11 bold', fg='#373E44') address.place(x=320, y=350) Label(details_ui, text='Complaint: ', font='Helvetica 11 bold',bg='#34383C',fg='white').place(x=140, y=380) complaint= Entry(details_ui, font='Helvetica 11 bold', fg='#373E44') complaint.place(x=320, y=380) def insert_sql(): try: cur.execute("insert into criminals values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (fid.get(),fname.get(), lname.get(), blood_group.get(), father_name.get(), gender.get(), age.get(), status.get(), address.get(), complaint.get())) showinfo('Inserted', 'Values are inserted') except: showerror('ERROR', 'Insertion failed') if(option=='insert'): Label(details_ui, text='Enter the Details ', borderwidth=0, bg='white',font=(12)).place(x=360, y=10) Button(details_ui, text='Insert', font='Helvetica 14 bold',bg='#373E44',fg='white',borderwidth=0, command=insert_sql).place(x=460, y=520) def update(): try: cur.execute("update criminals set lockup_id=?, fname=?, lname=?, blood_group=?, father_name=?, gender=?, age=?, status=?,crime=?,state=?, city=?, street_no=?, house_no=? where criminal_id=?",(lockup_id.get(), fname.get(), lname.get(), blood_group.get(), father_name.get(), gender.get(), age.get(), status.get(), crime.get(), state.get(), city.get(), street_no.get(), house_no.get(),criminal_id.get())) details_ui.destroy() showinfo('UPDATED', 'DATA UPDATED') except: showerror('ERROR', 'Failed to Update') if(option=='update'): Label(details_ui, text='Enter Criminial ID to update', borderwidth=0, bg='white', font=(12)).place(x=324, y=10) Button(details_ui, text='Update', font='Helvetica 14 bold',bg='#373E44',fg='white',borderwidth=0, command=update).place(x=460, y=520) def view_sql(FIR_id): try: cur.execute("select * from criminals where criminal_id=?", [fir_id]) details = cur.fetchall()[0] if(len(fname.get())!=0): fname.delete(0,END) fname.insert(0,details[2]) if(len(lname.get())!=0): lname.delete(0,END) lname.insert(0,details[3]) if(len(blood_group.get())!=0): blood_group.delete(0,END) blood_group.insert(0,details[4]) if(len(father_name.get())!=0): father_name.delete(0,END) father_name.insert(0,details[5]) if(len(gender.get())!=0): gender.delete(0,END) gender.insert(0,details[6]) if(len(age.get())!=0): age.delete(0,END) age.insert(0,details[7]) if(len(status.get())!=0): status.delete(0,END) status.insert(0,details[8]) if(len(address.get())!=0): address.delete(0,END) address.insert(0,details[9]) if(len(complaint.get())!=0): complaint.delete(0,END) complaint.insert(0,details[10]) except: showerror('ERROR', 'Complaint record is not available for this ID') if (option=='view'): Button(details_ui, text='VIEW', font='Helvetica 11 bold',bg='#373E44',fg='white',borderwidth=0, command=lambda:view_sql(fir_id.get())).place(x=460 , y=520) Label(details_ui, text='Enter Criminal id only', borderwidth=0, bg='white',font=(12)).place(x=360, y=10) details_ui.mainloop() def create_acc(): create_win = Toplevel() create_win.geometry("900x600+300+100") create_win.resizable(0,0) new_user_bg = PhotoImage(file="images/other_bg.gif") Label(create_win, image=new_user_bg).place(x=0, y=0) Label(create_win, text="CREATE AN ACCOUNT", font="Helvetica 15 bold", fg='white', bg='#34383C').place(x=331, y=60) username = Entry(create_win, font=(13)) Label(create_win, text='Username', fg = '#34383C', bg='white', font='Helvetica 11 bold').place(x=300, y=160) password = Entry(create_win, font=(13)) Label(create_win, text='Password', fg = '#34383C', bg='white',font='Helvetica 11 bold').place(x=300, y=260) name = Entry(create_win, font=(13)) Label(create_win, text='Name', fg = '#34383C', bg='white', font='Helvetica 11 bold').place(x=300, y=360) username.place(x=300, y=200) password.place(x=300, y=300) name.place(x=300, y=400) Button(create_win, text=' '*20+' SUBMIT'+' '*22, bg='#00BC90', fg='#34383C',font='Helvetica 15' ,borderwidth=0, command=lambda:submit()).place(x=270, y=490) def submit(): try: cur.execute("insert into login values(?,?,?)", (username.get(), password.get(), name.get())) showinfo("CREATED", "ACCOUNT CREATED, NOW YOU CAN LOG IN TO THE APPLICATION") con.commit() except: showerror("ERROR", "YOUR ACCOUNT IS PROBABLY ALREADY REGISTERED , TRY LOGGING IN AND IF THE PROBLEM PERSISTS SEE HELP MENU") create_win.mainloop() def remove(): remove_ui = Toplevel() remove_ui.geometry("900x600+300+100") remove_ui.resizable(0,0) bg = PhotoImage(file="images/other_bg.gif") Label(remove_ui, image=bg).place(x=0,y=0) Label(remove_ui, text='Remove a Complaint',font="times 15 bold", fg='white', bg='#34383C').place(x=356, y=60) Label(remove_ui, text='FIR ID', fg = '#34383C', bg='white', font='Helvetica 18').place(x=374, y=280) to_remove = Entry(remove_ui, font=(13)) to_remove.place(x=338, y=330) def execute_remove(to_remove): cur.execute("DELETE from complaint where fir_id = ?",[to_remove.get()]) Button(remove_ui, text=' '*20 + 'REMOVE' + ' '*20,bg='#F85661', fg='#34383C', font='Helvetica 15',command=lambda:execute_remove(to_remove)).place(x=270, y=490) con.commit() remove_ui.mainloop() def dashboard(username): dash_ui = Tk() dash_ui.geometry("900x600+300+100") dash_ui.resizable(0,0) bg = PhotoImage(file="images/background.gif") Label(dash_ui, relief="flat",image=bg).grid(row=0, column=0, rowspan=20, columnspan=20) user_bg = PhotoImage(file="images/user.gif") Label(dash_ui, image=user_bg,borderwidth=0).place(x=800 , y=6.5) logout = Button(dash_ui,bg='#16202C', borderwidth=0, command=lambda:dash_ui.destroy()) logout_bg = PhotoImage(file="images/logout.gif") logout.config(image=logout_bg) logout.place(x=850, y=4) Label(dash_ui, text='DASHBOARD',fg='white',bg='#34383C', font='Helvetica 18 bold').place(x=420, y=10) Label(dash_ui, text='WELCOME '+username.upper() , bg='#34383C', fg='#0B8FCC', font = 'Helvetica 10 bold').place(x=45, y=50) add_bg = PhotoImage(file="images/plus.gif") Label(dash_ui, bg='#16202C', borderwidth=0, image=add_bg).place(x=10, y=105) Button(dash_ui, text='ADD', bg='#34383C', fg='#0B8FCC', font='4', borderwidth=0, command=lambda:details_ui('insert')).place(x=80, y=105) minus_bg = PhotoImage(file="images/minus.gif") Label(dash_ui, bg='#16202C', borderwidth=0,image=minus_bg).place(x=8.4,y=155) Button(dash_ui, text='REMOVE', bg='#34383C', fg='#0B8FCC', font='4', borderwidth=0, command=lambda:remove()).place(x=60, y=156) update_bg = PhotoImage(file="images/update.gif") Label(dash_ui, bg='#16202C', borderwidth=0,image=update_bg).place(x=8.4,y=205) Button(dash_ui, text='UPDATE', bg='#34383C', fg='#0B8FCC', font='4', borderwidth=0, command=lambda:details_ui('update')).place(x=60, y=207) view_bg = PhotoImage(file="images/view.gif") Label(dash_ui, bg='#16202C', borderwidth=0,image=view_bg).place(x=9.6,y=255) Button(dash_ui, text='VIEW', bg='#34383C', fg='#0B8FCC', font='4', borderwidth=0, command=lambda:details_ui('view')).place(x=72, y=258) add_user = Button(dash_ui,borderwidth=0,bg='#16202C', command=create_acc) add_user_bg = PhotoImage(file="images/add_user.gif") add_user.config(image=add_user_bg) add_user.place(x=20, y=480) graph = PhotoImage(file="images/splash.gif") Label(dash_ui, image=graph, borderwidth=0).place(x=205,y=76) dash_ui.mainloop()
f946999aa32cb00ef3ffa6c95937deb1841aa7b5
scottkenanderson/advent-of-code-2018
/2018-12-01/second_star.py
991
3.671875
4
def get_file(filename): with open(filename) as f: return [(line[0], line[1:].strip()) for line in f] FUNCTIONS = { '+': lambda num, change: num + change, '-': lambda num, change: num - change } def get_number(num, operation, change): f = FUNCTIONS[operation] if not f: raise Exception('Unknown operation {}'.format(operation)) return f(num, change) numbers = set() def num_is_dupe(num): if num in numbers: return True numbers.add(num) return False def get_directions(directions, i): return directions[i % len(directions)] def calculate(directions): num = 0 i = 0 while not num_is_dupe(num): operation, change = get_directions(directions, i) i += 1 num = get_number(num, operation, int(change)) return num def main(): directions = get_file('second_star_input.csv') final_number = calculate(directions) print(final_number) if __name__ == '__main__': main()
34cbba0cf1f3f1a8982a2e15672c4d01e2774d4d
rishi4758/python-programmes-
/sql.py
430
3.609375
4
import sqlite3 c=sqlite3.connect("thpolkj2.db") s=c.cursor() s.execute("create table emp5(name text,address text,age real)") s.execute("insert into emp5 values('rishav','lpu',20)") s.execute("insert into emp5 values('adarsh','pune',000)") s.execute("select * from emp5") l1=[(4,'we',23),(25,'ty',9),(0,'oi',98)] s.executemany('insert into emp5 values(?,?,?)',l1) print(s.fetchmany(3)) c.commit() c.close()
87c593b7284aa67addbc59e21a02107da29b17af
rishi4758/python-programmes-
/gui prac.py
1,010
3.609375
4
from tkinter import * b=Tk() def fun1(): val=entry.get() val1=entry.get() sum=val+val1 sum.insert() def fun2(): val=entry.get() val1=entry.get() sum=val-val1 sum.insert() def fun3(): val=entry.get() val1=entry.get() sum=val*val1 sum.insert() def fun4(): val=entry.get() val1=entry.get() sum=val/val1 sum.insert() def fun5(): val=entry.get() val1=entry.get() sum=val**val1 sum.insert() l1=Label(b,text="input 1") l2=Label(b,text="input 2") l3=Label(b,text="operation") l4=Label(b,text="output") b1=Button(b,text="+",command=fun1) b2=Button(b,text="-",command=fun2) b3=Button(b,text="*",command=fun3) b4=Button(b,text="/",command=fun4) b5=Button(b,text="**",command=fun5) l1.place(x=200,y=100) l2.place(x=400,y=100) l3.place(x=600,y=100) l4.place(x=800,y=100) x=Entry() y=Entry() z=Entry() u=Entry() x.place(x=200,y=300) y.place(x=400,y=300) z.place(x=600,y=300) u.place(x=800,y=300)
0f71aa582878c764fd36666dc798c00b3fbf02c5
m1plessnit/AAURecommender
/Assignment2/task2_1.py
710
3.96875
4
# Task 2.1: Getting used to Series import pandas as pd import numpy as np def main(): print("Task 2.1: Getting used to Series") # Create Panda's Series-instance based on an array data = np.array(['Toy Story', 'Jumanji', 'Grumpier Old Men']) series = pd.Series(data) print("\n--- Print first element ---") print(series[0]) print("\n--- Print first two elements ---") print(series[:2]) print("\n--- Print last two elements ---") print(series[-2:]) # Create a new series /w defined indexes series = pd.Series(data, index=['a', 'b', 'c']) print("\n--- Print element at index position 'b' ---") print(series['b']) if __name__ == '__main__': main()
6f7b726e2501ac97cfe1c625ae5192c8f96300b5
ayush3298/geekforgeeks_practice
/contiguous integers in array.py
426
3.59375
4
#https://practice.geeksforgeeks.org/problems/check-if-array-contains-contiguous-integers-with-duplicates-allowed/0 # running time = 0.2 for _ in range(int(input())): l = int(input()) lst = sorted(list(map(int, input().split()))) lst = list(set(lst)) c = 0 for i in range(len(lst) - 1): if lst[i] + 1 != lst[i + 1]: c = 1 break print("Yes") if c == 0 else print("No")
25579f8fb61bfe94ad715aa3234c6aa16618a181
iisharankov/Effelsberg
/Protocol_Practice/UDP Suit/UDP_Basic_Server.py
2,679
3.546875
4
import socket # get the according IP address localIP = socket.gethostbyname(socket.gethostname()) # Sets the port and buffer size as constants for later use bufferSize = 1024 # port = 12345 server_address = ('', 0) # Create a datagram Socket UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) # Bind to address and ip UDPServerSocket.bind(server_address) #(localIP, port)) print("UDP server up and is listening for a client to connect") # Listen for incoming arguments firstMsg = True short = 'H' * 736 long = "L" * 1024 while True: # Receives and decodes the messaged given by the client message, address = UDPServerSocket.recvfrom(bufferSize) decodedmessage = message.decode('utf-8') print("New message from client from " "port {}: {}".format(address[1], decodedmessage)) if firstMsg: UDPServerSocket.sendto(str.encode(short), address) firstMsg = False else: UDPServerSocket.sendto(str.encode(long), address) UDPServerSocket.sendto(str.encode(short), address) UDPServerSocket.sendto(str.encode(long), address) UDPServerSocket.sendto(str.encode(short), address) UDPServerSocket.sendto(str.encode(long), address) UDPServerSocket.sendto(str.encode(short), address) UDPServerSocket.sendto(str.encode(long), address) UDPServerSocket.sendto(str.encode(short), address) UDPServerSocket.sendto(str.encode(long), address) UDPServerSocket.sendto(str.encode(short), address) UDPServerSocket.sendto(str.encode(long), address) UDPServerSocket.sendto(str.encode(short), address) # # Sends priliminary reply to the Client # if firstMsg: # firstMsgcontents = str.encode("Hello UDP Client, I am a UDP Server") # UDPServerSocket.sendto(firstMsgcontents, address) # firstMsg = False # sets to false to never send again during connection # # # Checks if message received matches, if so, replies. # elif decodedmessage == "Hello World": # print("Client said 'Hello World!'") # returnmessage = str.encode("Hello back!") # # # Replies with message # UDPServerSocket.sendto(returnmessage, address) # elif len(decodedmessage) <= 8: # print("Client message was short") # returnmessage = str.encode("Is that all you can bother to write?") # # UDPServerSocket.sendto(returnmessage, address) # # # If no message of importance recieved, No Reply sent (Client disposes it) # else: # returnmessage = str.encode("No Reply") # UDPServerSocket.sendto(returnmessage, address) # #
21c759af95e15cc503f9dd74189b237f891f549d
imriven/coding_challenges
/hour_to_seconds.py
239
3.875
4
# https: // edabit.com/challenge/nyeNvKWdDFKRAk4Da def how_many_seconds(hours): minutes = hours * 60 seconds = minutes * 60 return seconds print(how_many_seconds(2)) print(how_many_seconds(10)) print(how_many_seconds(24))
12efdf73aa2b9be29fead08b57895e7f1fcc072a
mikegleen/blackgold
/src/node.py
4,847
3.75
4
""" """ from __future__ import annotations import sys from typing import Union, TYPE_CHECKING if TYPE_CHECKING: # kludge to avoid circular imports at run time from player import Player class Node: """ cost: Number of movement points it costs to enter this node. exhausted: True if a derrick has been built and all the oil has been extracted. goal: Number of adjacent cells with wells. Decremented if a derrick is built """ def set_neighbors(self, board): """ This is called by Graph.__init__. :param board: the board from a Graph instance adjacent contains a list of nodes next to this node. A node can have up to 4 adjacent, reduced if it is on an edge. :return: None. The adjacent list in this node is set. """ def set1neighbor(nrow, ncol): """ :param nrow: neighbor row :param ncol: neighbor column :return: None; the neighbor is added to the list """ neighbor = board[nrow][ncol] self.adjacent.append(neighbor) # If the neighbor has wells, you aren't allowed to stop there, # so it can't be a goal. if self.wells and not self.derrick: if neighbor.wells == 0: neighbor.goal += 1 lastrow = len(board) - 1 lastcol = len(board[0]) - 1 if self.row > 0: set1neighbor(self.row - 1, self.col) if self.col > 0: set1neighbor(self.row, self.col - 1) if self.row < lastrow: set1neighbor(self.row + 1, self.col) if self.col < lastcol: set1neighbor(self.row, self.col + 1) def add_derrick(self): # Make the adjacent not to be goals. # Make this node impassable assert self.derrick is False self.derrick = True for node in self.adjacent: # Assume there are no adjacent cells with wells which is true on # the Giganten board. assert node.goal > 0 node.goal -= 1 def remove_derrick(self): # Make this node passable assert self.derrick is True self.derrick = False self.exhausted = True self.wells = 0 def print_path(self): nextprev = self.previous path = [] while nextprev: # print(f'nextprev: {nextprev}') path.append(nextprev) nextprev = nextprev.previous path.reverse() print(' ', path) def __init__(self, row: int, col: int, derrick=False): self.row: int = row self.col: int = col self.id: str = f'<{row},{col}>' self.terrain: int = 0 # wells: int in 0..3: the number of wells on the square. If non-zero # the square is covered with a tile at the start of the game. Wells # are assigned when the Graph is instantiated. self.wells: int = 0 # oil_reserve: the number on the bottom side of the tile covering a # square with well(s) or the number of plastic markers under a derrick. # If wells == 2 then we cannot peek at the oil reserve in deciding # whether to drill. self.oil_reserve: int = 0 self.exhausted: bool = False self.goal: int = 0 # count of adjacent nodes with unbuilt wells self.goal_reached: bool = False self.derrick: bool = derrick self.truck: Union[Player, None] = None # set when a truck moves here self.adjacent = [] # will be populated by set_neighbors self.cell = None # this node's string from rawboard # Fields set by dijkstra self.distance: int = sys.maxsize self.previous: Union[Node, None] = None # will be set when visited def __repr__(self): e = 'T' if self.exhausted else 'F' g = self.goal t = self.truck d = 'T' if self.derrick else 'F' # s = f'node[{self.row},{self.col}] terrain: {self.terrain}, ' # s += f'wells: {self.wells} ' # s += f'exhausted: {e}, goal: {g}, derrick: {d}, ' # s += f'totcost: {"∞" if self.distance == sys.maxsize else self.distance}, ' # s += f'adjacent: {sorted(self.adjacent)}' s = f'Node {self.id} t: {self.terrain}, ' s += f'w: {self.wells} ' s += f'ex={e}, goal={g}, derrick={d}, truck={t}, ' s += f'previous={self.previous}, ' s += f'dist: {"∞" if self.distance == sys.maxsize else self.distance}, ' sa = sorted(list(self.adjacent)) s += f'adjacent: {[ss.id for ss in sa]}' return s def __str__(self): s = f'{self.id}{"*" if self.goal_reached else ""}' return s # Needed by heapq def __lt__(self, other): return self.distance < other.distance
e13507decfacf5f7dd3570bf941733cf8eee7470
mikegleen/blackgold
/src/isort.py
540
3.671875
4
""" func insertionsort(A []*Node) { for i := 1; i < len(A); i++ { key := A[i] j := i - 1 for j > -1 && A[j].Distance > key.Distance { A[j+1] = A[j] j -= 1 } A[j+1] = key } } """ def insertionsort(a): for i in range(1, len(a)): key = a[i] j = i - 1 while j > -1 and a[j] > key: a[j + 1] = a[j] j -= 1 a[j + 1] = key if __name__ == '__main__': ll = [40, 30, 20, 10] insertionsort(ll) print(ll)
ce4e41633801a3c8925bb13d6f80b2a7fb086890
mhdz9/codewars
/Python/number-star-ladder.py
608
4.0625
4
#Task # Using n as a parameter in the function pattern, where n>0, complete the codes to get the pattern (take the help of examples): #Note: There is no newline in the end (after the pattern ends) #Examples # pattern(3) should return "1\n1*2\n1**3", e.g. the following: # 1 # 1*2 # 1**3 # # pattern(10): should return the following: # 1 # 1*2 # 1**3 # 1***4 # 1****5 # 1*****6 # 1******7 # 1*******8 # 1********9 # 1*********10 def pattern(n): patternList = [] patternList.append('1') for i in range(1, n): patternList.append('1' + ('*' * i) + str(i+1)) return "\n".join(patternList)
6c89918ec65409dfce3652bd902c75a889881234
OvernightFries/Mission-Bit-Projects
/Folder/Functions/lists.py
1,953
3.90625
4
last_semester_gradebook = [("politics", 80), ("latin", 96), ("dance", 97), ("architecture", 65)] subjects = [("physics"),("calculus"),("poetry"),("history")] grades = [(98), (97), (85), (88)] [print(values) for values in zip(subjects, grades)] subjects.append(("Computer Science")) grades.append((100)) gradebook = list(zip(subjects, grades)) [print(values) for values in zip(subjects, grades)] gradebook.append(("visual arts", 93)) print(list(zip(gradebook))) full_gradebook = gradebook + last_semester_gradebook print(full_gradebook) print(gradebook) names = ["jenny", "alexus"] name1 = names[0] print(names) print(names[0]) # # 0, 1, 2, 3, 4 ... # names_and_heights = [["jenny", 67, 100], ["alexus", 70, 100]] # print("name: " + names_and_heights[1][0] + "height: " + str(names_and_heights[1][1]) + "weight: " + str(names_and_heights[1][2])) #["jenny", 67] # print(names_and_heights[0][0] + " is " + str(names_and_heights[0][1]) + " inches tall") # names = ["jenny", "alexus", "sam"] # #zip() does not include extra items from the longer list if list lengths are not the same # heights = [67, 70] # names_and_heights = list(zip(names, heights)) # #names_and_heights == [('jenny', 67), ('alexus', 70)] # # tuples: (x, y) and cannot be changed # # list: [x, y] # print(list(names_and_heights)) # print(names_and_heights[0][0]) names = ["jenny", "alexus"] # print("Before adding \"sam\": " + str(names)) # names.append("sam") # print("After adding \"sam\": " + str(names)) # print("hello world") # "hello world" # names.insert(1, "alex") #names[1] == "alex" -> True names[1] = "alex" print(names) #["jenny", "alex"] #range(x) #start: 0 #stop: x-1 #step: 1 # new_range = list(range(10)) # print(new_range) # #range(x, y, z) # #start: x # #stop: y-1 # #step: z # even_range = list(range(0, 21, 2)) # print(even_range) # #range(x, y) # #start: x # #stop: y-1 # #step: 1 # zero_to_five = list(range(0, 6)) # print(zero_to_five)
e1877849ae9583f8ff64ae02aae1b613f308a14d
TFStudents/PythonLearn
/com/tfstudents/GUI/test2.py
702
3.5625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- from Tkinter import * # 导入 Tkinter 库 root = Tk() # 创建窗口对象的背景色 # 创建两个列表 li = ['C','python','php','html','SQL','java'] movie = ['CSS','jQuery','Bootstrap'] listb = Listbox(root) # 创建两个列表组件 listb2 = Listbox(root) for item in li: # 第一个小部件插入数据 listb.insert(0,item) for item in movie: # 第二个小部件插入数据 listb2.insert(0,item) listb.pack() # 将小部件放置到主窗口中 listb2.pack() root.mainloop() # 进入消息循环
de44aea78510612da8472d8d74ae4d2de4dca04f
hyuji946/project_euler
/untitled.py
97
3.71875
4
def fib(x): if x==1: return 1 if x==2: return 2 return fib(x-1)+fib(x-2) print fib(8)
2ea41c44a4335e6f9329bce0ea7efe410ba309fd
hyuji946/project_euler
/p001.py
510
3.75
4
# -*- coding: utf-8 -*- """ Project Euler Problem 1 10未満の自然数のうち, 3 もしくは 5 の倍数になっているものは 3, 5, 6, 9 の4つがあり, これらの合計は 23 になる. 同じようにして, 1000 未満の 3 か 5 の倍数になっている数字の合計を求めよ. """ def f35(x): if x%3==0 or x%5==0: return True else: return False ans=0 for i in range(1,1000): if f35(i): ans+=i print i print "ans=", ans
1c4f86c98c0e7d6aa7b32652eaba3b5c8500ea89
hyuji946/project_euler
/01 解答例/p038.py
1,197
3.65625
4
# -*- coding: utf-8 -*- """ =================================== Project Euler Problem 38 =================================== 192 に 1, 2, 3 を掛けてみよう. 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 積を連結することで1から9の パンデジタル数 192384576 が得られる. 192384576 を 192 と (1,2,3) の連結積と呼ぶ. 同じようにして, 9 を 1,2,3,4,5 と掛け連結することで パンデジタル数 918273645 が得られる. これは 9 と (1,2,3,4,5) との連結積である. 整数と (1,2,...,n) (n > 1) との連結積として得られる 9桁のパンデジタル数の中で最大のものはいくつか? =================================== """ def checkpan(a,b): c=a*array(b) d=map(str,c) e="".join(d) f=sorted(e) if f==['1', '2', '3', '4', '5', '6', '7', '8', '9']: return True,e return False,0 #print checkpan(192,[1,2,3]) #print checkpan(9,[1,2,3,4,5]) a="123456789" ans=0 for n in range(2,10): b=map(int,a[:n]) for m in range(1,10000): c,num=checkpan(m,b) if c: if int(num)>ans: ans=int(num) print n,m,num,ans print "max = ",ans
ecf576b0007158929c58eed930917367982a2419
cprimera/projects
/School Projects/Obstacle Avoider/Queue.py
587
3.75
4
#################################################################### # Created by Christopher Primerano on 05-03-2012. # # Copyright (c) 2012 Christopher Primerano. All rights reserved. # # # #################################################################### class Queue: def __init__(self): self.queue = [] def enqueue(self, obj): self.queue.append(obj) def front(self): return self.queue[0] def is_empty(self): return True if len(self.queue) == 0 else False def dequeue(self): return self.queue.pop(0)
313bf24b6a88a2458d94d3ecad0abf2e9c7ba83f
av1kav/jupyter-notebooks
/Data Analytics/dpad/chisquare.py
937
3.765625
4
#chi square test. def chiSquareTest(nrows,ncols,matrix): """ chiSquareTest(nrows,ncols,matrix): Returns the Chi-Square value (float) for a given matrix[nrows][ncols] of data. """ expectedMatrix = [[0.0 for j in range(ncols)] for i in range(nrows)] rowSum = [0 for i in range(nrows)] colSum = [0 for j in range(ncols)] currentRow = 0 currentCol = 0 for i in range(nrows): for j in range(ncols): rowSum[currentRow] = rowSum[currentRow] + matrix[i][j] if(j == currentCol): colSum[currentCol] = colSum[currentCol] + matrix[i][j] currentCol = currentCol + 1 currentRow = currentRow + 1 currentCol = 0 totalSum = sum(rowSum) chiSquareValue = 0.0 for i in range(nrows): for j in range(ncols): expectedMatrix[i][j] = float((rowSum[i]*colSum[j])/totalSum) chiSquareValue += ((matrix[i][j] - expectedMatrix[i][j])**2/expectedMatrix[i][j]) return chiSquareValue
817eb6d9822b5a8f701f71bb98e39dd07d9f50f0
ElianAbrao/Advanced-virtual-assistant-with-voice-control
/main.py
993
3.65625
4
#Importing Libraries import speech_recognition as sr import os #Main Function def voice_recorder(): #enable user microphone recorder = sr.Recognizer() #using microphone recordings with sr.Microphone() as source: recorder.adjust_for_ambient_noise(source) audio = recorder.listen(source) #doing some tests, to open programs just by speaking try: speech = recorder.recognize_google(audio, language='pt-BR') if ('Abra' in speech and ('ópera' in speech) or 'Google' in speech): os.system("start opera.exe") if 'Abra' in speech and 'calculadora' in speech: os.system('start calc.exe') #returns the pronounced sentence print('Você disse: '+ speech) except sr.UnknownValueError: #Indicates that the speech recognizer did not understand what was said print("Desculpe eu não entendi oque você disse!") return speech voice_recorder()
ae56a301dde6a0f4e3063170dcab02000c70b6f8
AdamHess/review-data-structures-in-python
/binarytree.py
1,221
3.75
4
class BinaryTreeNode: def __init__(self, value = None): self.__right = None self.__left = None self.__value = value def getLeft(self): return self.__left def setLeft(self, leftNode): self.__left = leftNode def getRight(self): return self.__right def setRight(self, rightNode): self.__right = rightNode def getValue(self): return self.__value def setValue(self, val) : self.__value = val def insertNode(aNode, aNewValue): if aNode.getValue() > aNewValue: if aNode.getLeft() == None: abst_node = BinaryTreeNode(aNewValue) aNode.setLeft(abst_node) else: insertNode(aNode.getLeft(), aNewValue) else : if aNode.getRight() == None: abst_node = BinaryTreeNode(aNewValue) aNode.setRight(abst_node) else: insertNode(aNode.getRight(), aNewValue) def inOrderTraversal(aNode): if aNode == None: return inOrderTraversal(aNode.getLeft()) print("in-order tree traversal: %s" % aNode.getValue()) inOrderTraversal(aNode.getRight()) def testingBinaryTree() : binarySearchTree = BinaryTreeNode(value = 70) elementsForTree = [10,40,3,100,51,103,44,323,500,1, 225] for val in elementsForTree: insertNode(binarySearchTree, val) inOrderTraversal(binarySearchTree)
d2c38d3b797e807201aad930bdeb22a2206a360a
PKR-808/30-Days-of-Code-in-Python-HackerRank-Challenge
/Day_9.py
508
3.90625
4
#!/bin/python3 #The additional codes of file write were already there in the HackerRank Python 3 Console import math import os import random import re import sys # Complete the factorial function below. def factorial(num): if num == 1: return 1 else: fact = num * factorial(num-1) return fact if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) result = factorial(n) fptr.write(str(result) + '\n') fptr.close()
b3f52b64596a5d29add18105564e5594693d3254
xiyanjun/LeetCode
/476NumberComplement.py
365
3.6875
4
class Solution: def findComplement(self, num): """ :type num: int :rtype: int """ i=1 while i<=num: num^=i i=i<<1 return num def main(): num=5 solution=Solution() result=solution.findComplement(num) print(result) if __name__=='__main__': main()
7c27d06882aab4e2fece0db82177a8b543cffc16
xiyanjun/LeetCode
/28ImplementstrStr().py
463
3.65625
4
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ for i in range(len(haystack)-len(needle)+1): if haystack[i:len(needle)+i]==needle: return i return -1 if __name__=='__main__': solution=Solution() haystack='hello' needle='ll' result=solution.strStr(haystack,needle) print(result)
eb0d5b8a30fdb14d5440b85d6aa5dbe60772b6f1
xiyanjun/LeetCode
/70ClimbingStairs.py
366
3.625
4
class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ F=list(range(n+1)) F[0]=1 F[1]=1 for i in range(2,n+1): F[i]=F[i-1]+F[i-2] return F[n] if __name__=='__main__': solution=Solution() result=solution.climbStairs(2) print(result)
9f4519c7c6314831ae221e86eb3f096e3fffa8eb
xiyanjun/LeetCode
/5LongestPalindromicSubstring.py
507
3.6875
4
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ for i in range(len(s)-1,-1,-1): j=0 while i+j<=len(s)-1: if s[j:i+j+1]==s[j:i+j+1][::-1]: return s[j:i+j+1] else: j+=1 def main(): s='babab' solution=Solution() result=solution.longestPalindrome(s) print(result) if __name__=='__main__': main()
a484c1fcb0fa8e8fa004feef5b22e8aaca455df0
xiyanjun/LeetCode
/216CombinationSum3.py
667
3.703125
4
class Solution(object): def combinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ ans=[] def search(s,count,sums,nums): if count==k and sums!=n: return if count==k and sums==n: ans.append(nums) return for i in range(s+1,10): search(i,count+1,sums+i,nums+[i]) search(0,0,0,[]) return ans def main(): k=3 n=9 solution=Solution() result=solution.combinationSum3(k,n) print(result) if __name__=='__main__': main()
e043503d5bd9f2fe849f73d606bb5c2880fcb0fb
arpancodes/learning-python-mit-6.00.1x
/week-2/gcd-recur.py
540
3.9375
4
''' A clever mathematical trick (due to Euclid) makes it easy to find greatest common divisors. Suppose that a and b are two positive integers: If b = 0, then the answer is a Otherwise, gcd(a, b) is the same as gcd(b, a % b) ''' def gcdRecur(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if b == 0: return a else: return gcdRecur(b, a % b) print(gcdRecur(2, 12)) print(gcdRecur(6, 12)) print(gcdRecur(3, 12)) print(gcdRecur(17, 12))
c5840f40495b9d156c201043fa3ffa80477d4618
k-vader/CST-205-lab13
/lab13.py
3,952
3.90625
4
# Ken Vader # Ngoan Nguyen # Chris Pina # Ken Vader # Lab 13, Part 1 # 12/8/2015 import time import random userInputCount = 0 story = """ As more than 100 stout and bearded men, all dressed in various shades of red and green, board a train to go rattling through the Michigan countryside for no apparent reason, I turn to Tom Valent and ask, "Why?" It's a loaded question. One that has been percolating for days. Why, in mid-October, would Valent load his entire Santa school onto charter buses and drive them 45 minutes to Huckleberry Railroad, a tourist attraction that is still very obviously in the midst of celebrating Halloween? Why, the day before, had his student Santas spent hours learning about the legend of Santa Claus -- from his birth in Patara to the names of all his elves? Why did Valent have them practice reindeer-handling and sleigh-driving and toy-making? I mean, come on. Doesn't Santa Claus use Amazon like the rest of us? "Do you know the movie 'The Polar Express'?" Tom asks, answering my question with a question. """ userArray = [] # Input function # def getInput(inputCount): wordsRemaining = inputCount while(wordsRemaining > 0): inputString = requestString("Enter a word (%d left), or enter 'Exit'" % wordsRemaining) if inputString == None: reset() return false elif inputString.lower() == "exit": reset() return false elif len(inputString) > 0: wordsRemaining -= 1 userArray.append(inputString) return true # This method accepts text and randomly removes content, leaving a "[index]" in its place # @param text - the input text # @param minLength - Ignores words that are less than the specified length (good for ignoring a, is, or, etc...) # @param percentCoverage - Frequency of replacement, IE: .1 would be 10% of the sentence is omitted # Example, input "This is a very nice sentence" # return, "This is a [0] nice [1]" def blankOutText(text, minLength, percentCoverage): totalWords = text.split() # determines how many times we should iterate, depending on size of string timesToIterate = max(1, int(percentCoverage * len(totalWords))) global userInputCount didFindWord = false for i in range(0, timesToIterate): randomIndex = random.randint(0, len(totalWords)-1) word = totalWords[randomIndex] # if the word meets the min length, and does not start with [, we replace if len(word) >= minLength and word[0] != "[": totalWords[randomIndex] = "[" + str(randomIndex) + "]" userInputCount += 1 didFindWord = true # if we couldn't find a word, error out if not didFindWord: printNow("Sample too short, try a longer sentence!") return "exit:" returnString = " " .join(totalWords) return returnString # This method accepts a string and replaces the marked words with items from an array def replaceTextWithArrayOfWords(text, array): splitWords = text.split() currentIndex = 0 # keeps track of the index of our words wordCount = 0 # keeps track of the ocurrence of the found word for word in splitWords: if word[0:1] == "[": splitWords[currentIndex] = array[wordCount].upper() wordCount += 1 currentIndex += 1 return " " .join(splitWords) def reset(): global userInputCount userInputCount = 0 global userArray userArray = [] def madLib(): minLength = 3 # Use this to filter out short words percentCoverage = .08 # percent replacement frequency, 1 is the most text = blankOutText(story, minLength, percentCoverage) if text == "exit:": reset() else: printNow("\n------\nMad Lib Before:\n %s" % text) inputSuccess = getInput(userInputCount) # now let's replace our text with the user's words if inputSuccess: final = replaceTextWithArrayOfWords(text, userArray) printNow("------\nMad Lib After:\n %s" % final) reset() # resets the global variables
87324442d3dabfdcae8ef4bbea84f21f1586d663
drdiek/Hippocampome
/Python/dir_swc_labels/lib/menu/select_processing.py
1,109
4.125
4
def select_processing_function(): reply = '' # main loop to display menu choices and accept input # terminates when user chooses to exit while (not reply): try: print("\033c"); # clear screen ## display menu ## print 'Please select your processing function of interest from the selections below:\n' print ' 1) Conversion of .swc file(s)' print ' 2) Plotting of an .swc file' print ' 3) Creation of a morphology matrix file' print ' !) Exit' reply = raw_input('\nYour selection: ') ## process input ## if reply == '!': return('!') else: num = int(reply) if ((num > 0) & (num <= 3)): return(num) else: reply = '' except ValueError: print 'Oops! That was not a valid number. Please try again ...'
c3c685f3afdbb97de4e31153df4804554bbeaf05
ankurshaswat/AlphaGo-Zero
/submission/alphago_zero_sim_3/utils_3/go_board.py
7,706
3.5625
4
""" Wrapper over Board class of pachiy_py """ import numpy as np import pachi_py BLACK = np.array([1, 0, 0]) WHITE = np.array([0, 1, 0]) EMPTY = np.array([0, 0, 1]) MAX_MOVES = 250 class GoBoard(): """ Wrapper over board class to modify representations and return new copies. """ def __init__(self, board_size, board=None, player=-1, done=False, last_passed=False, history=None, move_num=0): self.board_size = board_size self.pass_action = board_size**2 self.resign_action = board_size**2 + 1 assert player in [-1, 1] self.curr_player = player self.done = done self.last_passed = last_passed self.move_num = move_num if history is None: self.history = [None]*7 else: self.history = history if board is None: self.board = pachi_py.CreateBoard(board_size) else: self.board = board def set_move_num(self,move_num): self.move_num = move_num def coord_to_action(self, action_coord): """ Converts Pachi coordinates to actions """ if action_coord == pachi_py.PASS_COORD: return self.pass_action if action_coord == pachi_py.RESIGN_COORD: return self.resign_action i, j = self.board.coord_to_ij(action_coord) return i*self.board_size + j def action_to_coord(self, action): """ Converts actions to Pachi coordinates """ if action == self.pass_action: return pachi_py.PASS_COORD if action == self.resign_action: return pachi_py.RESIGN_COORD return self.board.ij_to_coord(action // self.board_size, action % self.board_size) def str_to_action(self, string): """ Convert D6 type coordinates to actions """ return self.coord_to_action(self.board.str_to_coord(string.encode())) def execute_move(self, action, player): """ Execute a move on pachi py board and return the obtained board(assuming copy has been created) """ # print(player,self.curr_player, flush=True) assert not self.done assert player == self.curr_player assert 0 <= action <= self.board_size**2 + 2 done = False last_passed = False curr_player = pachi_py.BLACK if player == -1 else pachi_py.WHITE if action == self.pass_action: last_passed = True if self.last_passed: done = True # print('2 Passes Done', flush=True) new_board = self.board.play(pachi_py.PASS_COORD, curr_player) elif action == self.resign_action: done = True # print('Someone Resigned', flush=True) new_board = self.board.play(pachi_py.RESIGN_COORD, curr_player) else: a_x, a_y = action // self.board_size, action % self.board_size new_board = self.board.play( self.board.ij_to_coord(a_x, a_y), curr_player) if self.move_num == -1: move_num = -1 elif self.move_num == MAX_MOVES: done = True move_num = self.move_num+1 else: move_num = self.move_num+1 new_history = [self.board] + self.history[:6] # print(len(new_history), flush=True) return GoBoard(self.board_size, new_board, -1*player, done, last_passed, new_history, move_num) def get_legal_moves_old(self, player): """ Iterate and find out legal position moves """ curr_player = pachi_py.BLACK if player == -1 else pachi_py.WHITE board_arr = self.board.encode() init_legal_coords = self.board.get_legal_coords(curr_player) legal_moves = [] # print(init_legal_coords) for coord in init_legal_coords: # print(coord) pos_x, pos_y = self.board.coord_to_ij(coord) if coord >= 0 and self.is_legal_action_old(board_arr, (pos_x, pos_y), curr_player): legal_moves.append(self.board_size*pos_x + pos_y) return legal_moves def get_legal_moves(self, player): """ Iterate and find out legal position moves """ # return self.get_legal_moves_old(player) curr_player = pachi_py.BLACK if player == -1 else pachi_py.WHITE init_legal_coords = self.board.get_legal_coords(curr_player) legal_moves = [] for coord in init_legal_coords: if coord >= 0 and self.is_legal_action(coord, curr_player): pos_x, pos_y = self.board.coord_to_ij(coord) legal_moves.append(self.board_size*pos_x + pos_y) return legal_moves def is_legal_action_old(self, board_arr, action, player): """ Basic checks if the given action on a board is legal """ (pos_x, pos_y) = action if not (0 <= pos_x < self.board_size and 0 <= pos_y < self.board_size): return False if not np.all(board_arr[:, pos_x, pos_y] == EMPTY): return False # curr_player = BLACK if player == -1 else WHITE opp_player = BLACK if player == 1 else WHITE if pos_x > 0 and not np.all(board_arr[:, pos_x-1, pos_y] == opp_player): return True if pos_x != self.board_size-1 and not np.all(board_arr[:, pos_x+1, pos_y] == opp_player): return True if pos_y > 0 and not np.all(board_arr[:, pos_x, pos_y-1] == opp_player): return True if pos_y != self.board_size-1 and not np.all(board_arr[:, pos_x, pos_y+1] == opp_player): return True return False def is_legal_action(self, action, player): """ Simple is legal action check. """ try: # print(action, player) _ = self.board.play(action, player) except pachi_py.IllegalMove: return False return True def print_board(self): """ Show complete game state. """ color_to_play = 'Black' if self.curr_player == -1 else 'White' print('To play: {}\n{}'.format( color_to_play, self.board.__repr__().decode()), flush=True) def is_terminal(self): """ Check if state is terminal (double pass or resign) """ board_terminal = self.board.is_terminal self_check = self.done return board_terminal or self_check def score(self, komi): """ Score the board configuration """ return self.board.official_score + komi def get_numpy_form(self, history, player): """ Convert into ML input form """ history_reps = [] stones = self.board.encode() if player is None or player == -1: history_reps.append(stones[:2, :, :]) else: history_reps.append(stones[1:2, :, :]) history_reps.append(stones[:1, :, :]) if history: for board in self.history: if board is None: stones = np.zeros((2, self.board_size, self.board_size)) else: stones = board.encode() if player is None or player == -1: history_reps.append(stones[:2, :, :]) else: history_reps.append(stones[1:2, :, :]) history_reps.append(stones[:1, :, :]) combined = np.concatenate(history_reps, axis=0) combined_in_order = np.transpose(combined, (1, 2, 0)) return combined_in_order
d70d2fe8ee72724461584894e11239525c42352e
TheSentinel36/DFS-Scraper
/lib/make_db_stats.py
10,794
3.8125
4
""" Add something to check that player ID is in ID list. """ class Player(object): def __init__(self, date, game_record): """ See specific sport subclasses for game_record format. """ self.date = date self.name = game_record[1] self.fd_position = None self.fd_pts = None self.fd_salary = None self.dk_position = None self.dk_pts = None self.dk_salary = None self.team = game_record[4].upper() self.opp = self.format_opp(game_record[5]) self.id = game_record[-1] site = game_record[-2] self.update_points(game_record[2], site) self.update_position(game_record[0], site) self.update_salary(game_record[3], site) def format_opp(self, opp_name): """ Formats the opponent name and sets location of game. :param opp_name: 'v kan' or '@ kan' :return: upper cased opp name and sets home/away game """ loc, name = opp_name.split() # Get rid of double-header indicator if it exists name = name.split('(')[0] if loc == 'v' or loc == 'v.': self.home_game = 'Y' elif loc == '@': self.home_game = 'N' return name.upper() def format_position(self, position): """Defer to subclass""" return position def format_stats(self, stat_dict): """ Attempts to format the stats for a player. No football stats are given so don't use for football. Method: Separate the numerical value from the stat name and update the dictionary. :stat_dict: A dictionary of stat_name keys with 0 for value. :return: Dictionary with updated stats. """ try: player_stats = self.stats.split() except: print 'no player stats available.' return stat_dict for n, stat in enumerate(player_stats): numbers = '0123456789-' idx = 0 stat_val = '' while stat[idx] in numbers: stat_val += stat[idx] idx += 1 if stat_val == '': stat_val = '1' stat_name = stat.strip(stat_val) # Try to convert to int try: stat_val = int(stat_val) except: pass stat_dict[stat_name] = stat_val return stat_dict def gen_db_stats(self): """ Generates a list of stats to be used in adding to the DB. :return: """ stat_order = self.get_stat_order() stat_list = [] dict_of_attrs = self.__dict__ dict_of_attrs.update(self.stats) for name in stat_order: stat_list.append(dict_of_attrs[name]) return stat_list def get_stat_order(self): """Used in subclasses""" pass def update_points(self, points, site): """Updates the points for given site""" if site == 'dk': self.dk_pts = float(points) elif site == 'fd': self.fd_pts = float(points) def update_position(self, position, site): """Updates the position of each site""" if site == 'dk': self.dk_position = self.format_position(position) elif site == 'fd': self.fd_position = self.format_position(position) def update_salary(self, dollars, site): """ Updates the salaries for the given site. :param dollars: string like '$5,700' :return: int like 5700 """ if dollars == 'N/A': salary = 0 else: salary = int(dollars.strip('$').replace(',', '')) if site == 'dk': self.dk_salary = salary elif site == 'fd': self.fd_salary = salary class Baseball(Player): def __init__(self, date, game_record): """ game_record format: [position, name, points, salary, team, opponent, game score, player game stats, site, player id] """ self.score = game_record[6] self.stats = game_record[7] Player.__init__(self, date, game_record) self.format_name() self.format_team() self.format_stats() def format_name(self): """ Sets starting info and removes it from name string. :return: """ if '^' in self.name: self.start = 'Y' self.name, self.bat_order = self.name.split('^') else: self.start = 'N' self.bat_order = '0' def format_position(self, position): """ Takes the numbered position format used by RG for Draft Kings stats :return: """ # Need a way to differentiate pitchers from hitters. if position == 'P': self.pitcher = True else: self.pitcher = False # Pick up the players with no listed position. if position == '': if 'IP' in self.stats: self.pitcher = True new_position = 'P' else: new_position = 'N/A' return new_position # Only need to format numeric positions if not position.isdigit(): return position position_convert = {'2': 'C', '3': '1B', '4': '2B', '5': '3B', '6': 'SS', '7': 'OF', '8': 'OF', '9': 'OF'} pos_string = '' for pos in position: pos_string += ' {},'.format(position_convert[pos]) return pos_string.strip(',').strip() def format_stats(self): """ Loops through all the stats and creates a dict to easily load into DB. """ batter_stats = {stat:0 for stat in ['H', 'AB', 'R', 'RBI', 'HR', '2B', '3B', 'BB', 'HBP', 'SO', 'SF', 'S', 'SB', 'CS', 'E']} pitcher_stats = {stat:0 for stat in ['IP', 'HB', 'K', 'BB', 'H', 'R', 'ER', 'E', 'Win', 'CG', 'Hold', 'Save', 'Loss']} stats = self.stats.split() stats_to_add = {} if self.pitcher: player_dict = pitcher_stats num_innings = stats.pop(0).strip('IP') stats_to_add['IP'] = float(num_innings) else: player_dict = batter_stats # Get hits and at bats for batters before parent method try: hits, atbats = stats.pop(0).split('/') except: hits, atbats = 0, 0 stats_to_add['H'] = int(hits) stats_to_add['AB'] = int(atbats) # Pull out 2B and 3B stats before because the parent stat method doesn't pick them up properly for hit_type in ['2B', '3B']: for s in stats: if s[-2:] == hit_type: if '-' in s: stat_val = s.split('-')[0] else: stat_val = 1 stats_to_add[hit_type] = stat_val stats.remove(s) self.stats = ' '.join(stats) self.stats = Player.format_stats(self, player_dict) self.stats.update(stats_to_add) def format_team(self): """ Reformats the team name to be more consistent with BBM and FG team names. """ team_convert = {'TAM': 'TB', 'KAN': 'KC', 'SFO': 'SF', 'SDG': 'SD'} if self.team in team_convert: self.team = team_convert[self.team] if self.opp in team_convert: self.opp = team_convert[self.opp] def get_stat_order(self): """ Gets the order of stats to format them for adding to database. :return: """ if self.pitcher: order = ['id', 'name', 'date', 'dk_position', 'dk_pts', 'dk_salary', 'fd_position', 'fd_pts', 'fd_salary', 'team', 'opp', 'score', 'home_game', 'bat_order', 'start', 'IP', 'K', 'BB', 'R', 'ER', 'H', 'HB', 'E', 'Win', 'Loss', 'Save', 'Hold', 'CG'] else: order = ['id', 'name', 'date', 'dk_position', 'dk_pts', 'dk_salary', 'fd_position', 'fd_pts', 'fd_salary', 'team', 'opp', 'score', 'home_game', 'bat_order', 'start', 'H', 'AB', '2B', '3B', 'HR', 'BB', 'SO', 'RBI', 'SB', 'CS', 'S', 'SF', 'HBP', 'E'] return order class Basketball(Player): def __init__(self, date, game_record): Player.__init__(self, date, game_record) self.mins = int(game_record[6]) self.stats = game_record[7] self.format_name() self.format_stats() def format_name(self): """ Sets starting info and removes it from name string. :return: """ if '^' in self.name: self.start = 'Y' self.name = self.name.strip('^') else: self.start = 'N' lname, fname = [x.strip() for x in self.name.split(',')] self.name = '{} {}'.format(fname, lname) def format_stats(self): """ Formats the stats of basketball players. Calls the parent method then formats a couple that are specific to basketball. :return: """ stat_dict = {stat: 0 for stat in ['pt', 'rb', 'as', 'st', 'bl', 'to', 'trey', 'fg', 'ft']} self.stats = Player.format_stats(self, stat_dict) #Need to format stats like ft and fg that are formatted like: att-made #Using two separate fields. for key in ['ft', 'fg']: try: att, made = self.stats[key].split('-') except: att, made = 0, 0 pass # Make new keys att_key = '{}_att'.format(key) made_key = '{}_made'.format(key) self.stats[att_key], self.stats[made_key] = int(att), int(made) # Delete old keys & stats del self.stats[key] def get_stat_order(self): return ['id', 'name', 'date', 'dk_position', 'dk_pts', 'dk_salary', 'fd_position', 'fd_pts', 'fd_salary', 'team', 'opp', 'home_game', 'mins', 'pt', 'rb', 'as', 'st', 'bl', 'to', 'trey', 'fg_made', 'fg_att', 'ft_made', 'ft_att'] class Football(Player): def __init__(self, date, game_record): self.stats = {} Player.__init__(self, date, game_record) def get_stat_order(self): return ['id', 'name', 'date', 'dk_position', 'dk_pts', 'dk_salary', 'fd_position', 'fd_pts', 'fd_salary', 'team', 'opp', 'home_game']
cd9d4078611c026fb4d55e116d5c0fd4d93ceaea
yuvika22/hackerrank-python
/basic/Lists.py
735
3.984375
4
# Solution https://www.hackerrank.com/challenges/python-lists/problem if __name__ == '__main__': n = int(input()) l = [] for _ in range(n): function, *param_input = input().split() param_list = list(map(int, param_input)) # print(function, param_list) if function == "insert": l.insert(param_list[0], param_list[1]) elif function == "print": print(l) elif function == "remove": l.remove(param_list[0]) elif function == "append": l.append(param_list[0]) elif function == "sort": l.sort() elif function == "reverse": l.reverse() elif function == "pop": l.pop()
f77924a09f7f0fd2a7eafd266a54a653dd79d13b
dmikos/PythonExercises
/geekbrains.ru/lesson_7759-Интенсив по Python/gibbet.py
2,401
4.125
4
#!/usr/bin/python3 import random import turtle import sys # https://geekbrains.ru/lessons/7759 # 1:25:16 def gotoxy(x, y): #перемещаем курсор turtle.penup() turtle.goto(x, y) turtle.pendown() def draw_line(from_x, from_y, to_x, to_y): # gotoxy(from_x, from_y) turtle.goto(to_x, to_y) def draw_circle(x, y, r): gotoxy(x, y) turtle.circle(r) def draw_gibbet_element(step): if step == 1: draw_line(-160, -100, -160, 80) elif step == 2: draw_line(-160, 80, -80, 80) elif step == 3: draw_line(-160, 40, -120, 80) elif step == 4: draw_line(-100, 80, -100, 40) elif step == 5: draw_circle(-100, 0, 20) elif step == 6: draw_line(-100, 0, -100, -50) elif step == 7: draw_line(-100, -10, -120, -20) elif step == 8: draw_line(-100, -10, -80, -20) elif step == 9: draw_line(-100, -50, -120, -60) elif step == 10: draw_line(-100, -50, -80, -60) x = random.randint(1, 100) print(x) turtle.write("Загаданное число от 1 до 100. \n Попробуй угадать!", font=("Arial", 18, "normal")) ans = turtle.textinput("Хотите играть?", "y/n") if ans == 'n': sys.exit(13) ans = turtle.textinput("Давать подсказки?", "y/n") hints = ans == 'y' try_count = 0 turtle.speed(0) while True: number = turtle.numinput("Попробуй угадать", "Число", 0, 0, 100) if hints: gotoxy(230,200 - try_count*15) turtle.color('black') if number < x: turtle.write(str(number) + " - Загаданное число больше") elif number > x: turtle.write(str(number) + " - Загаданное число меньше") if number == x: gotoxy(-150, -200) turtle.color('green') turtle.write("Вы угадали", font=("Arial", 24, "normal")) break else: gotoxy(-150, 200) turtle.color('red') turtle.write("Неверно", font=("Arial", 20, "normal")) try_count += 1 draw_gibbet_element(try_count) if try_count == 10: gotoxy(-150, 150) turtle.color('brown') turtle.write("Вы проиграли!", font=("Arial", 25, "normal")) break input('Нажмите Enter')
f294921e695cf0ff1c9bed573ffb86f3dd2fc56c
Ellian-aragao/URI
/py/area.py
395
3.6875
4
vet = [float(x) for x in input().split()] total = (vet[0] * vet[2])/2 print('TRIANGULO: {:.3f}'.format(total)) total = vet[2] * vet[2] * 3.14159 print('CIRCULO: {:.3f}'.format(total)) total = ((vet[0] + vet[1])*vet[2])/2 print('TRAPEZIO: {:.3f}'.format(total)) total = vet[1] * vet[1] print('QUADRADO: {:.3f}'.format(total)) total = vet[0] * vet[1] print('RETANGULO: {:.3f}'.format(total))
159de7145a60a9da5636b257b83af059efd80479
Riztydogcio/Python-for-Absolute-Beginners
/20181015_if_else_conditional_logic.py
478
3.921875
4
#age = input("enter age: ") #if int(age) >= 12: #print("Age in 10 years is", int(age) + 10) #else: #print("It's good to be", age) def check_guess(letter, guess): guess = input("guess the letter: ").lower() if guess.isdigit() == True: print ("Invalid") elif guess == letter: print("Correct") elif guess > letter: print("Guess is high") else: print("Guess is low") #check_guess("r", "r") '''calls the function'''
f46893c5784cc16ad9c4bcaf19d47a126e1f02a5
Granbark/supreme-system
/binary_tree.py
1,080
4.125
4
class Node(): def __init__(self, value): self.value = value self.left = None self.right = None class BST(): def __init__(self): self.root = None def addNode(self, value): return Node(value) #returns a Node, see class def addBST(self, node, number): #node = current node, number is what you wish to add if node is None: return self.addNode(number) #go left elif number < node.value: node.left = self.addBST(node.left, number) #go right elif number > node.value: node.right = self.addBST(node.right, number) return node def printBST(self, node): #Print values from root #In order if node.left is not None: self.printBST(node.left) print(node.value) if node.right is not None: self.printBST(node.right) return if __name__ == "__main__": bst = BST() root = Node(50) bst.root = root bst.addBST(bst.root, 15) bst.addBST(bst.root, 99) bst.addBST(bst.root, 25) bst.addBST(bst.root, 56) bst.addBST(bst.root, 78) bst.printBST(bst.root)
7c02ca47e32dcdb136b27e68fd1d2912f42f6852
traviskemper/streamm
/src/angles.py
10,748
3.53125
4
""" Class data structures for 2, 3, 4 point groupings of Particle objects """ import copy, sys class Angle: """ Data structure for describing any 3-point associatiaon of Particle-s """ def __init__(self, pgid1=0, pgid2=0, pgid3=0, theta0=0.0, type="blank"): """ Constructor for a general angle. Checks for types in arguments and throws a TypeError when appropriate Args: pgid1 (int) GlobalID of Particle object in angle pgid2 (int) GlobalID of Particle object in angle pgid3 (int) GlobalID of Particle object in angle theta0 (float) Equilibrium angle (in radians) type (str) Charge value in units of [e] """ if isinstance(pgid1, int): self.pgid1 = pgid1 else: print "1st arg should be int" raise TypeError if isinstance(pgid2, int): self.pgid2 = pgid2 else: print "2nd arg should be int type" raise TypeError if isinstance(pgid3, int): self.pgid3 = pgid3 else: print "3rd arg should be int type" raise TypeError if isinstance(theta0, float): self.theta0 = theta0 else: print "4th arg should be float value" raise TypeError if isinstance(type, str): self.type = type else: print "5th arg should be string value" raise TypeError self.lmpindx = 0 self.g_indx = 0 def __del__(self): """ Destructor, clears object memory """ del self.pgid1 del self.pgid2 del self.pgid3 del self.theta0 del self.type del self.lmpindx del self.g_indx def __contains__(self, pgid): """ 'Magic' method implementing 'in' keyword. Args: pgid (int) Particle GID to check against 'held' IDs """ if ( (pgid == self.pgid1) or \ (pgid == self.pgid2) or \ (pgid == self.pgid3) ): return True else: return False def set_lmpindx(self,lmpindx): """ Set bond type index for lammps """ self.lmpindx = lmpindx def get_lmpindx(self): """ Return bond type index for lammps """ return self.lmpindx def set_g_indx(self,g_indx): """ Set bond type index for gromacs """ self.g_indx = g_indx def get_g_indx(self): """ Return bond type index for gromacs """ return self.g_indx def __str__(self): """ 'Magic' method for printng contents """ return " %s - %s - %s %s "%(self.pgid1,self.pgid2,self.pgid3,self.type ) class AngleContainer: """ Main data structure for holding Angle objects. Map of global angle ID (integer) to Angle object instances """ def __init__(self, idList=[], verbose=False): """ Constructor: sets up a dictionary for indexing 'Angle' objects Args: idList (list): of angle IDs. If empty then ID starts at 1. If not empty then ID's (keys) are inititalized with Angle objects verbose (bool): flag for printing status/debug info """ self.verbose=verbose self.angles=dict() # Creates empty dict struc self.angles={key: Angle() for key in idList} # Creates empty Angle objs # if idList not empty if len(idList) == 0: # If list not set in constructor arg self.maxgid=0 # default=0 if idList empty else: # self.maxgid=max(idList) # take max in list for maxgid def __del__(self): """ Destructor, clears dictionary memory """ if self.verbose: print "Cleaning particle container" del self.angles del self.maxgid def clear(self): """ Clears angles out of AngleContainer """ self.maxgid = 0 self.angles=dict() # Creates empty dict struc def __len__(self): """ 'Magic' method for returning size of container """ return len(self.angles) def __str__(self): """ 'Magic' method for printng contents """ angleStr="\n Contains angle objects: \n" for gid in self.angles: angleStr += " %d : %s \n"%(gid,self.angles[gid]) return angleStr def keys(self): """ Return list of all ptcl IDs (keys) currently in container """ keyList = self.angles.keys() return keyList def __setitem__(self, gid, angle): """ 'Magic' method implementing obj[]=value operator Performs deep copy of value so container is managing memory """ if gid in self.angles.keys(): self.angles[gid]=copy.deepcopy(angle) else: print "Cannot add angle object to non-existent ID" sys.exit(3) def __getitem__(self, gid): """ 'Magic' method implementing obj[] operator Operations on returned elements change container """ return self.angles[gid] def __delitem__(self, gid): """ 'Magic' method implementing del obj[] operator """ del self.angles[gid] def __iter__(self): """ 'Magic' method implementing (for x in 'this').... """ return self.angles.iteritems() def __call__(self, idSubList=None): """ Callable magic method. Returns iterator to subset angles dictionary Args: idSubList (list) list of pid-s of particle objects to be returned Returns: iterator to subset of particle dictionary """ subGroupDct = dict() if idSubList != None: for gid, angleObj in self.angles.iteritems(): if gid in idSubList: subGroupDct[gid] = angleObj return subGroupDct.iteritems() else: print "Callable AngleContainer requires a list of subgroup angle IDs" sys.exit(3) def __contains__(self, gid): """ 'Magic' method implementing in keyword (key in obj').... """ return gid in self.angles def hasAngle(self, angleList): """ Check the ptcl IDs in angleList for any angle in container that is similar eg angle 1-2-3 is same as angle 3-2-1 Args: (list) ptcl IDs defining angle to search for Returns: (bool) is angle in container """ for gid, angleObj in self.angles.iteritems(): angle = [angleObj.pgid1, angleObj.pgid2, angleObj.pgid3] # Angle ID list angleRev = copy.deepcopy(angle) # Make reverse angle angleRev.reverse() # ID list if ( (angle == angleList) or (angleRev == angleList) ): return True return False def __iadd__(self, other): """ 'Magic' method to implement the '+=' operator Compare global IDs of angles and reassign globalIDs for angle container using the max ID between the two lists Note: for now this reassigns ID always """ keys1 = self.angles.keys() # global IDs in this object keys2 = other.angles.keys() # global IDs in object being added bothkeys = keys1 + keys2 # List of all keys if len(bothkeys) > 0: # If keys not empty... proceed self.maxgid = max(keys1 + keys2) # find max globalID in keys, set this object maxID for ptclkey2 in other.angles: self.put(other.angles[ptclkey2]) return self def put(self, angle): """ Append 'Angle' object to this container. Updates globalID for container by incrementing the maxgid member Args: ptcl (Particle) correctly initialized Particle object NOTE: (1) One can imagine extra conditions on angles inserted (2) This could check for uniqueness of all globalID's and throw error for copies """ if isinstance(angle, Angle): self.maxgid += 1 self.angles[self.maxgid] = copy.deepcopy(angle) else: print "Attempting to add non-Angle type to container" raise TypeError def replacePtclIDs(self, idFromTo): """ Replace ptclIDs given a dictionary of ID changes # eg {1:3, 3:5, 2:20...} Args: idFromTo (dict) map of ID changes """ fromIDs = idFromTo.keys() for gid in self.angles: angle = self.angles[gid] # Angle object pgid1 = angle.pgid1 # ptcl1 in angle pgid2 = angle.pgid2 # ptcl2 in angle pgid3 = angle.pgid3 # ptcl3 in angle if pgid1 in fromIDs: toID = idFromTo[pgid1] angle.pgid1 = toID if pgid2 in fromIDs: toID = idFromTo[pgid2] angle.pgid2 = toID if pgid3 in fromIDs: toID = idFromTo[pgid3] angle.pgid3 = toID # SWS: needs test def getTypeInfoDict(self): """ Return a map of type to typeIndex Method assigns a type index and checkes for consistency Returns: dictionary """ # Look for types and get unique list typeList = list() for gid, angleObj in self.angles.iteritems(): angleType = angleObj.type typeList.append(angleType) typeList = list(set(typeList)) # Generate list of unique type for keys to initialize dictionary typeIndexDict = {key:index+1 for index, key in enumerate(typeList)} # dict for typeIndex if self.verbose: print "Unique types = ", typeList print "typeIndexDict = ", typeIndexDict # Pack yypeIndex to new dictionary typeInfoDict = dict() for key in typeIndexDict: index = typeIndexDict[key] typeInfoDict[key] = index return typeInfoDict
788c30719fe1c0a38f2e94e785af84fbf17d2573
albertoferreirademelo/13-datastructure-and-algorithms
/s_sort.py
11,541
4.21875
4
#-*- coding: utf-8 -*- ''' Author: Alberto Ferreira Course: Datastructures and algorithms (Umeå University) Teacher: Lena Kallin Westin Python 3.3 ''' import string import random import sys from DirectedList import * #function to read a directed list. def read_DirList(dir_list): pos = dir_list.first() while dir_list.isEnd(pos) != True: print (dir_list.inspect(pos)) pos = dir_list.next(pos) #Function that will sort the list. The input needed is a list, the position of the letter, the place that will be sorted and a final list #where the first time should be a empty list ([]). def radix_sort(test, position, letter_place, final_list): #This part will check if the list given is a python list. In that case, the python list will be transformed to a directedlist if type(test) is list: temp_list = DirectedList() temp_pos = temp_list.first() for i in test: temp_list.insert(temp_pos, i) temp_pos = temp_list.next(temp_pos) d_list = DirectedList() pos = d_list.first() for i in test: d_list.insert(pos, i) pos = d_list.next(pos) test = d_list #It will check if the list has one item or no item (that does not need to be sorted) pos = test.first() #list with no item if (test.isEnd(pos) == True): pass #The item is the last one in the list, in that case it will be appended to the final list because it means it is sorted. if (test.isEnd(test.next(pos))): final_list.append(test.inspect(test.first())) return test.inspect(test.first()) #variable needed to make the right amount of empty lists where in a later moment it will needed for the sorting #originally I used "place = ord('ü') - ord(' ')" where ü would give 252 and ' ' would give 32 (max and min) but since may be #some other word that I could't think of, I will just write a little higher number than 252-32=220. place = 250 #creating empty lists for the sorting placement x_list = DirectedList() pos = x_list.first() for x in range(place+2): x_list.insert(pos, DirectedList()) pos = x_list.next(pos) pos = test.first() #read each word from the "main" list and place in the right sorting list while test.isEnd(pos) != True: #word by word i = test.inspect(pos) i_p = i[position] #In the case the position is the rating, this dictionary is needed for the right sorting. if position == 3: dic = {'NR-': '01', 'NR': '02', 'NR+': '03', 'G-': '04', 'G': '05', 'G+': '06', 'VG-': '07', 'VG': '08', 'VG+': '09', 'M-': '10', 'M': '11', 'M+': '12'} i_p = dic[i_p] #which position the word will be placed if len(i_p)-1 >= letter_place: nr = ord(i_p[letter_place]) - ord(' ') pos2 = x_list.first() for j in range(nr+1): pos2 = x_list.next(pos2) #inserting the word in the right list in the right position x_list.inspect(pos2).insert(x_list.inspect(pos2).first(), i) pos = test.next(pos) #This is in the case of the word be repeated word, then it does not need to recheck. else: final_list.append(i) pos = test.next(pos) pos = x_list.first() while x_list.isEnd(pos) != True: #it will check each list from the x_list a = x_list.inspect(pos) #if there is some item in the list: if a.isempty() != True: pos3 = a.first() Lash = [] #now it will check each item from the list while a.isEnd(pos3) != True: Lash.append(a.inspect(pos3)) pos3 = a.next(pos3) #it will sort each letter of each item (for example if it is the words: Ad and Ab they are saved in a list and resorted) Lash = radix_sort(Lash, position, letter_place+1, final_list) pos = x_list.next(pos) return (final_list) #this function will print the sorted list for a better visualisation. def header(listan): print ("%-40s %-40s %-3s %-5s" %("ARTIST","ALBUM", "TYPE", "RATE")) lines = 0 print (listan[-1]) for i in listan: lines +=1 #This will stop the list after each 20 lines if lines%20 == 0: print ("Press b to go back to main menu, q to quit or any other button to continue") answer = input ("") if answer == 'b': sort_menu(listan) elif answer == 'q': sys.exit("Thank you for using this software. If you like it, donate to the owner ;)") else: print ("%-40s %-40s %-3s %-5s" %("ARTIST","ALBUM", "TYPE", "RATE")) artist = i[0] album = i[1] typ = i[2] betyg = i[3] print ("%-40s %-40s %-3s %-5s" %(artist, album, typ, betyg)) #If the list gets to the last item, then the user will have the option to go back or to quit. if i == listan[-1]: print ("End of list. Press b to go back to the main menu or q to quit.") last_answer = input (" ") if last_answer == 'q': sys.exit('Thank you for using this software. If you like it, donate to the owner ;)') elif last_answer == 'b': main_menu(listan) else: input ("Please press b (main menu) or q (quit): ") #function to open the file def open_file(text): filen = open(text, 'r') lines = filen.readlines() all_file = [] for i in lines: i = i.strip() i = i.split(";") all_file.append(i) return all_file #this function is just for aesthetics where when the program is started this will be shown def head_menu(): print ("************************************************************") print ("********* Welcome to Albertos sorting list program **********") print ("") main_menu([]) #this is the first menu of the program where the user can opt for open a list, sort/print the list or quit. def main_menu(listan): print ("****************** Main Menu *******************************") print ("Choose your option:") print ("1. Open list") print ("2. Sort and print list") print ("3. Quit") answer = input("(Press 1, 2, or 3 (and Enter) for your choice: ") if answer == '1': listan = open_menu() main_menu(listan) elif answer == '2': listan = sort_menu(listan) elif answer == '3': sys.exit('Thank you for using this software. If you like it, donate to the owner ;)') else: main_menu(listan) #This function will open predetermined files or one where the user can choose him/herself def open_menu(): print ("****************** Open list menu **************************") print ("Choose your option:") print ("1. Open data100poster.txt") print ("2. Open dataAllaPoster.txt") print ("3. Choose your own txt file") print ("4. Quit") answer = input("(Press 1, 2, 3, or 4 (and Enter) for your choice: ") if answer == '1': try: result = open_file('data100poster.txt') except: sys.exit("The file you tried to open does not exist. Be sure to have the file in the right path and to write the right name.\nThe program will quit now.") elif answer == '2': try: result = open_file('dataAllaPoster.txt') except: sys.exit("The file you tried to open does not exist. Be sure to have the file in the right path and to write the right name.\nThe program will quit now.") elif answer == '3': try: result = open_file(input("Write the name of the file (make sure you have the file and that you write .txt in the end: ")) except: sys.exit("The file you tried to open does not exist. Be sure to have the file in the right path and to write the right name.\nThe program will quit now.") elif answer == '4': sys.exit('Thank you for using this software. If you like it, donate to the owner ;)') return result #Here the user can choose between sort the list by artist, album, type or rating and print the list. def sort_menu(listan): print ("*********************** Sorting menu ***********************") print ("") print ("Choose your option:") print ("1. Sort your list by artist") print ("2. Sort your list by album") print ("3. Sort your list by type of record") print ("4. Sort your list by rate") print ("5. Print the list") print ("6. Back to main menu") print ("7. Quit") answer = input("(Press 1, 2, 3, 4, 5 or 6 (and Enter) for your choice: ") #1 will sort by artist if answer == '1': try: print ("Sorting list by artist...") listan = radix_sort(listan,0, 0, []) print ("Done.") sort_menu(listan) return listan except: sys.exit("You have to open a file first. Open the program again and choose open file before trying to sort.") #2 will sort by album elif answer == '2': try: print ("Sorting list by album...") listan = radix_sort(listan,1, 0, []) print ("Done.") sort_menu(listan) return listan except: sys.exit("You have to open a file first. Open the program again and choose open file before trying to sort.") #3 will sort by type elif answer == '3': try: print ("Sorting list by type...") listan = radix_sort(listan, 2, 0, []) print ("Done.") sort_menu(listan) return listan except: sys.exit("You have to open a file first. Open the program again and choose open file before trying to sort.") #4 will sort by rate elif answer == '4': try: print ("Sorting list by rate...") listan = radix_sort(listan, 3, 0, []) print ("Done.") sort_menu(listan) return listan except: sys.exit("You have to open a file first. Open the program again and choose open file before trying to sort.") elif answer == '5': header(listan) elif answer == '6': main_menu(listan) elif answer == '7': sys.exit('Thank you for using this software. If you like it, donate to the owner ;)') return listan if __name__ == "__main__": head_menu()
6a5cf3421133b39a0108430efee4d3c9ba51933f
megnicd/programming-for-big-data_CA05
/CA05_PartB_MeganMcDonnell.py
2,112
4.1875
4
#iterator def city_generator(): yield("Konstanz") yield("Zurich") yield("Schaffhausen") yield("Stuttgart") x = city_generator() print x.next() print x.next() print x.next() print x.next() #print x.next() #there isnt a 5th element so you get a stopiteration error print "\n" cities = city_generator() for city in cities: print city print "\n" #list generator def fibonacci(n): """Fibonacci numbers generator, first n""" a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(5) #yields the first 5 fibonacci lists as the programme calculates them print x, print #convert to celcius using list comprehension def fahrenheit(t): return ((float(9)/5)*t + 32) def celsius(t): return (float(5)/9*(t - 32)) temp = (36.5, 37, 37.5, 39) F = map(fahrenheit, temp) print F C = map(celsius, F) print C #max using reduce def max(values): return reduce(lambda a,b: a if (a>b) else b, values) print max([47, 11, 42, 13]) #min using reduce def min(values): return reduce(lambda a,b: a if (a<b) else b, values) print min([47, 11]) #add using reduce def add(values): return reduce(lambda a,b: a+b, values) print add([47, 11, 42, 13]) #subtract using reduce def sub(values): return reduce(lambda a,b: a-b, values) print sub([47, 11]) #multiply using reduce def mul(values): return reduce(lambda a,b: a*b, values) print mul([2,5]) #divide using reduce def div(values): return reduce(lambda a,b: a/float(b) if (b != 0 and a != 'Nan') else 'Nan', values) print div([47, 'Nan', 0, 11]) #find even numbers using filter def is_even(values): return filter(lambda x: x % 2 == 0, values) print is_even([47, 11, 42, 13]) #conversion using map def to_fahrenheit(values): return map(fahrenheit, values) print to_fahrenheit([0, 37, 40, 100]) #conversion using map def to_celsius(values): return map(celsius, values) print to_celsius([0, 32, 100, 212])
1c538c48a6373675104d4596ce5837ca2ae4c57a
jshumate8/learnPython
/tipcal.py
285
3.8125
4
string1 = raw_input("What is the total amount?") string2 = raw_input("What percentage of tip do you want to leave?") num1 = float(string1) num2 = float(string2) result= (num1 * num2 *.01) money= "${:,.2f}" .format(result) message = "The tip amount is {0}" .format(money) print message
8b5c88b0e70652ccd9d545014f0ab49d4c2c2e6a
jshumate8/learnPython
/factorial.py
634
3.84375
4
#again_prompt = True #while again_prompt: user_num = int(raw_input("Please give me a number: ")) factorial = 1 for i in range(1, user_num +1): factorial = factorial*i print "The factorial of", user_num, "is",factorial #for i in range((user_num)-1, -1, -1): # print(user_num*i) # for i in range(len(user_num)-1, -1, -1): # rev_num = user_num[i] # if norm_num == rev_num: # else: # play_again = raw_input("Hit any key to play again, or press 'q' to Quit.") # if play_again == "q" or play_again == "Q": # break #user_num = input("Please give me a number: ")
5f1d15fdcae68cba74fd923ec972f9148ce33bcd
MiyaJ/py-study
/basic/set.py
320
3.546875
4
# -*- coding: utf-8 -*- # @Time : 2020/12/21 14:36 # @Author : Caixiaowei # @File : set.py # @Desc : 集合 set1 = set('abcdefgccc') set2 = {1, 2, 'hello', 'world', 1, 'a'} print(type(set1), set1) print(set1) print(set2) print('diff:', set1.difference(set2)) i = iter(set2) for x in i: print(x, end=' ')
386520fc408963500ee3799862d33f0945dd016a
xcyxiner/python_timesay
/2.py
848
3.515625
4
import json import numpy as np import matplotlib.pyplot as plt import random import pandas as pd import csv with open('timesay/items.json') as file_object: contents = file_object.read() totalMoneyJson = json.loads(contents) totalMoney=0 totalMoneyList=[] for tmpMoneyInfo in totalMoneyJson: tmpMoney= float(tmpMoneyInfo["money"]) totalMoneyList.append(tmpMoney) totalMoney+=tmpMoney totalMoneyResult=sum(totalMoneyList) # print max(totalMoneyList) # print min(totalMoneyList) # print np.mean(totalMoneyList) # print np.sort(totalMoneyList) print 'sum '+str(totalMoneyResult) print 'get '+str(totalMoneyResult*0.01) df=pd.read_json('timesay/money.json') printResult= df.describe() print printResult x= range(0,len(totalMoneyList)) y=totalMoneyList plt.plot(x,y,label="hello",color='r',marker='o',markerfacecolor='blue') plt.show()
4002465d6ff995f7e78df3460f1ed40c8afe33ad
hoanganhk52/Session-4
/session_8/game.py
3,012
3.59375
4
import pygame pygame.init() screen = pygame.display.set_mode([400,300]) done = False game_finish = False COLOR_BLUE = [0,255,255] class Player(): def __init__(self,x,y): self.x = x self.y = y def move(self,dx,dy): self.x += dx self.y += dy def calc_next_position(self,dx,dy): return [self.x + dx, self.y + dy] class Box(): def __init__(self,x,y): self.x = x self.y = y def move(self,dx,dy): self.x += dx self.y += dy def calc_next_position(self,dx,dy): return [self.x + dx, self.y + dy] class Gate(): def __init__(self,x,y): self.x = x self.y = y class Map(): def __init__(self,width,height): self.width = width self.height = height self.player = Player(1,1) self.box = Box(2,2) self.gate = Gate(3,3) def check_inside(self,x,y): if 0<= x < self.width and 0 <= y < self.height: return True return False def move_object(self,dx,dy): [next_px, next_py] = self.player.calc_next_position(dx,dy) [next_bx, next_by] = self.box.calc_next_position(dx,dy) if not self.check_inside(next_px,next_py): None else: if [next_px, next_py] == [self.box.x, self.box.y]: if self.check_inside(next_bx, next_by)==True: self.player.move(dx,dy) self.box.move(dx,dy) else: self.player.move(dx,dy) def check_win(self,game_finish): if self.box.x == self.gate.x and self.box.y == self.gate.y: game_finish = True return game_finish map = Map(5,5) SQUARE_SIZE = 32 mario = pygame.image.load("mario.png") square = pygame.image.load("square.png") box = pygame.image.load("box.png") gate = pygame.image.load("gate.png") you_win = pygame.image.load("you_win.png") while not done: dx=0 dy=0 for event in pygame.event.get(): if event.type == pygame.QUIT or map.check_win(game_finish): done = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: dx = -1 elif event.key == pygame.K_RIGHT: dx = 1 elif event.key == pygame.K_UP: dy = -1 elif event.key == pygame.K_DOWN: dy = 1 else: dx, dy = 0, 0 if dx !=0 or dy !=0: map.move_object(dx,dy) screen.fill(COLOR_BLUE) for y in range(map.height): for x in range(map.width): screen.blit(square,(x * SQUARE_SIZE, y * SQUARE_SIZE )) screen.blit(gate, (map.gate.x * SQUARE_SIZE, map.gate.y * SQUARE_SIZE)) screen.blit(box, (map.box.x * SQUARE_SIZE, map.box.y * SQUARE_SIZE)) screen.blit(mario, (map.player.x * SQUARE_SIZE, map.player.y * SQUARE_SIZE)) if map.check_win(game_finish): screen.blit(you_win, (0, 0)) pygame.display.flip()
5ea301010a36b255e734373562cdd2954bca1e6f
Tougee/udacity
/cs212/poker/poker.py
3,920
3.515625
4
import itertools def poker(hands): return max(hands, key=hand_rank) def hand_rank(hand): ranks = card_rank(hand) if straight(ranks) and flush(hand): return (8, max(ranks)) elif kind(4, ranks): return (7, kind(4, ranks), kind(1, ranks)) elif kind(3, ranks) and kind(2, ranks): return (6, kind(3, ranks), kind(2, ranks)) elif flush(hand): return (5, ranks) elif straight(ranks): return (4, max(ranks)) elif kind(3, ranks): return (3, kind(3, ranks), ranks) elif two_pair(ranks): return (2, two_pair(ranks), ranks) elif kind(2, ranks): return (1, kind(2, ranks), ranks) else: return (0, ranks) def card_rank(cards): ranks = ['--23456789TJQKA'.index(r) for r,s in cards] ranks.sort(reverse=True) return [5, 4, 3, 2, 1] if (ranks == [14, 5, 4, 3, 2]) else ranks def straight(ranks): return (max(ranks) - min(ranks) == 4) and len(set(ranks)) == 5 def flush(hand): colors = [c for r, c in hand] return len(set(colors)) == 1 def kind(n, ranks): for r in ranks: if ranks.count(r) == n: return r return None def two_pair(ranks): pair = kind(2, ranks) lowpair = kind(2, list(reversed(ranks))) if pair and lowpair != pair: return (pair, lowpair) else: return None # def test(): # "Test cases for functions in poker program." # sf = "6C 7C 8C 9C TC".split() # fk = "9D 9H 9S 9C 7D".split() # fh = "TD TC TH 7C 7D".split() # tp = "5S 5D 9H 9C 6S".split() # fkranks = card_rank(fk) # tpranks = card_rank(tp) # assert kind(4, fkranks) == 9 # assert kind(3, fkranks) == None # assert kind(2, fkranks) == None # assert kind(1, fkranks) == 7 # assert two_pair(fkranks) == None # assert two_pair(tpranks) == (9, 5) # assert straight([9, 8, 7, 6, 5]) == True # assert straight([9, 7, 7, 6, 5]) == False # assert flush(sf) == True # assert flush(fk) == False # assert card_rank(sf) == [10, 9, 8, 7, 6] # assert card_rank(fk) == [9, 9, 9, 9, 7] # assert card_rank(fh) == [10, 10, 10, 7, 7] # assert poker([sf, fk, fh]) == sf # assert poker([fk, fh]) == fk # assert poker([fh, fh]) == fh # assert poker([sf] + 99*[fh]) == sf # assert hand_rank(sf) == (8, 10) # assert hand_rank(fk) == (7, 9, 7) # assert hand_rank(fh) == (6, 10, 7) # return "test pass" # print test() def best_hand(hand): "From a 7-card hand, return the best 5 card hand." return max(itertools.combinations(hand,5), key=hand_rank) def test_best_hand(): assert (sorted(best_hand("6C 7C 8C 9C TC 5C JS".split())) == ['6C', '7C', '8C', '9C', 'TC']) assert (sorted(best_hand("TD TC TH 7C 7D 8C 8S".split())) == ['8C', '8S', 'TC', 'TD', 'TH']) assert (sorted(best_hand("JD TC TH 7C 7D 7S 7H".split())) == ['7C', '7D', '7H', '7S', 'JD']) return 'test_best_hand passes' print(test_best_hand()) allranks = '23456789TJQKA' blackcards = [r+s for r in allranks for s in 'SC'] redcards = [r+s for r in allranks for s in 'DH'] def best_wild_hand(hand): "Try all values for jokers in all 5-card selections." hands = set(best_hand(h) for h in itertools.product(*map(replacement, hand))) return max(hands, key=hand_rank) def replacement(card): if card == '?B': return blackcards elif card == '?R': return redcards else: return [card] def test_best_wild_hand(): assert (sorted(best_wild_hand("6C 7C 8C 9C TC 5C ?B".split())) == ['7C', '8C', '9C', 'JC', 'TC']) assert (sorted(best_wild_hand("TD TC 5H 5C 7C ?R ?B".split())) == ['7C', 'TC', 'TD', 'TH', 'TS']) assert (sorted(best_wild_hand("JD TC TH 7C 7D 7S 7H".split())) == ['7C', '7D', '7H', '7S', 'JD']) return 'test_best_wild_hand passes' print(test_best_wild_hand())
089de9f9ed8ba0657a889cebfbd9298a01689ce9
AllenZPGu/MUMS-PH-2019
/checkEmails.py
150
3.75
4
with open('emails.csv', 'r') as f: x = [] for i in f: y = i.split(',')[1][:-1] if y not in x: x.append(y) x.sort() print(x) print(len(x))
1a5391c61faf4ae21a5e340a7acba6a2a0c0dac0
onepcc/zoo-python
/animal.py
1,477
4
4
# Cada animal debe tener al menos un nombre, una edad, un nivel de salud y un nivel de felicidad. # La clase Animal debe tener un método display_info que muestre el nombre, la salud y la felicidad del animal. # También debe tener un método de alimentación que aumente la salud y la felicidad en 10. class Animal: def __init__(self, nombre,edad,salud =50,felicidad=50): self.nombre = nombre self.edad = edad self.salud = salud self.felicidad = felicidad def info(self): print(f""" Animal: {self.__class__.__name__} Nombre: {self.nombre.upper()} Edad: {self.edad} Salud: {self.salud} Felicidad {self.felicidad}""") return self def comer(self): if self.salud < 100: self.salud+= 10 self.felicidad+= 10 print(f"""Animal {self.nombre} ha comido ahora salud y felicidad aumento a: {self.felicidad}""") return self def ruido(self): raise NotImplementedError # Comience creando una clase Animal y luego al menos 3 clases específicas de animales que hereden de Animal. # En al menos una de las clases de Animal child que ha creado, agregue al menos un atributo único. # Dele a cada animal diferentes niveles predeterminados de salud y felicidad. # Los animales también deben responder al método de alimentación con diferentes niveles de cambios en la salud y la felicidad.
655a5ef00a324d30707e5ee318f30e0e32324d9b
sasingithub/storage
/ceph_radosgw/get_count_objects_s3.py
955
3.625
4
###Funcao para fazer count de numero de objetos dentro de um bucket ###Count number of object using paginate 1000 objects def get_count_objects(bucket_name, bucket_conn, CEPH_BUCKET_MAX_KEYS): bucket = bucket_conn.lookup(bucket_name) objects = bucket.get_all_keys(max_keys=CEPH_BUCKET_MAX_KEYS) objects_len = len(objects) n = objects_len print "Number objects:%s" %(n) while True: if objects_len < 1: #logger.warn("The Bucket:'%s' has no objects ", bucket.name) break last_key_name = objects[-1].name #for key in objects: #yield key # n += 1 objects = bucket.get_all_keys(max_keys=CEPH_BUCKET_MAX_KEYS, marker=last_key_name) objects_len = len(objects) n += objects_len print "Number objects:%s" %(n) if objects_len < 1: break return n Eg: get_all_objects('Catalog', bucket_src_conn, 1000)
0c0de06a03d52d8cf86523b07153d27032dd3cb0
sedakurt/pythonProject
/venv/conditionals.py
786
4.21875
4
#comparison Operastors ''' print(1 < 1) print(1 <= 1) print(1 > 1) print(1 >= 1) print(1 == 1) print(1 != 1) ''' ##if, elif, else code block #if name = input("What is your name? ") if name == "Seda": print("Hello, nice to see you {}".format(name)) elif name == "Bayraktar": print("Hello, you are a surname!") elif name == "Kurt": print("Hi, {}, you are a second surname for Seda".format(name)) elif name != "Özcan": #en baştan conditionları çalıştırır yani bir order içerisinde akış devam edeceğinden ilk if e göre çalışır. Bu sorgu eğer koşullar arasında olmayan bir name değeri input olarak verirsem çalışacaktır. ''' What is your name? sdsdasda You are not Özcan! ''' print("You are not Özcan!") print("\nHave a nice day!")
927faddf89f6af3e0987bb549e6e964b30ecead9
pvcraven/isometric_test
/Source/isometric_example.py
6,311
3.984375
4
""" Example code showing Isometric Grid coordinates """ import arcade import os SCREEN_WIDTH = 700 SCREEN_HEIGHT = 700 MAP_WIDTH = 5 MAP_HEIGHT = 4 TILE_WIDTH = 128 TILE_HEIGHT = 128 def get_screen_coordinates(tile_x, tile_y, width, height, tilewidth, tileheight): screen_x = tilewidth * tile_x // 2 + height * tilewidth // 2 - tile_y * tilewidth // 2 screen_y = (height - tile_y - 1) * tileheight // 2 + width * tileheight // 2 - tile_x * tileheight // 2 return screen_x, screen_y def get_tile_coordinates(screen_x, screen_y, width, height, tilewidth, tileheight): x2 = ((1 / tilewidth) * (screen_x / 2 - screen_y / 2) + width / 2) * 2 - (width / 2 + 0.5) y2 = (height - 1) - ((1 / tileheight) * (screen_x / 2 + screen_y / 2) * 2 - (width / 2 + 0.5)) x2 = round(x2) y2 = round(y2) return x2, y2 class MyGame(arcade.Window): """ Main application class. """ def __init__(self, width, height): super().__init__(width, height) self.axis_shape_list = None self.isometric_grid_shape_list = None self.view_left = 0 self.view_bottom = 0 def setup(self): """ Set up the game and initialize the variables. """ # Set the background color arcade.set_background_color((50, 50, 50)) self.axis_shape_list = arcade.ShapeElementList() # Axis start_x = 0 start_y = 0 end_x = 0 end_y = SCREEN_HEIGHT line = arcade.create_line(start_x, start_y, end_x, end_y, arcade.color.WHITE, 2) self.axis_shape_list.append(line) # Axis start_x = 0 start_y = 0 end_x = SCREEN_WIDTH end_y = 0 line = arcade.create_line(start_x, start_y, end_x, end_y, arcade.color.WHITE, 2) self.axis_shape_list.append(line) # x Tic Marks for x in range(0, SCREEN_WIDTH, 64): start_y = -10 end_y = 0 line = arcade.create_line(x, start_y, x, end_y, arcade.color.WHITE, 2) self.axis_shape_list.append(line) # y Tic Marks for y in range(0, SCREEN_HEIGHT, 64): start_x = -10 end_x = 0 line = arcade.create_line(start_x, y, end_x, y, arcade.color.WHITE, 2) self.axis_shape_list.append(line) tilewidth = TILE_WIDTH tileheight = TILE_HEIGHT width = MAP_WIDTH height = MAP_HEIGHT # Gridlines 1 for tile_row in range(-1, height): tile_x = 0 start_x, start_y = get_screen_coordinates(tile_x, tile_row, width, height, tilewidth, tileheight) tile_x = width - 1 end_x, end_y = get_screen_coordinates(tile_x, tile_row, width, height, tilewidth, tileheight) start_x -= tilewidth // 2 end_y -= tileheight // 2 line = arcade.create_line(start_x, start_y, end_x, end_y, arcade.color.WHITE) self.axis_shape_list.append(line) # Gridlines 2 for tile_column in range(-1, width): tile_y = 0 start_x, start_y = get_screen_coordinates(tile_column, tile_y, width, height, tilewidth, tileheight) tile_y = height - 1 end_x, end_y = get_screen_coordinates(tile_column, tile_y, width, height, tilewidth, tileheight) start_x += tilewidth // 2 end_y -= tileheight // 2 line = arcade.create_line(start_x, start_y, end_x, end_y, arcade.color.WHITE) self.axis_shape_list.append(line) for tile_x in range(width): for tile_y in range(height): screen_x, screen_y = get_screen_coordinates(tile_x, tile_y, width, height, tilewidth, tileheight) point_width = 3 point_height = 3 point = arcade.create_rectangle_filled(screen_x, screen_y, point_width, point_height, arcade.color.LIGHT_CORNFLOWER_BLUE, 3) self.axis_shape_list.append(point) print(f"{tile_x}, {tile_y} => {screen_x:3}, {screen_y:3}") def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing arcade.start_render() self.axis_shape_list.draw() # x Labels for x in range(0, SCREEN_WIDTH, 64): text_y = -25 arcade.draw_text(f"{x}", x, text_y, arcade.color.WHITE, 12, width=200, align="center", anchor_x="center") # y Labels for y in range(0, SCREEN_HEIGHT, 64): text_x = -50 arcade.draw_text(f"{y}", text_x, y - 4, arcade.color.WHITE, 12, width=70, align="right", anchor_x="center") tilewidth = TILE_WIDTH tileheight = TILE_HEIGHT width = MAP_WIDTH height = MAP_HEIGHT for tile_x in range(width): for tile_y in range(height): screen_x, screen_y = get_screen_coordinates(tile_x, tile_y, width, height, tilewidth, tileheight) arcade.draw_text(f"{tile_x}, {tile_y}", screen_x, screen_y + 6, arcade.color.WHITE, 12, width=200, align="center", anchor_x="center") def update(self, delta_time): self.view_left = -50 self.view_bottom = -50 arcade.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom) def on_mouse_press(self, x, y, button, key_modifiers): screen_x = x + self.view_left screen_y = y + self.view_bottom tilewidth = TILE_WIDTH tileheight = TILE_HEIGHT width = MAP_WIDTH height = MAP_HEIGHT map_x, map_y = get_tile_coordinates(screen_x, screen_y, width, height, tilewidth, tileheight) print(f"({screen_x}, {screen_y}) -> ({map_x}, {map_y})") def main(): """ Main method """ window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT) window.setup() arcade.run() if __name__ == "__main__": main()
4bb989ebaca1ed9e289611696a31e7db58cd04d1
tretyakovr/sobes-Lesson03
/Task-02.py
1,549
4.125
4
# Третьяков Роман Викторович # Факультет Geek University Python-разработки # Основы языка Python # Урок 3 # Задание 2: # Написать программу, которая запрашивает у пользователя ввод числа. На введенное число # она отвечает сообщением, целое оно или дробное. Если дробное — необходимо далее выполнить # сравнение чисел до и после запятой. Если они совпадают, программа должна возвращать # значение True, иначе False input_value = input('Введите число: ') if '.' in input_value: if input_value.count('.') == 1: if input_value.split('.')[0].isdigit() and input_value.split('.')[1].isdigit(): print('Введено число с плавающей точкой!') if input_value.split('.')[0] == input_value.split('.')[1]: print('Значения целой и дробной части совпадают!') else: print('Значения целой и дробной части отличаются!') else: print('В введенной строке присутствуют нечисловые символы!') else: print('Введено не числовое значение!') else: if input_value.isdigit(): print('Введено целое число!')
f831b12f35358f0d7f8a9abc0db9f85b54097db2
joanenricb/Data-Science---Washington-University
/MapReduce/asymmetric_friend.py
636
3.5
4
""" Generate a list of all non-symmetric friend relationships. """ import MapReduce import sys mr = MapReduce.MapReduce() def mapper(record): # key: document identifier # value: document contents name = record[0] friend = record[1] mr.emit_intermediate(tuple(sorted((name, friend))), 1) def reducer(name, friends): # key: word # value: list of occurrence counts if len(friends) == 1: mr.emit(name) mr.emit(name[::-1]) #mr.emit((name, k)) #mr.emit((k,name)) if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)