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
7ca7a468dcc8aea1cc45757f9430b5fa0c0d736f
JuanHernandez2/Ormuco_Test
/Ormuco/Strings comparator/comparator.py
1,188
4.25
4
import os import sys class String_comparator: """ Class String comparator to compare two strings and return which is greater, less or equal than the other one. Attributes: string_1: String 1 string_2: String 2 """ def __init__(self, s1, s2): """ Class constructor Params: s1: string 1 s2: string 2 """ self.string_1 = s1 self.string_2 = s2 def compare(self): """ This function compares if both strings are greater, less or equal to the other one """ if str(self.string_1) > str(self.string_2): return "{} is greater than {}".format(self.string_1, self.string_2) elif str(self.string_1) < str(self.string_2): return "{} is less than {}".format(self.string_1, self.string_2) else: return "{} is equal to {}".format(self.string_1, self.string_2) def check_strings(self): """ Checks if the two strings are valid """ if self.string_1 is None or self.string_2 is None: raise ValueError("One of the arguments is missing or NoneType")
c0ed1fdb6dfa3fa3c880af25c18e281354276737
mwbelyea/Dictionary
/fun.py
437
3.5625
4
def mike(): for i in range(0,1): print("Choose your own adventure") print("Dad's trip to work") print("-*-*-*-*-*-*-*-*-*-*-*-*") print("Lisa gone, Mike could finally start a new adventure.") print("Should he?") response_1 = raw_input("Reply: (Y)es (N)o: ") if response_1.lower == "y": print("So he set off.") else: print("Instead of an adventure, he took a nap on the couch.") mike()
e5524037b810b62eca82b3b75c27260fd77e1b21
Sharmaanuj10/Phase1-basics-code
/python book/book project 2/class & module/lottery.py
168
3.78125
4
from random import choice name = ["jack","jill","qwerty","Anuj","Aditya"] # you can also also use tuples instead of the list winner = choice(name) print(winner)
1ed4ea179560b5feec261b094bdbe5b2848b4e03
Sharmaanuj10/Phase1-basics-code
/python book/book projects 1/4-7/input while loop/flag.py
321
4.1875
4
active = True print("if you want to quit type quit") while active: message = input("Enter your message: ") if message == 'quit': # break # to break the loop here active = False #comtinue # to execute left over code exiting the if else: print(message)
f0b8df90473a9d20d78162dc0da0e37bad461061
Sharmaanuj10/Phase1-basics-code
/python book/book projects 1/4-7/input while loop/whileloop.py
363
3.984375
4
message = '' # you can use this for game to run as long as user want while message != 'quit': message = input('hi : ') # in her i use user input and store to number and pass through the loop Again if message != 'quit': print(message) elif message == 'quit': print('quiting...') print('Quited')
0227e6263035a7b7e6cf67dadde3eb91576afc0b
Sharmaanuj10/Phase1-basics-code
/python book/book projects 1/4-7/input while loop/deli.py
710
4.28125
4
user_want = {} # fistly define a dictonairy empty poll_active = True while poll_active: name = input('Enter your name: ') want = input('if you visit one place in the world where you visit? ') repeat = input('waant to know others wnats (yes,no)? ') # after input store the data at dictionary user_want user_want[name] = want # but user dont want to know about other if he/she type no so to stop the loop we can do: if repeat == 'no': poll_active = False # at last we take keys and values form the user_want dictionary and just print them for names,wants in user_want.items(): print(f'\tHi! {names} you want to visit {wants}')
8592b3147c28ef1b09589c048dfa30e0eb87aa5a
Sharmaanuj10/Phase1-basics-code
/python book/Python/password.py/password 1.5.py/password1.5.py
1,287
4.28125
4
name = input("Enter your username: ") passcode = input("Enter you password: ") # upper is used to capatilize the latter name = name.upper() # all the password saved def webdata(): webdata= input("Enter the key word : ") user_passwords = { 'youtube' : 'subscribe', # here now you can save infinte number of password 'twitter' : 'qwerty', # '' : '', # I created many string to store the data } print(user_passwords.get(webdata)) # here the attribute '.get' get the data from the names; # username and their passwords userdata = { 'ANUJ' : 'lol', 'ANUJ SHARMA' : 'use', '' : '' } # now we looped the dictonairy and get the keys and values or username and password to check for username , password in userdata.items(): # In this case if the name == username we enter so it check wether passcode is equal or not if name == username: if passcode == password: # now the user is verified so we import the webdata or passowords data webdata() # in this the the username and passowrd are linked so they are not going to mess with each other like older have # Note : still it have a problem can you find out what??🧐🧐
e591a0397c93d835d46d6780ad0c7d71b97975b7
schin7/Rosalind-Problems
/Bioinformatics Stronghold/011 - FIBD - Mortal Fibonacci Rabbits/011_FIBD.py
828
3.5
4
with open('C:/Users/Owner/Desktop/rosalind_fibd.txt') as input_data: n,m = map(int, input_data.read().split()) # Populate the initial rabbits. Rabbits = [1]+[0]*(m-1) # Calculate the new rabbits (bunnies), in a given year. # Start at use range(1,n) since our initial population is year 0. for year in range(1, n): Bunnies = 0 # Get the number of Rabbits able to old enough to give birth. for j in range(1,m): Bunnies += Rabbits[(year-j-1)%m] # Bunnies replace the old rabbits who died. Rabbits[(year)%m] = Bunnies # Total rabbits is the sum of the living rabbits. Total_Rabbits = sum(Rabbits) # Write the output data. with open('C:/Users/Owner/Desktop/011_FIBD.txt', 'w') as output_data: print (Total_Rabbits) output_data.write(str(Total_Rabbits)) if __name__ == '__main__': main()
a1308f390e918ed81896ed2fcdee02f9cc0dd03d
coolroboticsmaster/Class
/class7.py
571
3.9375
4
def canyoudriveacar(): x = input(" what is your name ") y = int(input(" what is your age ")) if y >= 18: return" You are eligble to drive a car" else: return" You can not eligble drive a car" print(canyoudriveacar()) def leapyear(): x = int(input(" which year is going on ")) if x%4 ==0: return "that year is a leap year" else: return "that year is not a leap year" print(leapyear()) def hello_f(greetings = "hi",name="you"): return "{}{}".format(greetings,name) print(hello_f("hi,amogh"))
404f12ef160e037fa2c28006d41bdae7f996627d
coolroboticsmaster/Class
/class6.py
632
3.90625
4
# import math # y = int(input(" please enter a number as your radius ")) # peremeter = 2*math.pi*y # print( "The permeter of ",y, " is " ,peremeter) # a=math.ceil(peremeter) # print(a) # x = input(" enter your name ") # z = input(" enter your age ") # print (" your name is ",x,"and your age is ",z) # print (" your name is ",x,"and your age is ",z) # print (" your name is ",x,"and your age is ",z) # print (" your name is ",x,"and your age is ",z) # print (" your name is ",x,"and your age is ",z) import datetime a = datetime.date.today() b = datetime.date(2017,6,27) c = a - b s = datetime.timedelta(days = 7) z=c/s print(z)
6c8f4e352e21d4203902d5da9441a0162d7c0134
alexoch/python_101_course
/py_course/1-4/test4.py
259
3.53125
4
""" :10 : python lab3_1.py 10 : 55 : 0 :python lab3_1.py 0 : 0 """ import sys X = int(sys.argv[1]) P = 0 C = 1 if X == 0: print P elif X == 1: print C else: for count in range(int(X)-1): R = C + P P = C C = R print R
946af25e363f71c279bc2a06d9862461aa7d9a04
The-Xceros/Earthsupasin-CS01
/CS01-16.py
114
3.625
4
import numpy as np arr = np.array([1,2,3,4,5,6,7,8,9,10]) newarr = arr.reshape(5,2) print(newarr) print(newarr+10)
213ebf4489f815cf959de836a11e2339ca8bcfaa
rsleeper1/Week-3-Programs
/Finding Max and Min Values Recursively.py
2,148
4.21875
4
#Finding Max and Min Values #Ryan Sleeper def findMaxAndMin(sequence): #This method finds the max and min values of a sequence of numbers. if len(sequence) < 2: #This catches a sequence that doesn't have enough numbers to compare (less than 2) and returns the invalid sequence. print("Please create a sequence of at least 2 numbers.") minNum = sequence maxNum = sequence return minNum, maxNum elif len(sequence) == 2: #This is my base case. Once the sequence gets down to two numbers we have found the max and min. sequence.sort() return sequence[0], sequence[1] else: if sequence[0] <= sequence[1]: #This if statement initializes the minimum number and the maximum number. minNum = sequence[0] maxNum = sequence[1] else: minNum = sequence[1] maxNum = sequence[0] if minNum < sequence[2]: #Once we have a minimum and maximum, the method checks the next number and compares it to the if maxNum > sequence[2]: #minimum value and the maximum value. If it is less than the minimum, then it becomes the new sequence.remove(sequence[2]) #minimum value. If it is greater than the maximum value then it becomes the new max value. If return findMaxAndMin(sequence) #it is neither than it gets removed from the list. else: sequence.remove(maxNum) maxNum = sequence[1] return findMaxAndMin(sequence) else: sequence.remove(minNum) minNum = sequence[1] return findMaxAndMin(sequence) def main(): sequence = [54, 79, 8, 0, 9, 9, 23, 120, 40] #This is my sequence, feel free to change it to see different results. minNum, maxNum = findMaxAndMin(sequence) print("The minimum number is: {}".format(minNum)) #I had the program print out the results to make sure it was producing the correct answers. print("The maximum number is: {}".format(maxNum)) main()
e79bebbfef3ecb282ae91f22f81dbab1aed8bd2a
therealnacho19/SecondDay
/magicMaze.py
829
3.734375
4
moves=0 fails=0 lives=3 lock=['S', 'S', 'N', 'W', 'E', 'S'] flag=True lockRecord=0 while flag: play=input("You are in the magic maze. Which way (N,S,E,W) do you want to go?: ") moves +=1 lockRecord +=1 if moves <= (len(lock)-1): if play != lock[lockRecord - 1]: lockRecord=0 fails+=1 if (fails==5): lives -=1 if (lives > 0): flag=True print("You lost one life! You still have" ,lives, "lives left.") else: flag=False print("You have run out of lives!") break print("You are starting back from the beginning!") else: print("You have escaped the maze in" ,moves, "moves.") break
d075b9df570b98066efa80959ee3d102bca91614
chigozieokoroafor/DSA
/one for you/code.py
259
4.28125
4
while True: name = input("Name: ") if name == "" or name==" ": print("one for you, one for me") raise Exception("meaningful message required, you need to put a name") else: print(f"{name} : one for {name}, one for me")
28e8f771a7968081d3ced6b85ddec657163ad7d1
avi527/Tuple
/different_number_arrgument.py
248
4.125
4
#write a program that accepts different number of argument and return sum #of only the positive values passed to it. def sum(*arg): tot=0 for i in arg: if i>0: tot +=i return tot print(sum(1,2,3,-4,-5,9))
f94cb136e8f293d2a204dc22442a04c16ddf6e9a
avi527/Tuple
/variable_length_argument_tuple.py
556
4.09375
4
#programm to manipulate efficiently each value that is passed to the tuple #using variable length argument def display(*args): print(args) Tup=(1,2,3,4,5,6) Tup1=(7,8,9,10,11,12) display(Tup,Tup1) #agr krke aap kitna bhi variablepass kr skte hai #NOTE :- if youhave a function that displays all the parameters passed to it, #then even the function does not know how many value it will be passed.in such cases #we use a variable-length argument that begains with a'*' symbolis know as gather #and specifies a variable length argument.
f80b9e983eaaa1f4473aa1916a38e0faef027d81
aldayanid/python
/guess.py
425
4.0625
4
import random n = int(random.random() * 10) i = int(input("Please enter your number: ")) attempts = 1 while True: attempts += 1 if attempts == 3: print("max number of attempts reached.") break if i > n: print("Enter lesser") elif i < n: print("Enter higher") else: print("Bingo") break i = int(input("Please enter your number: ")) print("The end!")
f84fdcc10c21393862a7c726a5073b608e929b06
aldayanid/python
/validator.py
273
3.734375
4
def is_compliant(psswrd:str)->bool: return len(psswrd)>=8 and any(chr.isdigit() for chr in psswrd) def main(): psswrd=input("Password: ") if is_compliant(psswrd): print("OK") else: print("Wrong") if __name__ == '__main__': main()
2c64aa987fb60710b4c1f47d0837853f3dc232fa
khlidar/Concrete_Beam_Program
/Shapes.py
5,457
3.90625
4
''' Description: Definition of shapes class and sup classes Information on authors: Name: Contribution: --------- ------------------ Jacob Original code Kristinn Hlidar Gretarsson Original code Version history: ''' # Import from math import sqrt # Definitions class Shapes(object): def __init__(self): self.name = 'I\'m just a blob' self.h = 0 self.b = 0 def changeShape(self, new_shape): shapes = ['rectangle', 'triangle', 'circle'] if new_shape.lower() in shapes: self.name = new_shape.lower() def giveParameters(self): return print(self.parameter()) def parameter(self): return 'I\'m just a blob' def changeParameter(self): print('I don\'t know how to do that') def width(self, location): return 0 def getWidth(self, location): return self.width(location) def getHeight(self): return self.h def isValidShapeParameter(self, input): if type(input) == float: return True else: print(f'{input} is not valid input into {self}') def __str__(self): return self.name class Rectangle(Shapes): def __init__(self, breadth=0., height=0.): self.name = 'rectangle' self.b = breadth self.h = height def parameter(self): return f'{self.name} width = {self.b} and height = {self.h}' def width(self, location): if location <= self.h: return self.b else: print(f'location is outside of shape with height {self.h}') def changeParameter(self, breadth=0., height=0.): if breadth: self.b = breadth if height: self.h = height class Triangle(Shapes): def __init__(self, breadth=0., height=0.): self.name = 'triangle' self.b = breadth self.h = height def parameter(self): return f'{self.name} width = {self.b} and height = {self.h}' def width(self, location): if location <= self.h: b = self.b * location / self.h return b else: print(f'location is outside of shape with height {self.h}') def changeParameter(self, breadth=0., height=0.): if breadth: self.b = breadth if height: self.h = height class Circle(Shapes): def __init__(self, diameter=0): self.name = 'circle' self.d = diameter def width(self, location): if location <= self.d: b = 2 * sqrt(2 * location * self.d / 2 - location * location) return b else: print(f'location is outside of circle with diameter {self.d}') def changeParameter(self, diameter=0): if diameter: self.d = diameter def getHeight(self): return self.d class T_beam(Shapes): def __init__(self, breadth=0, height=0, flange_breadth=0, flange_height=0): self.name = 'T-beam' self.b = breadth self.h = height self.f_b = flange_breadth self.f_h = flange_height def width(self, location): if 0 <= location <= self.f_h: b = self.f_b return b elif self.f_h < location <= self.h: b = self.b return b else: print(f'location {location} is outside of shape T-beam') def changeParameter(self, breadth=0, height=0, flange_breadth=0, flange_height=0): if breadth: self.b = breadth if height: self.h = height if flange_breadth: self.f_b = flange_breadth if flange_height: self.f_h = flange_height class I_beam(Shapes): def __init__(self, breadth=0, height=0, flange_u_breadth=0, flange_u_height=0, flange_l_breadth=0, flange_l_height=0): self.name = 'I-beam' self.b = breadth self.h = height self.fu_b = flange_u_breadth self.fu_h = flange_u_height self.fl_b = flange_l_breadth self.fl_h = flange_l_height def width(self, location): if 0 <= location <= self.fu_h: return self.fu_b elif self.fu_h < location <= self.h - self.fl_h: return self.b elif self.h - self.fl_h < location <= self.h: return self.fl_b else: print(f'Location {location} is outside of shape I-beam') def changeParameter(self, breadth=0, height=0, flange_u_breadth=0, flange_u_height=0, flange_l_breadth=0, flange_l_height=0): if breadth: self.b = breadth if height: self.h = height if flange_u_breadth: self.fu_b = flange_u_breadth if flange_u_height: self.fu_h = flange_u_height if flange_l_breadth: self.fl_b = flange_l_breadth if flange_l_height: self.fl_h = flange_l_height # Run main program if __name__ == '__main__': a = Rectangle(16, 28) print(a.getHeight()) test = isinstance(a, Shapes) a.changeParameter(16., 28.) a.giveParameters() print(test)
7c371a69d4aa59583b2ab9ffb24bd4047f378a14
Renatkg20/CodewarsofTask
/RBB.py
461
3.734375
4
import re def rgb(r, g, b): for i in [r,g,b]: if r > 255: r = 255 elif r < 0: r = 0 elif g > 255: g = 255 elif g < 0: g = 0 elif b > 255: b = 255 elif b < 0: b = 0 t = "#{:02x}{:02x}{:02x}".format(r,g, b) result = re.findall('[a-z0-9]', t) result1 = ''.join(result) return result1.upper() print(rgb(260, 32, 500)) def rgb(r, g, b): return "%02X%02X%02X" % (max(0,min(r,255)),max(0,min(g,255)),max(0,min(b,255)))
ce0ae5c217bde3ff4b5a55f3ba3de206cf724068
angelrpb/Py-AI
/AI-Assistant.py
6,557
3.5
4
# Este es el asistente AIpy en proceso (iniciado pero falta el ML, AI, etc) # Este asistente todavia no cuenta con el complemento de la IA o AI # La mente arquitecta (yo) aun no cuenta con esos conocimientos #engine.say("Hello world. My name is December.") #engine.runAndWait() #ajuste de veloc de hablado # y cambio del genero de la voz a fem voices[0] señora # [1] voz femenina mas juvenil # [2] voz masculina tipo español de castilla import pyttsx3 #pip install pyttsx3 import datetime import speech_recognition as sr #pip install SpeechRecognition engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) newVoiceRate = 130 #Veloc dentro de lo normal / Normal talk speed engine.setProperty('rate', newVoiceRate) def speak(audio): engine.say(audio) engine.runAndWait() #speak("This is December, a personal assistant") def time(): #Now it tell us the current date Time = datetime.datetime.now().strftime("%I:%M:%S") speak("The current time is ") speak(Time) #time() #This tells the machine to say it first def date(): #Tell us the current date in numbers year = int(datetime.datetime.now().year) month = int(datetime.datetime.now().month) date = int(datetime.datetime.now().day) speak("The current date is ") speak(date) speak(month) speak(year) #date() #same as above but like time is upper, this one is the second one to be said def wishme(): speak("Welcome back Sir!") time() date() hour = datetime.datetime.now().hour if hour >= 6 and hour <= 12: speak ("Good morning!") elif hour >= 12 and hour < 18: speak ("Good afternoon!") elif hour >= 18 and hour <= 24: speak("Good evening!") else: speak("Good night!") speak("December at your service. How can i help you?") #wishme() # With this the assistant can hear us and write/shows in terminal # what we were saying or trying to say... def takeCommand(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening Sir...") r.pause_threshold = 1 audio = r.listen(source) try: print("Recognizing...") query = r.recognize_google(audio, language = "en-US") print(query) except Exception as e: print(e) speak("Kindly say it again....") return "None" return query takeCommand() ## email feature def sendmail(to, content): msg = MIMEMultipart() msg.attach(MIMEText("Hello, my name is December", 'plain')) server = smtplib.SMTP('smtp.gmail.com: 587') server.ehlo() server.starttls() server.login("userr@gmail.com","Password") server.sendmail("user@gmail.com", to, content) server.quit() ##In this we are giving the power to take screenshots or screencapture when we told it to do it def screenshot(): screencapture = pyautogui.screenshot() screencapture.save("D:\Documentos\Proyectos\AI - Inteligencia Artificial\Proyectos\sc.png") def cpu(): usage = str(psutil.cpu_percent()) speak("CPU is at " + usage) print(usage) # cpu_temp = psutil.sensors_temperatures(fahrenheit=False)() # speak("CPU temp is at "+ cpu_temp) # print(cpu_temp) # fans = psutil.sensors_fans() # speak("Fans are at "+ fans) # print(fans) # speak("CPU temp is at " + str(psutil.sensors_temperatures())) # speak("Fans are at " + psutil.sensors_fans) battery = psutil.sensors_battery() speak("Battery is at ") speak(battery.percent) print(battery.percent) def jokes(): speak(pyjokes.get_joke()) if __name__ == "__main__": wishme() while True: query = takeCommand().lower() print(query) if "time" in query: time() elif "date" in query: date() elif "offline" in query: quit() elif "wikipedia" in query: #ver como hacer un comando global speak("Searching...") query = query.replace("wikipedia","") result = wikipedia.summary(query, sentences=2) speak(result) ## Here December will tell us what she is looking at ## and the results, aun necesita mejoras.. elif "send email" in query: try: ## Will ask us what the mail should contain speak("Sir, what should I say?") content = takeCommand() to = "user@gmail.com" sendmail(to, content) #speak(content) speak("Sir the email was successfully sent to the recipient.") except Exception as e: speak(e) speak("Sir im unable to send the email") elif "search in chrome" in query: speak("Sir, what should I search?") chromepath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s" search = takeCommand().lower() wb.get(chromepath).open_new_tab(search + ".com") elif "logout" in query: ##log off, the same as type win logon + L os.system("shutdown -l") elif "shutdown" in query: ##shutdown in 1 min, can be less if we choose zero = 0, than 1 os.system("shutdown /s /t 1") elif "restart" in query: ##restart the computer os.system("shutdown /r /t 1") elif "play music" in query: ##Play music inside a folder songs_dir = "D:\Música" songs = os.listdir(songs_dir) os.startfile(os.path.join(songs_dir, songs[0])) ## This one is under development because can be used for path traversal elif "Remember that" in query: #Recordar cosas speak("What should I remember?") data = takeCommand() speak("Sir, you told me to remember" + data) Remember = open("data.txt", "w") Remember.write(data) Remember.close() elif "What we have for on point" in query: #The AI assistant will tell us what he/she saved Remember = open("data.txt", "r") speak("Sir, you told me to remember that"+Remember.read()) elif "screenshot" in query: #The AI wil tell us that he/she took the screenshot screenshot() speak("Sir, I took the screenshot") elif "cpu" in query: cpu() elif "joke" in query: jokes()
2482c28267330bb414ebc2542de92589f26a1779
Jurph/aoc2018
/day1/day1p1.py
1,649
4.03125
4
#!/usr/bin/python # Solves (https://adventofcode.com/2018/day/1) given input.txt in the same path def tuner(frequency, seenbefore, tuned): with open('input.txt', "r") as inputfile: while tuned == False: inputline = inputfile.readline() if inputline == "": return frequency, seenbefore, tuned # print("Got {}".format(inputline)) direction = str(inputline[0]) # print("Direction is {}".format(direction)) magnitude = int(inputline[1:]) # print("Magnitude is {}".format(magnitude)) if direction == "+": frequency += magnitude # print("Added {} // new frequency is {}".format(magnitude, frequency)) elif direction == "-": frequency -= magnitude # print("Subtracted {} // new frequency is {}".format(magnitude, frequency)) else: break if frequency in seenbefore: print("Saw repeated frequency at {} MHz".format(frequency)) tuned = True break else: seenbefore.append(frequency) print("Added {} MHz to list of {} seen frequencies".format(frequency, len(seenbefore))) inputfile.close() return frequency, seenbefore, tuned def main(): frequency = 0 seenbefore = [] tuned = False while True: frequency, seenbefore, tuned = tuner(frequency, seenbefore, tuned) if tuned: break print("The frequency is {}".format(frequency)) if __name__ == "__main__": main()
ada5b9a0682efc8b27bbd0b12d199c7d0751efcb
mikossheev/qa-tools
/lession_2/test_string.py
981
4.0625
4
"""Here are the tests with string""" def test_string_length_and_space(string_prepare, random_number): """Test checks the length of string, depending on random text length, and that string does not start with a space""" assert len(string_prepare) == 22 + random_number assert not string_prepare.startswith(" ") def test_string_all_parts(string_prepare, random_number): """This test checks if the string starts with known start and end parts, and whether random part consists of letters in upper case""" start_of_the_string = "Some random text " end_of_the_string = " here" assert string_prepare.startswith(start_of_the_string) string_prepare = string_prepare.replace(start_of_the_string, "") assert string_prepare.endswith(end_of_the_string) string_prepare = string_prepare.replace(end_of_the_string, "") assert string_prepare.isupper() assert string_prepare.isalpha() assert len(string_prepare) == random_number
95100b93ecb1d5fc9fe936869b7fc50f56c0f859
k-schmidt/Insight_Data_Engineering_Coding_Challenge
/src/pkg/trie.py
3,513
4.09375
4
""" Trie Implementation Kyle Schmidt Insight Data Engineering Coding Challenge """ from typing import Optional, Tuple class Node(dict): def __init__(self, label: Optional[str]=None): """ Node class representing a value in the Trie class. Node inherits from dict providing dictionary functionality while being able to store additional data Attributes: label: Character of word within Trie count: Number of times the word has been seen Count is only incremented when we reach the end of a word. is_in_heap: Boolean indicator letting us know when to traverse a heap looking for the node """ self.label = label self.count = 0 # type: int self.is_in_heap = False # type: bool def add_child(self, key: str) -> None: """ Add a value to the Node which itself is another Node Arguments: key: Character of word """ self[key] = Node(key) def increment_priority(self, priority_incrementer: int) -> None: """ Nodes will also be stored in a heap and we need to be able to update a Nodes priority within that heap Priority Incrementer tells us how much to increment the priority by Arguments: priority_incrementer: Number to increment instance attribute count """ self.count += priority_incrementer def __repr__(self): if not self.keys(): return "Node(label={}, count={}, is_in_heap={}"\ .format(self.label, self.count, self.is_in_heap) else: return "Node({})".format([(key, value) for key, value in self.items()]) class Trie: def __init__(self): """ Class used as an ADT of Trie A Trie contains Nodes which contain characters of a word and pointers to additonal characters of words. Attributes: head: Empty Node instance """ self.head = Node() # type: Node def add(self, item: str, priority_incrementer: int=1) -> Tuple[Node, str]: """ Add a word to the Trie by traversing the characters of that word. If the word is already in the Trie then we will visit of the Nodes representing that word. Otherwise we will create new Nodes to represent that word. Finally we will increment the counter for that word. Arguments: item: The word to add to the Trie priority_incrementer: Number to increase the Node's count attribute Returns: Node instance representing the last character of the word and the word itself """ current_node = self.head item_finished = True for index in range(len(item)): char = item[index] if char in current_node: current_node = current_node[char] else: item_finished = False break if not item_finished: while index < len(item): char = item[index] current_node.add_child(char) current_node = current_node[char] index += 1 current_node.increment_priority(priority_incrementer) return current_node, item
f8cb9b51b864de1687f94faaf863cc32c355dc08
iggy18/oop_tic_tac_toe
/hang/hang.py
1,394
3.828125
4
import random from words import words class Hangman: def __init__(self): self.word = random.choice(words) self.display = ['_' for letter in self.word] self.guesses = 0 def show(self): display = ' '.join(self.display) print(f'the word is: {display}') def get_word_index(self, guess): locations = [] for index, char in enumerate(list(self.word)): if char == guess: locations.append(index) return locations def update(self, idx, letter): for number in idx: self.display[number] = letter def check_guess(self, guess): if guess in self.word: idx = self.get_word_index(guess) self.update(idx, guess) def check_for_win(self): display = ''.join(self.display) word = self.word if display == word: print('You Win!!!') return True def game(): word = Hangman() while True: guess = input('guess a letter\n>>> ') word.check_guess(guess) word.show() word.guesses += 1 if word.check_for_win(): print(f'you\'ve won in {word.guesses} guesses!') break def loop(): while True: response = input('Do you want to play a game?') if response == 'no': break game() loop()
28d8091a488554191c40bb32dfd42a6d4ecaa4ee
Hana-Noorudheen/CG_LAB
/Extra_works/pattern.py
97
3.578125
4
for i in range(1,6): for x in range(i): print("*",end=" ") print("\n")
2bc983fc4b50355f771b34dc909b3c7b1eb607dd
technolingo/AlgoStructuresPy
/queue/index.py
503
3.96875
4
''' Create a queue data structure. The queue should be a class with methods 'enqueue' and 'dequeue'. --- Examples q = Queue() q.enqueue(1) q.dequeue() # returns 1; ''' class Queue: ''' A rudimentary queue ''' def __init__(self): self.lst = [] def enqueue(self, elem): self.lst.insert(0, elem) def dequeue(self): try: return self.lst.pop() except: return None def __repr__(self): return str(self.lst)
a75f041e351186c86ba29f4d12aa3ab4c3439b1a
technolingo/AlgoStructuresPy
/weave/queue.py
369
3.640625
4
#!/usr/bin/env python3 class Queue: def __init__(self): self.data = [] def enqueue(self, elem): self.data.insert(0, elem) def dequeue(self): try: return self.data.pop() except: return None def peek(self): try: return self.data[-1] except: return None
ceda1a0f1e1cae42099a7f86803e12bbf987c757
arresejo/enigma
/validation.py
2,468
3.703125
4
import re from abc import ABC from abc import abstractmethod class Validatable(ABC): @abstractmethod def validate(self, item): pass class Validator(ABC): def __init__(self, *validators): self.__validators = validators def validate(self, item): return all(map(lambda x: x.validate(item), self.__validators)) class TypeValidator(Validatable): def __init__(self, item_type): self.__item_type = item_type def validate(self, item): if not isinstance(item, self.__item_type): raise TypeError(f"must be a {self.__item_type.__name__}") return True class LengthValidator(Validatable): def __init__(self, item_len, compare_fct=lambda x, y: x == y): self.__item_len = item_len self.__compare_fct = compare_fct def validate(self, item): if not self.__compare_fct(len(item), self.__item_len): raise ValueError(f"length is invalid") return True class AlphaValidator(Validatable): def validate(self, item): if not str(item).isalpha(): raise ValueError("must be alphabetical") return True class UniqueValuesValidator(Validatable): def __init__(self, nb_unique, case_sensitive=False): self.__nb_unique = nb_unique self.__case_sensitive = case_sensitive def validate(self, item): if not self.__case_sensitive: item = str(item).lower() if len(set(item)) != self.__nb_unique: raise ValueError(f"must composed of {self.__nb_unique} unique values") return True class RegexValidator(Validatable): def __init__(self, regex): self.__regex = re.compile(regex) def validate(self, item): if not self.__regex.match(item): raise ValueError(f"must match with regex {self.__regex}") return True class RangeValidator(Validatable): def __init__(self, min_range, max_range, inclusive=True): self.__min_range = min_range self.__max_range = max_range self.__inclusive = inclusive def validate(self, item): if self.__inclusive: valid_range = self.__min_range <= item <= self.__max_range else: valid_range = self.__min_range < item < self.__max_range if not valid_range: raise ValueError(f"must be between {self.__min_range} and {self.__max_range}") return True if __name__ == "__main__": pass
dc06fc22506a86cbb14537349fffb4fbe1769394
jonasrauber/plotspikes.py
/example.py
859
3.828125
4
#!/usr/bin/env python from plotspikes import plotspikes from matplotlib import pyplot as plt import numpy as np def main(): """Example how to use plotspikes""" # create a figure and plot some random signal plt.figure(0, figsize=(15,3)) np.random.seed(22) xsignal = 20 * np.arange(100) ysignal = 6. + np.cumsum(np.random.randn(100)) plt.plot(xsignal, ysignal, 'm', hold=True) # create random spikes and plot them using plotspikes spiketimes = 40 * np.arange(0, 50) + 40 * np.random.randn(50) plotspikes(spiketimes, 'c-', -2.5, -1.5) # add labels plt.xlabel("time in ms") # save the plot without axes plt.axis('off') plt.savefig("images/example.png", bbox_inches='tight') plt.axis('on') # show the complete plot plt.show() if __name__ == "__main__": main()
383b602071ce487d64fe5c3302c64a10a3adb8a6
ltnguy16/Python-Practices
/Sudoku_Solver.py
1,592
3.8125
4
board = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] def print_board(board): for row in board: output = "" for value in row: output += str(value) + " " print(output) def find_zero(board): for row in range(len(board)): for col in range(len(board[row])): if board[row][col] == 0: return [row, col] return [] def is_valid(board, row, col, value): for i in range(len(board)): if board[i][col] == value: return False for i in range(len(board[row])): if board[row][i] == value: return False for i in range((row//3)*3,(((row//3)*3) + 3)): for j in range((col//3)*3,(((col//3)*3) + 3)): if board[i][j] == value: return False return True def solve(board): if find_zero(board) == []: return board new_board = board row, col = find_zero(new_board) for i in range(1,10): if is_valid(new_board, row, col, i): new_board[row][col] = i result = solve(new_board) if result == None: new_board[row][col] = 0 else: return result return None #result = solve(board) #print_board(result) #print(is_valid(board, 0, 2, 1)) #print(is_valid(board, 0, 2, 7)) #print(is_valid(board, 0, 2, 6)) #print(is_valid(board, 8, 7, 1)) #print(find_zero(board)) #print_board(board)
7884efac3e626ba6884d5e2d55d80582796b3552
Viswalahiri/Preprocessing-boilerplate
/feature_scaling.py
786
3.921875
4
## Feature Scaling import sklearn # we perform feature scaling since we must ensure that none of the dependant variables overlap on each other and thus are considered more important. # For example, when we perform euclidean distance on two columns, then we see that one is very much larger than the other, in which case we normalize. from sklearn.preprocessing import StandardScalar sc_X = StandardScalar() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) # Two types of features scaling exist, which are normalizing and standardizing # Should one go about feature scaling dummy variables? # For easy implementation - no # For higher accuracy - yes # Feature scaling should generally be done for the dependent variable as well, particularly during regression.
529681e15d29d0a98e1e4ac2c4c3309e82390219
aleche01/Travelling-Salesman-Problem
/Project/project_code.py
5,653
3.6875
4
# ENGSCI233: Project # Alex Chen # 500193517 # ache934 from project_utils import * import networkx as nx from time import time import numpy as np # start time t0 = time() # initial reading of files auckland = read_network('network.graphml') rest_homes = get_rest_homes('rest_homes.txt') # function for finding shortest length of the shortest path def closest_node(network, start, destinations): ''' Find the shortest length of the shortest path between a starting node and possible destinations. Parameters ---------- network : networkx.Graph The graph that contains the node and edge information start : str Name of the starting node. destinations : list List of possible destinations from the starting node. Returns ------- closest_node : str Name of node from the list of destinations that is closes to the starting node in the network. roads : list List of shortest path to take to get form the start node to the closest node. ''' # find the nearest node to the starting node closest_node = destinations[0] for i in destinations: if nx.shortest_path_length(network, start, i, weight='weight') < nx.shortest_path_length(network, start, closest_node, weight='weight'): closest_node = i roads = nx.shortest_path(network, start, closest_node, weight='weight') return closest_node, roads def nearest_neighbour_algorithm(network, start, destinations): ''' Algorithm which returns a list of nodes visited and the total path length Parameters ---------- network : networkx.Graph The graph that contains the node and edge information start : str Name of the starting node. destinations : list List of possible destinations from the starting node. Returns ------- nodes_visited : list Name of node from the list of destinations that is closes to the starting node in the network. total_path_length: int Length of the path in hours roads_list : list List of all the roads taken from start to finish in the path. ''' # initialise path list and total path length tracker nodes_visited = [start, ] total_path_length = 0 roads_list = [] while len(destinations) != 0: # find nearest node to starting node x, roads = closest_node(network, start, destinations) # remove this node from dest. list and add to path list destinations.remove(x) nodes_visited.append(x) # add roads to roads list roads_list.extend(roads) # add distance to running total of path length total_path_length = total_path_length + nx.shortest_path_length(network, start, x, weight='weight') start = x # return to airport nodes_visited.append('Auckland Airport') # add final distance total_path_length = total_path_length + nx.shortest_path_length(network, start, 'Auckland Airport', weight='weight') roads_list.extend(nx.shortest_path(network, start, 'Auckland Airport', weight='weight')) return nodes_visited, total_path_length, roads_list def text_map_gen(filename, nodes_visited, network, roads): ''' This function generates a .txt file of a path and a .png map of a path including the roads in-between. Parameters ---------- filename : str The filename of the generated output. nodes_visited : list A list of the nodes visited to form the path. network : networkx.Graph The graph that contains the node and edge information roads : list A list of the roads taken. ''' np.savetxt(filename+'.txt', nodes_visited, delimiter = "", newline = "\n", fmt="%s") plot_path(auckland, roads, save=filename) def list_splitter(list, network, longitude, latitude): ''' This function splits a list into four sub-lists based on longitude and latitude of the nodes within. Parameters ---------- list : list Original list to be split. network : networkx.Graph The graph that contains the node and edge information. longitude : float Longitude value to split east and west. latitude : float Latitude value to split north and south. Returns ------- list_1-4 : list Four separate lists ''' list_east = [] list_west = [] # split into east and west for i in rest_homes: if network.nodes[i]['lng'] < 174.78: list_west.append(i) else: list_east.append(i) # split into east and west lists into north and west list_1 = [] list_2 = [] list_3 = [] list_4 = [] for i in list_west: if network.nodes[i]['lat'] < -36.87: list_1.append(i) else: list_2.append(i) for i in list_east: if network.nodes[i]['lat'] < -36.95: list_3.append(i) else: list_4.append(i) return list_1, list_2, list_3, list_4 route_1, route_2, route_3, route_4 = list_splitter(rest_homes, auckland, 174.7, -36.9) # route 1 n1, l1, r1 = nearest_neighbour_algorithm(auckland, 'Auckland Airport', route_1) print(l1) text_map_gen('path_1', n1, auckland, r1) # route 2 n2, l2, r2 = nearest_neighbour_algorithm(auckland, 'Auckland Airport', route_2) print(l2) text_map_gen('path_2', n2, auckland, r2) # route 3 n3, l3, r3 = nearest_neighbour_algorithm(auckland, 'Auckland Airport', route_3) print(l3) text_map_gen('path_3', n3, auckland, r3) # route 4 n4, l4, r4 = nearest_neighbour_algorithm(auckland, 'Auckland Airport', route_4) print(l4) text_map_gen('path_4', n4, auckland, r4) # end time t1 = time() print('Completion time: {:3.2f} seconds'.format(t1-t0))
b3d7df6708a1c331b0632c1688a6fdddfba8fe16
tvarol/leetcode_solutions
/medianTwoArrays/findMedianSortedArrays_numpy.py
557
3.96875
4
#There are two sorted arrays nums1 and nums2 of size m and n respectively. #Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). import numpy as np class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ nums1.extend(nums2) nums1.sort() return np.median(nums1) nums1 = [1, 2] nums2 = [3,4] mySol = Solution() print(mySol.findMedianSortedArrays(nums1,nums2))
d2a852feb91c2ca56b39ca06588281110e325624
tvarol/leetcode_solutions
/addTwoNumbers/addTwoNumbers.py
1,188
3.90625
4
#You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. #You may assume the two numbers do not contain any leading zero, except the number 0 itself. #Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) #Output: 7 -> 0 -> 8 #Explanation: 342 + 465 = 807. class ListNode(self,x): self.val = x self.next = None class Solution: def addTwoNumbers(self,l1,l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ numbers=[0,0] for i in range(2): idx = 0 if i == 0: node = l1 else: node = l2 while node: numbers[i] += node.val*pow(10,idx) node = node.next idx += 1 twoSum = numbers[0] + numbers[1] dummyRoot = ListNode(0) ptr = dummyRoot for item in str(twoSum)[::-1]: ptr.next = ListNode(int(item)) ptr = ptr.next ptr = dummyRoot.next return ptr
b2c6835595f629bba3d6f59879d00c8948006522
tvarol/leetcode_solutions
/sortColors/sortColors.py
1,332
4.03125
4
#Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. #Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. #Note: You are not suppose to use the library's sort function for this problem. # https://leetcode.com/problems/sort-colors/discuss/26481/Python-O(n)-1-pass-in-place-solution-with-explanation # Beats 78% of submissions, 37 ms class Solution: def sortColors(self,nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ r = 0 #index of red w = 0 # index of white b = len(nums)-1 # index of blue while w <= b: if nums[w] == 0: nums[r], nums[w] = nums[w], nums[r] w += 1 r += 1 elif nums[w] == 1: w += 1 else: nums[w], nums[b] = nums[b], nums[w] b -= 1 nums = [2,0,2,1,1,0] mySol = Solution() mySol.sortColors(nums) print(nums) """ # Beats 8%, 57 ms for idx in range(1, len(nums)): while idx > 0 and nums[idx-1] > nums[idx]: nums[idx-1], nums[idx] = nums[idx], nums[idx-1] idx -= 1 """
3b8cdcb53800ece9e490f95c50ea0bb4f3a1d8df
pratamawijaya/learnpython
/helloworld/stringFormatting.py
412
3.953125
4
''' %s - String (or any object with a string representation, like numbers) %d - Integers %f - Floating point numbers %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot. %x/%X - Integers in hex representation (lowercase/uppercase) ''' name = "John Cenna" age = 30 print("%s is %d years old" % (name,age)) number = float(10000) print("number is %.2f" % (number))
4214b85a8864f4e177baab65cc99e3ef264a5f2c
KenMatsutaka/pythonSample
/sample14.py
394
3.578125
4
import numpy as np #1次元配列の生成 arr = np.asarray([1,2,3]) print('①', arr) #2次元配列の生成 arr = np.asarray([[1, 2, 3],[4, 5, 6]]) print('②', arr) #平均の取得 print('③', np.mean(arr)) # #最大値、最小値の取得 print('④', np.max(arr)) print('⑤', np.min(arr)) #和の取得 print('⑥', np.sum(arr)) #標準偏差の取得 print('⑦', np.std(arr))
9e6ce9d59e9dc0cfd0830e47723f1dd638fb7f26
KenMatsutaka/pythonSample
/sample09.py
786
3.578125
4
# csv : csvファイルを扱うライブラリ import csv import sys try: # CSVファイル書き込み # ファイルを開く with open('sample09.csv', 'w', encoding='utf8') as csvfile: #writerオブジェクトの生成 writer = csv.writer(csvfile, lineterminator='\n') #内容の書き込み writer.writerow(["a","b","c"]) writer.writerow(['あ','い','う']) # ファイルの読み込み # ファイルを開く with open('sample09.csv', 'r', encoding='utf8') as csvfile: # readerオブジェクトの生成 reader = csv.reader(csvfile) for row in reader: print(row) except FileNotFoundError as e: print(e) sys.exit() except csv.Error as e: print(e) sys.exit()
704e58c261aca0dedc7e1cb5a00c1f11b54d0f5f
JitendraDandekar/BasicPrograms
/Rolling Dice/RollingDice.py
774
3.515625
4
from tkinter import * import random root = Tk() root.geometry("300x350") root.title("Rolling Dice") photo = PhotoImage(file = "dice5.png") root.iconphoto(False, photo) header = Label(root, text="Hello..!!", font="Times 25 bold") header.pack(pady=10) #Images dice = ['dice1.png','dice2.png','dice3.png','dice4.png','dice5.png','dice6.png'] diceImage = PhotoImage(file = (random.choice(dice))) #widget for image img = Label(root, image=diceImage) img.image = diceImage img.pack(expand=True) #Function after button clicked def rolling(): diceImage = PhotoImage(file = (random.choice(dice))) img.configure(image=diceImage) img.image = diceImage btn = Button(root, text="Click Me!", font="Times 20 bold", command=rolling) btn.pack(pady=10) root.mainloop()
655e38557a1241686644ce8c74b9d43e68740f87
maelhos/InductorGen
/module/polygon.py
809
3.875
4
#!/usr/bin/env python3 # -.- coding: utf-8 -.- # InductorGen.polygon from module.utils import snaptogrid from math import cos,sin,radians # Defining the "poly" function wich take : # rad : radius of the circle # s : number of sides of the geometry def poly(radius, sides,a,s,ggg): # this function return an array on point for one geometry (one polygon) x = [] y = [] i = 1 if s == 4 : # i2 is weird but here are some values of it ... (in fact too much values are useless because we only do octagon ) i2 = 45+90 elif s == 8: i2 = 22.5 while i < sides + 1 : x.append(snaptogrid(radius*cos(radians(a+i2)),ggg)) y.append(snaptogrid(radius*sin(radians(a+i2)),ggg)) i += 1 i2 += a return x,y
baf7ec342ee0f56065d7e05a9cd67be4f936a367
allonbrooks/cainiao
/No4/未使用的最小的ID.py
1,264
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/2/20 11:00 # @Author : HandSome # @File : 未使用的最小的ID.py ''' 你需要管理大量数据,使用零基础和非负ID来使每个数据项都是唯一的! 因此,需要一个方法来计算下一个新数据项返回最小的未使用ID... 注意:给定的已使用ID数组可能未排序。出于测试原因,可能存在重复的ID,但你无需查找或删除它们! def next_id(arr): #your code here 测试用例: verify.assert_equals(next_id([0,1,2,3,4,5,6,7,8,9,10]), 11) verify.assert_equals(next_id([5,4,3,2,1]), 0) verify.assert_equals(next_id([0,1,2,3,5]), 4) verify.assert_equals(next_id([0,0,0,0,0,0]), 1) verify.assert_equals(next_id([]), 0) ''' class verify: @staticmethod def assert_equals(fun,res): assert fun == res,'error' # 方法一 def next_id(arr): t = 0 while t in arr: t += 1 return t if __name__ == '__main__': verify.assert_equals(next_id([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 11) verify.assert_equals(next_id([5, 4, 3, 2, 1]), 0) verify.assert_equals(next_id([0, 1, 2, 3, 5]), 4) verify.assert_equals(next_id([0, 0, 0, 0, 0, 0]), 1) verify.assert_equals(next_id([]), 0) verify.assert_equals(next_id([0, 0, 1, 1, 2, 2]), 3)
0c72edf860392975f00af289e83e860a16349892
allonbrooks/cainiao
/No11/1.用函数计算.py
2,795
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/2/27 9:29 # @Author : HandSome # @File : 1.用函数计算.py ''' 这次我们想用函数编写计算并得到结果。我们来看看一些例子: 例如: seven(times(five())); // must return 35 four(plus(nine())); // must return 13 eight(minus(three())); // must return 5 six(dividedBy(two())); // must return 3 ''' #方法二 class verify: @staticmethod def assert_equals(fun,res): assert fun == res,'error' ''' 值得学习的地方: 1、三元表达式,返回操作符的函数,并将当前参数传入 2、操作符函数使用了简洁的lambda表达式 3、lambda的写法还是挺难理解的,这里应该从里往外看,比如:eight(divided_by(four())) 应该先算出four()这个式子,然后再看divided_by(four())->lambda x: x/4 看得出来这个时候lambda还没有被调用 最后eight(operation)的时候,调用了当前的lambda 等效于 执行了 divided_by(4)(8) ''' def zero(f=None): return 0 if not f else f(0) def one(f=None): return 1 if not f else f(1) def two(f=None): return 2 if not f else f(2) def three(f=None): return 3 if not f else f(3) def four(f=None): return 4 if not f else f(4) def five(f=None): return 5 if not f else f(5) def six(f=None): return 6 if not f else f(6) def seven(f=None): return 7 if not f else f(7) def eight(f=None): return 8 if not f else f(8) def nine(f=None): return 9 if not f else f(9) def plus(y): return lambda x: x + y def minus(y): return lambda x: x - y def times(y): return lambda x: x * y def divided_by(y): return lambda x: x/y # #方法一 def zero(operation=None): return int(eval('0%s' % operation)) if operation else 0 def one(operation=None): return int(eval('1%s' % operation)) if operation else 1 def two(operation=None): return int(eval('2%s' % operation)) if operation else 2 def three(operation=None): return int(eval('3%s' % operation)) if operation else 3 def four(operation=None): return int(eval('4%s' % operation)) if operation else 4 def five(operation=None): return int(eval('5%s' % operation)) if operation else 5 def six(operation=None): return int(eval('6%s' % operation)) if operation else 6 def seven(operation=None): return int(eval('7%s' % operation)) if operation else 7 def eight(operation=None): return int(eval('8%s' % operation)) if operation else 8 def nine(operation=None): return int(eval('9%s' % operation)) if operation else 9 def plus(num): return '+%s' % num def minus(num): return '-%s' % num def times(num): return '*%s' % num def divided_by(num):return '/%s' % num if __name__ == '__main__': verify.assert_equals(seven(times(five())),35) verify.assert_equals(eight(minus(three())), 5) verify.assert_equals(four(plus(nine())), 13) verify.assert_equals(six(divided_by(two())), 3)
d5286f33dd6d3b53406f9bc4df05f60700ba2bab
ashrafishaheen/python_mini_projects
/rename.py
572
3.640625
4
import os def rename_files(): #(1) get file names from folder file_list = os.listdir(r"C:\Users\shahid\Downloads\Compressed\prank") #print(file_list) save_path = os.getcwd() print("Current Working Directory is"+save_path) os.chdir(r"C:\Users\shahid\Downloads\Compressed\prank") #(2) Rename each file name with removig numbers. for file_name in file_list: os.rename(file_name, file_name.translate(None, "0123456789")) os.chdir(save_path) rename_files()
f6970056797126b940373ecf3fd7f3092575b1e6
Yashkhatsuriya/java
/empinsert.py
917
3.78125
4
import mysql.connector; print("establish connection with mysql now"); con = mysql.connector.connect(host="localhost", database="employee", user="root", password=""); print("connection mydb",con); eno=input("enter employee no "); nm=input("enter name "); gen=input("enter gender "); if(gen == "male" or gen=="Male"): gender = "1"; elif(gen == "female" or gen=="Female"): gender = "0"; bdate=input("enter birthdate "); jdate=input("enter joindate "); bs=input("enter basic salary "); Insert= " Insert into emp11 values("; Insert=Insert+eno+","; Insert=Insert+"'"+nm+"',"; Insert=Insert+"'"+gender+"',"; Insert=Insert+bdate+","; Insert=Insert+jdate+","; Insert=Insert+bs+ ")"; cursor=con.cursor(); result=cursor.execute(Insert); con.commit(); print("sussesfullY inserted");
73261a25fbcbfac443b2f251ae11d9cc9557c541
ppkantorski/Astro_121
/Lab_1/Code/central_limit.py
3,355
4.21875
4
#!/usr/bin/env python # ========================================================================== # # File: central_limit.py # # Programmer: Patrick Kantorski # # Date: 02/09/14 # # Class: Astronomy 121 - Radio Astronomy Lab # # Time: T 6:00-9:00 PM # # Instructor: Aaron Parsons # # Description: This program was written in Python to demonstrate the # # "Central Limit Theorem." What this theorem purposes is that # # in the large-N limit, samples drawn from a non-Gaussian # # random distribution converge to a Gaussian distribution. # # Additionally, the standard deviation of the mean of N # # Gaussian-random samples should decrease as sqrt(N). # # ========================================================================== # import random as rn import numpy as np import matplotlib.pyplot as plt import sys def main(): print("-- Central Limit Theorem Demonstration --\n") dim = int(raw_input("Sample Size: ")) N = int(raw_input("N Random Samples: ")) b = int(raw_input("# Bars in Histogram: ")) Plot_Data(Gaussian_Distribution(dim, N, b), N, dim, b) def Gaussian_Distribution(dim, N, b): # Produces a Gaussian distribution from a non-Gaussian random distribution. sample_array = np.array([]) mean_array = np.array([]) for x in range(0,N): for x in range(0, dim): sample_array = np.r_[sample_array, rn.random()] mean_array = np.r_[mean_array, np.mean(sample_array)] sample_array = np.array([]) return mean_array def Standard_Dev_Test(N, b): # Performs an Allen variance test on the random distribution. std_array = np.array([]) for x in [1, 2, 3, 6, 10, 20, 30, 60, 100, 200, 300, 600, 1000]: m_array = Gaussian_Distribution(x, N, b) std_array = np.r_[std_array, np.std(m_array)] return std_array def STD_vs_N(dim, b): # Plots the standard deviation vs N samples. std_array2 = np.array([]) axis = 10.**((np.arange(100.) + 1.) / (100./3.)) axis = axis.astype(int) for x in axis: m_array2 = Gaussian_Distribution(dim, x, b) std_array2 = np.r_[std_array2, np.std(m_array2)] return std_array2 def Plot_Data(mean_array, N, dim, b): # Calls and plots data from the previous three functions. print("\nGaussian Distribution:") print("~ For continuous distribution from [0, 1]...") plt.hist(mean_array, bins = b) plt.show() pause1 = raw_input("\nHit enter to continue... ") print("\nStandard Deviation Test:") print("~ For sample size from [1, 1000]...") plt.loglog([1, 2, 3, 6, 10, 20, 30, 60, 100, 200, 300, 600, 1000], Standard_Dev_Test(N, b), 'o') plt.show() pause2 = raw_input("\nHit enter to continue... ") print("\nStandard Deviation vs N-samples:") print("~ For N ranging from [1, 10000]...") y = STD_vs_N(dim, b) avg = np.average(y[30:-1]) axis = 10.**((np.arange(100.) + 1.) / (100./3.)) axis = axis.astype(int) plt.plot(axis, y, 'o') plt.plot(range(1000), np.zeros(1000) +avg) plt.xscale("log") plt.show() print("\nTests are complete!\n") if __name__ == '__main__': main() sys.exit()
5d8dcb0e6652829d9db011912689507f9c876fd6
dpalma9/cursoITNowPython
/conceptos/11-operaciones-masivas-colecciones.py
776
3.828125
4
lista=[1,2,3,4,5,6,7,8,9] pares= [item for item in lista if item % 2 == 0] print(pares) diccionario={"clave1":"valor1", "clave2":"valor2", "clave3":"valor3"} lista2=[valor for clave, valor in diccionario.items() if clave == "clave1" or clave == "clave2"] print(lista2) otro_diccionario={clave:valor for clave, valor in diccionario.items() if clave == "clave1" or clave == "clave2"} print(otro_diccionario) #otra_lista=filter(funcion_de_filtro,coleccion) otra_lista=list(filter(lambda numero: numero % 2 == 1,lista)) print(otra_lista) #otra_coleccion=map(funcion,coleccion) # De forma que en la nueva coleccion estarán los resultados de aplicar # la funcion de mapeo sobre los elementos originales otra_lista=list(map(lambda numero: numero*2,lista)) print(otra_lista)
5a6da2154ad5803c1f50e463547ce8b76dfed593
dpalma9/cursoITNowPython
/conceptos/10-orientacion-a-objetos-4.py
329
3.609375
4
class Servicio: def __init__(self,nombre,servidor): self.nombre=nombre self.servidor=servidor def __str__(self): return "Soy el servicio: "+self.nombre +", disponible en el servidor: "+self.servidor un_servicio=Servicio("Google","google.es") print(un_servicio)
4927e7e65dbc4c19d8b03e6e57827c3b9bd2fc6f
sirisha-8/Array-3
/h_index.py
436
3.578125
4
#Time Complexity: O(N) #Space Complexity: O(N) class Solution: def hIndex(self, citations: List[int]) -> int: n = len(citations) counts = [0]*(n+1) for item in citations: if item>=n: counts[n]+=1 else: counts[item]+=1 papers = 0 for i in range(n,-1,-1): papers+=counts[i] if papers>=i: return i
d22c3655414193408a1207fc0e310473a3da7257
lyz21/MachineLearning
/SIR_Model_1/test/test1.py
3,126
3.546875
4
# encoding=utf-8 """ @Time : 2020/4/19 16:32 @Author : LiuYanZhe @File : test1.py @Software: PyCharm @Description: """ import numpy as np from scipy.optimize import minimize import pandas as pd def test_zip(): np1 = np.random.rand(5, 2) print(np1) # a = [1, 2, 3] # b = [5, 6] # c = [7, 8, 9] for a, b, c in zip([np1[:, 0], np1[:, 1]], ['red', 'black'], ['line1', 'line2']): print(a, b, c) def test_linspace(): np1 = np.linspace(1, 360, 360) # 1-360分成360份 print(np1) def test_lambda(): y = lambda x: x ** 2 print(y(9)) # 输出81 def test_asarry(): x0 = np.asarray((5)) print(x0) def test_scipy_optimize_minimize(): # 反向传播求最优值。即求y最小时的x值 def fun1(parameters, arg): # 参数为要优化的变量 a, b = parameters y = 0 for x in arg: y += a ** 2 * x ** 2 + b ** 2 return y # minimize(fun, x0, args=()),fun :优化的目标函数,x0 :初值,一维数组,shape (n,),args : 元组,可选,额外传递给优化函数的参数 min = minimize(fun1, x0=[0.1, 0.21], args=([1, 2, 3, 4])) # 此方法求出不准确,且依赖初始值 print(min) print('min_y=', min.fun, '; min(a,b)=', min.x) def test_data1(): add_days = 39 # 从封城开始 pd1 = pd.read_csv('../data/History_country_2020_04_19.csv').iloc[4193 + add_days:4271, :].loc[:, ('date', 'total_confirm', 'total_dead', 'total_heal', 'name')] print(pd1.values) def test_data2(): add_days = 39 # 从封城开始 pd1 = pd.read_csv('../data/History_country_2020_04_19.csv').iloc[4193 + add_days:4271, :].loc[:, ('date', 'today_confirm', 'today_heal', 'today_dead', 'name')] print(pd1.values) def test_list(): list1 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) list2 = 2 * list1 + 3 print(list2) def test_list2(): list1 = [1, 2, 3, 4] a = max(list1) sub = list1.index(a) print(sub) def test_list3(): list1 = [1, 2] list2 = [3, 4] list3 = list1 + list2 print(list3) def test_add(i): i += 1 return i def test_range(): l = np.zeros([2, 2]) print(l) def test_list_0430(): # 二维数组求最大值 list1 = [[1, 2], [3, 4]] print(min(list1)) def merge(s_list): size = len(s_list) for i in range(size): for j in range(size): x = list(set(s_list[i] + s_list[j])) y = len(s_list[i]) + len(s_list[j]) if i == j or s_list[i] == 0 or s_list[j] == 0: break elif len(x) < y: s_list[i] = x s_list[j] = [0] for item in s_list: if item == [0]: s_list.remove(item) print(s_list) if __name__ == '__main__': # test_zip() # test_linspace() # test_lambda() # test_asarry() # test_scipy_optimize_minimize() # test_data2() # test_list() # test_list2() # test_list3() # i = 1 # j = test_add(i) # print(i, j) # test_range() # test_list_0430() merge([[1, 2], [3, 4], [0, 1]])
410707b20bf8289a43f7f2a9c151631ae0db6440
lyz21/MachineLearning
/SIR_in_Model_1/test/test_data.py
834
3.609375
4
# encoding=utf-8 """ @Time : 2020/5/6 17:08 @Author : LiuYanZhe @File : test_data.py @Software: PyCharm @Description: 关于数据的测试 """ import pandas as pd import numpy as np def test_pd1(): df = pd.read_csv('../data/History_country_2020_05_06.csv') list1 = df[df.name == '突尼斯'].index.tolist() df2 = df.iloc[list1[0]:list1[len(list1) - 1], :] print(df2) return df2 def test_pd2(): df = test_pd1() date = str(df.loc[0, 'date']) print(date, type(date)) date_list = date.split('-') print(date_list) print(int(date_list[0])) print(int(date_list[1])) def test_list(): list1 = np.array([1, 2, 3]) list2 = np.array([2, 6, 9]) b = 10 list2 = list1 / list2 * b print(list2) if __name__ == '__main__': # test_pd1() # test_pd2() test_list()
711646003de502ae59915ebcd3fff47b56b0144d
Wh1te-Crow/algorithms
/sorting.py
1,318
4.21875
4
def insertion_sorting(array): for index in range(1,len(array)): sorting_part=array[0:index+1] unsorting_part=array[index+1:] temp=array[index] i=index-1 while(((i>0 or i==0) and array[i]>temp)): sorting_part[i+1]=sorting_part[i] sorting_part[i]=temp i-=1 array=sorting_part+unsorting_part return(array) def bubble_sorting(array): indicator_of_change=1 index_of_last_unsorted=len(array) while(indicator_of_change): indicator_of_change=0 for index in range(0,index_of_last_unsorted-1): if (array[index]>array[index+1]): temp=array[index] array[index]=array[index+1] array[index+1]=temp indicator_of_change+=1 index_of_last_unsorted-=1 return array def sorting_by_choice(array): sorting_array=[] while(len(array)>0): minimum = array[0] for index in range(1,len(array)): if minimum>array[index]: minimum=array[index] array.remove(minimum) sorting_array.append(minimum) return sorting_array print(insertion_sorting([1,2,3,8,9,0,-1,-5,0])) print(bubble_sorting([1,2,3,8,9,0,-1,-5,0])) print(sorting_by_choice([1,2,3,8,9,0,-1,-5,0]))
a450f6ff1ab86cad9d68483c879268fa73c7881e
HoneczyP/Sal-s-Shipping
/ss.py
1,503
3.953125
4
# Cost of ground shipping def cost_ground_ship(weight): flat_charge = 20.00 if weight <= 2: return flat_charge + 1.50 * weight elif 2 < weight <= 6: return flat_charge + 3.00 * weight elif 6 < weight <= 10: return flat_charge + 4.00 * weight else: return flat_charge + 4.75 * weight # Cost of drone shipping def cost_drone_ship(weight): flat_charge = 0.00 if weight <= 2: return flat_charge + 4.50 * weight elif 2 < weight <= 6: return flat_charge + 9.00 * weight elif 6 < weight <= 10: return flat_charge + 12.00 * weight else: return flat_charge + 14.25 * weight # Cost of premium shipping cost_premium = 125.00 # Function for cheapest method def cheapest_ship(weight): ground = cost_ground_ship(weight) drone = cost_drone_ship(weight) premium = cost_premium = 125.00 if ground < drone and ground < premium: print("The ground shipping method is the cheapest for you. With your package it is cost $" + str(ground) + ".") elif drone < ground and drone < premium: print("The drone shipping method is the cheapest for you. With your package it is cost $" + str(drone) + ".") else: print("The premium shipping method is the cheapest for you. It is cost $" + str(premium) + ".") #TEST CODE print(cost_ground_ship(8.4)) #$53.60 print(cost_drone_ship(1.5)) #$6.75 cheapest_ship(17) #$100.75 ground cheapest_ship(4.8) #$34.40 ground cheapest_ship(41.5) #$125.00 premium
16a3e3acee1e28ba12e638c7dff9dedb0a5a4056
cwczarnik/Python_Practice
/Project Euler/probtest2.2.py
279
3.734375
4
import numpy from numpy import * a = [] for i in range(1,6): print(i) a.append(i) print(a) a.append("hello") print(a) ## ##def fib(n): ## fibarray = [] ## a, b = 0, 1 ## while b < n: ## fibarray.append(b) ## a, b = b, a+b ## print fibarray
df89b847a4ea040e1d373e19b7b345ead0ee7d8e
cwczarnik/Python_Practice
/Computational/sodiumchloride.py
336
3.6875
4
from visual import sphere,color count = 3 R=0.3 for x in range(-count,count+1): for y in range(-count,count+1): for z in range(-count,count+1): if ((x+y+z)%2) == 0: sphere(pos=[x,y,z],radius=R,color=color.green) else: sphere(pos=[x,y,z],radius=R,color=color.yellow)
6013c234451639ee65be29212fb9a46b1f52af8e
ManaliKulkarni30/Python_Practice_Programs
/Iteration1.py
372
3.640625
4
def StartDynamic(No,message = "Jay Ganesh"): iCnt = 0 while iCnt < No: print(message) iCnt = iCnt + 1 def main(): print("How many times do you want output:") no = int(input()) print("Enter a message you want to print:") msg = input() StartDynamic(no,msg) StartDynamic(no) if __name__ == "__main__": main()
714c641e13e016bf79f45239f2cd031aa0eb8701
ManaliKulkarni30/Python_Practice_Programs
/file.py
215
3.640625
4
def main(): name = input("Enter the name of file:") fobj = open(name,"w") str = input("Enter the data you want to write in file") fobj.write(str) if __name__ == '__main__': main()
b147f4dd4bc5cb2cb53beb8aa5a3925dca541265
ManaliKulkarni30/Python_Practice_Programs
/Exc1.py
204
3.8125
4
def main(): no1 = int(input("Enter first number: ")) no2 = int(input("Enter second number: ")) ans = no1 / no2 print("Divison is: ",ans) if __name__ == '__main__': main()
3d1c22b0705f618b43e9a19f93a54bcb91b88c7f
ManaliKulkarni30/Python_Practice_Programs
/Exc2.py
317
3.640625
4
def main(): no1 = int(input("Enter first number: ")) no2 = int(input("Enter second number: ")) try: ans = no1 / no2 except Exception as eobj: print("Exception occurs:",eobj) else: print("Divison is: ",ans) if __name__ == '__main__': main()
0ebeaa2cd19ec1f27932f32447af1ea72268f8b5
ManaliKulkarni30/Python_Practice_Programs
/selection.py
352
3.875
4
#14 Feb 2021 #Selection import MrvellousNumber as mn def main(): no = int(input("Enter a number:")) bRet = m.chkEven(no) if bRet == True: print("No {} is even".format(no)) else: print("No {} is odd".format(no)) if __name__ == "__main__": main() #Camel Case: chkEven #Hungerian Case : CheckEven
1ecd5f97b22e0044c21d614dc6390bf0c978f1aa
ManaliKulkarni30/Python_Practice_Programs
/List1.py
338
3.765625
4
def DisplayL(list): iCnt = 0 for iCnt in range(len(list)): print(list[iCnt]) def main(): arr = [10,20,30,40,50] print(arr) print(arr[3]) #we can store heterogenous data in list Brr =[10,"Manali",66.48,"Pune"] print(Brr) DisplayL(arr) if __name__ == "__main__": main()
833e39fe7b287f67970d39eca9dbb911a5da9220
KevOrr/Tide-Clock
/control/station_selector.py
1,467
3.515625
4
#!/usr/bin/env python3 import sys from math import sin, cos, acos, radians, sqrt, pi import json from control.util import get_abs_path USAGE = '%s lat lon' % sys.argv[0] IN_FILE = get_abs_path('stations.json') # https://en.wikipedia.org/wiki/Great-circle_distance#Formulas # All angles in radians def get_angle(lat1, lon1, lat2, lon2): return acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(lon2 - lon1)) #dlat = lat1 - lat2 #dlon = lon1 - lon2 #return 2*asin(sqrt(sin(dlat/2)**2 + cos(lat1)*cos(lat2)*sin(dlon/2)**2)) # All angles in degrees def get_closest_station(lat, lon): lat = radians(lat) lon = radians(lon) with open(IN_FILE) as f: stations = json.load(f) min_angle = 2*pi for station, meta in stations.items(): angle = get_angle(lat, lon, radians(float(meta['lat'])), radians(float(meta['lon']))) if angle <= min_angle: min_angle = angle closest_station = station return closest_station if __name__ == '__main__': try: lat = float(sys.argv[1]) lon = float(sys.argv[2]) except (IndexError, ValueError): print(USAGE) sys.exit(1) with open(IN_FILE) as f: stations = json.load(f) closest_station = get_closest_station(lat, lon) print('{}: {}'.format(closest_station, stations[closest_station]['name'])) print('{}, {}'.format(stations[closest_station]['lat'], stations[closest_station]['lon']))
315bc09a11f42cd7b010bee38ac8fa52d06e172c
calazans10/algorithms.py
/basic/var.py
242
4.125
4
# -*- coding: utf-8 -*- i = 5 print(i) i = i + 1 print(i) s = '''Esta é uma string de múltiplas linhas. Esta é a segunda linha.''' print(s) string = 'Isto é uma string. \ Isto continua a string.' print(string) print('O valor é', i)
e47ac33a8196b93669f7ee2217eefeafbe99ef45
calazans10/algorithms.py
/data structs/str_methods.py
368
3.984375
4
# -*- coding: utf-8 -*- nome = 'Jeferson' if nome.startswith('Jef'): print('Sim, a string começa com "Jef"') if 'e' in nome: print('Sim, ela também contém a string "e"') if nome.find('son') != -1: print('Sim, ela contém a string "son"') delimitador = '_*_' minhalista = ['Brasil', 'Russia', 'Índia', 'China'] print(delimitador.join(minhalista))
ac6d580d3ae712924c44bd4bdffbf4b15e3cf88e
calazans10/algorithms.py
/functions/func_doc.py
292
4.03125
4
# -*- coding: utf-8 -*- def printMax(x, y): """Imprime o maior entre dos números. Os dois valores devem ser inteiros.""" x = int(x) y = int(y) if x > y: print(x, 'é o maior') else: print(y, 'é o maior') printMax(3, 5) print(printMax.__doc__)
34ae06f5fea1a3886a7208998a729c3900280424
gugry/FogStreamEdu
/lesson1_numbers_and_strings/string_tusk.py
261
4.125
4
#5.Дана строка. Удалите из нее все символы, чьи индексы делятся на 3. input_str = input() new_str = input_str[0:3]; for i in range(4,len(input_str), 3): new_str = new_str + input_str[i:i+2] print (new_str)
358cd42a66be05b4606d01bcb525afa140181ccc
PRASADGITS/shallowcopyvsdeepcopy
/shallow_vs_deep_copy.py
979
4.5
4
import copy ''' SHALLOW COPY METHOD ''' old_list = [[1,2,3],[4,5,6],[7,8,9]] new_list=copy.copy(old_list) print ("old_list",old_list) print ("new_list",new_list,"\n") old_list.append([999]) print ("old_list",old_list) print ("new_list",new_list,"\n") old_list[1][0]="x" # both changes Because the refernce is same for nested objects in shallow copy, # poinsta to the same object in memory print ("old_list",old_list) print ("new_list",new_list,"\n") ''' Deep copy method ''' print ("Deep copy starts \n") old_list_1 = [[1,2,3],[4,5,6],[7,8,9]] new_list_1=copy.deepcopy(old_list_1) print ("old_list_1",old_list_1) print ("new_list_1",new_list_1,"\n") old_list_1.append([999]) print ("old_list_1",old_list_1) print ("new_list_1",new_list_1, "\n") old_list_1[1][0]="x" # Because the old list was recursively copied print ("old_list_1",old_list_1) print ("new_list_1",new_list_1)
6f68a4199b712c59b6edcce230f7946e8b1ed612
rad5ahirui/data_structure_and_algorithms
/chapter5/hanoi.py
355
3.625
4
#!/usr/bin/env python3 # coding: utf-8 a = [] b = [] c = [] def move(n, x, y, z): if n > 0: move(n - 1, x, z, y) z.append(x.pop()) print('Move:', a, b, c,sep='\n') move(n - 1, y, x, z) def main(): global a a = [3, 2, 1] print(a, b, c,sep='\n') move(3, a, b, c) if __name__ == '__main__': main()
83c79053f124896efc381a7e5f60a9ad0c1ce1fa
rad5ahirui/data_structure_and_algorithms
/chapter6/p6_1.py
1,326
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from abc import ABC, abstractmethod from p6_2 import Stack from p6_3 import Queue class A(ABC): @abstractmethod def add(self, x): pass @abstractmethod def pop(self): pass @abstractmethod def empty(self): pass class AStack(A): def __init__(self, n): self.stack = Stack(n) def add(self, x): self.stack.push(x) def pop(self): return self.stack.pop() def empty(self): return self.stack.empty() class AQueue(A): def __init__(self, n): self.que = Queue(n) def add(self, x): self.que.insert(x) def pop(self): return self.que.get() def empty(self): return self.que.empty() def graph_search(initial_v, T, a): # a must be empty b = set() # visited a.add(initial_v) b.add(initial_v) while not a.empty(): v = a.pop() print(f'{v} -> ', end='') for u in T[v]: if u not in b: a.add(u) b.add(u) print('END') return b def main(): T = [[1, 2], [3, 4], [5], [], [], [6], []] print('(1)') print(graph_search(0, T, AQueue(len(T)))) print('(2)') print(graph_search(0, T, AStack(len(T)))) if __name__ == '__main__': main()
f91cfa00ce619f708d72448c83c1f76a704448fe
a6741/some-python-code-which-was-wrote-when-I-was-boring
/untitled12.py
530
3.703125
4
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np time = [i for i in range(0,19)] number = [9.6,18.3,29,47.2,71.1,119.1,174.6,257.3, 350.7,441.0,513.3,559.7,594.8,629.4,640.8, 651.1,655.9,659.6,661.8] plt.title('Relationship between time and number')#创建标题 plt.xlabel('time')#X轴标签 plt.ylabel('number')#Y轴标签 plt.plot(time,number)#画图 #plt.show()#显示 F=np.polyfit(time,number,3) print(F) y=np.polyval(F,time) plt.plot(time,y) plt.show()#显示
ba0bf77d3202493747e94c0a686c739d6cb98e9f
srisreedhar/Mizuho-Python-Programming
/Session-18-NestedConditionals/nestedif.py
510
4.1875
4
# ask user to enter a number between 1-5 and print the number in words number=input("Enter a number between 1-5 :") number=int(number) # if number == 1: # print("the number is one") # else: # print("its not one") # Nested conditions if number==1: print("number is one") elif number==2: print("number is two") elif number==3: print("number is Three") elif number==4: print("number is Four") elif number==5: print("number is Five") else: print("The number is out of range")
3b413b76a9d13081098a6305627c63da576d5a28
lgigek/alura
/python3-oo-avançado/model.py
1,805
3.75
4
class TvShow: def __init__(self, name, year, ): self._name = name.title() self.year = year self._likes = 0 def like(self): self._likes += 1 @property def name(self): return self._name @property def likes(self): return self._likes @name.setter def name(self, value): self._name = value def __str__(self): return f'{self._name} - {self.year}: {self._likes} likes' class Movie(TvShow): def __init__(self, name, year, duration): super().__init__(name, year) self.duration = duration def __str__(self): return f'{self._name} - {self.year} - {self.duration} minutes: {self._likes} likes' class Series(TvShow): def __init__(self, name, year, season): super().__init__(name, year) self.season = season def __str__(self): return f'{self._name} - {self.year} - {self.season} seasons: {self._likes} likes' class Playlist: def __init__(self, name, shows): self.name = name self._shows = shows def __getitem__(self, item): return self._shows[item] def __len__(self): return len(self._shows) avengers = Movie("avengers - infinity war", 2018, 160) got = Series("game of thrones", 2015, 7) tamarindo_adventures = Movie("tamarindo adventures", 2018, 20000) holy_querupita = Series("holy querupita", 2017, 5) tamarindo_adventures.like() tamarindo_adventures.like() tamarindo_adventures.like() holy_querupita.like() holy_querupita.like() avengers.like() got.like() got.like() tv_shows = [avengers, got, tamarindo_adventures, holy_querupita] weekend_playlist = Playlist('Weekend playlist', tv_shows) print(f"Playlist length: {len(weekend_playlist)}") for show in weekend_playlist: print(show)
4a4f19c2ab1fe0b6079b4954d0697cb0f8433b3e
tarzioo/AnAlgorithmADay2018
/Day-24/isSameTree.py
1,194
3.6875
4
# Day 24/365 #AnAlgorithmAday2018 # Problem is from Leetcode 100 # # Same Tree # #GGiven two binary trees, write a function to check if they are the same or not. # #Two binary trees are considered the same if they are structurally identical and the nodes have the same value. # # #Example 1: # #Input: 1 1 # / \ / \ # 2 3 2 3 # # [1,2,3], [1,2,3] # #Output: true #Example 2: # #Input: 1 1 # / \ # 2 2 # # [1,2], [1,null,2] # #Output: false #Example 3: # #Input: 1 1 # / \ / \ # 2 1 1 2 # # [1,2,1], [1,1,2] # #Output: false ######################################################################################################################## class TreeNode(object): def __init__(self, x): self.val = x: self.right = None self.left = None class Solution(object): def isSameTree(self, tree1, tree2): if tree1 and tree2: return tree1.val == tree2.val and self.isSameTree(tree1.left, tree2.left) and self.isSameTree(tree1.right, tree2.right) return tree1 is tree2
242a80f4856b65906c9c51d8a0ee2d1b0bc63ec5
tarzioo/AnAlgorithmADay2018
/Day-4/reverseBits.py
642
3.53125
4
# Day 4/365 #AnAlgorithmAday2018 # Problem is from Leetcode 190 # # Reverse bits of a given 32 bits unsigned integer. # #For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as #00111001011110000010100101000000). # #Follow up: #If this function is called many times, how would you optimize it? ######################################################################################################################## def reverseBits(n): binary = '{0:032b}'.format(n) rev = "" for item in binary: rev = item + rev return int(rev, 2)
363363bf8cfe4a9e583310722c2657693a15648e
tarzioo/AnAlgorithmADay2018
/Day-11/containsDuplicate.py
749
3.640625
4
# Day 11/365 #AnAlgorithmAday2018 # Problem is from Leetcode 217 # # Contains Duplicate # #Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least #twice in the array, and it should return false if every element is distinct. # # ######################################################################################################################## def containsDuplicate(nums): if not nums: return False values = {} for item in nums: values[item] = values.get(item, 0) + 1 for key, value in values.iteritems(): if value >= 2: return True return False
6331a3de630ca916cee1eb3294bf9153b059824a
himichael/Cracking_the_Coding_Interview
/10.01.合并排序的数组/sorted-merge-lcci.py
502
3.625
4
class Solution(object): def merge(self, A, m, B, n): """ :type A: List[int] :type m: int :type B: List[int] :type n: int :rtype: None Do not return anything, modify A in-place instead. """ if not A or not B: return A if A else B i = m-1 j = n-1 tail = m+n-1 while i>=0 or j>=0: if i==-1: A[tail] = B[j] j -= 1 elif j==-1: A[tail] = A[i] i -= 1 elif A[i]>=B[j]: A[tail] = A[i] i -= 1 else: A[tail] = B[j] j -= 1 tail -= 1
858e0b0d2aa236a806f37a17fb11beef01c9d365
muskankhurana053/games
/tictactoegame.py
2,191
3.9375
4
import sys print("""hey player yu can enter your input by choosing a number from 1-9 1|2|3 ----- 4|5|6 ----- 7|8|9 """) board=[" "," "," "," "," "," "," "," "," "] def disp(): print(f"{board[0]}|{board[1]}|{board[2]}") print("_____") print(f"{board[3]}|{board[4]}|{board[5]}") print("_____") print(f"{board[6]}|{board[7]}|{board[8]}") def onepl(): posi=int(input("player1 enter the position you want to choose")) if board[posi-1]==" ": board[posi-1]="X" else: print("That position is occupied, kindly pick another") onepl() def twopl(): posi=int(input("player2 enter the position you want to choose")) if board[posi-1]==" ": board[posi-1]="0" else: print("That position is occupied, kindly pick another") twopl() def statuscheck(): if(board[0]==board[1]==board[2]=="X"or board[3]==board[4]==board[5]=="X" or board[6]==board[7]==board[8]=="X" or board[1]==board[4]==board[7]=="X" or board[0]==board[3]==board[6]=="X" or board[2]==board[5]==board[8]=="X" or board[0]==board[4]==board[7]=="X" or board[2]==board[4]==board[6]=="X"): print('congratulation!!player1 is the winner') sys.exit() elif(board[0]==board[1]==board[2]=="0"or board[3]==board[4]==board[5]=="0" or board[6]==board[7]==board[8]=="0" or board[1]==board[4]==board[7]=="0" or board[0]==board[3]==board[6]=="0" or board[2]==board[5]==board[8]=="0" or board[0]==board[4]==board[7]=="0" or board[2]==board[4]==board[6]=="0"): print('congratulation!!player2 is the winner') sys.exit() elif(board[0]!=" "and board[1]!=" " and board[2]!=" " and board[3]!=" " and board[4]!=" " and board[5]!=" " and board[6]!=" " and board[7]!=" " and board[8]!=" "): print('its a tie') sys.exit() def runcode(): i=1 while i<=5: onepl() disp() statuscheck() twopl() disp() statuscheck() i+=1 runcode()
cfdd7c6c577c38c42822bc9ec361d948e0adb63c
H-Cavid/LessonTasks
/task06.py
329
3.765625
4
# sort methodundan istifade olunacaq # sort()elifba sirasi ve ya artan sira ile gosterir # sort(reverse=True) elifba sirasinin eksi,azalan sira ile gosterecek L = [3, 6, 7, 4, -5, 4, 3, -1] #1. if sum(L)>2: print(len(L)) #2. if abs(max(L)-min(L))>10: print(sorted(L)) else: print("Ferq 10-dan kichik-beraberdir.")
a3c3b97acacaa48621f0fd0339d3695176bb56f7
JuanLengyel/mintic_learning_python_contact_directory_interface
/contact_book.py
2,348
3.734375
4
import csv from contact import Contact class ContactBook: def __init__(self): self._contacts = [] self._load() def add(self, name, phone, email): self._contacts.append(Contact(name, phone, email)) self._save() def remove(self, name): try: self._contacts.remove(self._search(name)) except ValueError: self._not_found(name) finally: self._save() def searchAndPrint(self, name): try: self._print_contact(self._search(name)) except AttributeError: self._not_found(name) def update(self, name): try: foundContact = self._search(name) foundContact.set_name(str(raw_input("Input updated name: "))) foundContact.set_phone(str(raw_input("Input updated phone: "))) foundContact.set_email(str(raw_input("Input updated email: "))) except AttributeError: self._not_found(name) finally: self._save() def show_contacts(self): map(lambda contact: self._print_contact(contact), self._contacts) def _print_contact(self, contact): print("***-----------------------****") print("Name: {}".format(contact.get_name())) print("Phone: {}".format(contact.get_phone())) print("Email: {}".format(contact.get_email())) print("***-----------------------****") def _not_found(self, name): print("The contact with name {} was not found".format(name)) def _search(self, name): for contact in self._contacts: if (contact.get_name().lower() == name.lower()): return contact break else: return AttributeError def _save(self): with open("contacts.csv", "w") as f: f.write("name,phone,email\n") f.write(str.join("\n", map(lambda contact: "{},{},{}".format(contact.get_name(), contact.get_phone(), contact.get_email()), self._contacts))) f.close def _load(self): with open('contacts.csv', 'r') as f: reader = csv.reader(f) for idx, row in enumerate(reader): if idx < 1: continue self._contacts.append(Contact(row[0], row[1], row[2]))
13257e9375fe5674e7940b95610a68fa2ee8c79e
lruczu/learning
/natural_language_processing/ner/training/processing.py
490
3.546875
4
import re def normalize(text: str) -> str: text = re.sub('\([^\s]*?\)', '', text) # one word in bracket text = re.sub('\[[^\s]*?\]', '', text) text = re.sub('\{[^\s]*?\}', '', text) text = text.strip() text = re.sub(' +', ' ', text) text = re.sub(' ,', ',', text) text = re.sub(' ;', ';', text) text = re.sub(' \.', '\.', text) text = re.sub(' !', '!', text) text = re.sub(' \?', '\?', text) text = re.sub(' +', ' ', text) return text
2b2b2dcc0c42190451e919ae7297fe633087fa7e
sthasuman/Assign
/File.py
1,435
3.6875
4
import csv class VDC(object): def __init__(self, district, name, number ,pop_male,pop_female): self.district = district self.name = name self.number = number self.pop_male = pop_male self.pop_female = pop_female def __str__(self): return str("District: %s, Name: %s, Total_Households: %s, Male Population: %s, Female Population: %s, Total_population: %s " % (self.district , self.name , self.number , self.pop_male , self.pop_female , int(self.pop_male)+int(self.pop_female))) with open ('population.csv', "r") as file: reader = csv.reader(file) my_list = list(reader) #Print the list for i in range (1, len(my_list),3): new = VDC(my_list[i][0], my_list[i][1], my_list[i][3], my_list[i+1][3],my_list[i+2][3]) if not my_list [i][3].isdigit(): my_list[i+1] #skip the list if string in 4th column is not digit else: print (new) #print the list # User Input def checkvdc(name): for i in range (1, len(my_list),3): if not my_list [i][3].isdigit(): print ("Not Found") break else: new = VDC(my_list[i][0], my_list[i][1], my_list[i][3], my_list[i+1][3],my_list[i+2][3]) if name.lower() == my_list[i][1].lower(): return (new) vdcname = input ("\nEnter the VDC name:") print (checkvdc(vdcname))
9284b5980c6c04f0a322cdab5ed48ae617a16c59
varnitsaini/python-graphs
/AdjacencyList.py
3,280
4.375
4
""" Illustrating adjacency list in undirected graph Two classes are used, one for adding new Verted and one for Graph class. Space Complexity : O(|V| + |E|) Time Complexity : O(|V|) Where |V| -> vertex |E| -> edge """ """ Creating vertex for adjacency list """ class Vertex: """ defining the constructor for vertex class, which will have parameters id and edges to which it is connected to """ def __init__(self,key): self.id = key self.connectedTo = {} """ adding an edge to the vertex node to nbr having the weight equal to "weight" """ def addNeighbor(self,nbr,weight=0): self.connectedTo[nbr] = weight """ print in readable format, wherever vertex object is returned from the function call """ def __str__(self): return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo]) """ get all the nodes to which the vertex is connected to """ def getConnections(self): return self.connectedTo.keys() def getId(self): return self.id """ get the weight/distance from vertex object and the nbr(neighbour) """ def getWeight(self,nbr): return self.connectedTo[nbr] class Graph: """ initialise the constructor for Graph object having vertex list ie total number of vertices in the graph and also maintain a count of number of vertices in the graph """ def __init__(self): self.vertList = {} self.numVertices = 0 """ add the vertex to the graph with the given key. this function increments the vertices counter and creates a new vertex object and assigns the created vertex object to vertex list of the graph object """ def addVertex(self,key): self.numVertices = self.numVertices + 1 newVertex = Vertex(key) self.vertList[key] = newVertex return newVertex """ gets the vertex of the vertex list with given node id as n """ def getVertex(self,n): if n in self.vertList: return self.vertList[n] else: return None def __contains__(self,n): return n in self.vertList """ adds the edge with the given weight between two vertices """ def addEdge(self,f,t,cost=0): if f not in self.vertList: nv = self.addVertex(f) if t not in self.vertList: nv = self.addVertex(t) self.vertList[f].addNeighbor(self.vertList[t], cost) def getVertices(self): return self.vertList.keys() def __iter__(self): return iter(self.vertList.values()) graph = Graph() for i in range(7): print graph.addVertex(i) graph.addEdge(3, 5, 20) graph.addEdge(3, 7, 20) graph.addEdge(3, 10, 20) graph.addEdge(3, 11, 20) print graph.getVertex(3) for item, vertex in graph.vertList.iteritems(): for vertexConnectedTo, edgeWeight in vertex.connectedTo.iteritems(): print vertexConnectedTo.getId(), edgeWeight # print str(item), value.connectedTo for vertex in graph: print vertex for vertexConnectedTo in vertex.getConnections(): print("( %s , %s )" % (vertex.getId(), vertexConnectedTo.getId())) print vertex.connectedTo[vertexConnectedTo]
69b56300410df2703f37c21f0b7c473b51b22538
Herringway/twittersearch
/oauthsign.py
1,093
3.53125
4
import oauth2 import sys import time import settings # Build an oauth-signed request using the supplied url # Use .to_url() on the return value to get an URL that will authenticate against the # Twitter API. Build your URL, then call this function to get the URL that you will # send to Twitter. def sign_oauth_request(url): # Set up consumer and token objects. consumer = oauth2.Consumer(key=settings.CONSUMERKEY, secret=settings.CONSUMERSECRET) token = oauth2.Token(key=settings.ACCESSTOKEN, secret=settings.ACCESSTOKENSECRET) # Set up oauth parameters params = {} params['oauth_version'] = '1.0' params['oauth_nonce'] = oauth2.generate_nonce() params['oauth_timestamp'] = int(time.time()) params['oauth_token'] = token.key params['oauth_consumer_key'] = consumer.key # Create and sign the request. request = oauth2.Request(method='GET', url=url, parameters=params) request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) return request if __name__ == "__main__": print(sign_oauth_request(sys.argv[1]).to_url())
23c2533773c90efe45b80b05153f00bf2f09a055
artmaks/HeadHunterTask
/island/island.py
4,935
3.609375
4
# coding: utf-8 import numpy as np from numpy import sum # Проверяем, является ли клетка низиной # И все ее соседи с той же высотой (функция рекурентная) # Если не является (вода уходит) => False # Если явлется (вода остается) => набор клеток являющихся низиной (частный случай, когда 1 клетка) def isBottom(map, x, y, route): point = {'x': x, 'y': y} # Точка останова рекурсии if point in route: return True # Добавляем точку в историю посещения route.append(point) # Проверка на пограничные значения (около моря) if(x == 0 or x == map.shape[0] - 1): return False if(y == 0 or y == map.shape[1] - 1): return False # Проверка соседей точки # Если есть точка одинаковой высоты, то проверяем ее рекурентно # Если есть соседи ниже точки (рекурентно) => прерываем проверку (False) if(map[x][y] == map[x + 1][y] and 'right' not in route and isBottom(map, x + 1, y, route) == False): return False if(map[x][y] == map[x][y - 1] and 'down' not in route and isBottom(map, x, y - 1, route) == False): return False if(map[x][y] == map[x - 1][y] and 'left' not in route and isBottom(map, x - 1, y, route) == False): return False if(map[x][y] == map[x][y + 1] and 'up' not in route and isBottom(map, x, y + 1, route) == False): return False # Если мы прошли проверки выше, значит # точки равные нашей нам подходят # проверяем, что все соседи хотя бы не больше # возвращаем весь путь, проделанный рекурсией if(map[x][y] <= map[x + 1][y] and map[x][y] <= map[x - 1][y] and map[x][y] <= map[x][y + 1] and map[x][y] <= map[x][y - 1]): return route else: return False # Вернуть всех соседей для клетки def getNeighbors(p): neighbors = [{'x' : p['x'] + 1, 'y' : p['y']}, {'x' : p['x'] - 1, 'y' : p['y']}, {'x' : p['x'], 'y' : p['y'] + 1}, {'x' : p['x'], 'y' : p['y'] -1}] return neighbors #Находит минимального соседа для группы клеток (место через которое утекает вода) def getMinimumAmount(map, points): data = [] for p in points: for neighbor in getNeighbors(p): if neighbor not in points: data.append(neighbor) data = [island[i['x']][i['y']] for i in data] current_height = map[points[0]['x']][points[0]['y']] return np.min(data) - current_height #Заполняет указанные клетки, указанным количеством воды def fillCells(map, amount, points): for p in points: map[p['x']][p['y']] += amount return amount * len(points) # Главный метод для подсчета осадков def rain(island): rain_amount = 0 # кол-во осадков old_sum = 0 # переменная для отслеживания изменений на острове # Пока сумма высот на острове меняется while sum(sum(island)) != old_sum: # Записываем новую сумму высот old_sum = sum(sum(island)) # Пробегаем по клеткам острова последовательно for x in range(island.shape[0]): for y in range(island.shape[1]): # Проверяем состояние ячейки res = isBottom(island, x, y, []) # Если ячейка - низменность if(res): amount = getMinimumAmount(island, res) # Находим максимум, который мы можем добавить rain_amount += fillCells(island, amount, res) # Заполняем ячейки, добавляем результат в rain_amount return rain_amount stdin = open("stdin", "r") stdout = open("stdout", "r+") stdout.seek(0) stdout.truncate() island_count = int(stdin.readline()) for i in range(island_count): island = [] size = [int(i) for i in stdin.readline().split(' ')] for i in range(size[0]): numbers = [int(i) for i in stdin.readline().split(' ')] island.append(numbers) island = np.array(island) stdout.write(str(rain(island)) + '\n') stdin.close() stdout.close()
04c4b07e6e7e980e7d759aff14ce51d38fa89413
davelpat/Fundamentals_of_Python
/Ch2 exercises/employeepay.py
843
4.21875
4
""" An employee’s total weekly pay equals the hourly wage multiplied by the total number of regular hours, plus any overtime pay. Overtime pay equals the total overtime hours multiplied by 1.5 times the hourly wage. Write a program that takes as inputs the hourly wage, total regular hours, and total overtime hours and displays an employee’s total weekly pay. Below is an example of the program inputs and output: Enter the wage: $15.50 Enter the regular hours: 40 Enter the overtime hours: 12 The total weekly pay is $899.0 """ # Get employee weekly data wage = float(input("Enter the wage: ")) regHours = float(input("Enter the regular hours: ")) overtime = float(input("Enter the overtime hours: ")) # Calculate the pay pay = wage * regHours + wage * overtime * 1.5 # and display it print("The total weekly pay is $"+str(pay))
618b0630f3a7f64378a0ce82502753fe4b28ffb8
davelpat/Fundamentals_of_Python
/Ch11 exercises/merge_sort.py
2,041
4.09375
4
def merge(lyst, copybuffer, low, middle, high): # lyst liist being sorted # copybuffer temp space needed during the merge # low beginning of the first sorted sublist # middle end of the first sorted sublist # middle + 1 beginning of the second sorted sublist # high end of the second sorted sublist # Initialize i1 and i2 to the first items in each sublist i1 = low i2 = middle + 1 # Interleave items from the sublists into the # copybuffer in such a way that order is maintained. for i in range(low, high + 1): if i1 > middle: copybuffer[i] = lyst[i2] # First sublist exhausted i2 += 1 elif i2 > high: copybuffer[i] = lyst[i1] # Second sublist exhausted i1 += 1 elif lyst[i1] < lyst[i2]: copybuffer[i] = lyst[i1] # Item in first sublist is < i1 += 1 else: copybuffer[i] = lyst[i2] # Item in second sublist is < i2 += 1 for i in range(low, high + 1): lyst[i] = copybuffer[i] def mergeSortHelper(lyst, copybuffer, low, high): # lyst liist being sorted # copybuffer temp space needed during the merge # low, high boundaries of the sublist # middle midpoint of the list if low < high: middle = (low + high) // 2 mergeSortHelper(lyst, copybuffer, low, middle) mergeSortHelper(lyst, copybuffer, middle + 1, high) merge(lyst, copybuffer, low, middle, high) def mergeSort(lyst): # lyst the list being sorted # copybuffer temp space needed during the merge copybuffer = list(lyst) mergeSortHelper(lyst, copybuffer, 0, len(lyst) - 1) import random def main(size = 10, sort = mergeSort): """Sort a randomly ordered list and print before and after.""" lyst = list(range(1, size + 1)) random.shuffle(lyst) print(lyst) sort(lyst) print(lyst) if __name__ == "__main__": main()
a5396eb5f2d7009e92844031778dd176abf12ab3
davelpat/Fundamentals_of_Python
/Student_Files/Ch_09_Student_Files/die.py
597
3.890625
4
""" File: die.py This module defines the Die class. """ from random import randint class Die: """This class represents a six-sided die.""" def __init__(self): """Creates a new die with a value of 1.""" self.value = 1 def roll(self): """Resets the die's value to a random number between 1 and 6.""" self.value = randint(1, 6) def getValue(self): """Returns the value of the die's top face.""" return self.value def __str__(self): """Returns the string rep of the die.""" return str(self.getValue())
d5367ee9332da2c450505cb454e4e8dac87b2bf8
davelpat/Fundamentals_of_Python
/Student_Files/ch_11_student_files/Ch_11_Student_Files/testquicksort.py
1,817
4.15625
4
""" File: testquicksort.py Tests the quicksort algorithm """ def quicksort(lyst): """Sorts the items in lyst in ascending order.""" quicksortHelper(lyst, 0, len(lyst) - 1) def quicksortHelper(lyst, left, right): """Partition lyst, then sort the left segment and sort the right segment.""" if left < right: pivotLocation = partition(lyst, left, right) quicksortHelper(lyst, left, pivotLocation - 1) quicksortHelper(lyst, pivotLocation + 1, right) def partition(lyst, left, right): """Shifts items less than the pivot to its left, and items greater than the pivot to its right, and returns the position of the pivot.""" # Find the pivot and exchange it with the last item middle = (left + right) // 2 pivot = swap(lyst, middle, right) # pivot = lyst[middle] # lyst[middle] = lyst[right] # lyst[right] = pivot # Set boundary point to first position boundary = left # Move items less than pivot to the left for index in range(left, right): if lyst[index] < pivot: swap(lyst, index, boundary) boundary += 1 # Exchange the pivot item and the boundary item swap(lyst, right, boundary) return boundary quicksortHelper(0, len(lyst) - 1) def swap(lyst, i, j): """Exchanges the items at positions i and j.""" # You could say lyst[i], lyst[j] = lyst[j], lyst[i] # but the following code shows what is really going on temp = lyst[i] lyst[i] = lyst[j] lyst[j] = temp return temp import random def main(size = 20, sort = quicksort): """Sort a randomly ordered list and print before and after.""" lyst = list(range(1, size + 1)) random.shuffle(lyst) print(lyst) sort(lyst) print(lyst) if __name__ == "__main__": main()
65284af9158c3db8a764b7cb07296d2b89a4c93c
davelpat/Fundamentals_of_Python
/Student_Files/ch_08_Student_Files/counterdemo.py
1,424
3.75
4
""" File: counterdemo.py """ from breezypythongui import EasyFrame class CounterDemo(EasyFrame): """Illustrates the use of a counter with an instance variable.""" def __init__(self): """Sets up the window, label, and buttons.""" EasyFrame.__init__(self, title = "Counter Demo") self.setSize(200, 75) # Instance variable to track the count. self.count = 0 # A label to displat the count in the first row. self.label = self.addLabel(text = "0", row = 0, column = 0, sticky = "NSEW", columnspan = 2) # Two command buttons. self.addButton(text = "Next", row = 1, column = 0, command = self.next) self.addButton(text = "Reset", row = 1, column = 1, command = self.reset) # Methods to handle user events. def next(self): """Increments the count and updates the display.""" self.count += 1 self.label["text"] = str(self.count) def reset(self): """Resets the count to 0 and updates the display.""" self.count = 0 self.label["text"] = str(self.count) def main(): """Entry point for the application.""" CounterDemo().mainloop() if __name__ == "__main__": main()
1a7183d7758f27abb21426e84019a9ceeb5da7c7
davelpat/Fundamentals_of_Python
/Ch3 exercises/right.py
1,344
4.75
5
""" Write a program that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is a right triangle. Recall from the Pythagorean theorem that in a right triangle, the square of one side equals the sum of the squares of the other two sides. Use "The triangle is a right triangle." and "The triangle is not a right triangle." as your final outputs. An example of the program input and proper output format is shown below: Enter the first side: 3 Enter the second side: 4 Enter the third side: 5 The triangle is a right triangle. """ # Get the side lengths sideA = float(input("Enter length of side 1 of the triangele: ")) sideB = float(input("Enter length of side 2 of the triangele: ")) sideC = float(input("Enter length of side 3 of the triangele: ")) # Determine which side is potentially the hypotenuse if sideA == max(sideA, sideB, sideC): hypot = sideA side2 = sideB side3 = sideC elif sideB == max(sideA, sideB, sideC): hypot = sideB side2 = sideA side3 = sideC else: hypot = sideC side2 = sideB side3 = sideA # Determinei if it is a right triangle using the Pythagorean theorem if hypot ** 2 == (side2 ** 2 + side3 ** 2): print("The triangle is a right triangle.") else: print("The triangle is not a right triangle.")
82808ac569c685a2b864fd668edebbb7264cd07d
davelpat/Fundamentals_of_Python
/Ch9 exercises/testshapes.py
772
4.375
4
""" Instructions for programming Exercise 9.10 Geometric shapes can be modeled as classes. Develop classes for line segments, circles, and rectangles in the shapes.py file. Each shape object should contain a Turtle object and a color that allow the shape to be drawn in a Turtle graphics window (see Chapter 7 for details). Factor the code for these features (instance variables and methods) into an abstract Shape class. The Circle, Rectangle, and Line classes are all subclasses of Shape. These subclasses include the other information about the specific types of shapes, such as a radius or a corner point and a draw method. Then write a script called testshapes.py that uses several instances of the different shape classes to draw a house and a stick figure. """
f9a84cff7e4e9c4a92167506a09fcf09726ecfc1
davelpat/Fundamentals_of_Python
/Ch3 exercises/salary.py
1,387
4.34375
4
""" Instructions Teachers in most school districts are paid on a schedule that provides a salary based on their number of years of teaching experience. For example, a beginning teacher in the Lexington School District might be paid $30,000 the first year. For each year of experience after this first year, up to 10 years, the teacher receives a 2% increase over the preceding value. Write a program that displays a salary schedule, in tabular format, for teachers in a school district. The inputs are: Starting salary Annual percentage increase Number of years for which to print the schedule Each row in the schedule should contain the year number and the salary for that year An example of the program input and output is shown below: Enter the starting salary: $30000 Enter the annual % increase: 2 Enter the number of years: 10 Year Salary ------------- 1 30000.00 2 30600.00 3 31212.00 4 31836.24 5 32472.96 6 33122.42 7 33784.87 8 34460.57 9 35149.78 10 35852.78 """ salary = int(input("Please enter starting salary in dollars: ")) incr = float(input("Please enter the percent annual increase: ")) / 100 service = int(input("Please enter the years of service (max = 10): ")) print("%4s%10s" % ("Year", "Salary")) print("-"*14) for year in range(1, service + 1): print("%-6i%0.2f" % (year, salary)) salary += salary * incr
2ee467b7f70e740bce32e857df97bd311034e494
davelpat/Fundamentals_of_Python
/Ch4 exercises/decrrypt-str.py
1,106
4.5625
5
""" Instructions for programming Exercise 4.7 Write a script that decrypts a message coded by the method used in Project 6. Method used in project 6: Add 1 to each character’s numeric ASCII value. Convert it to a bit string. Shift the bits of this string one place to the left. A single-space character in the encrypted string separates the resulting bit strings. An example of the program input and output is shown below: Enter the coded text: 0010011 1001101 1011011 1011011 1100001 000011 1110001 1100001 1100111 1011011 1001011 000101 Hello world! """ DIST = 1 FIRST_ORD = 0 LAST_ORD = 127 SPACE = " " charList = input("Enter the coded text: ").split() eTxt = "" for bstring in charList: # Shift bit string 1 to the left bStrSize = len(bstring) bstring = bstring[-DIST:bStrSize] + bstring[0:bStrSize - DIST] # Convert ordinal bit string to decimal charOrd = 0 exponent = bStrSize - 1 for digit in bstring: charOrd = charOrd + int(digit) * 2 ** exponent exponent = exponent - 1 # Readjust ordinal value eTxt += chr(charOrd - 1) print(eTxt)
5b3f98828c1aa52309d9450094ecb3ab990bae91
davelpat/Fundamentals_of_Python
/Ch4 exercises/encrypt-str.py
1,246
4.53125
5
""" Instructions for programming Exercise 4.6 Use the strategy of the decimal to binary conversion and the bit shift left operation defined in Project 5 to code a new encryption algorithm. The algorithm should Add 1 to each character’s numeric ASCII value. Convert it to a bit string. Shift the bits of this string one place to the left. A single-space character in the encrypted string separates the resulting bit strings. An example of the program input and output is shown below: Enter a message: Hello world! 0010011 1001101 1011011 1011011 1100001 000011 1110001 1100001 1100111 1011011 1001011 000101 """ DIST = 1 FIRST_ORD = 0 LAST_ORD = 127 SPACE = " " txt = input("Enter a message: ") eTxt = "" for char in txt: # get and increment character's ASCII value charOrd = ord(char) + DIST # Not sure if the wrap around is required if charOrd > LAST_ORD: charOrd = FIRST_ORD + LAST_ORD - charOrd # Convert it to a bit string bstring = "" while charOrd > 0: remainder = charOrd % 2 charOrd = charOrd // 2 bstring = str(remainder) + bstring # Shift bit string 1 to the left bstring = bstring[DIST:len(bstring)]+bstring[0:DIST] eTxt += bstring + SPACE print(eTxt)
8b70613ee7350c54156a4eb076f11b82356055f7
davelpat/Fundamentals_of_Python
/Ch3 exercises/population.py
1,828
4.65625
5
""" Instructions A local biologist needs a program to predict population growth. The inputs would be: The initial number of organisms The rate of growth (a real number greater than 1) The number of hours it takes to achieve this rate A number of hours during which the population grows For example, one might start with a population of 500 organisms, a growth rate of 2, and a growth period to achieve this rate of 6 hours. Assuming that none of the organisms die, this would imply that this population would double in size every 6 hours. Thus, after allowing 6 hours for growth, we would have 1000 organisms, and after 12 hours, we would have 2000 organisms. Write a program that takes these inputs and displays a prediction of the total population. An example of the program input and output is shown below: Enter the initial number of organisms: 10 Enter the rate of growth [a real number > 0]: 2 Enter the number of hours to achieve the rate of growth: 2 Enter the total hours of growth: 6 The total population is 80 """ curPop = initPop = int(input("Enter the initial number of organisms: ")) growthRate = float(input("Enter the rate of growth [a real number > 0]: ")) growthCycle = float(input("Enter the number of hours to achieve the rate of growth: ")) period = float(input("Enter the total hours of growth: ")) fullCycles = int(period // growthCycle) # print("fullCycles =", fullCycles) partCycle = (period % growthCycle) / growthCycle # print("partCycle =", partCycle) for cycle in range(0, fullCycles): curPop = round(curPop * growthRate) # print("Population after", cycle + 1, "cycles is", curPop) # the Python course test is only looking for complete growth cycles # partPop = round((curPop * growthRate - curPop) * partCycle) # urPop = curPop + partPop print("The total population is", curPop)
ac12b691a1035565a9359b767f64815f34704622
davelpat/Fundamentals_of_Python
/Ch5 exercises/doctor.py
3,622
4.21875
4
""" Instructions for programming Exercise 5.9 In Case Study: Nondirective Psychotherapy, when the patient addresses the therapist personally, the therapist’s reply does not change persons appropriately. To see an example of this problem, test the program with “you are not a helpful therapist.” Fix this problem by repairing the dictionary of replacements. An example of the program input and output is shown below: Good morning, I hope you are well today. What can I do for you? >> You can help me Many of my patients tell me the same thing. >> your abilites are limited Why do you say that my abilites are limited >> Quit Have a nice day! """ """ Instructions for programming Exercise 5.10 Conversations often shift focus to earlier topics. Modify the therapist program to support this capability. Add each patient input to a history list. Then, occasionally choose an element at random from this list, change persons, and prepend (add at the beginning) the qualifier “Earlier you said that” to this reply. Make sure that this option is triggered only after several exchanges have occurred. An example of the program input and output is shown below: Good morning, I hope you are well today. What can I do for you? >> everyone hates me Please tell me more. >> my professor thinks I cheated Why do you say that your professor thinks you cheated >> he thought he saw me with my phone out during an exam Many of my patients tell me the same thing. >> but it was just my calculator Please tell me more. >> his class is my favorite! Please tell me more. >> even though it is at eight, I love getting up for it Earlier you said that your professor thinks you cheated >> I never would Can you explain why you never would >> quit Have a nice day! """ """ File: doctor.py Project 5.9 Conducts an interactive session of nondirective psychotherapy. Fixes problem of responding to sentences that address the doctor using second-person pronouns. """ import random hedges = ("Please tell me more.", "Many of my patients tell me the same thing.", "Please continue.") qualifiers = ("Why do you say that ", "You seem to think that ", "Can you explain why ") # The fix is in this dictionary, third line of data replacements = {"I":"you", "me":"you", "my":"your", "we":"you", "us":"you", "mine":"yours", "you":"I", "your":"my", "yours":"mine"} change_topic = "Earlier you said that " history = [] def reply(sentence): """Implements two different reply strategies.""" probability = random.randint(1, 4) hist_size = len(history) if probability == 1: return random.choice(hedges) elif hist_size > 4 and probability == 2: return change_topic + changePerson(history[random.randint(1, hist_size - 2)]) else: return random.choice(qualifiers) + changePerson(sentence) def changePerson(sentence): """Replaces first person pronouns with second person pronouns.""" words = sentence.split() replyWords = [] for word in words: replyWords.append(replacements.get(word, word)) return " ".join(replyWords) def main(): """Handles the interaction between patient and doctor.""" print("Good morning, I hope you are well today.") print("What can I do for you?") while True: sentence = input("\n>> ") history.append(sentence) if sentence.upper() == "QUIT": print("Have a nice day!") break print(reply(sentence)) # The entry point for program execution if __name__ == "__main__": main()
2027688365d98d030c980e3ebff511be738f6816
aditya-c/leetcode_stuff
/N_Queens.py
543
3.546875
4
import numpy as np size = 4 board = np.zeros((size, size)) # backtrack def iter(board, column): for row in range(board.shape[0]): if is_stable(board, row, column): board[row][column] = 1 iter(board, column + 1) board[row][column] = 0 print(board) def is_stable(board, row, column): for r in range(row): if board[r][column] == 1: return False r = row c = column while r > -1 and c > -1: r -= 1 c -= 1 return True iter(board, 0)
3863a109340c593950fe070133e5f4cc60342b5c
aditya-c/leetcode_stuff
/numpy_tests.py
2,008
3.984375
4
import numpy as np from scipy.spatial.distance import pdist, squareform import matplotlib.pyplot as plt # Create a new array from which we will select elements a = np.arange(1, 13).reshape(4, 3) print(a) # prints "array([[ 1, 2, 3], # [ 4, 5, 6], # [ 7, 8, 9], # [10, 11, 12]])" # Create an array of indices b = np.array([0, 2, 0, 1]) # Select one element from each row of a using the indices in b print("----\n", a[np.arange(4), b]) # Prints "[ 1 6 7 11]" # Mutate one element from each row of a using the indices in b a[np.arange(4), b] += 10 print("======\n", a) # prints "array([[11, 2, 3], # [ 4, 5, 16], # [17, 8, 9], # [10, 21, 12]]) print("+++") x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) v = np.array([1, 0, 1]) print(np.shape(v)) y = x + v # Add v to each row of x using broadcasting print(y) print(v) print(".....") """Broadcasting""" w = np.array([4, 5]) x = np.array([[1, 2, 3], [4, 5, 6]]) # Add a vector to each column of a matrix # x has shape (2, 3) and w has shape (2,). # If we transpose x then it has shape (3, 2) and can be broadcast # against w to yield a result of shape (3, 2); transposing this result # yields the final result of shape (2, 3) which is the matrix x with # the vector w added to each column. Gives the following matrix: # [[ 5 6 7] # [ 9 10 11]] print((x.T + w).T) # Another solution is to reshape w to be a column vector of shape (2, 1); # we can then broadcast it directly against x to produce the same # output. print(x + np.reshape(w, (2, 1))) """distance""" print("'''''''''") x = np.array([[0, 1], [1, 0], [2, 0]]) print(x) d = squareform(pdist(x, 'euclidean')) print(help(pdist)) ###### # Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, np.pi / 2) y = np.sin(x) # Plot the points using matplotlib plt.plot(x, y) plt.show() # You must call plt.show() to make graphics appear.
91d17b10301f316f489e218c8cf69749efceed98
aditya-c/leetcode_stuff
/numDecodings.py
323
3.796875
4
def decodeNumber(s): if not s: return 0 prev, curr, prev_value = 0, 1, "" print(prev, curr, prev_value) for digit in s: prev, curr, prev_value = curr, (digit > '0') * curr + int(10 <= int(prev_value + digit) <= 26) * prev, digit return curr print("*" * 10) print(decodeNumber("1234"))