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
0ebfa784abeddd768186f99209602dd7ef870e56
feleHaile/my-isc-work
/python_work_RW/6-input-output.py
1,745
4.3125
4
print print "Input/Output Exercise" print # part 1 - opening weather.csv file with open ('weather.csv', 'r') as rain: # opens the file as 'read-only' data = rain.read() # calls out the file under variable rain and reads it print data # prints the data # part 2 - reading the file line by line with open ('weather.csv', 'r') as rainy: line = rainy.readline() # uses .readline() while line: # while there is still data to read print line # print the line line = rainy.readline() # need to re-iterate here so it goes beyond just line 1. print "That's the end of the data" # part 3 - using a loop and collecting just rainfall values with open ('weather.csv', 'r') as rainfall: header = rainfall.readline() # this reads and discards the first line of the data (we dont want to use the header line with the text in it droplet = [] # creating an empty list to store rainfall data for line in rainfall.readlines(): # readlines reads the whole file, readline just takes the first line r = line.strip() .split(',')[-1] # takes last variable, see below r = float(r) # make it a float (with decimals) droplet.append(r) # append r to droplet list (store the data) print droplet # prints the data for rainfall with open ('myrain.txt', 'w') as writing: # creates a text file with the result for r in droplet: # prints the rainfall results in the text file writing.write(str(r) + '\n') """ Explantation for r = line.strip() .split(',')[-1] one line as example: 2014-01-01,00:00,2.34,4.45\n line.strip() removes the \n, so takes just one line without the paragraphing .split(',') splits the list by the comma, and takes each as a seperate item .split(',')[-1] means, seperate out and then take the last item """ print
a40fd3e7668b013a356cfa8559e993e770cc7231
feleHaile/my-isc-work
/python_work_RW/13-numpy-calculations.py
2,314
4.3125
4
print print "Calculations and Operations on Numpy Arrays Exercise" print import numpy as np # importing the numpy library, with shortcut of np # part 1 - array calculations a = np.array([range(4), range(10,14)]) # creating an array 2x4 with ranges b = np.array([2, -1, 1, 0]) # creating an array from a list # multiples the array by each other, 1st line of a * b, then the 2nd line of a * b multiply = a * b b1 = b * 1000 # creates a new array with every item in b * 1000 b2 = b * 1000.0 # creates new array similar to b1 but with floats rather than int b2 == b1 # yes, this is True. b2 is a float but they are the same print b1.dtype, b2.dtype # how to print the type of each # part 2 - array comparisons arr = np.array([range(10)]) # creates an array with items 0 to 9 print arr < 3 # prints true and false values in the array where item is <3 print np.less(arr, 3) # exactly the same as above, just different format of asking # sets a condition to call true or false based on two parameters, <3 OR > 8 condition = np.logical_or(arr < 3, arr > 8) print "condition: ", condition # uses "where" function to create new array where value is arr*5 if "condition" is true, and arr*-5 where "condition" is false new_arr = np.where(condition, arr * 5, arr * -5) # part 3 - mathematical functions working on arrays """ Calculating magnitudes of wind, where a minimum acceptable value is 0.1, and all values below this are set to 0.1. Magnitude of wind is calculated by the square-root of the sum of the squares of u and v (which are east-west and north-south wind magnitudes) """ def calcMagnitude(u, v, minmag = 0.1): # these are the argument criteria mag = ((u**2) + (v**2))**0.5 # the calculation # sets a where function so that minmag is adopted where values are less than 0.1: output = np.where(mag > minmag, mag, minmag) return output u = np.array([[4, 5, 6],[2, 3, 4]]) # the east-west winds v = np.array([[2, 2, 2],[1, 1, 1]]) # the north-south winds print calcMagnitude(u,v) # calls the argument with the u and v arrays # testing on different wind values, these values use the minmag clause u = np.array([[4, 5, 0.01],[2, 3, 4]]) # the east-west winds v = np.array([[2, 2, 0.03],[1, 1, 1]]) # the north-south winds print calcMagnitude(u,v) # calls the argument with the u and v arrays print
51971384be9ec9e203ccfbea516624d8af552254
TatyanaDovzhich/Project_25.01.2019
/file_25.01.2019.py
286
3.6875
4
def addition(a, b): return a+b print (addition(25, 10)) def subtraction (a, b): return a-b print (subtraction(25, 10)) def multiplication (a, b): return a*b print (multiplication(25, 10)) def division(a, b): return a/b print (division (25, 10))
09db0244598717c41277e24f5036c951c11d40fb
jasonzzx/python-learning
/practice.py
106
3.546875
4
dict = {"key1": "value1", "key2": "value2"} print(dict.keys()) print(dict.values()) print(dict.items())
7c572960ed2b5e510f74bd0c7078bc36ceacd320
olliechick/sockets
/receiver.py
3,168
3.8125
4
#!/usr/bin/env python3 """ A program to receive packets from a channel. For a COSC264 assignment. Author: Ollie Chick Date modified: 29 August 2017 """ import sys, socket, os, select from packet import Packet, MAGIC_NO, PTYPE_DATA, PTYPE_ACK from socket_generator import create_sending_socket, create_listening_socket def main(args): # Check arguments are valid try: in_port = int(args[1]) out_port = int(args[2]) channel_in_port = int(args[3]) filename = args[4] except: print("Usage: {} <in_port> <out_port> <channel_in_port> <filename>".format(args[0])) # Check that ports are in the valid range for port in [in_port, out_port, channel_in_port]: if port < 1024 or port > 64000: print("All port numbers should be integers in the range [1024, 64000].") return # Create sockets (and connect socket_out) socket_in = create_listening_socket(in_port) socket_out = create_sending_socket(out_port, channel_in_port) if None in [socket_in, socket_out]: sys.exit("One of the sockets failed to be created.") # Check if file exists if os.path.isfile(filename): sys.exit("Error: {} already exists.".format(filename)) # Initialisation expected = 0 file = open(filename, 'wb') input("Please acknowledge on the channel that you have started the receiver, then press enter.") # Accept connection from channel socket_in, addr = socket_in.accept() print("Receiving data...") # Main loop i = 0 while True: readable, _, _ = select.select([socket_in], [], []) # got a response print("Got packet {}".format(i), end = '\r') i += 1 s = readable[0] data = s.recv(1024) rcvd = Packet() rcvd.decode(data) if rcvd.is_valid_data(): # got a valid data packet # Prepare an acknowledgement packet and send it magic_no = MAGIC_NO packet_type = PTYPE_ACK seq_no = rcvd.seq_no data_len = 0 data = b"" pack = Packet(magic_no, packet_type, seq_no, data_len, data) socket_out.send(pack.encode()) if rcvd.seq_no == expected: expected = 1 - expected if rcvd.data_len > 0: # has some data file.write(rcvd.data) else: # no data - indicates end of file file.close() socket_in.shutdown(socket.SHUT_RDWR) socket_in.close() socket_out.shutdown(socket.SHUT_RDWR) socket_out.close() print("\nData received.") return if __name__ == "__main__": # Get arguments from the command line. # These should be: # * two port numbers to use for the two receiver sockets r_in and r_out # * the port number where the socket c_r_in should be found # * a file name, indicating where the received data should be stored args = sys.argv main(args)
f175a5ed6a74560d9c4bafee94da753332691d6a
RobertsHenry/Pythonian
/StudentDiningClass.py
3,584
3.59375
4
# Author: Henry Roberts # 4/16/2018 class studentDining(object): # A Student at JMU who has punches, dining, and FLEX in an account. # Attributes: # Name: Their name. # Punch Balance: How many punches they have left. # Dining Balance: How much money they have left in dining dollars. # FLEX Balance: How much money they have left in FLEX. name = 'temp' punchBalance = 123 punchBalanceMax = 123 diningBalance = 123 flexBalance = 123 def __init__(self, name, punch_balance, punch_balance_max, dining_balance, flex_balance): # The students name self.name = name self.punchBalance = punch_balance self.punchBalanceMax = punch_balance_max self.diningBalance = dining_balance self.flexBalance = flex_balance def set_punch_balance(self, balance): # Sets how many punches the student has. if balance > self.punchBalanceMax: self.punchBalance = self.punchBalanceMax else: self.punchBalance = balance def set_dining_balance(self, balance): # Sets how much money the student has in their dining account. self.diningBalance = balance def set_flex_balance(self, balance): # Sets how much money the student has in their flex account. self.flexBalance = balance def withdraw_punch(self, punches): # Withdraws *punches* amount of punches. Fails if not enough # punches in balance. if punches > self.punchBalance: raise RuntimeError('Amount greater than available balance.') self.punchBalance -= punches return self.punchBalance def withdraw_dining(self, amount): # Withdraws *amount* amount of money from dining. Fails if not enough # dining in balance. if amount > self.diningBalance: raise RuntimeError('Amount greater than available balance.') self.diningBalance -= amount return self.diningBalance def withdraw_flex(self, amount): # Withdraws *amount* amount of money from flex. Fails if not enough # flex in balance. if amount > self.flexBalance: raise RuntimeError('Amount greater than available balance.') self.flexBalance -= amount return self.flexBalance def deposit_punches(self, punches): # Deposits more punches into the account. self.punchBalance += punches return self.punchBalance def deposit_dining(self, amount): # Deposits more dining into the account. self.diningBalance += amount return self.diningBalance def deposit_flex(self, amount): # Deposits more flex into the account. self.flexBalance += amount return self.flexBalance def get_punch(self): # Returns the amount of remaning punches. print self.punchBalance return self.punchBalance def get_dining(self): # Returns the amount of remaining dining. print self.diningBalance return self.diningBalance def get_flex(self): # Returns the amount of remaning flex. print self.flexBalance return self.flexBalance def get_name(self): # Returns students name. print self.name return self.name # Created a student called Orlando orlando = studentDining('Orlando', 14, 14, 250, 50) # For loop that goes through his typical week for x in range(0, 6): orlando.withdraw_punch(2) orlando.withdraw_dining(10) orlando.withdraw_flex(4) # Tests Depositing orlando.deposit_flex(35) orlando.deposit_dining(70) # Checks getters and if the amounts have changed print 'Amounts' orlando.get_punch() orlando.get_dining() orlando.get_flex() # Tests setting over max punches, # print statement is so able to track in console print 'Setting punches over max' orlando.set_punch_balance(500) orlando.get_punch() # Prints students name print 'Students Name' orlando.get_name()
2927aa5e3bf5ac0fbd47f3d91c2581d4136451e2
lewis1905/codecademy-challenges
/pokemon/pokemon.py
3,808
3.875
4
#creating a class for the pokemon. class Pokemon: def __init__(self, name, level, health, max_health, group, knocked_out = False): self.name = name self.level = level self.health = health self.max_health = max_health self.group = group self.knocked_out = knocked_out #method for losing health when attacked. def lose_health(self, decrease): hp_decrease = self.health - decrease print("{} health was lost! {} has " + str(self.health) + " points remaining!".format(hp_decrease, self.name)) return self.health - decrease #Method for regaining health. def regain_health(self, increase): hp_increase = self.health + increase print("{} health was gained! {} has " + str(self.health) + " points remaining!".format(hp_increase, self.name)) return self.health + increase #Method for a pokemon who has lost all health points. def knock_out(self): if self.knocked_out == True and self.health < 1: print("{} has died, choose your next pokemon!".format(self.name)) #Method to revive a pokemon with a potion. def revive(self): potion = 25 if self.health < 1: print("{} has been revived! You can win this!".format(self.name)) return self.health + potion #Method for pokemon when attacking, which gives damage depending on type of pokemon. def attack(self, rival): damage = 5 if self.group == "fire" and rival.group == "grass": print("{} has dealt double the damage!").format(self.name) elif self.group == "water" and rival.group == "fire": print("{} has dealt double the damage!").format(self.name) elif self.group == "grass" and rival.group == "water": print("{} has dealt double the damage!").format(self.name) return rival.lose_health(damage * 2) if self.group == "fire" and rival.group == "water": print("{} has only dealt half the damage!".format(self.name)) elif self.group == "water" and rival.group == "grass": print("{} has only dealt half the damage!".format(self.name)) elif self.group == "grass" and rival.group == "fire": print("{} has only dealt half the damage!".format(self.name)) return rival.lose_health(damage * 0.5) #Creating a trainer class. class Trainer: def __init__(self, pokemons, potions, current_pokemon, name, knocked_out = True): self.pokemons = [] self.potions = potions self.current_pokemon = current_pokemon self.name = name self.knocked_out = knocked_out if len(self.pokemons) > 6: print("a trainer has a limit of 6 pokemon") #Method for using a potion on the current pokemon with a potion. def heal(self): print("You have used a potion on {}!".format(self.current_pokemon)) if self.potions > 0: self.current_pokemon.gain_health(15) self.potions -= 1 else: print("You're out of potions!") #Method for the trainer attacking the opponent with both current pokemons. def attack(self, rival): atk = self.current_pokemon defe = rival.current_pokemon print("{} attacks {} with {}".format(self.name, rival.name, self.current_pokemon)) return atk.attack(defe) #Method for switching pokemon whilst in battle. def switch(self): if self.current_pokemon == self.knocked_out and self.pokemons > 1: print("Your pokemon has been defeated, please choose another!") else: print("You have sadly lost this battle, dont give up and train harder!") squirtle = Pokemon("squirtle", 4, 99, 99, "water") charmeleon = Pokemon("charmeleon", 9, 99, 99, "fire") venusaur = Pokemon("venusaur", 8, 99, 99, "grass") lewis = Trainer([squirtle, charmeleon, venusaur], 5, 3, "Lewis") brok = Trainer([charmeleon, venusaur], 2, 2, "Brok")
278b100aef964098fce3aeb2fafad6d748b38889
SunShineSeason/EnglishShuffledWord
/EnglishWord.py
638
3.8125
4
from itertools import permutations import enchant d = enchant.Dict("en_US") # Dict object defined in enchant module list_a = list(input("please input a shuffled word:")) a_length = len(list_a) list_copy=[] for permu in list(permutations(range(a_length), a_length)): for i in permu: list_copy.append(list_a[i]) maybe_word = "".join(list_copy) if d.check(maybe_word): # if this is a valid English word, then return print("This is a possible valid word : "+ maybe_word) break list_copy = [] if list_copy == []: print("There is no valid word for the shuffled characters")
f8323b264fbc205c5f10227d118dd5f606427ef9
dcadavidzuleta/momento2nuevastecnologias
/Ejercicios con ciclos y estructuras de control/Ejcec07.py
322
3.78125
4
vocales = ["a", "e", "i", "o", "u"] def dividirEnLetras(texto): return [char for char in texto] def contarVocales(texto): lista = dividirEnLetras(texto) dic = {} for vocal in vocales: dic[vocal] = lista.count(vocal) return dic texto = input("ingrese el texto") print(contarVocales(texto))
a61b28b6d392379fc71a057e452a08c4c450761f
dcadavidzuleta/momento2nuevastecnologias
/Ejercicios basicos para python/Ejbp03.py
428
4.0625
4
seguir = 1 estaturas = [] continuar = 1 def promediar(lista): sum = 0 for item in lista: sum += int(item) return sum / len(lista) while int(seguir) == 1: estatura = input("Ingrese la estatura a evaluar\n") estaturas.append(estatura) seguir = input("Si desea ingresar otra estatura para evaluar digite 1, sino digite 0\n") print("el promedio de estatura es", promediar(estaturas))
fabdf9bef92c77a7d290249f53c92fb32270183e
raynerng/raspberrypi3
/pushLED.py
1,314
3.84375
4
import threading import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) class Button(threading.Thread): """A Thread that monitors a GPIO button""" def __init__(self, channel): threading.Thread.__init__(self) self._pressed = False self.channel = channel #set up pin as input GPIO.setup(self.channel,GPIO.IN) #terminate this thread when main program finishes self.daemon = True #start thread running self.start() def pressed(self): if self._pressed: #clear the pressed flag now that we have detected it self._pressed = False return True else: return False def run(self): previous= None while 1: #read GPIO channel current = GPIO.input(self.channel) time.sleep(0.01) #wait 10ms #detect change from 1 to 0( with a button press) if current == False and previous == True: self._pressed = True #wait for flag to be cleared while self._pressed: time.sleep(0.05) #wait 50ms previous = current def onButtonPress(): print("the button has been pressed") #create a button thread for a button on pin 11 button = Button(11) while True: #ask for a name an say hello name =raw_input("Enter a name or Q to quit") if name.upper()==('Q'): break print("Hello", name) #check if button has been pressed if button.pressed(): onButtonPress()
fe9d692477b2fcde1e64b5c3a248f347d83abe90
TestardR/Python_Fundamentals
/return_statement.py
161
3.96875
4
# return statements are necessary to get a value back from a function def cube(num): return num * num * num result = cube(4) print(cube(3)) print(result)
c6712fcb64227ba87d1bef13e85ff0a8f9163e00
Alruk-art/mod_17
/число и список.py
1,658
3.984375
4
def sort(arr): for i in range(len(arr)): for j in range(len(arr)-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr def find_position(arr, key): left = -1 right = len(arr) while right > left + 1: mid = (left + right) // 2 if arr[mid] >= key: right = mid else: left = mid return right raw_string = (11, 66, 33, 44, 55) list_of_numbers = list(raw_string) print ('Дан ряд чисел', list_of_numbers) while True: raw_value = input('Введите целое число: ') try: value = int(raw_value) break except ValueError as e: # print('Ввод %s содержит недопустимые символы' % (raw_value)) print(f'Ввод {raw_value} содержит недопустимые символы') sorted_list = sort(list_of_numbers) print(sorted_list) if value < sorted_list[0]: print('Введенное число меньше всех остальных') elif value == sorted_list[0]: print(f'Введеное число равно самому маленькому элементу в списке') elif value > sorted_list[-1]: print('Введенное число больше всех остальных') else: list_of_numbers.append(value) print (list_of_numbers.append(value)) #sorted_list = sort(list_of_numbers) pos = find_position(sorted_list, value) print (pos) print(f'Индекс элемента меньше чем введеное число - {pos}')
5fc10a276f8505ceb89031b36fcd0f0c62557883
Amanikashema/python-excercise-1
/Conditionals ex.py
1,113
3.90625
4
print("************Salary employees Check***************") annual_salary = int(input("Please enter your annual salary:R ")) contract_type = input("what is your contract type: ") if contract_type == "full-time": print("***Full time Employee***") income_tax = float(input("Please enter your income tax without percentage sign:")) gross_monthly_salary = (annual_salary/12) monthly_tax = (income_tax/12) net_monthly_salary = (gross_monthly_salary) - (gross_monthly_salary*0.295) print("Gross monthly salary:R", gross_monthly_salary) print("Monthly tax:",monthly_tax) print("Net monthly salary:R",net_monthly_salary) elif contract_type == part-time: print("***Part Time***") income_tax = float(input("Please enter your income tax without percentage sign:")) gross_monthly_salary = (annual_salary/12) monthly_tax = (income_tax/12) net_monthly_salary = (gross_monthly_salary) - (gross_monthly_salary*0.25) print("Gross monthly salary:R", gross_monthly_salary) print("Monthly tax:",monthly_tax) print("Net monthly salary:R",net_monthly_salary)
43d743a8305ec3018125f0589211a74bd61863d4
Bucknell-ECE/Micromanipulator
/Joystick.py
3,865
3.546875
4
''' This file contains the functions that the joytick uses. Last Modified: R. Nance 5/15/2018 #####################DO NOT EDIT BELOW INFORMATION################################## Originating Branch: Joystick Originally Created: R. Nance 12/2017 ''' import pygame from helper import * #from helper import mapval xAxisNum = 0 yAxisNum = 1 throttleAxisNum = 2 buttonMap = { 1: 'Zdown', 2: 'Zup', 3: 'Home', 4: 'ChangeMode', 6: 'GetStatus', 7: 'Z Sensitivity Up', 8: 'Z Sensitivity Down', 9: 'ResetHome' } class CustomJoystick: #will need to create a button mapping function that imports text file stuff here. THis is to get a GUI working #will need to create a button mapping function that imports text file stuff here. def __init__(self, name, number): self.name = name self.joystick = pygame.joystick.Joystick(number) pygame.init() # Used to manage how fast the screen updates clock = pygame.time.Clock() # Initialize the joysticks pygame.joystick.init() joystick_count = pygame.joystick.get_count() joystick = pygame.joystick.Joystick(0) # For each joystick: for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) #print('this is joystick: ', i) joystick.init() axes = joystick.get_numaxes() #print(axes) def getAxisPosition(self, axisIndex): joystick = pygame.joystick.Joystick(0) return joystick.get_axis(axisIndex) def convertPosition(self, axisIndex): currPos = self.getAxisPosition(axisIndex) newPos = (currPos + 1)*127.5 return newPos ############################CODE WRITTTEN BY RYDER######################################### def getButtons(self): clock = pygame.time.Clock() commands = [] for event in pygame.event.get(): # User did something #print(event) if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION if event.type == pygame.JOYBUTTONDOWN: button = event.button #commands += button commands += [buttonMap[button]] clock.tick(20) return commands def getAbsoluteX(self): pygame.event.get() #joystick = pygame.joystick.Joystick(0) return self.joystick.get_axis(xAxisNum) def getAbsoluteY(self): pygame.event.get() #joystick = pygame.joystick.Joystick(0) return self.joystick.get_axis(yAxisNum) def getAbsoluteThrottle(self): pygame.event.get() #joystick = pygame.joystick.Joystick(0) return self.joystick.get_axis(throttleAxisNum) def getAbsolutePosition(self): pygame.event.get() position = [round(self.joystick.get_axis(xAxisNum), 3), round(self.joystick.get_axis(yAxisNum), 3)] return position def getX(self): pygame.event.get() #joystick = pygame.joystick.Joystick(0) absoluteX = self.getAbsoluteX() + 1 return mapval(absoluteX, 0, 2, 0, 2000) def getY(self): pygame.event.get() #joystick = pygame.joystick.Joystick(0) absoluteY = self.getAbsoluteY() + 1 return mapval(absoluteY, 0, 2, 0, 2000) def getThrottle(self): pygame.event.get() absoluteThrottle = self.getAbsoluteThrottle() return mapval(absoluteThrottle, -1, 1, 0, 100) def getPosition(self): pygame.event.get() absolutePosition = [self.getAbsoluteX() + 1, self.getAbsoluteY() + 1] return map(lambda x: mapval(x, 0, 2, 0, 2000), absolutePosition)
12f3789e81a69e4daa75f9497dd94f382f5f0153
zamunda68/python
/main.py
507
4.21875
4
# Python variable function example # Basic example of the print() function with new line between the words print("Hello \n Marin") print("Bye!") # Example of .islower method which returns true if letters in the variable value are lower txt = "hello world" # the variable and its value txt.islower() # using the .islower() boolean method to print true or false print("\n") # print a new line print(txt) # print the variable # Example of .isupper method txt2 = "UPPER" y = txt2.isupper() print("\n", y)
1ef4a7869a5048f6d66fbdb56203fa2f0198fb22
zamunda68/python
/dictionaries.py
1,116
4.75
5
""" Dictionary is a special structure, which allows us to store information in what is called key value pairs (KVP). You can create one KVP and when you want to access specific information inside of the dictionary, you can just refer to it by its key """ # Similar to actual dictionary, the word is the key and the meaning is the value # Word - meaning == Key - value # Every dictionary has a name: # directory_name = {key_value_pair1, key_value_part2,} monthConversions = { "Jan": "January", # "Jan" is the key, "January" is the value "Feb": "February", "Mar": "March", "Apr": "April", "May": "May", "Jun": "June", "Jul": "July", "Aug": "August", "Sep": "September", "Oct": "October", "Nov": "November", "Dec": "December", } # Printing out the value of the key, by referring to the key itself: print(monthConversions["Nov"]) # Another way to retrieve the value is using the "get()" function: print(monthConversions.get("Dec")) # If we want to pass a default value, which is not listed in the list above: print(monthConversions.get("Dec", "Not a valid key"))
b87ff95c0c33ab60f41047922b83134b0621e3f2
C-likethis123/adventOfCode
/2019/Day 6/part1.py
1,250
3.71875
4
''' Some observations: A)B B)C C)D number of indirect orbits for p+1 is number of direct orbits of planet p + number of indirect orbits of planet p number of direct orbits can be calculated when input is read. ''' class Planet: def __init__(self, name): self.name = name self.planets_orbiting = [] self.orbits = None def add_planet(self, planet): self.planets_orbiting.append(planet) def getOrbits(self): if self.orbits == None: self.orbits = len(self.planets_orbiting) for planet in self.planets_orbiting: self.orbits += planet.getOrbits() return self.orbits import sys import resource import time start_time = time.time() dict_of_orbits = {} for line in sys.stdin: planets = line.rstrip().split(")") first_planet, second_planet = planets[0], planets[1] if first_planet not in dict_of_orbits: dict_of_orbits[first_planet] = Planet(first_planet) if second_planet not in dict_of_orbits: dict_of_orbits[second_planet] = Planet(second_planet) dict_of_orbits[second_planet].add_planet(dict_of_orbits[first_planet]) #start graph traversal total_orbits = 0 for planets in dict_of_orbits: total_orbits += dict_of_orbits[planets].getOrbits() print(time.time() - start_time) print(total_orbits)
7f16d717ee4786370e5edc84df7f710ba0611486
shin202j/find_the_site
/find_the_site/fw.py
1,014
3.59375
4
"""Get a website from http://ddg.gg/ .""" import requests from bs4 import BeautifulSoup from user_agent import generate_user_agent def get_website(need_website=None): """Return a website.""" website = None if need_website: # Find website find_website_ddg = "website " + need_website ua = generate_user_agent() headers = {"User-Agent": ua} payload = {"q": find_website_ddg, "kl": "us-en"} r = requests.post("https://duckduckgo.com/lite/", headers=headers, data=payload) soup = BeautifulSoup(r.text, "html.parser") website_list = [ i.get("href") for i in soup.find_all("a", {"class", "result-link"}) ] if website_list: website = website_list[0] return website_list cName = '' while cName != 'q': try: cName=str(raw_input('Company Name (Enter \'q\' to quit): ')) except ValueError: print ("Invalid Input") for company in get_website(cName): print (company)
a95b3e4a2102e76c1a6b4932d6053a66b9593d5d
b-zhang93/CS50-Intro-to-Computer-Science-Harvard-Problem-Sets
/pset6 - Intro to Python/caesar/caesar.py
1,022
4.21875
4
from cs50 import get_string from cs50 import get_int from sys import argv # check for CLA to be in order and return error message if so if len(argv) != 2: print("Usage: ./caesar key k") exit(1) # checks for integer and positive elif not argv[1].isdigit(): print("Usage: ./caesar key k") exit(1) # defining the key and converting it to an integer key = argv[1] k = int(key) # prompt for user and return cipher word = get_string("plaintext: ") print("ciphertext: ", end="") # c is the iterator for each letter in input for c in word: # for lowercase letters to convert and mod to wrap around then convert back to letter if c.islower(): x = (ord(c) - 97 + k) % 26 y = 97 + x z = chr(y) print(z, end="") # do the same for upper case elif c.isupper(): x = (ord(c) - 65 + k) % 26 y = 65 + x z = chr(y) print(z, end="") # every other non-alpha char just print it out no conversion else: print(c, end="") print()
0dfe3bd5b3a5ff53b9c3950372415138caaea83f
sukruthananth/A-path-finding-with-obstruction
/ShortestPath.py
5,904
3.59375
4
import pygame from queue import PriorityQueue pygame.init() width = 600 rows = 50 win = pygame.display.set_mode((width,width)) pygame.display.set_caption("Shortest Path with obstruction(A* Algorithm)") class Node: def __init__(self, i, j, width, rows): self.width = width self.x = i self.y = j self.rows = rows self.color = (255,255,255) self.gap = self.width // self.rows def make_start(self,win): self.color = (255, 165 ,0) #orange def make_end(self,win): self.color = (128,0,128) #green def make_block(self,win): self.color = (0, 0 ,0) #black def draw(self,win): pygame.draw.rect(win, self.color, (self.y*self.gap, self.x *self.gap, self.gap,self.gap)) def make_boundary(self): self.color = (255,0,0) def make_closed(self): self.color = (0,0,255) def reset_node(self): self.color = (255,255,255) def isbarrier(self): if self.color == (0,0,0): return True else: return False def find_neighbour(self, grid): self.neighbour = [] if self.x>0 and not grid[self.x-1][self.y].isbarrier(): #left self.neighbour.append(grid[self.x-1][self.y]) if self.x<self.rows -1 and not grid[self.x+1][self.y].isbarrier(): #right self.neighbour.append(grid[self.x+1][self.y]) if self.y >0 and not grid[self.x][self.y-1].isbarrier(): #up self.neighbour.append(grid[self.x][self.y-1]) if self.y <self.rows -1 and not grid[self.x][self.y+1].isbarrier():#down self.neighbour.append(grid[self.x][self.y+1]) def position(self): position = self.x, self.y return position def draw_endpath(path, end, draw, start): current = end while current!=start: if path[current]==start: current = path[current] else: current = path[current] current.color = (0,255,0) draw() def h_score(position1, position2): x1,y1 = position1 x2, y2 = position2 return abs(x1-x2) + abs(y1-y2) def make_grid(rows, width): grid = [] for i in range(rows): grid.append([]) for j in range(rows): node = Node(i,j,width, rows) grid[i].append(node) return grid def draw_grid(rows, width, win): gap = width // rows for i in range(rows): pygame.draw.line(win,(0,0,0),(0,i*gap),(width,i*gap)) pygame.draw.line(win,(0,0,0),(i*gap,0),(i*gap,width)) def draw_nodes(rows, width, win, grid): win.fill((255, 255, 255)) for row in grid: for node in row: node.draw(win) draw_grid(rows, width, win) pygame.display.update() def algorithm(draw, start,end, grid): tie_breaker = 0 open_set = PriorityQueue() open_set.put((0,tie_breaker, start)) g_score = {node: float("inf") for row in grid for node in row} g_score[start] = 0 f_score = {node: float("inf") for row in grid for node in row} f_score[start] = h_score(start.position(),end.position()) from_path = {} open_set_hash = {start} while not open_set.empty(): current = open_set.get()[2] open_set_hash.remove(current) if current == end: draw_endpath(from_path, end, draw, start) return True for events in pygame.event.get(): if events.type == pygame.QUIT: pygame.quit() for neighbour in current.neighbour: temp_g_score = g_score[current] +1 if temp_g_score < g_score[neighbour]: g_score[neighbour] = temp_g_score f_score[neighbour] = g_score[neighbour] + h_score(neighbour.position(), end.position()) if neighbour not in open_set_hash: open_set_hash.add(neighbour) tie_breaker+=1 open_set.put((f_score[neighbour],tie_breaker, neighbour)) if neighbour!=end: neighbour.make_boundary() from_path[neighbour] = current draw() if current!= start and current!= end: current.make_closed() return False grid = make_grid(rows,width) draw_grid(rows,width,win) pygame.display.update() start = None end = None gap = width//rows run = True while run: draw_nodes(rows, width, win, grid) for events in pygame.event.get(): if events.type == pygame.QUIT: run = False pygame.quit() elif pygame.mouse.get_pressed()[0]: position = pygame.mouse.get_pos() x = position[1] // gap y = position[0] // gap node = grid[x][y] if not start and node != end: start = node node.make_start(win) elif not end and start!=node: end = node node.make_end(win) elif end!=node and start!=node: node.make_block(win) elif pygame.mouse.get_pressed()[2]: position = pygame.mouse.get_pos() x = position[1] // gap y = position[0] // gap node = grid[x][y] if node == start: start = None node.reset_node() elif node == end: end = None node.reset_node() else: node.reset_node() if events.type == pygame.KEYDOWN: if events.key == pygame.K_SPACE and start and end: for row in grid: for node in row: node.find_neighbour(grid) if algorithm(lambda: draw_nodes(rows, width, win, grid), start, end, grid): print("found the shortest path") else: print("There is no path") pygame.quit()
9dc9e3405a329105c9700b04146e0b814b3bbc5d
dkong3/pylearning
/practice5.py
290
3.640625
4
import datetime import math # help(datetime.date) d1=datetime.date(2014, 7, 2) d2=datetime.date(2014, 7, 11) delta = d2-d1 print(delta.days) print("%3.5f" %(math.pi*4/3*6**3)) def diff(n): if n>17: return 2*(n-17) else: return 17-n print(diff(22)) print(diff(3))
cd316cf1233735f58c2926bf26a746ef2299dfc8
castroandrew/cs114
/random1.py
189
3.9375
4
import random print('enter a number to see what it trully is') base_number= len(input()) random_number = random.randint(1,15) new_number= random_number + int(base_number) print(new_number)
65a854c69f0817a2ee611efeec08a5b56620d740
castroandrew/cs114
/Castro_space_dungeon.py
501
3.546875
4
print("welcome to Space Dungeon") print("Press Enter To Continue") input() print("Choose your Class") print("Space Duck") print("That One Human") print("Sexy Alien") classes = input() print("Delegate Points. You have 100 to spend. ") print("How Many points to magic") magic = input() print("How many points to attack") attack =input() print("What is your name") name = input() print("welcome " +name+ "You have "+magic+" magic points and "+attack+ " attack points") print("and is "+classes+" class.")
71b2c28b3417017184b8b2719bef9d997b30673e
Mat-Nishi/labs-do-uri-2k21-python
/lab 5/Instruções do Robo.py
431
3.59375
4
n = int(input()) for i in range(n): instrucoes = int(input()) movimentos = [] for i in range(instrucoes): instrucao = input() if instrucao == 'LEFT': movimentos.append(-1) elif instrucao == 'RIGHT': movimentos.append(1) else: idx = int(instrucao.split()[-1]) - 1 movimentos.append(movimentos[idx]) print(sum(movimentos))
fca00ca32bccf6122ce946e27382d9676477d574
Mat-Nishi/labs-do-uri-2k21-python
/lab 2/Aposentar.py
161
3.921875
4
a = int(input()) b = int(input()) if (a >= 65 or b >= 30 or (a >= 60 and b >= 25)): print('Apto a aposentadoria') else: print('Inapto a aposentadoria')
e8980b19bafa240bbfe5cfef4f9e7410d00cfe58
Mat-Nishi/labs-do-uri-2k21-python
/lab 1/Media Ponderada.py
132
3.875
4
# -*- coding: utf-8 -*- a = float(input())*3 b = float(input())*5 c = float(input())*2 print("Media = {:.2f}".format((a+b+c)/10))
5115af6bdbd754c100d544519146e51a0c9a6d96
Mat-Nishi/labs-do-uri-2k21-python
/lab 4/Produto Escalar.py
448
3.53125
4
v1 = [] v2 = [] soma = 0 val = int(input()) while val >= 0: v1.append(val) val = int(input()) val = int(input()) while val >= 0: v2.append(val) val = int(input()) if len(v1) > len(v2): for i in range(len(v1) - len(v2)): v2.append(0) else: for i in range(len(v2) - len(v1)): v1.append(0) for i in range(len(v1)): soma += v1[i]*v2[i] print('Produto Escalar: {}'.format(soma))
7d6030f334900160ba8f969346b622b38667999d
Mat-Nishi/labs-do-uri-2k21-python
/lab 6.py
2,308
3.9375
4
# -*- coding: utf-8 -*- """ Created on Fri Aug 13 19:44:10 2021 @author: Mateus """ # Conjunto de funções para uma calculadora. def soma(x, y): resultado = x+y return resultado def subtracao(x, y): resultado = x-y return resultado def multiplicacao(x, y): resultado = x*y return resultado def divisao(x, y): resultado = x/y if y else None return resultado def exponenciacao(x, y): if (x == 0 and y < 0) or type(y) != int: resultado = None else: resultado = x**y return resultado def somasRec(N, denominador, ciclo): if N == ciclo: return 0 else: return (((-1)**N)/denominador) + somasRec(N+1, denominador+2, ciclo) def pi(N): if N < 0 or type(N) != int: return None elif N == 0: return 0 else: return float(4*(1 + somasRec(1, 3, N))) def fatorial(x): if x < 0 or type(x) != int: return None elif x == 0 or x == 1: return 1 else: return x*fatorial(x-1) def permutacao(n, p): if n >= 0 and type(n) == int and p <= n and p >= 0 and type(p) == int: resultado = fatorial(n)/fatorial(n-p) else: resultado = None return int(resultado) def combinacao(n, p): if n >= 0 and type(n) == int and p <= n and p >= 0 and type(p) == int: resultado = fatorial(n)/(fatorial(n-p)*fatorial(p)) else: resultado = None return int(resultado) def somatorio(i, f): if type(i) == int and type(f) == int: resultado = sum(range(i, f+1)) else: resultado = None return resultado def exp(x): soma = 0 for i in range(100): soma += (x**i)/fatorial(i) if soma == 1: soma = int(soma) return soma def ln(x): if x > 0: soma = 0 for i in range(100): soma += (1/((i*2)+1))*(((x-1)/(x+1))**(i*2)) resultado = 2*((x-1)/(x+1))*soma else: resultado = None return resultado def superExponenciacao(x, y): if x > 0: resultado = exp(y*ln(x)) else: resultado = None return resultado def raizQuadrada(x): if x >= 0: # resultado = x**(0.5) ou resultado = superExponenciacao(x, 0.5) else: resultado = None return resultado
1507b6a0ca2b69bca216644ffcabc281d4f446b3
gmarler/courseware-tnl
/labs/py3/decorators/returns.py
1,035
3.734375
4
''' >>> f(3,4) 7 >>> f(4,3) Traceback (most recent call last): ... TypeError: Incorrect return type >>> a_to_upper("alpha") 'ALPHA' >>> a_to_upper("Andrew") 'ANDREW' >>> a_to_upper("Bart") Traceback (most recent call last): ... TypeError: Incorrect return type >>> a_to_upper("Zed") Traceback (most recent call last): ... TypeError: Incorrect return type ''' # Implement your returns decorator here: def returns(type): def decorator(func): def wrapper(*args, **kwargs): returnval = func(*args, **kwargs) if isinstance(returnval, type): return returnval else: raise TypeError("Incorrect return type") return wrapper return decorator # Do not edit any code below this line! @returns(int) def f(x, y): if x > 3: return -1.5 return x + y @returns(str) def a_to_upper(s): if s.startswith('a') or s.startswith('A'): return s.upper() if __name__ == '__main__': import doctest doctest.testmod() # Copyright 2015-2017 Aaron Maxwell. All rights reserved.
c891f23d90e49fa066d06e90fd5ad2d45c9afd7d
gmarler/courseware-tnl
/labs/py3/decorators/memoize.py
1,122
4.1875
4
''' Your job in this lab is to implement a decorator called "memoize". This decorator is already applied to the functions f, g, and h below. You just need to write it. HINT: The wrapper function only needs to accept non-keyword arguments (i.e., *args). You don't need to accept keyword arguments in this lab. (That is more complex to do, which is why it's saved for a later next lab.) >>> f(2) CALLING: f 2 4 >>> f(2) 4 >>> f(7) CALLING: f 7 49 >>> f(7) 49 >>> g(-6, 2) CALLING: g -6 2 4.0 >>> g(-6, 2) 4.0 >>> g(6, 2) CALLING: g 6 2 -2.0 >>> g(6, 2) -2.0 >>> h(2, 4) CALLING: h 2 4 42 7 >>> h(2, 4) 7 >>> h(3, 2, 31) CALLING: h 3 2 31 6 >>> h(3, 2, 31) 6 ''' # Write your code here: # Do not edit any code below this line! @memoize def f(x): print("CALLING: f {}".format(x)) return x ** 2 @memoize def g(x, y): print("CALLING: g {} {}".format(x, y)) return (2 - x) / y @memoize def h(x, y, z=42): print("CALLING: h {} {} {}".format(x, y, z)) return z // (x + y) if __name__ == '__main__': import doctest doctest.testmod() # Copyright 2015-2017 Aaron Maxwell. All rights reserved.
7a0db229f0af3b6ea99b7b0a8919c245233c3be0
BigerWANG/pythoncookbook
/chapter1/pyck15.py
1,039
3.84375
4
# coding: utf-8 import heapq """ 用py实现一个优先级队列, 每次pop都返回优先级最高的那个元素 """ class PriorityQueue(object): """用py实现一个优先级队列, 每次pop都返回优先级最高的那个元素""" def __init__(self): self._queue = list() self._index = 0 def push(self, iterm, priority): # 优先级,元素的原始索引, 元素值, 按照数字越大优先级越大的规则 heapq.heappush(self._queue, (-priority, self._index, iterm)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1] class Iterm(object): """docstring for Iterm""" def __init__(self, name): self.name = name def __repr__(self): return "< name: %s >" % self.name def main(): p = PriorityQueue() p.push(Iterm("foo"), 0) p.push(Iterm("foo1"), 1) p.push(Iterm("foo2"), 2) p.push(Iterm("foo3"), 3) p.push(Iterm("foo4"), 4) p.push(Iterm("foo5"), 5) p.push(Iterm("foo6"), 6) print p.pop() print p.pop() print p.pop() if __name__ == '__main__': main()
e665e98a3ee81dde5ec3f219258971339c703d33
RXCORE/healthcare_twitter_analysis
/code/twitter_functions.py
13,048
3.78125
4
def twitterreq(url, method, parameters): """ Send twitter URL request Utility function used by the others in this package Note: calls a function twitter_credentials() contained in a file named twitter_credentials.py which must be provided as follows: api_key = " your credentials " api_secret = " your credentials " access_token_key = " your credentials " access_token_secret = " your credentials " return (api_key,api_secret,access_token_key,access_token_secret) This function is based on a shell provided by Bill Howe University of Washington for the Coursera course Introduction to Data Science Spring/Summer 2014 (which I HIGHLY recommend) """ import oauth2 as oauth import urllib2 as urllib # this is a private function containing my Twitter credentials from twitter_credentials import twitter_credentials api_key,api_secret,access_token_key,access_token_secret = twitter_credentials() _debug = 0 oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret) oauth_consumer = oauth.Consumer(key=api_key, secret=api_secret) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() http_method = "GET" http_handler = urllib.HTTPHandler(debuglevel=_debug) https_handler = urllib.HTTPSHandler(debuglevel=_debug) ''' Construct, sign, and open a twitter request using the hard-coded credentials above. ''' req = oauth.Request.from_consumer_and_token(oauth_consumer, token=oauth_token, http_method=http_method, http_url=url, parameters=parameters) req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token) headers = req.to_header() if http_method == "POST": encoded_post_data = req.to_postdata() else: encoded_post_data = None url = req.to_url() opener = urllib.OpenerDirector() opener.add_handler(http_handler) opener.add_handler(https_handler) response = opener.open(url, encoded_post_data) return response def lookup_tweet(tweet_id): """ Ask Twitter for information about a specific tweet by its id the Twitter API for this is here: https://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid #Use: #import json #from twitter_functions import lookup_tweet # #result = lookup_tweet("473010591544520705") #for foo in result: # tweetdata = json.loads(foo) # break # there must be a better way # #print json.dumps(tweetdata, sort_keys = False, indent = 4) """ url = "https://api.twitter.com/1.1/statuses/show.json?id=" + tweet_id parameters = [] response = twitterreq(url, "GET", parameters) return response def lookup_multiple_tweets(list_of_tweet_ids): """ Ask Twitter for information about a bulk list of tweets by id the Twitter API for this is here: https://dev.twitter.com/docs/api/1.1/get/statuses/lookup Use: import json from twitter_functions import lookup_multiple_tweets list_of_tweet_ids = ["473010591544520705","473097867465224192"] result = lookup_multiple_tweets(list_of_tweet_ids) for foo in result: tweetdata_list = json.loads(foo) break # there must be a better way for tweetdata in tweetdata_list: print json.dumps(tweetdata, sort_keys = False, indent = 4) """ csv_of_tweet_ids = ",".join(list_of_tweet_ids) url = "https://api.twitter.com/1.1/statuses/lookup.json?id=" + csv_of_tweet_ids parameters = [] response = twitterreq(url, "GET", parameters) return response def lookup_user(rsarver): """ Ask Twitter for information about a user name the Twitter API for this is here: https://dev.twitter.com/docs/api/1.1/get/users/show Use: import json from twitter_functions import lookup_user result = lookup_user("flgprohemo") for foo in result: userdata = json.loads(foo) break # there must be a better way print json.dumps(userdata, sort_keys = False, indent = 4) # all may be null; have to check userdata["location"].encode('utf-8') userdata["description"].encode('utf-8') userdata["utc_offset"].encode('utf-8') userdata["time_zone"].encode('utf-8') userdata["status"]["lang"].encode('utf-8') """ url = "https://api.twitter.com/1.1/users/show.json?screen_name=" + rsarver parameters = [] response = twitterreq(url, "GET", parameters) return response def lookup_multiple_users(csv_of_screen_names): """ Ask Twitter for information about up to 100 screen names The input argument must be a string of screen names separated by commas the Twitter API for this is here: https://dev.twitter.com/docs/api/1.1/get/users/lookup Version 0.1 uses GET; Twitter urges POST; I will get to that later Use: import json from twitter_functions import lookup_multiple_users screen_name_list = ["grfiv","flgprohemo"] csv_of_screen_names = ",".join(screen_name_list) result = lookup_multiple_users(csv_of_screen_names) for foo in result: userdata = json.loads(foo) break # there must be a better way for user in userdata: print "For screen name: " + user["screen_name"] print json.dumps(user, sort_keys = False, indent = 4) """ url = "https://api.twitter.com/1.1/users/lookup.json?screen_name=" + csv_of_screen_names parameters = [] response = twitterreq(url, "GET", parameters) return response def parse_tweet_json(line, tweetdata): """ Take in a line from the file as a dict Add to it the relevant fields from the json returned by Twitter """ line["coordinates"] = str(tweetdata["coordinates"]) line["favorited"] = str(tweetdata["favorited"]) if tweetdata["entities"] is not None: if tweetdata["entities"]["hashtags"] is not None: hashtag_string = "" for tag in tweetdata["entities"]["hashtags"]: hashtag_string = hashtag_string + tag["text"] + "~" hashtag_string = hashtag_string[:-1] line["hashtags"] = str(hashtag_string.encode('utf-8')) else: line["hashtags"] = "" if tweetdata["entities"]["user_mentions"] is not None: user_mentions_string = "" for tag in tweetdata["entities"]["user_mentions"]: user_mentions_string = user_mentions_string + tag["screen_name"] + "~" user_mentions_string = user_mentions_string[:-1] line["user_mentions"] = str(user_mentions_string) else: line["user_mentions"] = "" line["retweet_count"] = str(tweetdata["retweet_count"]) line["retweeted"] = str(tweetdata["retweeted"]) line["place"] = str(tweetdata["place"]) line["geo"] = str(tweetdata["geo"]) if tweetdata["user"] is not None: line["followers_count"] = str(tweetdata["user"]["followers_count"]) line["favourites_count"] = str(tweetdata["user"]["favourites_count"]) line["listed_count"] = str(tweetdata["user"]["listed_count"]) line["location"] = str(tweetdata["user"]["location"].encode('utf-8')) line["utc_offset"] = str(tweetdata["user"]["utc_offset"]) line["listed_count"] = str(tweetdata["user"]["listed_count"]) line["lang"] = str(tweetdata["user"]["lang"]) line["geo_enabled"] = str(tweetdata["user"]["geo_enabled"]) line["time_zone"] = str(tweetdata["user"]["time_zone"]) line["description"] = tweetdata["user"]["description"].encode('utf-8') # why no return? Because Python uses call by reference # and our modifications to "line" are actually done to # the variable the reference to which was passed in #return line def find_WordsHashUsers(input_filename, text_field_name="content", list_or_set="list"): """ Input: input_filename: the csv file text_field_name: the name of the column containing the tweet text list_or_set: do you want every instance ("list") or unique entries ("set")? Output: lists or sets of words hashtags users mentioned urls Usage: word_list, hash_list, user_list, url_list, num_tweets = \ find_WordsHashUsers("../files/Tweets_BleedingDisorders.csv", "content", "list") word_set, hash_set, user_set, url_set, num_tweets = \ find_WordsHashUsers("../files/Tweets_BleedingDisorders.csv", "content", "set") """ import csv if list_or_set != "set" and list_or_set != "list": print "list_or_set must be 'list' or 'set', not " + list_or_set return() if list_or_set == "list": word_list = list() hash_list = list() user_list = list() url_list = list() else: word_set = set() hash_set = set() user_set = set() url_set = set() with open(input_filename, "rb" ) as infile: reader = csv.DictReader(infile) lines = list(reader) # list of all lines/rows in the input file totallines = len(lines) # number of lines in the input file # read the input file line-by-line # ================================ for linenum, row in enumerate(lines): content = row[text_field_name] words, hashes, users, urls = parse_tweet_text(content) if list_or_set == "list": word_list.extend(words) hash_list.extend(hashes) user_list.extend(users) url_list.extend(urls) else: word_set.update(words) hash_set.update(hashes) user_set.update(users) url_set.update(urls) if list_or_set == "list": return (word_list, hash_list, user_list, url_list, totallines) else: return (word_set, hash_set, user_set, url_set, totallines) def parse_tweet_text(tweet_text, AFINN=False): """ Input: tweet_text: a string with the text of a single tweet AFINN: (optional) True (must have "AFINN-111.txt" in folder) Output: lists of: words hashtags users mentioned urls (optional) AFINN-111 score Usage: from twitter_functions import parse_tweet_text words, hashes, users, urls = parse_tweet_text(tweet_text) words, hashes, users, urls, AFINN_score = parse_tweet_text(tweet_text, AFINN=True) """ import re content = tweet_text.lower() urls = re.findall(r"\b((?:https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$])", content, re.IGNORECASE) content = re.sub(r"\b((?:https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$])", "", content, 0, re.IGNORECASE) hashes = re.findall(r"#(\w+)", content) content = re.sub(r"#(\w+)", "", content, 0) users = re.findall(r"@(\w+)", content) content = re.sub(r"@(\w+)", "", content, 0) # strip out singleton punctuation raw_words = content.split() words = list() for word in raw_words: if word in ['.',':','!',',',';',"-","-","?",'\xe2\x80\xa6',"!"]: continue words.append(word) if AFINN: sentiment_words, sentiment_phrases = parse_AFINN("AFINN-111.txt") AFINN_score = 0 # single words for word in words: if word in sentiment_words: AFINN_score += sentiment_words[word.lower()] # phrases for phrase in sentiment_phrases: if phrase in words: AFINN_score += sentiment_phrases[phrase] return (words, hashes, users, urls, AFINN_score) return (words, hashes, users, urls) def parse_AFINN(afinnfile_name): """ Parse the AFIN-111 sentiment file Input: afinnfile_name: the [path/] file name of AFIN-111.txt Output: dicts of: sentiment_words: score sentiment_phrases: score Usage: from twitter_functions import parse_AFINN sentiment_words, sentiment_phrases = parse_AFINN("AFINN-111.txt") """ afinnfile = open(afinnfile_name) sentiment_phrases = {} sentiment_words = {} for line in afinnfile: key, val = line.split("\t") if " " in key: sentiment_phrases[key.lower()] = int(val) else: sentiment_words[key.lower()] = int(val) return (sentiment_words, sentiment_phrases)
529b20dc528b3a96fa6ad7229e63cfd91328da17
Snickers97/algoirthms
/algo2.py
298
3.78125
4
import math import matplotlib.pyplot as plt def T(n): if n<1: return 1 return T(n-1)+3*n+1 y1 = [] y2 = [] x = range(0,501) for i in range (0,501): y1.append(T(i)) y2.append(i**2) #print(i,": ",T(i)," ",i**3) plt.plot(y1,x) plt.show()
240a99862d3fb48da26e6622d5fac4bd6856f88f
escovin/Delivery_Routing_System
/ReadCSV.py
3,288
3.625
4
import csv from HashTable import HashMap with open('WGUInputData.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') insert_into_hash_table = HashMap() # Calls the Hashmap class to create an object first_truck = [] # first truck delivery list second_truck = [] # second truck delivery list first_truck_second_trip = [] # third truck delivery list # Reads values from CSV and creates key/value pairs # Space-time complexity is O(N) for row in readCSV: package_ID_row_value = row[0] address_row_value = row[1] city_row_value = row[2] state_row_value = row[3] zip_row_value = row[4] delivery_row_value = row[5] size_row_value = row[6] note_row_value = row[7] delivery_start = '' address_location = '' delivery_status = 'At hub' iterate_value = [package_ID_row_value, address_location, address_row_value, city_row_value, state_row_value, zip_row_value, delivery_row_value, size_row_value, note_row_value, delivery_start, delivery_status] key = package_ID_row_value value = iterate_value # Constraints for the list of packages that are loaded onto the trucks # The data structure transfers all attributes of a package into a nested list. # This allows for quick lookup and sorting based on package details. # The set of constraints that determine which packages are loaded in either of the two trucks follows. if value[6] != 'EOD': if 'Must' in value[8] or 'None' in value[8]: first_truck.append(value) # this is a list that represents the first truck if 'Can only be' in value[8]: second_truck.append(value) if 'Delayed' in value[8]: second_truck.append(value) # corrects package address if '84104' in value[5] and '10:30' not in value[6]: first_truck_second_trip.append(value) if 'Wrong address listed' in value[8]: value[2] = '410 S State St' value[5] = '84111' first_truck_second_trip.append(value) if value not in first_truck and value not in second_truck and value not in first_truck_second_trip: if len(second_truck) > len(first_truck_second_trip): first_truck_second_trip.append(value) else: second_truck.append(value) insert_into_hash_table.insert(key, value) # adds all values in csv to to hash table # function for getting the full list of values at the start of the day. # Space-time complexity is O(1) def get_hash_map(): return insert_into_hash_table # function for grabbing packages loaded into the first truck # Space-time complexity is O(1) def check_first_truck_first_trip(): return first_truck # function for grabbing packages loaded into the second truck # Space-time complexity is O(1) def check_second_truck_first_trip(): return second_truck # function for grabbing the packages that are loaded into the first truck last # Space-time complexity is O(1) def check_first_truck_second_trip(): return first_truck_second_trip
f23af68d6156597af0f012338971efa70f524812
kpetrone1/kpetrone1
/s11_who_is_thief.py
633
4.03125
4
""" Four suspects; one of them is a thief. In interrogation John said: I am not the thief. Paul said: George is the thief. George said: It must be Ringo. Ringo said: George is lying. Among them, three were telling the truth while one was lying. Could you find out who is the thief? """ for thief in ['John','Paul','George','Ringo']: # assume theif is John (or the lement in the list) sum = (thief != 'John') + (thief == 'George') + (thief == 'Ringo') + (thief != 'Ringo') # test each statement and add the sum of truths (truth = 1, False = 0) if sum == 3: print("The thief is {}." .format(thief))
3f7a247198d94307902d20edec5016511a4343e6
kpetrone1/kpetrone1
/s7hw_mysqrt_final.py
1,348
4.4375
4
#23 Sept 2016 (Homework following Session 7) #While a few adjustments have been made, the majority of the following code has been sourced from a blog titled "Random Thoughts" by Estevan Pequeno at https://epequeno.wordpress.com/2011/01/04/solutions-7-3/. #function to test Newton's method vs. math.sqrt() to find square root #Note: Newton's method is represented below as "mysqrt," and math.sqrt, I believe, is represented as "libmath_method." import math def mysqrt(n): a = float(n) x = n / 2 #rough estimate i = 0 while i < 10: y = (x + n/x) / 2 #Newton's method x = y i += 1 return y def libmath_method(n): a = float(n) return math.sqrt(n) #This function has a mix of int, str and float, so there is a bit of conversion going on. def test_square_root(): for i in range(1,10): n = str(mysqrt(i)) #mysqrt() gets int and returns float. Change to str. l = str(libmath_method(i)) #libmath_method() gets int and returns float. Change to str. ab = abs(mysqrt(i)-libmath_method(i)) #out as int in as float, no str if (len(n) or len (l)) == 3: print(i, n, ' ', 1, ' ', ab) elif len(n) == 12: print(i, n, ' ', ab) else: print(i, n, l, ' ', ab) test_square_root()
a046002c3988d9265c2e8095e592bed65e041a5f
kpetrone1/kpetrone1
/s11hw_dict.py
1,141
3.875
4
# >> HOMEWORK: DICTIONARIES << # Exercise 1 # def histogram(s): # d = {} # for c in s: # d[c] = s.get(c, 0) #? How does one add an entire item (that is, BOTH the key and its corresponding value) to a dictionary? # return d # name = 'kaija' # print(histogram(name)) def check_if_word_is_in_wordlist(s): document = open('words.txt') d = {} for line in document: word = line.strip() # define a function that determines if s (the string) is in the dictionary # new dictionary if word in d: d[word] += 1 # the value of word in dictionary increases by 1 else: d[word] = 1 return s in d print(check_if_word_is_in_wordlist('apple')) print(check_if_word_is_in_wordlist('kaija')) # 2. def has_duplicates(l): # l = given list d = {} for i in l: if i not in d: d[i] = 1 else: return True return False name = ['k','a','i','j','a'] print(has_duplicates(name))
ce31d13f1220f58de9e54d501219344e4123eadd
ads2100/paython
/day10.py
358
3.875
4
age = 33 text ="my name bodour i am {}" print(text.format(age)) qunantity = 77 itemno = 123 price= 78 myorder = "i want {} pieces of item {} for {} dollars." print(myorder.format(qunantity,itemno,price)) qunantity = 77 itemno = 123 price= 78 myorder = "i want {2} pieces of item {0} for {1} dollars." print(myorder.format(qunantity,itemno,price))
bec28c0850c9da9d478884a986ba990df8a16b37
ads2100/paython
/day.17.2.py
335
4
4
thistuple = ("mohamed","ahmed","sarh") if "mohamed" in thistuple: print("yes,he is here") thistuple = ("bodour amizing girl,")*4 print(thistuple) x = (1,3,5,5) q = (9,6,6) v = x+q print(v) print (len(v)) i = (("hi","wlcome","sir")) print(i) thistuple =[2,4,4,"a","e"] thistuple = tuple(thistuple) print(thistuple)
17338eb251bf410b6b300ec7d34bbd80b1101041
ads2100/paython
/day20.py
274
3.890625
4
thisset = {} print(thisset) thisset = {"a","h","y"} print(thisset) y = {"ahmed","bodour","asma","bodour",1,8,8} print(y) for x in y: print(x) print("bodour" in y) y.add("soso") print(y) u = {"say","hi"} u.update(["welcome"]) print(u)
fd729bb04abad4f1467bc547006bc5efac30e373
hliu1006/Python-Project
/Machine Learning/Predict Quality Of Wine/game-of-wines.py
24,490
3.671875
4
#!/usr/bin/env python # coding: utf-8 # # Part 1: Using Data Science to Understand What Makes Wine Taste Good # ## Section 1: Data Exploration # # In this section, we'll do some exploratory analysis to understand the nature of our data and the underlying distribution. # ### First, import some necessary libraries. # # ### Click the below cell block and run it. # In[4]: # Import libraries necessary for this project import numpy as np import pandas as pd from time import time from IPython.display import display # Allows the use of display() for displaying DataFrames import matplotlib.pyplot as plt import seaborn as sns # Import supplementary visualization code visuals.py from project root folder import visuals as vs # Pretty display for notebooks get_ipython().run_line_magic('matplotlib', 'inline') # ### Usage of these libraries: # * [numpy](http://www.numpy.org/) is a package in python that is used for scientific computing. It supports higher-order mathematical functions, higher dimensional arrays, matrices and other data structures. # * [pandas](https://pandas.pydata.org/) is a very popular library that is used for a lot of data analysis and statistics related problems. # * [time](https://docs.python.org/3.7/library/time.html) - standard module in python that allows for time related functions # * [display](http://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html?highlight=display) is a module in the IPython toolkit that helps you display data structures in a nice, readable format. # * [matplotlib](https://matplotlib.org/) is a very popular visualization library that lets you create a wide array of figures, charts and graphs in the IPython Notebook # * [seaborn](https://seaborn.pydata.org/index.html) is another visualization tool that uses matplotlib underneath, and provides you with easy-to-use APIs for visualization. It also makes your graphs more prettier! # ### Next, we'll load the dataset for red wines, and display the first 5 columns. Run the below cell block # In[5]: # TODO: Load the Red Wines dataset data = pd.read_csv("data/winequality-red.csv", sep=';') # TODO: Display the first five records display(data.head(n=5)) # ## Now, let's do some basic preliminary analysis of our data: # ### We'll begin by first seeing if our data has any missing information # In[6]: # TODO: Find if the data has any null information data.isnull().any() # ### Get additional information about the features in the data-set and their data types: # In[7]: #TODO: Get additional information about the data data.info() # #### The last column *quality* is a metric of how good a specific wine was rated to be. For our purposes, let's consider all wines with ratings 7 and above to be of very good quality, wines with 5 and 6 to be of average quality, and wines less than 5 to be of insipid quality. # In[9]: # Total number of wines n_wines = data.shape[0] # Number of wines with quality rating above 6 quality_above_6 = data.loc[(data['quality'] > 6)] n_above_6 = quality_above_6.shape[0] # TODO: Number of wines with quality rating below 5 quality_below_5 = data.loc[(data['quality'] < 5)] n_below_5 = quality_below_5.shape[0] # TODO: Number of wines with quality rating between 5 to 6 quality_between_5 = data.loc[(data['quality'] >= 5) & (data['quality'] <= 6)] n_between_5 = quality_between_5.shape[0] # Percentage of wines with quality rating above 6 greater_percent = n_above_6*100/n_wines # Print the results print("Total number of wine data: {}".format(n_wines)) print("Wines with rating 7 and above: {}".format(n_above_6)) print("Wines with rating less than 5: {}".format(n_below_5)) print("Wines with rating 5 and 6: {}".format(n_between_5)) print("Percentage of wines with quality 7 and above: {:.2f}%".format(greater_percent)) # ### Run the following cell block to see the distributions on a graph: # In[11]: # TODO: Visualize skewed continuous features of original data vs.distribution(data, "quality") # ### Get useful statistics, such as mean, median and standard deviation of the features: # In[12]: #TODO: Get some additional statistics, like mean, median and standard deviation # Some more additional data analysis display(np.round(data.describe())) # As we can see, most fines fall under **average quality (between 5 and 6)**. Wines which were rated high are in the lower hundreds, whereas there are very few wines that aren't tasty enough (low ratings). # # Next, since our aim is to predict the quality of wines, we’ll now extract the last column and store it separately. # ## Section 2: Exploring Relationships between features # In[13]: #TODO: Draw a scatter-plot of features pd.plotting.scatter_matrix(data, alpha = 0.3, figsize = (40,40), diagonal = 'kde'); # In[14]: #TODO: Draw a heatmap between features correlation = data.corr() # display(correlation) plt.figure(figsize=(14, 12)) heatmap = sns.heatmap(correlation, annot=True, linewidths=0, vmin=-1, cmap="RdBu_r") # In[17]: #Visualize the co-relation between pH and fixed Acidity #Create a new dataframe containing only pH and fixed acidity columns to visualize their co-relations fixedAcidity_pH = data[['pH', 'fixed acidity']] #Initialize a joint-grid with the dataframe, using seaborn library gridA = sns.JointGrid(x="fixed acidity", y="pH", data=fixedAcidity_pH, height=6) #Draws a regression plot in the grid gridA = gridA.plot_joint(sns.regplot, scatter_kws={"s": 10}) #Draws a distribution plot in the same grid gridA = gridA.plot_marginals(sns.distplot) # In[19]: #TODO: Visualize a plot between Citric Acid levels and Fixed Acidity #Create a new dataframe containing only Citric Acid and fixed acidity columns to visualize their co-relations fixedAcidity_citricAcid = data[['citric acid', 'fixed acidity']] #Initialize a joint-grid with the dataframe, using seaborn library gridB = sns.JointGrid(x="fixed acidity", y="citric acid", data=fixedAcidity_citricAcid, height=6) #Draws a regression plot in the grid gridB = gridB.plot_joint(sns.regplot, scatter_kws={"s": 10}) #Draws a distribution plot in the same grid gridB = gridB.plot_marginals(sns.distplot) # In[21]: # Visualize density vs fixed acidity fixedAcidity_density = data[['density', 'fixed acidity']] gridB = sns.JointGrid(x="fixed acidity", y="density", data=fixedAcidity_density, height=6) gridB = gridB.plot_joint(sns.regplot, scatter_kws={"s": 10}) gridB = gridB.plot_marginals(sns.distplot) # In[26]: #Visualize quality vs volatile acidity volatileAcidity_quality = data[['quality', 'volatile acidity']] g = sns.JointGrid(x="volatile acidity", y="quality", data=volatileAcidity_quality, height=6) g = g.plot_joint(sns.regplot, scatter_kws={"s": 10}) g = g.plot_marginals(sns.distplot) # In[25]: #We can visualize relationships of discreet values (quality vs volatile acidity) better with a bar plot fig, axs = plt.subplots(ncols=1,figsize=(10,6)) sns.barplot(x='quality', y='volatile acidity', data=volatileAcidity_quality, ax=axs) plt.title('quality VS volatile acidity') plt.tight_layout() plt.show() plt.gcf().clear() # In[28]: quality_alcohol = data[['alcohol', 'quality']] g = sns.JointGrid(x="alcohol", y="quality", data=quality_alcohol, height=6) g = g.plot_joint(sns.regplot, scatter_kws={"s": 10}) g = g.plot_marginals(sns.distplot) # In[32]: #TODO: Visualize quality vs alcohol with a bar plot fig, axs = plt.subplots(ncols=1,figsize=(10,6)) sns.barplot(x='quality', y='alcohol', data=quality_alcohol, ax=axs) plt.title('quality VS alcohol') plt.tight_layout() plt.show() plt.gcf().clear() # In[37]: # TODO (OPTIONAL): Select any two features of your choice and view their relationship quality_alcohol = data[['citric acid', 'residual sugar']] g = sns.JointGrid(x="residual sugar", y="citric acid", data=quality_alcohol, height=6) g = g.plot_joint(sns.regplot, scatter_kws={"s": 10}) g = g.plot_marginals(sns.distplot) fig, axs = plt.subplots(ncols=1,figsize=(10,6)) sns.barplot(x='residual sugar', y='citric acid', data=quality_alcohol, ax=axs) plt.title('citric acid VS residual sugar') plt.tight_layout() plt.show() plt.gcf().clear() # ## Outlier Detection: # # Detecting outliers in the data is extremely important in the data preprocessing step of any analysis. The presence of outliers can often skew results which take into consideration these data points. There are many "rules of thumb" for what constitutes an outlier in a dataset. Here, we will use [Tukey's Method for identfying outliers](http://datapigtechnologies.com/blog/index.php/highlighting-outliers-in-your-data-with-the-tukey-method/): An **outlier step** is calculated as **1.5** times the **interquartile range (IQR)**. A data point with a feature that is beyond an outlier step outside of the IQR for that feature is considered abnormal. # # In the code block below: # # * Assign the value of the 25th percentile for the given feature to Q1. Use np.percentile for this. # * Assign the value of the 75th percentile for the given feature to Q3. Again, use np.percentile. # * Assign the calculation of an outlier step for the given feature to step. # * Optionally remove data points from the dataset by adding indices to the outliers list. # # **NOTE:** If you choose to remove any outliers, ensure that the sample data does not contain any of these points! # Once you have performed this implementation, the dataset will be stored in the variable good_data. # In[38]: #TODO: Find outliers for each feature # For each feature find the data points with extreme high or low values for feature in data.keys(): # TODO: Calculate Q1 (25th percentile of the data) for the given feature Q1 = np.percentile(data[feature], q=25) # TODO: Calculate Q3 (75th percentile of the data) for the given feature Q3 = np.percentile(data[feature], q=75) # TODO: Use the interquartile range to calculate an outlier step (1.5 times the interquartile range) interquartile_range = Q3 - Q1 step = 1.5 * interquartile_range # Display the outliers print("Data points considered outliers for the feature '{}':".format(feature)) display(data[~((data[feature] >= Q1 - step) & (data[feature] <= Q3 + step))]) # OPTIONAL: Select the indices for data points you wish to remove outliers = [] # Remove the outliers, if any were specified good_data = data.drop(data.index[outliers]).reset_index(drop = True) # # Part 2: Using Machine Learning to Predict the Quality of Wines # ### Data Preparation: # # ### First, we'll apply some transforms to convert our regression problem into a classification problem. Then, we'll use our data to create feature-set and target labels: # In[46]: #TODO: Convert the regression problem into a classification problem """ For our purposes, all wines with ratings less than 5 will fall under 0 (poor) category, wines with ratings 5 and 6 will be classified with the value 1 (average), and wines with 7 and above will be of great quality (2). """ #Defining the splits for categories. 1–4 will be poor quality, 5–6 will be average, 7–10 will be great bins = [1,4,6,10] #0 for low quality, 1 for average, 2 for great quality quality_labels=[0,1,2] data['quality_categorical'] = pd.cut(data['quality'], bins=bins, labels=quality_labels, include_lowest=True) display(data[~((data[feature] >= Q1 - step) & (data[feature] <= Q3 + step))]) # ### Next, shuffle and split our data-set into training and testing subsets: # In[44]: # Split the data into features and target label quality_raw = data['quality_categorical'] features_raw = data.drop(['quality', 'quality_categorical'], axis = 1) # Import train_test_split from sklearn.model_selection import train_test_split # Import train_test_split from sklearn.model_selection import train_test_split # Split the 'features' and 'income' data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(features_raw, quality_raw, test_size = 0.2, random_state = 0) # Show the results of the split print("Training set has {} samples.".format(X_train.shape[0])) print("Testing set has {} samples.".format(X_test.shape[0])) # ## [scikit-learn](http://scikit-learn.org/) is a handy data science and machine learning library that lets you use ML algorithms in easy to use APIs. # ### Supervised Learning Models # **The following are some of the supervised learning models that are currently available in** [`scikit-learn`](http://scikit-learn.org/stable/supervised_learning.html) **that you may choose from:** # - Gaussian Naive Bayes (GaussianNB) # - Decision Trees # - Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting) # - K-Nearest Neighbors (KNeighbors) # - Stochastic Gradient Descent Classifier (SGDC) # - Support Vector Machines (SVM) # - Logistic Regression # ### Implementation - Creating a Training and Predicting Pipeline # To properly evaluate the performance of each model you've chosen, it's important that you create a training and predicting pipeline that allows you to quickly and effectively train models using various sizes of training data and perform predictions on the testing data. Your implementation here will be used in the following section. # In the code block below, you will need to implement the following: # - Import `fbeta_score` and `accuracy_score` from [`sklearn.metrics`](http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics). # - Fit the learner to the sampled training data and record the training time. # - Perform predictions on the test data `X_test`, and also on the first 300 training points `X_train[:300]`. # - Record the total prediction time. # - Calculate the accuracy score for both the training subset and testing set. # - Calculate the F-score for both the training subset and testing set. # - Make sure that you set the `beta` parameter! # ### Next, we will write a function that will accept a ML algorithm of our choice, and use our data to train it # In[48]: # Import two classification metrics from sklearn - fbeta_score and accuracy_score from sklearn.metrics import fbeta_score from sklearn.metrics import accuracy_score def train_predict_evaluate(learner, sample_size, X_train, y_train, X_test, y_test): ''' inputs: - learner: the learning algorithm to be trained and predicted on - sample_size: the size of samples (number) to be drawn from training set - X_train: features training set - y_train: quality training set - X_test: features testing set - y_test: quality testing set ''' results = {} """ Fit/train the learner to the training data using slicing with 'sample_size' using .fit(training_features[:], training_labels[:]) """ start = time() # Get start time of training learner = learner.fit(X_train[:sample_size], y_train[:sample_size]) #Train the model end = time() # Get end time of training # Calculate the training time results['train_time'] = end - start """ Get the predictions on the first 300 training samples(X_train), and also predictions on the test set(X_test) using .predict() """ start = time() # Get start time predictions_train = learner.predict(X_train[:300]) predictions_test = learner.predict(X_test) end = time() # Get end time # Calculate the total prediction time results['pred_time'] = end - start # Compute accuracy on the first 300 training samples which is y_train[:300] results['acc_train'] = accuracy_score(y_train[:300], predictions_train) # Compute accuracy on test set using accuracy_score() results['acc_test'] = accuracy_score(y_test, predictions_test) # Compute F1-score on the the first 300 training samples using fbeta_score() results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta=0.5, average='micro') # Compute F1-score on the test set which is y_test results['f_test'] = fbeta_score(y_test, predictions_test, beta=0.5, average='micro') # Success print("{} trained on {} samples.".format(learner.__class__.__name__, sample_size)) # Return the results return results # ### Implementation: Initial Model Evaluation # In the code cell, you will need to implement the following: # - Import the three supervised learning models you've discussed in the previous section. # - Initialize the three models and store them in `'clf_A'`, `'clf_B'`, and `'clf_C'`. # - Use a `'random_state'` for each model you use, if provided. # - **Note:** Use the default settings for each model — you will tune one specific model in a later section. # - Calculate the number of records equal to 1%, 10%, and 100% of the training data. # - Store those values in `'samples_1'`, `'samples_10'`, and `'samples_100'` respectively. # # **Note:** Depending on which algorithms you chose, the following implementation may take some time to run! # # Further reading: https://stackoverflow.com/questions/31421413/how-to-compute-precision-recall-accuracy-and-f1-score-for-the-multiclass-case # In[50]: # TODO: Import any three supervised learning classification models from sklearn from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier #from sklearn.linear_model import LogisticRegression # TODO: Initialize the three models clf_A = GaussianNB() clf_B = DecisionTreeClassifier(max_depth=None, random_state=None) clf_C = RandomForestClassifier(max_depth=None, random_state=None) # TODO: Calculate the number of samples for 1%, 10%, and 100% of the training data # HINT: samples_100 is the entire training set i.e. len(y_train) # HINT: samples_10 is 10% of samples_100 # HINT: samples_1 is 1% of samples_100 samples_100 = len(y_train) samples_10 = int(samples_100 * 0.1) samples_1 = int(samples_100 * 0.01) # TODO: Collect results on the learners results = dict() clfs = [clf_A, clf_B, clf_C] samples = [samples_100, samples_10, samples_1] for clf in clfs: clf_name = str(type(clf)) results[clf_name] = dict() for i in range (len(samples)): results[clf_name][i] = train_predict_evaluate(clf, samples[i], X_train, y_train, X_test, y_test) # TODO: Run metrics visualization for the three supervised learning models chosen using function in visuals.py vs.visualize_classification_performance(results) # ### Question: Why does Gaussian Naive Bayes perform poorly compared to the other methods? # ### Answer: # GNB assumes independence between features. # ---- # ## Feature Importance # # An important task when performing supervised learning on a dataset like the census data we study here is determining which features provide the most predictive power. By focusing on the relationship between only a few crucial features and the target label we simplify our understanding of the phenomenon, which is most always a useful thing to do. In the case of this project, that means we wish to identify a small number of features that most strongly predict the quality of wines. # # Choose a scikit-learn classifier (e.g., adaboost, random forests) that has a `feature_importance_` attribute, which is a function that ranks the importance of features according to the chosen classifier. In the next python cell fit this classifier to training set and use this attribute to determine the top 5 most important features for the wines dataset. # ### Implementation - Extracting Feature Importance # Choose a `scikit-learn` supervised learning algorithm that has a `feature_importance_` attribute availble for it. This attribute is a function that ranks the importance of each feature when making predictions based on the chosen algorithm. # # In the code cell below, you will need to implement the following: # - Import a supervised learning model from sklearn if it is different from the three used earlier. # - Train the supervised model on the entire training set. # - Extract the feature importances using `'.feature_importances_'`. # In[51]: # TODO: Import a supervised learning model that has 'feature_importances_' model = RandomForestClassifier(max_depth=None, random_state=None) # TODO: Train the supervised model on the training set using .fit(X_train, y_train) model = model.fit(X_train, y_train) # TODO: Extract the feature importances using .feature_importances_ importances = model.feature_importances_ print(X_train.columns) print(importances) # TODO: Plot importances vs.feature_plot(importances, X_train, y_train) # ## Hyperparameter tuning using GridSearchCV: # In[52]: # TODO: Import 'GridSearchCV', 'make_scorer', and any other necessary libraries from sklearn.model_selection import GridSearchCV from sklearn.metrics import make_scorer # TODO: Initialize the classifier clf = RandomForestClassifier(max_depth=None, random_state=None) # Create the parameters or base_estimators list you wish to tune, using a dictionary if needed. # Example: parameters = {'parameter_1': [value1, value2], 'parameter_2': [value1, value2]} """ n_estimators: Number of trees in the forest max_features: The number of features to consider when looking for the best split max_depth: The maximum depth of the tree """ parameters = {'n_estimators': [10, 20, 30], 'max_features':[3,4,5, None], 'max_depth': [5,6,7, None]} # TODO: Make an fbeta_score scoring object using make_scorer() scorer = make_scorer(fbeta_score, beta=0.5, average="micro") # TODO: Perform grid search on the claszsifier using 'scorer' as the scoring method using GridSearchCV() grid_obj = GridSearchCV(clf, parameters, scoring=scorer) # TODO: Fit the grid search object to the training data and find the optimal parameters using fit() grid_fit = grid_obj.fit(X_train, y_train) # Get the estimator best_clf = grid_fit.best_estimator_ # Make predictions using the unoptimized and model predictions = (clf.fit(X_train, y_train)).predict(X_test) best_predictions = best_clf.predict(X_test) # Report the before-and-afterscores print("Unoptimized model\n------") print("Accuracy score on testing data: {:.4f}".format(accuracy_score(y_test, predictions))) print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, predictions, beta = 0.5, average="micro"))) print("\nOptimized Model\n------") print(best_clf) print("\nFinal accuracy score on the testing data: {:.4f}".format(accuracy_score(y_test, best_predictions))) print("Final F-score on the testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = 0.5, average="micro"))) # ## Finally, you can test out your model by giving it a bunch of inputs: # In[53]: """Give inputs in this order: fixed acidity, volatile acidity, citric acid, residual sugar, chlorides, free sulfur dioxide, total sulfur dioxide, density, pH, sulphates, alcohol """ wine_data = [[8, 0.2, 0.16, 1.8, 0.065, 3, 16, 0.9962, 3.42, 0.92, 9.5], [8, 0, 0.16, 1.8, 0.065, 3, 16, 0.9962, 3.42, 0.92, 1 ], [7.4, 2, 0.00, 1.9, 0.076, 11.0, 34.0, 0.9978, 3.51, 0.56, 0.6]] # Show predictions for i, quality in enumerate(best_clf.predict(wine_data)): print("Predicted quality for Wine {} is: {}".format(i+1, quality)) # ## Question: What conclusions can you draw based on the above observations? Would you say that the model is more good at predicting average quality wines? Why? # # TODOS: # 1. Try solving this exercise again as a regression problem. Some of the common algorithms you can try from sklearn are *DecisionTreeRegressor*, *RandomForestRegressor*, and using *AdaBoostRegressor* with *DecisionTreeRegressor*. Some of the performance metrics that you might need to use in place of Accuracy and f1score are Mean Squared Error and R2Score # # 2. Try using the White Wines data-set in place of the Red Wines #
72608782eca9e07321c885c499b88d168795cae4
mrollins/ithelps
/ithelps/impl.py
863
3.953125
4
#!/usr/bin/env python3 import itertools as it from typing import Iterable def munch(iterable: Iterable, n: int): """ Consume an iterable in sequential n-length chunks. >>> [list(x) for x in munch([1, 2, 3, 4], 2)] [[1, 2], [3, 4]] :param iterable: sequence to iterate. :param n: int - Chunk length. :return: Iterator """ args = [iter(iterable)] * n return zip(*args) def slide(iterable: Iterable, n: int): """ Slide an n-length window over an iterable. >>> [list(x) for x in slide([1, 2, 3, 4], 2)] [[1, 2], [2, 3], [3, 4]] :param iterable: Sequence to iterate. :param n: int - Window length. :return: Iterator """ iterators = it.tee(iterable, n) for i, iterator in enumerate(iterators): for _ in range(i): next(iterator, None) return zip(*iterators)
dd6787ead793162ffc2fdca263fd49ba64611fa7
AustinRivers100/exercises100
/exercises7.py
2,514
3.765625
4
#第7次作业记录请朋友来玩 #step1 把文本文件读取进来 from random import randint f = open('Record.txt') #打开文件 Record_lines = f.readlines() #用readlines把文件内容按行读取进来得到一个列表 #print(type(Record_lines), Record_lines ) #可以查看下处理效果 f.close() #step2 因为读进来的是一个包含多项字符串的列表,需要还处理成可以直接使用的数据 game_dict = {} for i in Record_lines: Record = i.split()#去处空白符 #print(Record ) game_dict[Record[0]] = Record[1:] #给字典赋值 #print (game_dict) name = input('what is your name:') players_name = game_dict.get(name) #如果用户在字典里,直接获取对应玩家游戏数据 if players_name is None: players_name = [0,0,0]#如果是新用户,则各项数据初始化 total_Rounds = int(players_name[0]) total_times = int(players_name[1]) Thefastest_Round = int(players_name[2]) #print(players_name) #查看下处理效果 print('Welcome',name, ",In Last Record,You have played %d Rounds,try for %d times,fastest try is %d." % (total_Rounds, total_times,Thefastest_Round )) while True: total_Rounds += 1 #重新开始游戏,总轮数+1次,所以要放在这行 time = 0 #这是内层循环的变量,初始值放这里 guess = randint(1,10) #重新开始游戏,随机数变化1次 while True: answer = int(input(" What is your guess: ")) time +=1 #每次游戏的轮数,猜一次就记录一次,所以要放在这一行 total_times += 1 #猜一次,轮数加1次 if answer > guess: print( "too big") elif answer < guess: print( "too small") else: print("Oh,that's great,you did it!") print("IN this round,you have guessed %d times."%(time)) break if Thefastest_Round>time or Thefastest_Round == 0: #求最快值,最快不可能是0,所以。。。 Thefastest_Round = time print("You have played %d Rounds,try for %d times,fastest try is %d." % (total_Rounds, total_times,Thefastest_Round )) tips = input("'y' key to Continue,else to EXIT") if tips != str('y'): print("see you next!") break ##step3写入数据保存 game_dict[name] = [str(total_Rounds),str(total_times),str(Thefastest_Round)] new_data = '' for j in game_dict: line = j + ' ' + ' '.join(game_dict[j])+ '\n' new_data += line F = open('Record.txt','w') F.write(new_data) F.close()
0797bf0cd9f567df436e5a6ee8842418c09863bf
TheChandaChen/github-upload
/Assignment_7.1.py
162
4.0625
4
# Use words.txt as the file name fname = input("Enter file name: ") fh = open(fname) for line in fh: cap = line.upper() cap = cap.rstrip() print(cap)
023879185123a87e7b9c8f6f949f93a66f417e77
harsh52/Assignments-competitive_coding
/Algo_practice/MissingInterger.py
813
3.6875
4
''' Write a function: def solution(A) that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000]. ''' def solution(A): A.sort() set1 = set(A) #print(set1) #set1.sort() j = 0 for i in set1: j += 1 if(i!=j): #print(j) return j elif(j==len(set1)): #print(j+1) if(j+1<0): return 1 else: return(j+1) A = [-1, -3] solution(A)
195af12c76b90e4a16b44df8482e3a3cc2f65a64
harsh52/Assignments-competitive_coding
/Algo_practice/link_list.py
745
3.78125
4
class node: def __init__(self,data): self.data = data self.next = None; class Link_list: def __init__(self): self.start = None; def make_node(self,value): if(self.start==None): self.start = node(value) else: temp = self.start while(temp.next!=None): temp = temp.next temp.next = node(value) def view_list(self): if(self.start==None): print("list is empty",end='\n') else: temp = self.start while(temp!=None): print(temp.data) temp = temp.next link = Link_list() link.make_node(2) link.make_node(8) link.make_node(6) link.view_list()
5b1daf62fd1dd3b13617393cd23ce42ea58a08b4
harsh52/Assignments-competitive_coding
/Amazon_question/function.py
281
3.703125
4
def f(x): if abs(x)<=1: if x==1: return 1 if(x== -1): return -1 if x==0: return 0 else: if x>0: return f(x-1) + f(x-2) if x<0: return f(x+1) + f(x+2) print (f(int(input())))
92297bb3778093c35679b32b2a1ffd22a3339403
harsh52/Assignments-competitive_coding
/Algo_practice/LeetCode/Decode_Ways.py
1,874
4.1875
4
''' A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: "AAJF" with the grouping (1 1 10 6) "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". Given a string s containing only digits, return the number of ways to decode it. Input: s = "12" Output: 2 Explanation: "12" could be decoded as "AB" (1 2) or "L" (12). ''' class Solution: def numDecodings(self, s: str) -> int: s = list(s) #print(s) dp = [0 for _ in range(len(s))] dp[0] = 1 if(len(s) == 1 and s[0] == '0'): return 0 if(s[0] == '0'): dp[0]=0 for i in range(1,len(s)): print(s) #print("in loop") if(s[i-1] == '0' and s[i] == '0'): dp[i] = 0 elif(s[i-1] == '0' and s[i] != '0'): #print("in second") dp[i] = dp[i-1] elif(s[i-1] != '0' and s[i] == '0'): #print("here") if(s[i-1] == '1' or s[i-1] == '2'): dp[i] = (dp[i-2] if i>=2 else 1) print(dp) else: dp[i]=0 else: #print("in last") temp = ''.join(map(str,s[i-1:i+1])) if(int(temp) <= 26): dp[i] = dp[i-1] + (dp[i-2] if i>=2 else 1) else: dp[i] = dp[i-1] #print("test") return(dp[-1])
7acd01f6e13eb10829295829580ae63783583294
harsh52/Assignments-competitive_coding
/Algo_practice/LeetCode/Minimum_Depth_of_Binary_Tree_leetcode.py
918
4.09375
4
''' Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDepth(self, root: TreeNode) -> int: if(root == None): return 0 q = collections.deque() q.append((root,1)) while(q != None): root, depth = q.popleft() if(root.left == None and root.right == None): return(depth) if(root.left != None): q.append((root.left,depth + 1)) if(root.right != None): q.append((root.right,depth + 1))
0780b7873326cf08a41f744731aed432c6244c91
Battleship-Potemkin-Village/RPN-Calculator
/rpn.py
45,136
3.65625
4
#! /usr/bin/env python3 # vim:fileencoding=utf-8 """ Type in your equation using Reverse Polish Notation. Values (numbers) are added to the stack. Operators act upon the values in the stack. Values/operators can be input individually (pressing ENTER after every number/operator) or by separating the tokens with spaces. Values get "pulled" from the stack when operated upon. For example: the equation "4+22/7=" can be keyed in as "4 22 7 / +" this will divide 22 by 7 then add 4 to the result. Unary operators work on what is in the x register. Binary operators use the x & y registers. A complete list of operators can be displayed by typing in: "help op" """ version = "RPN Calculator version 1.09" # Notes: # ------ # All numbers are stored in floating point notation and are accurate # to within about 15 decimal places. Use the 'show' operator to # display the internal value. # - # The '%' & '%c' operators do NOT consume the y value. This is so # it can be used in subsequent computations. Also, because that's # how the HP-15c does it. # - # The trig functions assume the angle to be in radians. # - # Operators are not case sensitive. SIN, sin and sIn are the same. # Only labels and memory register names ARE case sensitive. # - # Some operators return two values, these will be placed in the x # & y registers. # - # 'fix' uses the absolute value of the integer supplied # - # The ',' & '.' can be used in place of the '<' & '>' symbols. # - # Type 'k' to see keyboard shortcuts. # - # Type 'help op' for a list of available operators. # """ # Products currently used to create this script: # Python 3.9.1 (www.python.org) # Vim 8.1.1401 (www.vim.org) # The next line is for the VIM text editor: # vim: tabstop=2 expandtab shiftwidth=2 softtabstop=2 # Going to keep it simple. This calculator reads the input # line and anything that it determines to be a number gets # pushed onto the stack's bottom while everything in the stack # gets "lifted" up one position (what was in "t:" gets # discarded. # # Every value determined NOT to be a number is assumed to be an # operator. Every number or operator must be separated by # either a [space] or an [enter]. All operators operate on the # contents of the stack. # # Every value used by an operator gets pulled from the stack # causing the stack to "drop" (exceptions made for '%' & '%c") # everytime a value is used. When the stack "drops" the "t:" # value is copied to the "z:" register and stays in the "t:" # register. # # The size of the stack can be changed below to something larger # than 4, but caution: this might upset programs that rely on # a fixed stack size. I suppose one could easily edit this # program to have an 'infinite' stack just by replacing the body # of 'push()' & 'pull()' with stack.append(x) & stack.pop(). # # Only known issue I know of is that the display doesn't show really # small numbers in scientific notation. It just shows them as '0.0' import math import os import ast import random import readline # all you need to recall command history. # Global variables: # stack_size can be changed below (4 is the minimum), but only if # there isn't a .mem file to read the stack from. # memnam is the file that stores the calculator's memory settings. # prognam is a text file that contains user defined programs. # op_dict is a help file for all commands. stack_size = 4 # size of the stack. stack_min = 4 # minimum stack size. stack = [] # List of ? size to hold the stack's values. mem = {} # Dictionary of memory registers. memnam = os.path.splitext(__file__)[0] + ".mem" prognam = os.path.splitext(__file__)[0] + ".txt" # common usage: print(f'{XXX}') if os.name == "posix": # other OS might not handle these properly: RED = "\033[91m" # Makes the text following it red GRN = "\033[92m" # Green YLW = "\033[93m" # Yellow BLU = "\033[94m" # Blue PUR = "\033[35m" # Purple CYN = "\033[36m" # Cyan WHT = "\033[0m" # White (default) CLS = "\x1b[2J" # Clears the screen above the stack SIG = "\u03A3" # Sigma character LSG = "\u03C3" # Lowercase Sigma character SS2 = "\u00B2" # Superscript 2 (as in ^2) OVR = "\u0304" # Puts a line over the char that precedes it SQR = "\u221A" # square root symbol else: RED = "" GRN = "" YLW = "" BLU = "" PUR = "" CYN = "" WHT = "" CLS = "" SIG = "E" LSG = "o" SS2 = "^2" OVR = "(mn)" SQR = "" kbsc2 = { # just so we don't have to use shift key very much "c.f": "c>f", "f.c": "f>c", "p.r": "p>r", "r.p": "r>p", "x,0?": "x<0?", "x,=0?": "x<=0?", "x,=y?": "x<=y?", "x,y?": "x<y?", "x.0?": "x>0?", "x.=0?": "x>=0?", "x.=y?": "x>=y?", "x.y?": "x>y?", "=": "+", # we don't use '=' in RPN, so save the shift key. "**": "^", # This one's just for Python compatibility. } op_dict = { # dictionary of operators for 'help' function "+": "Sums the contents of x and y.", "-": "Subtracts x from y.", "*": "Multiplies x times y.", "/": "Divide y by x.", "xroot": "The xth root of base y.", "r>p": "Rectangular to polar (y = angle, x = magnitude)", "p>r": "Polar to rectangular (y = angle, x = magnitude)", "%": "x percent of y (y remains in stack).", "%c": "Percentage change from y to x (y remains in stack).", "cnr": "Combinations of x in y items.", "pnr": "Permutations of x in y items.", "sqrt": "Square root of x.", "sq": "Square of x.", "e": "Natural antilogaritm of x (e^x).", "ln": "Natural logarithm of x.", "tx": "Base 10 raised to the x (10^x).", "log": "Base 10 log of x.", "rcp": "reciprocal of x (1/x).", "chs": "Change the current sign of x (+/-).", "abs": "Absolute value of x (|x|).", "ceil": "raises x to the next highest integer.", "floor": "lowers x to the next lowest integer.", "!": "Factorial of integer x (x!).", "gamma": "The Gamma of x.", "frac": "Fractional portion of x.", "int": "Integer portion of x.", "rnd": "Rounds x to the displayed value.", "ratio": "Convert x to a ratio of 2 integers (y/x).", "sin": "Sine of angle in x (x is in radians).", "cos": "Cosine of angle in x (x is in radians).", "tan": "Tangent of angle in x (x is in radians).", "asin": "Arcsine of y/r ratio in x (returns angle in radians).", "acos": "Arccosine of x/r ratio in x (returns angle in radians).", "atan": "Arctangent of y/x ratio in x (returns angle in radians).", "sinh": "Hyperbolic sine of angle in x (x in radians).", "cosh": "Hyperbolic cosine of angle in x (x in radians).", "tanh": "Hyperbolic tangent of angle in x (x in radians).", "asinh": "Hyperbolic arcsine of ratio x (result in radians).", "acosh": "Hyperbolic arccosine of ratio x (result in radian).", "atanh": "Hyperbolic arctangent of ratio x (result in radians).", "atan2": "Arctangent of y/x (considers signs of x & y).", "hyp": "Hypotenuse of right sides x & y.", "rad": "Converts degrees to radians.", "deg": "Converts radians to degrees.", "in": "Converts centimeters to inches.", "cm": "Converts inches to centimeters.", "gal": "Converts litres to gallons.", "ltr": "Converts gallons to litres.", "lbs": "Converts kilograms to lbs.", "kg": "Converts lbs. to kilograms.", "c>f": "Converts celsius to fahrenheit.", "f>c": "Converts fahrenheit to celsius.", "pi": "Returns an approximate value of pi.", "tau": "Returns approximate value of 2pi.", "swap": "Exchanges the values of x and y.", "dup": "Duplicates the value x in y (lifting the stack).", "clr": "Clears all values in the stack.", "rd": "Rolls the contents of stack down one postition.", "ru": "Rolls the contents of stack up one position.", "cs": "Copy the sign of y to the x value.", "rand": "Generate a random number between 0 and 1.", "fix": "Set the # of decimal places displayed by the value that follows.\n\ If nothing follows it: returns # of decimal places to the stack.", "show": "Display the full value of x.", "sto": "Save the value in x to a named register (STO <ab0>).", "rcl": "Recall the value in a register (RCL <ab0>).", "mem": "Display the memory registers and their contents.", "clrg": "Clears the contents of all the registers.", "lbl": "Designates a label name to follow (LBL <a>).", "exc": "Executes a program starting at a label (EXC <a>).", "gsb": "Branches program to subroutine a label (GSB <a>).", "gto": "Sends program to a label (GTO <a>)", "rtn": "Designates end of program or subroutine.", "pse": "Pauses program and displays current result.", "nop": "Takes up a space. Does nothing else.", "x=0?": "Tests if x equals 0. Skips the next 2 objects if false.", "x!=0?": "Tests if x does not equal 0. Skips the next 2 objects on false.", "x>0?": "Tests if x is greater than 0. Skips the next 2 objects on false.", "x<0?": "Tests if x is less than 0. Skips the next 2 objects on false.", "x>=0?": "Tests if x is greater than or equal to 0. Skips the next 2 objects on false.", "x<=0?": "Tests if x is less than or equal to 0. Skips then next 2 objects on false.", "x=y?": "Tests if x is equal to y. Skips the next 2 objects on false.", "x!=y?": "Tests if x is not equal to y. Skips the next 2 objects on false.", "x>y?": "Tests if x is greater than y. Skips the next 2 objects on false.", "x<y?": "Tests if x is less than y. Skips the next 2 objects on false.", "x>=y?": "Tests if x is greater than or equal to y. Skips the next 2 objects on false.", "x<=y?": "Tests if x is less than or equal to y. Skips the next 2 objects on false.", "del": "Delete a register by name (DEL x).", "^": "Raises y(base) to the x(exponent).", "quit": "Exits the program and saves the contents of the stack and registers.", "ptr": "Returns the value of the command line's pointer.", "dh": "Converts h.mmss to decimal equivalent.", "hms": "Convert decimal time to h.mmss.", "prog": "Print programming memory.", "gcd": "Greatest common divisor of integers x & y.", "cls": "Clear screen of any messages.", "edit": "Enter programming memory.", "scut": "Displays keyboard shortcuts.", "scutadd": "Add a keyboard shortcut: scutadd <shortcut> <operator/value>", "scutdel": "Delete a keyboard shortcut: scutdel <shortcut>", "help": "I'm being repressed! Also: followed by an operator gives detailed info\n\ on that operator, while 'op' will list all operators.", "version": "Display the current version number.", "stat": "When not followed by a modifier adds x & y to the data set.\n\ Following with a number will enter x & y into the data set that many times.\n\ Following with 'show' displays stat info without adding to it.\n\ Following with 'undo' subtracts the values of x & y from the data sets.\n\ Following with 'clear' resets data to zero.\n\ Following with 'save' copies the statistic registers to the user registers.\n\ Following with 'est' uses 'x' to return an estimated 'y'.\n\ Follow with 'n', 'Ex', 'Ey', 'Ex2', 'Ey2', 'Exy', 'x', 'y', 'ox', 'oy',\n\ 'r', 'a', or 'b' to return that value to the stack.", } # function to initialize the size of the stack and fill it with zeros: def initstack(st_size): """Initializes the stack. Fills it with zeros if the .mem file is missing.""" stack = [] st_size = max(st_size, stack_min) while st_size: stack.append(0.0) st_size -= 1 return stack # push a number onto the bottom of the stack raising everything # else up. def push(num): """Push a number onto the stack.""" i = len(stack) - 1 while i: stack[i] = stack[i - 1] i -= 1 stack[0] = float(num) # pull a number off the bottom of stack and drop everything down one. def pull(): """Pull a number off the stack.""" i = 0 num = stack[i] while i < len(stack) - 1: stack[i] = stack[i + 1] i += 1 return num # pull the program data from the text file. # apparently, 'for line in...' closes the file for you # after reading the last line. Thanks, Python! def program_data(progf): """Copies .txt file to memory.""" if os.path.exists(progf): prog = "" for line in open(progf, "r", encoding="utf-8"): line = line.split("#")[0] prog += line prog = prog.split() return prog # This is the guts of the whole thing... def calc(stack, mem, prog_listing, decimal_places, stat_regs): """Processes all input.""" # statistical variables: Sn = stat_regs["Sn"] Sx = stat_regs["Sx"] Sy = stat_regs["Sy"] Sx2 = stat_regs["Sx2"] Sy2 = stat_regs["Sy2"] Sxy = stat_regs["Sxy"] if Sn > 1 and Sn * Sx2 != Sx ** 2 and Sn * Sy2 != Sy ** 2: Mx = Sx / Sn # mean of x My = Sy / Sn # mean of y SDx = math.sqrt((Sn * Sx2 - Sx ** 2) / (Sn * (Sn - 1))) SDy = math.sqrt((Sn * Sy2 - Sy ** 2) / (Sn * (Sn - 1))) # correlation coefficent(r): CCr = (Sn * Sxy - Sx * Sy) / math.sqrt( (Sn * Sx2 - Sx ** 2) * (Sn * Sy2 - Sy ** 2) ) Sa = (Sn * Sxy - Sx * Sy) / (Sn * Sx2 - Sx ** 2) # slope(a): YIb = Sy / Sn - Sa * Sx / Sn # y intercept(b): else: Mx = My = SDx = SDy = CCr = Sa = YIb = 0 incr = True # in case you want to stop the pointer (it_r) from incrementing print(f"{CLS}{YLW}Type 'help' for documentation.") print(f"Type 'help op' for a list of available operators.") print(f"Type 'help <operator>' (without braces) for specifics on an operator.") print(f"Type 'scut' for a list of keyboard shortcuts.{WHT}\n") while True: # loop endlessly until a break statement it_r = 0 # token iterator # Display the stack and prompt for input: reg = ["x:", "y:", "z:", "t:"] # our stack labels i = len(reg) - 1 # index of the last label while i: # prints out 'y', 'z' and 't' print(f"{YLW}{reg[i]}{WHT} {stack[i]:,.{decimal_places}f}") i -= 1 # Now display x and prompt for the command line: # note: cmd_ln is the input line as a Python list. cmd_ln = input(f"{RED}{reg[0]}{WHT} {stack[0]:,.{decimal_places}f} ").split() # clear the screen; probably shouldn't be here. # this works in linux on my chromebook. # remove if you're a history buff. if os.name == "posix": # not sure this will work on other systems print(f"{CLS}") # clear the screen. try: if cmd_ln[it_r].lower() in ["quit", "exit", "close"]: fh = open(memnam, "w", encoding="utf-8") fh.write(f"{stack}\n{mem}\n{decimal_places}\n{kbsc}\n") stat_regs["Sn"] = Sn stat_regs["Sx"] = Sx stat_regs["Sy"] = Sy stat_regs["Sx2"] = Sx2 stat_regs["Sy2"] = Sy2 stat_regs["Sxy"] = Sxy fh.write(f"{stat_regs}") fh.close() break except IndexError: # just pressing ENTER is the same as 'dup' x = pull() push(x) push(x) # Execute the command line # while it_r < len(cmd_ln): try: # make the space delimited string object a token: token = cmd_ln[it_r].lower() # is anything NaN. # # substitute a type shortcut for its operator. if token in kbsc.keys(): token = kbsc[token] if token in kbsc2.keys(): # shift not needed. token = kbsc2[token] # # convoluted way to figure out if the token is a number: if token[0].isdigit() or (token[0] in ".+-" and len(token) > 1): push(token) # # if it doesn't satisfy the above criteria for being a number # it's assumed to be an operator. # # binary operators: # # addition: elif token == "+": x = pull() y = pull() push(x + y) # # subtraction: elif token == "-": x = pull() y = pull() push(y - x) # # multiplication: elif token == "*": x = pull() y = pull() push(x * y) # # division: elif token == "/": x = pull() y = pull() push(y / x) # # raise y to the x: elif token == "^": x = pull() y = pull() push(y ** x) # # x root of y: elif token == "xroot": x = pull() y = pull() push(y ** (1 / x)) # # rectangular to polar conversion: elif token == "r>p": x = pull() y = pull() push(math.atan2(y, x)) # angle push(math.hypot(x, y)) # magnitude print( f"{YLW}Angle(y): {WHT}{math.atan2(y,x):.4f}{YLW};" + f" Magnitude(x): {WHT}{math.hypot(x,y):.4f}\n" ) # # polar to rectangular conversion: elif token == "p>r": x = pull() # magnitude y = pull() # angle push(x * math.sin(y)) # y push(x * math.cos(y)) # x # # x percent of y (leaves y in the stack): elif token == "%": x = pull() y = pull() push(y) push((x / 100) * y) # # percentage change from y to x (leaves y in the stack): elif token == "%c": x = pull() y = pull() push(y) push((x / y - 1) * 100) # # combinations of x into y: elif token == "cnr": x = int(pull()) # forced int here to prevent push line from y = int(pull()) # from getting too long. push( math.factorial(y) / (math.factorial(x) * math.factorial(y - x)) ) # # permutations of x in y: elif token == "pnr": x = int(pull()) # see "cnr" above y = int(pull()) push(math.factorial(y) / math.factorial(y - x)) # # greatest common divisor of x & y: elif token == "gcd": x = pull() y = pull() push(math.gcd(int(x), int(y))) # different method forcing ints # # unary operators: # # square root of x: elif token == "sqrt": x = pull() push(math.sqrt(x)) # # square of x:` elif token == "sq": x = pull() push(x ** 2) # # e to the x (e^x): elif token == "e": x = pull() push(math.exp(x)) # # natural log of x: elif token == "ln": x = pull() push(math.log(x)) # # Base of 10 raised to x: elif token == "tx": x = pull() push(10 ** x) # # base 10 log of x: elif token == "log": x = pull() push(math.log10(x)) # # reciprocal of x (1/x): elif token == "rcp": x = pull() push(1 / x) # # change sign of x: elif token == "chs": x = pull() push(x * -1) # # absolute value of x: elif token == "abs": x = pull() push(math.fabs(x)) # # ceiling of x: elif token == "ceil": x = pull() push(math.ceil(x)) # # floor of x: elif token == "floor": x = pull() push(math.floor(x)) # # factorial of x: elif token == "!": x = pull() push(math.factorial(int(x))) # # gamma of x: elif token == "gamma": x = pull() push(math.gamma(x)) # # fractional portion of x: elif token == "frac": x = pull() push(math.modf(x)[0]) # # integer portion of x: elif token == "int": x = pull() push(math.modf(x)[1]) # # round a number to the display value elif token == "rnd": x = pull() push(round(x, decimal_places)) # # convert a float into a ratio (y/x): elif token == "ratio": x = pull() push(x.as_integer_ratio()[0]) push(x.as_integer_ratio()[1]) # # trigonometry operators: # elif token == "sin": x = pull() push(math.sin(x)) elif token == "cos": x = pull() push(math.cos(x)) elif token == "tan": x = pull() push(math.tan(x)) elif token == "asin": x = pull() push(math.asin(x)) elif token == "acos": x = pull() push(math.acos(x)) elif token == "atan": x = pull() push(math.atan(x)) elif token == "sinh": x = pull() push(math.sinh(x)) elif token == "cosh": x = pull() push(math.cosh(x)) elif token == "tanh": x = pull() push(math.tanh(x)) elif token == "asinh": x = pull() push(math.asinh(x)) elif token == "acosh": x = pull() push(math.acosh(x)) elif token == "atanh": x = pull() push(math.atanh(x)) elif token == "atan2": # arctangent of y/x (considers signs of x & y): x = pull() y = pull() push(math.atan2(y, x)) elif token == "hyp": # hypotenuse of x & y: x = pull() y = pull() push(math.hypot(x, y)) # # angle conversions: # # convert angle in degrees to radians: elif token == "rad": x = pull() push(math.radians(x)) # # convert angle in radians to degrees: elif token == "deg": x = pull() push(math.degrees(x)) # # metric/imperial conversions: # # convert length in centimeters to inches: elif token == "in": x = pull() push(x / 2.54) # # convert length in inches to centimeters: elif token == "cm": x = pull() push(x * 2.54) # # convert volume in litres to gallons: elif token == "gal": x = pull() push((((x * 1000) ** (1 / 3) / 2.54) ** 3) / 231) # # convert volume in gallons to litres: elif token == "ltr": x = pull() push(x * 231 * 2.54 ** 3 / 1000) # # convert weight in kilograms to lbs.: elif token == "lbs": x = pull() push(x * 2.204622622) # # convert weight in lbs. to kilograms: elif token == "kg": x = pull() push(x / 2.204622622) # # convert temperature from celsius to fahrenheit: elif token == "c>f": x = pull() push(x * 9 / 5 + 32) # # convert temperature from celsius to fahrenheit: elif token == "f>c": x = pull() push((x - 32) * 5 / 9) # # convert h.mmss to a decimal value: elif token == "dh": x = pull() h = int(x) m = int((x - h) * 100) s = round((x - h - (m / 100)) * 10000, 4) print(f"{YLW}{h}h:{m}m:{s}s{WHT}\n") push(h + (m / 60) + (s / (60 ** 2))) # # convert decimal time value to h.mmss: elif token == "hms": x = pull() h = int(x) m = int((x * 60) % 60) s = round((x * 3600) % 60, 4) print(f"{YLW}{h}h:{m}m:{s}s{WHT}\n") push(h + m / 100 + s / 10000) # # constant(s): # # the approximate value of pi: elif token == "pi": push(math.pi) # # the approximate value of 2pi: elif token == "tau": push(math.tau) # # stack manipulators: # # swap x and y: elif token == "swap": x = pull() y = pull() push(x) push(y) # # duplicate the value in x: elif token == "dup": x = pull() push(x) push(x) # # clear the contents of the stack: elif token == "clr": i = len(stack) while i: push(0.0) i -= 1 # # 'roll' the stack down one: elif token == "rd": i = 0 t = stack[0] while i < len(stack) - 1: stack[i] = stack[i + 1] i += 1 stack[i] = t # # 'roll' the stack up one: elif token == "ru": i = len(stack) - 1 t = stack[i] while i: stack[i] = stack[i - 1] i -= 1 stack[i] = t # # miscellaneous: # # copy the sign of y to x: elif token == "cs": x = pull() y = pull() push(y) push(math.copysign(x, y)) # # return the value of the cmd line pointer elif token == "ptr": push(it_r) # # generate a pseudo random number between 0 and 1: elif token == "rand": push(random.random()) # # set the number of decimals to the following value: elif token == "fix": it_r += 1 if it_r == len(cmd_ln): # there's nothing after 'fix' push(decimal_places) else: decimal_places = abs(int(cmd_ln[it_r])) # # show the whole value of the x register: elif token == "show": x = pull() push(x) print(f"{YLW}{x:,}{WHT}\n") # # store x in a named 'register': elif token == "sto": x = pull() push(x) it_r += 1 mem[cmd_ln[it_r]] = x # # recall a value from 'memory': elif token == "rcl": it_r += 1 if cmd_ln[it_r] in mem.keys(): push(mem[cmd_ln[it_r]]) print(f"{YLW}{cmd_ln[it_r]}{WHT}\n") else: print( f"{RED}Register {WHT}{cmd_ln[it_r]}{RED} not found.{WHT}\n" ) # # delete a register: elif token == "del": it_r += 1 if cmd_ln[it_r] in mem.keys(): del mem[cmd_ln[it_r]] else: print( f"{RED}Register {WHT}{cmd_ln[it_r]}{RED} not found.{WHT}\n" ) # # display the contents of the memory regsiters: elif token == "mem": print(f"{YLW}Memory registers:") print(f"{str(mem)[1:-1]}{WHT}\n") # # display keyboard shortcuts: elif token == "scut": print(f"{YLW}Keyboard shortcuts:") print(f'{str(kbsc)[1:-1].replace(": ",":")}{WHT}\n') # # add a shortcut to the list: elif token == "scutadd": it_r += 1 key = cmd_ln[it_r] it_r += 1 kbsc[key] = cmd_ln[it_r] # # delete a shortcut from the list: elif token == "scutdel": it_r += 1 key = cmd_ln[it_r] if key in kbsc: del kbsc[key] else: print(f"{RED}Shortcut {WHT}{key}{RED} not found.{WHT}\n") # # clear the contents of the memory registers: elif token == "clrg": mem.clear() print(f"{YLW}Registers cleared.{WHT}\n") # # clear the screen of unwanted messages: elif token == "cls": print(f"{CLS}") # # Programming related commands # # label: only purpose is to be ignored, # along with the token immediately after it. # EXC, GSB, GTO & RTN will use labels. elif token == "lbl": it_r += 1 # now points to the labels descriptor # the it_r += 1 at the end will step over the label's # descriptor # # executes the program starting at label x: # Things got a lot more complicated when I decided # to allow basic calculator style programming... elif token == "exc": # setup a few things to allow jumping around it_r += 1 x = 0 pdict = {} # build dict of labels in the format: {name: location} while x < len(prog_listing): if prog_listing[x].lower() == "lbl": x += 1 pdict[prog_listing[x]] = x x += 1 # if the label exists replace the command line # and set the pointer (it_r) to the start. if cmd_ln[it_r] in pdict: lbl_nam = cmd_ln[it_r] lbl_rtn = [] cmd_ln = prog_listing it_r = pdict[lbl_nam] else: print(f"{RED}Label {WHT}{cmd_ln[it_r]}{RED} not found.{WHT}\n") # # gosub routine: # This tosses the calling location onto the lbl_rtn # stack we created in 'EXC' so we'll know where to # return to. elif token == "gsb": it_r += 1 lbl_rtn.append(it_r) it_r = pdict[cmd_ln[it_r]] # # goto routine: # Just like 'gsb' but no need to go back. elif token == "gto": it_r += 1 it_r = pdict[cmd_ln[it_r]] # # return - for end of program or subroutine: # if called by a 'gsb' will go back to the token # following the 'gsb'. Otherwise it will end the # program. elif token == "rtn": if len(lbl_rtn): it_r = lbl_rtn.pop() else: it_r = 0 cmd_ln = ["nop", "nop"] # # pauses a running program elif token == "pse": input(f"\n{YLW}Press ENTER to continue.{WHT}") # # does nothing. Short for "No OPeration" elif token == "nop": pass # # tests: lots of tests. No branching, just jumping if # false. if true, continues execution at the the next # token, otherwise: skip the next two(2) tokens. # # test if x is equal to 0: elif token == "x=0?": x = pull() push(x) if x: # same as "if not x=0" it_r += 2 # # test if x in not equal to 0: elif token == "x!=0?": x = pull() push(x) if not x: it_r += 2 # # test if x is greater than 0: elif token == "x>0?": x = pull() push(x) if not x > 0: it_r += 2 # # test if x is less than 0: elif token == "x<0?": x = pull() push(x) if not x < 0: it_r += 2 # # test if x is greater than or equal to 0: elif token == "x>=0?": x = pull() push(x) if not x >= 0: it_r += 2 # # test if x is less than or equal to 0: elif token == "x<=0?": x = pull() push() if not x <= 0: it_r += 2 # # test if x is equal to y: elif token == "x=y?": x = pull() y = pull() push(y) push(x) if x != y: it_r += 2 # # test if x is NOT equal to y: elif token == "x!=y?": x = pull() y = pull() push(y) push(x) if x == y: it_r += 2 # # test if x is greater than y: elif token == "x>y?": x = pull() y = pull() push(y) push(x) if not x > y: it_r += 2 # # test if x is less than y: elif token == "x<y?": x = pull() y = pull() push(y) push(x) if not x < y: it_r += 2 # # test if x is greater than or equal to y: elif token == "x>=y?": x = pull() y = pull() push(y) push(x) if not x >= y: it_r += 2 # # test if x is less than or equal to y: elif token == "x<=y?": x = pull() y = pull() push(y) push(x) if not x <= y: it_r += 2 # # dump the program listing: elif token == "prog": print(f"{YLW}Programming space:\n ", end="") print(f" ".join(i for i in prog_listing).replace("RTN", "RTN\n")) print(f"{WHT}") # # edit the program data file: elif token == "edit": if os.name == "posix": os.system( "vim {}".format(os.path.splitext(__file__)[0] + ".txt") ) prog_listing = program_data(prognam) # reload print(f"{CLS}") # # print the version number: elif token == "version": print(f"{RED}{version}{WHT}\n") # # display help (in a convoluted fashion, but this *is* # an exercise in learning how to program). elif token == "help": it_r += 1 if it_r < len(cmd_ln): if cmd_ln[it_r].lower() in ["op", "o"]: # list operators s = str(op_dict.keys())[11:-2] s = s.replace("'", "") s = s.replace(",", "") s = s.upper() s = s.split() s.sort() print( f"{YLW}Type 'help xxx' for specific help on an operator." ) print(f"Available operators are:") for x in s: print(f"'{x}'", end=" ") print(f"\nOperators are not case sensitive.") print(f"Shortcut key shows in parentheses.{WHT}\n") # look up help on a particular operator: elif cmd_ln[it_r].lower() in op_dict: print(f"{YLW}{cmd_ln[it_r].upper()}", end="") if cmd_ln[it_r].lower() in kbsc.values(): # confusing way to sort a dictionary for printing. print( f"({list(kbsc.keys())[list(kbsc.values()).index(cmd_ln[it_r].lower())]})", end="", ) print(f": {str(op_dict[cmd_ln[it_r].lower()])}{WHT}\n") else: print( f"{RED}Operator {WHT}{cmd_ln[it_r]}{RED} not found.{WHT}\n" ) else: # just print the __doc__ string from the top print(f"{YLW}{__doc__}{WHT}") # # # 2 variable statistics: elif token == "stat": x = pull() y = pull() push(y) # put the stack back the way you found it push(x) # Note that the stat identifiers for the user do not match what's used # internally by the script. So we made a new dictionary just for the # user to retrieve these values. stat_dict = { "n": Sn, "Ex": Sx, "Ey": Sy, "Ex2": Sx2, "Ey2": Sy2, "Exy": Sxy, "x": Mx, "y": My, "ox": SDx, "oy": SDy, "r": CCr, "a": Sa, "b": YIb, } num = 0 if it_r + 1 == len(cmd_ln): # blank after 'stat'? num = 1 # then just make one entry else: it_r += 1 # increment to the next item in cmd_ln if cmd_ln[it_r].isdigit(): num = int(cmd_ln[it_r]) if num > 0: i = 0 while i < num: # All the statistical variables we need Sn += 1 # incr it_r - tracks # of xy pairs Sx += x # sum of the x entries Sy += y # sum of the y entries Sx2 += x ** 2 # sum of the squares of the x entries Sy2 += y ** 2 # sum of the squares of the y entries Sxy += x * y # sum of the product of the x & y entries i += 1 if cmd_ln[it_r].lower() == "undo": Sn -= 1 Sx -= x Sy -= y Sx2 -= x ** 2 Sy2 -= y ** 2 Sxy -= x * y if Sn > 1 and Sn * Sx2 != Sx ** 2 and Sn * Sy2 != Sy ** 2: Mx = Sx / Sn # mean of x My = Sy / Sn # mean of y # ox = sqrt((n*Ex^2-(Ex)^2)/(n*(n-1))) std deviation of x SDx = math.sqrt((Sn * Sx2 - Sx ** 2) / (Sn * (Sn - 1))) # oy = sqrt((n*Ey^2-(Ey)^2)/(n*(n-1))) std deviation of y SDy = math.sqrt((Sn * Sy2 - Sy ** 2) / (Sn * (Sn - 1))) # correlation coefficent(r): CCr = (Sn * Sxy - Sx * Sy) / math.sqrt( (Sn * Sx2 - Sx ** 2) * (Sn * Sy2 - Sy ** 2) ) Sa = (Sn * Sxy - Sx * Sy) / (Sn * Sx2 - Sx ** 2) # slope(a): YIb = Sy / Sn - Sa * Sx / Sn # y intercept(b): if cmd_ln[it_r].lower() == "clear": Sn = ( Sx ) = ( Sy ) = Sx2 = Sy2 = Sxy = Mx = My = SDx = SDy = CCr = Sa = YIb = 0 elif ( cmd_ln[it_r].lower() == "save" ): # Add the stat regs to the user regs mem.update(stat_dict) # mem = mem | stat_dict # << I think this method requires Python 3.9. # elif cmd_ln[it_r].lower() == "est": x = pull() # just to clear the estimate off the stack push(Sa * x + YIb) # y=ax+b; put y onto the stack print(f"{YLW}x: {WHT}{x}{YLW}, ~y: {WHT}{Sa * x + YIb}\n") elif cmd_ln[it_r] in stat_dict.keys(): push(stat_dict[cmd_ln[it_r]]) # Essentially anything after 'stat' will stop x & y from being added. # Originally required 'show' to display stat data, but now you can # type anything that's not a number or specified above. print(f"{YLW}n: {WHT}{Sn:.0f}") print(f"{YLW}{SIG}x: {WHT}{Sx:.4f}") print(f"{YLW}{SIG}y: {WHT}{Sy:.4f}") print(f"{YLW}{SIG}x{SS2}: {WHT}{Sx2:.4f}") print(f"{YLW}{SIG}y{SS2}: {WHT}{Sy2:.4f}") print(f"{YLW}{SIG}xy: {WHT}{Sxy:.4f}") if Sn > 1: # need 2 or more data points for these print(f"{YLW}x{OVR}: {WHT}{Mx:.4f}") print(f"{YLW}y{OVR}: {WHT}{My:.4f}") if Sn > 2: # Std Deviation appears to need at least 3 sets print(f"{YLW}{LSG}x: {WHT}{SDx:.4f}") print(f"{YLW}{LSG}y: {WHT}{SDy:.4f}") print(f"{YLW}r: {WHT}{CCr:.4f}") print(f"{YLW}a: {WHT}{Sa:.4f}") print(f"{YLW}b: {WHT}{YIb:.4f}") print(f"{WHT}") # blank line # # it didn't match any token above, check to see if it's # a register. If not, assume it's an error. # # last chance to do something with the token. # note that if you name a register the same as a command # you'll need to use 'rcl'. elif token in mem.keys(): push(mem[cmd_ln[it_r]]) # # it's not recognized. else: print(f"{RED}Invalid Operator: {WHT}{token}\n") # # increment the command line pointer to the next token # and go back through this loop: if incr == True: it_r += 1 incr = True # exception list except ValueError: print(f"{RED}Value error: {WHT}{token}\n") break except ZeroDivisionError: print(f"{RED}Division by zero error: {WHT}{token}\n") break except OverflowError: print(f"{RED}Overflow error: {WHT}{token}\n") break except IndexError: print(f"{RED}Index Error: {WHT}{token}\n") except KeyError: print(f"{RED}Key Error: {WHT}{token}\n") # end of the very long looping function calc() # This part initializes/recalls everything now # if the mem file exists use it instead of initstack() if os.path.exists(memnam): fh = open(memnam, "r", encoding="utf-8") stack = ast.literal_eval(fh.readline()) # a list of floats mem = ast.literal_eval(fh.readline()) # dictionary of memory registers decimal_places = int(ast.literal_eval(fh.readline())) # single int kbsc = ast.literal_eval(fh.readline()) # dictionary of keyboard shortcuts stat_regs = ast.literal_eval(fh.readline()) # statistical registers fh.close() else: # no mem file? Just create everything from scratch stack = initstack(stack_size) mem = {} decimal_places = 4 kbsc = { "#": "rand", "[": "stat", "a": "+", "b": "xroot", "c": "chs", "d": "/", "f": "!", "g": "gamma", "h": "help", "i": "rcp", "j": "rad", "k": "scut", "l": "ln", "m": "mem", "n": "frac", "o": "^", "p": "prog", "q": "exc", "r": "sqrt", "s": "-", "t": "sq", "u": "deg", "v": "int", "w": "show", "x": "*", "y": "swap", "z": "abs", } stat_regs = {"Sn": 0, "Sx": 0, "Sy": 0, "Sx2": 0, "Sy2": 0, "Sxy": 0} # if a program file exists dump its contents into memory. # we'll 'import' its contents into memory whether we use it or not if os.path.exists(prognam): prog_listing = program_data(prognam) else: prog_listing = [] if __name__ == "__main__": calc(stack, mem, prog_listing, decimal_places, stat_regs) # Addenda. # Differences between this and the HP15c include: # No complex number support (though it would be easy to implement). # No GOTO <line #> (no line numbers to go to). # No matrix support. I'm lazy. # No DSE or ISG commands (they're useful if space is limited... it's not). # No integration. Slept thru calculus. # No statistical functionality. Shouldn't be hard. I should do this... # No solver (though the one in the 15c is really cool). # While 15c programs don't require a label or ending 'RTN', this does. # No H.M.S conversion (but would be easy to implement). # No "last x" register (forgot about this, should do it, might be useful). # Does include the 'atan2' function that the 15c lacks. # The 15c had 448 bytes of user memory for programs and storage. # # Known bugs and annoyances: # Really small numbers are displayed as 0.0 rather than say, 6.674e-11 # for example, and really large numbers are displayed in full rather # than a fixed decimal number. # Update 1.03: # Made it so that you don't have to use 'rcl' if the register name # is unique. # Fixed 'quit' so it now works with 'exit' and 'close'. # Added 'prog' keyword to display the users programs. # Added color to 'show', 'mem', and 'prog' results. # Update 1.04 & 1.05 # Numerous tweaks; cleaned out some useless code; tightend some functions. # Added a clear screen to end scrolling of previous results. # Added GCD function (added in Python 3.5). # Added 'edit' command to mod/add programs without leaving the calculator. # Update 1.06 # Got operators 'dh' and 'hms' working. # Added helpful info to 'r>p' operator upon use. # Made minor changes to some print statements. # # Update 1.08a # Added two variable statistics # Cleaned up some code. # used lots of f strings -- you'll need Python >= 3.6 # # Update 1.08b # Think I finally got 'stat' to not do division by 0. # Ran it through Black just for fun. # # Update 1.08c # Just replaced 'n' with 'it_r' to avoid confusion over what 'n' is. # typing 'h o' is the same as 'help op'... unless 'o' becomes an operator. # fixed a minor bug where it wouldn't show short cut key when using 'help X' # # Update 1.09 # Added standard deviation for x & y to the statistics engine. # Adjusted 'stat' logic to better display input results. # Renamed 'inv' 'rcp' i.e.: 1/x is referred to as the 'reciprocal' in HP-15c # manual. # # To do: # Help text needs lots of improvement. # Keyboard shortcuts display needs cleaning up.
690e69c6d13e8bcb9ed1b787ff71e4269dde04ea
UzarKarz/PA1
/Week3/Kontrollülesanne 3.1 - Mantra.py
566
3.671875
4
"""Mantra on silp, sõna, lause või heli, mida kasutatakse paljudes idamaistes religioonides mediteerimisel. Mantrat korratakse nii kaua kui vajalikuks peetakse. Koostada programm, mis 1. küsib kasutajalt lause, mida ta soovib mantrana kasutada, 2. küsib kasutajalt, mitu korda ta soovib mantrat korrata, 3. väljastab sama arv kordi ekraanile kasutaja sisestatud mantra.""" sisend = input("Sisestage mantra: ") kordaja = int(input("Sisestage mitu korda soovite mantrat korrata: ")) while kordaja > 0: print(sisend) kordaja -= 1
4c98de9380eba70b40f0f14ad1a12e57c784aa30
yunlum/Directions-Application-with-MapQuest-API
/P3_class.py
7,757
3.53125
4
# YUNLU MA ID: 28072206 class LATLONG: ''' This class is used to get the useful data of LATLONG from the dictionary named "data_base" and make some adjustments to let the data match the format of output requirements. Finally, return a list of required data ''' def __init__(self): ''' Build four lists in the class self ''' self._lng=[] self._lat=[] self._print_lng=[] self._print_lat=[] def get_latlong(self,data_base:dict): ''' Find the sub-dictionary with the key "locations" in the dictionary named "data_base" Divide the dictionary named "locations" by the keys and match the key "latLng" in the sub-dictionaries. Add the data in the sub-key named "lng" / "lat" to the list self._lng / self._lat ''' locations=data_base["locations"] for Dict in locations: for key in Dict: if key=="latLng": for i in Dict[key]: if i=="lng": self._lng.append(Dict[key][i]) elif i=="lat": self._lat.append(Dict[key][i]) def adjust_latlng(list1:list, string1:str, string2:str, list2:list): ''' Make some adjustments of the data in self._lng and self._lat by keeping two decimal places and add "W", "E", "S", "N" to the end Finally, add the new data to the list self._print_lng / self._print_lat ''' for i in list1: x=str('{:.02f}'.format(round(i,2))) if x[0]=="-": list2.append(x[1:]+string1) else: list2.append(x+string2) def output(self,data_base:dict) -> list: ''' Return the output list of LATLONG by adding the title "LATLONGS" and the adjusted data from the list self._lng and self._lat ''' output_list=[] LATLONG.get_latlong(self,data_base) LATLONG.adjust_latlng(self._lng,"W","E",self._print_lng) LATLONG.adjust_latlng(self._lat,"S","N",self._print_lat) output_list.append("\nLATLONGS") for i in range(len(self._print_lng)): output_list.append(str(self._print_lat[i]+" "+self._print_lng[i])) return output_list class STEPS: ''' This class is used to get the useful directions of STEPS from the dictionary named "data_base" Finally, return a list of required directions ''' def __init__(self): ''' Build a list in the class self ''' self._steps=[] def get_steps(self,data_base:dict): ''' Find the sub-dictionary with the key "legs" in the dictionary named "data_base" Divide the dictionary "legs" by the keys and match the key "maneuvers" in the sub-dictionaries . Add the directions in the sub-key named "narrative" to the list self._steps ''' legs=data_base["legs"] for Dict in legs: for key in Dict: if key == "maneuvers": Mane=Dict[key] for Dict in Mane: for key in Dict: if key == "narrative": self._steps.append(Dict[key]) def output(self,data_base:dict) -> list: ''' Return the output list of STEPS by adding the title "DIRECTIONS" and directions from the list self._steps ''' output_list=[] STEPS.get_steps(self,data_base) output_list.append("\nDIRECTIONS") for i in self._steps: output_list.append(i) return output_list class TOTALTIME: ''' This class is used to get the useful datum of TOTALTIME from the dictionary named "data_base" and make some adjustments to let the datum match the format of output requirements. Finally, return a list of required datum ''' def __init__(self): ''' Build two variables in the class self ''' self._datum=0 self._time='' def get_adjust_time(self,data_base:dict): ''' Add the datum to the self._data in the key "time" of the dictionary named "data_base" And adjust the datum with unit conversion, rounding, and add the unit ''' self._datum = data_base["time"] self._time = str(round(self._datum/60))+ " minutes" def output(self,data_base:dict): ''' Return the output list of TOTALTIME by adding the title "TOTAL TIME" and the adjusted datum(str) from the self._time ''' output_list=[] TOTALTIME.get_adjust_time(self,data_base) output_list.append("\nTOTAL TIME: "+ self._time) return output_list class TOTALDISTANCE: ''' This class is used to get the useful datum of TOTALDISTANCE from the dictionary named "data_base" and make some adjustments to let the datum match the format of output requirements. Finally, return a list of required datum ''' def __init__(self): ''' Build two variables in the class self ''' self._data=0 self._distance='' def get_adjust_distance(self,data_base:dict): ''' Add the datum to the self._data in the key "distance" of the dictionary named "data_base" And adjust the datum with rounding, and add the unit ''' self._data=data_base["distance"] self._distance=str(round(self._data)) + " miles" def output(self,data_base:dict): ''' Return the output list of TOTALDISTANCE by adding the title "TOTAL DISTANCE" and the adjusted datum(str) from the self._distance ''' output_list=[] TOTALDISTANCE.get_adjust_distance(self,data_base) output_list.append("\nTOTAL DISTANCE: "+ self._distance) return output_list class ELEVATION: ''' This class is used to get the useful datum of ELEVATION from the dictionary named "data_base" and make some adjustments to let the datum match the format of output requirements. Finally, return a list of required datum ''' def __init__(self): ''' Build two variables in the class self ''' self._height = 0 self._elevation = 0 def get_height(self,data_base:dict): ''' Add the datum in the key "height" of the sub-dictionary of the dictionary named "data_base" to the self._height ''' for Dict in data_base: for key in Dict: if key == "height": self._height = Dict[key] def adjust_elevation(self): ''' Adjust the datum in the self._height with unit conversion and rounding Add it to the self._elevation ''' elevation = round(int(self._height)*3.2808399) self._elevation = elevation def output(self,data_base:dict): ''' Return the output list of ELEVATION by adding the adjusted datum from the self._elevation ''' output_list=[] ELEVATION.get_height(self,data_base) ELEVATION.adjust_elevation(self) output_list.append(self._elevation) return output_list
f4913c5520d6ca539395680dbf13250466297843
louizoslogic/mini_capstone
/atm.py
1,974
3.84375
4
import pickle from datetime import datetime class atm: def __init__(self, user): self.transaction = '' self.user = user self.balance = 0 self.pin = input('Create a 4 digit pin: ') with open('user_data.txt', 'r') as file: account_number = file.read() account_number = int(account_number) account_number = account_number + 1 account_number = str(account_number) self.account_number = account_number with open('user_data.txt', 'w') as file: file.write(self.account_number) def deposit(self, amount): self.balance = self.balance + amount now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M") newtransaction = f'{dt_string}: {self.user} deposited ${amount}: Total ${self.balance}' self.transaction = self.transaction + newtransaction + '\n' return newtransaction def check_withdraw(self, amount): if self.balance - amount < 0: print("Invalid amount\nYou're broke") else: return True def withdraw(self, amount): if self.check_withdraw(amount) == True: self.balance = self.balance - amount now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M") newtransaction = f'{dt_string}: {self.user} withdrew ${amount}: Total ${self.balance}' self.transaction = self.transaction + newtransaction + '\n' newtransaction def print_transactions(self): print(self.transaction) def save_user(self): with open(self.account_number + '.txt', 'wb') as file: pickle.dump(self, file, pickle.HIGHEST_PROTOCOL) def get_user(account_number): account_number = str(account_number) user = None with open(account_number + '.txt', 'rb') as file: user = pickle.load(file) return user
be9473d6a960a65afbcf112ee915cb3145ba3c36
CAMcDonald/oc-cs240
/Lab 1/flag.py
3,751
3.546875
4
import pygame ## Colors that need to be used for the program to draw a flag white = pygame.Color(255, 255, 255) blue = pygame.Color(0, 0, 205) yellow = pygame.Color(255, 255, 0) black = pygame.Color(0, 0, 0) green = pygame.Color(0, 100, 0) red = pygame.Color(255, 0, 0) class Rect(object): def __init__(self, left, top, width, height): ## Given parameters self.left = left self.top = top self.width = width self.height = height ## Calculated parameters self.right = self.left + self.width self.bottown = self.top + self.height def move_ip(self, xoffset, yoffset): self.left += xoffset self.top += yoffset ## Calculated parameters self.right = self.left + self.width self.bottown = self.top + self.height def move(self, xoffset, yoffset): return Rect(self.left + xoffset, self.top + yoffset, self.width, self.height) def top_left(self): return (self.top, self.left) class Olympic_Flag(object): """A class that shows an olympic flag and is pygame and pygame.Rect aware""" def __init__(self, left, top, width = 400, height = 240): self.rect = pygame.Rect(left, top, width, height) self.horizontal = 1 self.vertical = 1 ## Draws flag self.image = pygame.Surface(self.rect.size) self.image.fill(white) ## Draws rings on flag rings = [((blue), (80, 80)), ((yellow), (135, 140)), ((black), (190, 80)), ((green), (245, 140)), ((red), (295, 80))] for ring in rings: pygame.draw.circle(self.image, ring[0], ring[1], 50, 5) def draw(self, screen): ## Draws flag as single image. screen.blit(self.image, self.rect) def update(self, screen): screen_width, screen_height = screen.get_size() self.rect.left += self.horizontal self.rect.top += self.vertical if self.rect.right > screen_width: self.horizontal = -self.horizontal elif self.rect.left < 0: self.horizontal = -self.horizontal if self.rect.top < 0: self.vertical = -self.vertical elif self.rect.bottom > screen_height: self.vertical = -self.vertical class Ball(object): """Draws a ball that is pygame and pygame.Rect aware""" def __init__(self, x, y, radius): self.rect = pygame.Rect(0, 0, 2*radius, 2*radius) self.rect.center = (x, y) self.horizontal = 5 self.vertical = 5 ## Draws ball on rectangle self.image = pygame.Surface(self.rect.size) self.image.fill((0, 191, 255)) ## Draws ball on rectangle surface pygame.draw.circle(self.image, black, (radius, radius), 50) def draw(self, screen): ## Draws ball as single image. screen.blit(self.image, self.rect) def update(self, screen): screen_width, screen_height = screen.get_size() self.rect.left += self.horizontal self.rect.top += self.vertical if self.rect.right > screen_width: self.horizontal = -self.horizontal elif self.rect.left < 0: self.horizontal = -self.horizontal if self.rect.top < 0: self.vertical = -self.vertical elif self.rect.bottom > screen_height: self.vertical = -self.vertical class Picture(object): """Inserts a picture of Michael Phelps in the background""" def insert(self, screen): ## Inserts the picture into the file Michael = pygame.image.load(Michael.jpg).convert_alpha() Michael_rect = Michael.get_rect()
91716b641f0ef3d030c23fbf3c48345c61eb1377
PhoenixTAN/A-Vanilla-Neural-Network
/A naive nerual network/P1SkeletonDataset1.py
13,495
3.90625
4
import csv import numpy as np import random import matplotlib.pyplot as plt class NeuralNetwork: def __init__(self, X, Y): # Activate function has been define in this class self.X = X self.Y = Y self.num_of_input = self.X.shape[1] self.num_of_output = self.Y.shape[1] self.NNodes = 75 # the number of nodes in the hidden layer self.epochs = 100 self.learningRate = 0.01 # Learning rate self.regLambda = 0.0000001 # a parameter which controls the importance of the regularization term self.w1 = [] self.w2 = [] self.splitList = [] def fit(self): """ This function is used to train the model. Parameters ---------- X : numpy matrix The matrix containing sample features for training. Y : numpy array The array containing sample labels for training. Returns ------- None """ # Initialize your weight matrices first. # (hint: check the sizes of your weight matrices first!) # numpy.random.uniform(low, high, size) # numpy.random.randn(x, y) normal distribution mean 0, variance 1 randn_amplifier = 3 x = self.NNodes y = self.num_of_input+1 # self.w1 = np.reshape(np.random.uniform(-2, 2, x*y), (x, y)) self.w1 = np.random.randn(x, y) * randn_amplifier x = self.num_of_output y = self.NNodes+1 # self.w2 = np.reshape(np.random.uniform(-2, 2, x*y), (x, y)) self.w2 = np.random.randn(x, y) * randn_amplifier # print("w1 initialize") # print(self.w1) # print("w2 initialize") # print(self.w2) # For each epoch, do for i in range(self.epochs): # For each training sample (X[i], Y[i]), do for j in range(self.X.shape[0]): # 1. Forward propagate once. Use the function "forward" here! self.forward(self.X[j]) # 2. Backward progate once. Use the function "backpropagate" here! self.backpropagate(self.X[j], self.Y[j]) pass def predict(self, X): """ Predicts the labels for each sample in X. Parameters X : numpy matrix The matrix containing sample features for testing. Returns ------- YPredict : numpy array The predictions of X. ---------- """ YPredict = self.forward(X) return YPredict def forward(self, X): # Perform matrix multiplication and activation twice (one for each layer). # (hint: add a bias term before multiplication) bias = np.ones((1, 1)) X = np.concatenate((X, bias), axis=1) X = np.transpose(X) # print("[Sample with bias]") # print(X) # w1 is 4 by 3 # X is 3 by 1 self.net1 = np.dot(self.w1, X) # net1 is 4 by 1 self.z1 = self.activate(self.net1) # z1 is 4 by 1 # w2 is 1 by 5 # Add bias to z1 self.z1 = np.concatenate((self.z1, bias)) # z1 is 5 by 1 self.net2 = np.dot(self.w2, self.z1) # net2 is 1 by 1 self.z2 = self.activate(self.net2) # print("net1") # print(self.net1) # print("z1") # print(self.z1) # print("net2") # print(self.net2) # print("z2") # print(self.z2) return self.z2 def backpropagate(self, X, YTrue): # Compute loss / cost using the getCost function. # print("Ground true") # print(YTrue) cost = self.getCost(YTrue, self.z2) # print("cost") # print(cost) # Compute gradient for each layer. diff = self.z2 - YTrue # dloss_dw2 dloss_dw2 = np.transpose(self.z1 * diff) # 5 by 1 # print("dloss_dw2") # print(dloss_dw2) # dloss_dw1 w2_trans = np.transpose(self.w2) w2_trans = w2_trans[:-1] # 4 by 1 d_activate = self.deltaActivate(self.z1)[:-1] # 4 by 1 bias = np.ones((1, 1)) X = np.concatenate((X, bias), axis=1) # print("X") # print(X) dloss_dw1 = np.dot(np.multiply(np.multiply(diff, w2_trans), d_activate), X) # print("dloss_dw1") # print(dloss_dw1) # Update weight matrices. self.w2 = self.w2 - self.learningRate * dloss_dw2 - self.learningRate * self.regLambda*self.w2 self.w1 = self.w1 - self.learningRate * dloss_dw1 - self.learningRate * self.regLambda*self.w1 # print("new w1") # print(self.w1) # print("new w2") # print(self.w2) pass def getCost(self, YTrue, YPredict): # Compute loss / cost in terms of cross entropy. # (hint: your regularization term should appear here) cross_entropy_cost = -((1-YTrue)*np.log2(1-YPredict)+YTrue*np.log2(YPredict)) \ - ( np.sum(np.multiply(self.regLambda*self.w1, self.w1)) + np.sum(np.multiply(self.regLambda*self.w2, self.w2)) ) return cross_entropy_cost # Custom function def activate(self, x): return 1.0 / (1.0 + np.exp(-x)) def deltaActivate(self, x): return np.multiply(self.activate(x), (1.0 - self.activate(x))) ################################################################################## def getData(dataDir): ''' Returns ------- X : numpy matrix Input data samples. Y : numpy array Input data labels. ''' # TO-DO for this part: # Use your preferred method to read the csv files. # Write your codes here: csv_file = open(dataDir, 'r') reader = csv.reader(csv_file) data = [] for row in reader: data.append(row) data = [[float(x) for x in row] for row in data] # transfer string to float data = np.asmatrix(data) csv_file.close() # print(data) # print(data.shape) return data def splitData(X, Y, K): ''' Returns ------- result : List[[train, test]] "train" is a list of indices corresponding to the training samples in the data. "test" is a list of indices corresponding to the testing samples in the data. For example, if the first list in the result is [[0, 1, 2, 3], [4]], then the 4th sample in the data is used for testing while the 0th, 1st, 2nd, and 3rd samples are for training. ''' # Make sure you shuffle each train list. for i in range(X.shape[0] - 1): index1 = random.randint(0, X.shape[0] - 1) index2 = random.randint(0, X.shape[0] - 1) # Switch X X[[index1, index2], :] = X[[index2, index1], :] # Switch Y Y[[index1, index2], :] = Y[[index2, index1], :] # return List[ # [ [x1, y1], [x2, y2], [x3, y3], [x4, y4] , .. [datak]] # ] list = [] N = int(X.shape[0]/K) # print("N", N) for k in range(K): # print(k) index1 = k*N index2 = (k+1)*N-1+1 # print(index1) # print((k+1)*N-1) Xk = X[index1:index2, :] Yk = Y[index1:index2, :] list.append([Xk, Yk]) # print(list) return list def test(Xtest, Ytest, model): # def test(self, XTest): """ This function is used for the testing phase. Parameters ---------- XTest : numpy matrix The matrix containing samples features (not indices) for testing. model : NeuralNetwork object This should be a trained NN model. Returns ------- YPredict : numpy array The predictions of X. """ correct = 0 YPredict = [] for i in range(Xtest.shape[0]): # print(Ytest[i]) # print(model.predict(Xtest[i])) Y = np.round(model.predict(Xtest[i])) YPredict.append(Y) if Ytest[i] == Y: correct = correct + 1 # i = i + 1 # print(correct) return YPredict def plotDecisionBoundary(model, X, Y): """ Plot the decision boundary given by model. Parameters ---------- model : model, whose parameters are used to plot the decision boundary. X : input data Y : input labels """ # x1_array, x2_array = np.meshgrid(np.arange(-4, 4, 0.01), np.arange(-4, 4, 0.01)) # grid_coordinates = np.c_[x1_array.ravel(), x2_array.ravel()] # Z = model.predict(grid_coordinates) # Z = Z.reshape(x1_array.shape) # plt.contourf(x1_array, x2_array, Z, cmap=plt.cm.bwr) # plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.bwr) # plt.show() x = np.transpose(X[:, 0: 1]) y = np.transpose(X[:, 1: 2]) x = np.asarray(x) y = np.asarray(y) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.set_title('Scatter Plot') plt.xlabel('X1') plt.ylabel('X2') for i in range(len(Y)): if Y[i] == 0: ax1.scatter(x[0][i], y[0][i], c='r', marker='o') pass if Y[i] == 1: ax1.scatter(x[0][i], y[0][i], c='b', marker='o') pass plt.show() def getConfusionMatrix(YTrue, YPredict): """ Computes the confusion matrix. Parameters ---------- YTrue : numpy array This array contains the ground truth. YPredict : numpy array This array contains the predictions. Returns CM : numpy matrix The confusion matrix. """ TP = 0 TN = 0 FP = 0 FN = 0 for i in range(len(YPredict)): if YPredict[i] == YTrue[i]: if YPredict[i] == 1: TP = TP + 1 if YPredict[i] == 0: TN = TN + 1 if YPredict[i] != YTrue[i]: if YPredict[i] == 1: FP = FP + 1 if YPredict[i] == 0: FN = FN + 1 print("TP:", TP) print("TN:", TN) print("FP:", FP) print("FN:", FN) return {"TP": TP, "TN": TN, "FP": FP, "FN": FN} def getPerformanceScores(confusion): """ Computes the accuracy, precision, recall, f1 score. Parameters ---------- confusion matrix = [TP, TN, FP, FN] Returns {"CM" : numpy matrix, "accuracy" : float, "precision" : float, "recall" : float, "f1" : float} This should be a dictionary. """ TP = confusion['TP'] TN = confusion['TN'] FP = confusion['FP'] FN = confusion['FN'] total = TP + TN + FP + FN accuracy = (TP+TN)/total precision = TP/(TP+FP) recall = TP/(TP+FN) F1 = 2*(precision*recall)/(precision+recall) print("Accuracy: ", accuracy) print("Precision: ", precision) print("Recall: ", recall) print("F1score: ", F1) return {"accuracy": accuracy, "precision": precision, "recall": recall, "F1": F1} def printSourceImage(X, Y): x = np.transpose(X[:, 0: 1]) y = np.transpose(X[:, 1: 2]) x = np.asarray(x) y = np.asarray(y) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.set_title('Scatter Plot') plt.xlabel('X1') plt.ylabel('X2') for i in range(len(Y)): if Y[i] == 0: ax1.scatter(x[0][i], y[0][i], c='r', marker='o') pass if Y[i] == 1: ax1.scatter(x[0][i], y[0][i], c='b', marker='o') pass plt.show() def main(): # Get data # x_path = './dataset1/LinearX.csv' # y_path = './dataset1/LinearY.csv' x_path = './dataset1/NonlinearX.csv' y_path = './dataset1/NonlinearY.csv' X = getData(x_path) Y = getData(y_path) # printSourceImage(X, Y) # split data and train K = 5 # cross validation K cross_list = splitData(X, Y, K) # [[x1, y1], [x2, y2], [x3, y3], [x4, y4],..[datak]] my_neural_network = [] accuracy = 0 precision = 0 recall = 0 f1 = 0 for i in range(K): # Training for j in range(K): if j == i: continue Xtrain = cross_list[j][0] Ytrain = cross_list[j][1] # print(Xtrain) # print(Ytrain) my_neural_network = NeuralNetwork(Xtrain, Ytrain) my_neural_network.fit() # Testing print("K =", i) Xtest = cross_list[i][0] Ytest = cross_list[i][1] YPredict = test(Xtest, Ytest, my_neural_network) confusion = getConfusionMatrix(Ytest, YPredict) performance = getPerformanceScores(confusion) accuracy = accuracy + performance['accuracy'] precision = precision + performance['precision'] recall = recall + performance['recall'] f1 = f1 + performance['F1'] plotDecisionBoundary(my_neural_network, Xtest, YPredict) print() accuracy = accuracy/K precision = precision/K recall = recall/K f1 = f1/K print("Accuracy: ", accuracy) print("Precision: ", precision) print("Recall: ", recall) print("F1score: ", f1) main()
fd47e93bd8b9eeb2cd56f4d165b5c6c19b7081db
sevenqwl/PythonProjects
/Learning/Python12期/day5/re模块.py
589
3.59375
4
import re string = "192.168.2.2" m = re.match("([0-9]{1,3}\.){3}\d{1,3}", string) print(m.group()) string2 = "Alex li" m = re.search("[a-z]", string2, flags=re.I) # flags=re.I不区分大小写 string2 = "alexi \nseven\bli" m = re.search("^a.*$", string2, flags=re.M) print(m.group()) # 匹配手机号 phone_str = "hey my name is alex, and my phone number is 13651054607, please call me if you are pretty!" phone_str2 = "hey my name is alex, and my phone number is 18651054604, please call me if you are pretty!" m = re.search("(1)([358]\d{9})", phone_str2) if m: print(m.group())
ed133799d812bb8f85473917e26c8639ce31a3ec
sevenqwl/PythonProjects
/Learning/Python12期/day4/二维数组90度旋转.py
330
3.625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Seven" # 二维数组90度旋转 data = [[col for col in range(4,10)] for row in range(4,110)] # print(len(data[0])) for i in data: print(i) print('') for r_index,row in enumerate(data[0]): print([data[c_index][r_index] for c_index in range(len(data))])
bb62c720f28e25b1841b61f2207282ab225ef447
Silvio622/Computational_Alogrithm
/Sorting3.py
34,195
3.765625
4
''' import random import time import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Create a Dataframe df = pd.DataFrame({'Algoritms':["Bubble Sort","Selection Sort","Insertion Sort","Quick Sort","Merge Sort","Count Sort"]},index:=None) samples = [100,200,500,1000,5000] #create an array with different sample sizes def random_array(n): array = [] for i in range(0,n,1): array.append(random.randint(0,100)) return array def bubble_sort(bubblearr): n = len(bubblearr) for outer in range(n-1, 0, -1): # starts at the end of the array n-1 and goes to the start of the array 0 decrease every time by -1 for inner in range(0,outer,1): #print(f"inner is {inner} swapping {arr[inner]} and {arr[inner+1]}") if bubblearr[inner] > bubblearr[inner+1]: temp = bubblearr[inner] bubblearr[inner] = bubblearr[inner+1] bubblearr[inner+1] = temp #print(f"outer is {outer}") #print(arr) # Selection Sort def selection_sort(selectionarr): n = len(selectionarr) for outer in range(0,n,1): min = outer #print(f"outer is {outer}") for inner in range(outer+1,n,1): if selectionarr[inner] < selectionarr[min]: min = inner #print(f"min is {min}") #print(f"swapping {arr[outer]} and {arr[min]}") temp = selectionarr[outer] selectionarr[outer] = selectionarr[min] selectionarr[min] = temp # Insertion Sort def insertion_sort(insertionarr): n = len(insertionarr) for indexelement in range(1,n,1): # step through each index element start with the second position in step of 1 you don't have to set the step keyvalue = insertionarr[indexelement] # use the array element to write the array element value into the key previousposition = indexelement - 1 # decrease array index by 1 and write it in a new variable currentposition # Move element of array[0...currentposition-1], that are greater than the key, to one position ahead of their current position while previousposition >=0 and insertionarr[previousposition] > keyvalue: # the current position must be on indexelement 0 or greater and the # value of the previuos position must be greater than actual keyvalue insertionarr[previousposition + 1] = insertionarr[previousposition] # than increase array index by one (arr[previousposition + 1])and write the value # from the previous index into it previousposition = previousposition - 1 # decrease the index previous position by 1 insertionarr[previousposition + 1] = keyvalue # if the value of the previuos position is not greater than actual keyvalue the while loops stops # # increase the index previous position by 1 again in the array and write actual value of the # arr[indexelement] into it = the keyvalue # Quick Sort def quick_sort(quickarr): if not quickarr: return [] return (quick_sort([x for x in quickarr[1:] if x < quickarr[0]])) + [quickarr[0]] + quick_sort([x for x in quickarr[1:] if x > quickarr[0]]) # Merger sort # found this code on https://www.geeksforgeeks.org/merge-sort/ and adopted this def merge_sort(mergearr): if len(mergearr)>1: mid = len(mergearr)//2 # Finding the mid of the array left = mergearr[:mid] # Dividing the array elements into left from middle right = mergearr[mid:] # Dividing the array elements into right from middle merge_sort(left) # Sorting the left half merge_sort(right) # Sorting the right half i = j = k = 0 # set the array index i,j,k to 0 while i < len(left) and j < len(right):# Copy data to temp arrays left[] and right[] if left[i] < right[j]: mergearr[k] = left[i] i = i + 1 # increment the index i for the left side else: mergearr[k] = right[j] j = j + 1 # increment the index j for the right side k = k + 1 # increment the index k for the mergearr while i < len(left): # Checking if any element was on the left side mergearr[k] = left[i] # write the left index i value in the mergearr on the appropiate position i = i + 1 # increment the index i for the left side k = k + 1 # increment the index k for the mergearr while j < len(right): # Checking if any element was on the right side mergearr[k] = right[j] # write the right index j value in the mergearr on the appropiate position j = j + 1 # increment the index j for the right side k = k + 1 # increment the index k for the mergearr #mergearr = [7,5,2,3,1] # call function here #merge_sort(arr) #print(mergearr) # Counting sort # https://www.geeksforgeeks.org/counting-sort/ def count_sort(countarr): max_element = int(max(countarr)) min_element = int(min(countarr)) range_of_elements = max_element - min_element + 1 count_arr = [0 for _ in range(range_of_elements)]# Create a count array to store count of individual elements and initialize count array as 0 output_arr = [0 for _ in range(len(countarr))]# Create a output array to store the count array of individual elements and initialize output array as 0 for i in range(0, len(countarr)): # Store count of each count array element count_arr[countarr[i]-min_element] += 1 for i in range(1, len(count_arr)): # Change count_arr[i] so that count_arr[i] now contains actual position of this element in output array count_arr[i] += count_arr[i-1] for i in range(len(countarr)-1, -1, -1): # Build the output array output_arr[count_arr[countarr[i] - min_element] - 1] = countarr[i] count_arr[countarr[i] - min_element] -= 1 for i in range(0, len(countarr)):# Copy the output array to arr, so that arr now contains sorted characters countarr[i] = output_arr[i] #return countarr #countarr = [7,5,2,3,1] # call function here #count_sort(countarr) #print(countarr) #def main(): #elapsedtimesbubblesort = [] elapsed_timetotal = 0 elapsed_timeaverage = 0 elapsedtimes = [] elapsedtimesbubblesortall = [] elapsedtimesselectionsortall = [] elapsedtimesinsertionsortall = [] elapsedtimesquicksortall = [] elapsedtimesmergesortall = [] elapsedtimescountsortall = [] sampleindex = 0 columnposition = 1 for i in samples: # loops through each sample size sample = random_array(i) # call the random_array function and pass in the array and shuffle around the numbers sampleruns = range(0,10,1) # runs 10 times through the samples # Runs through the Bubble sorting function bubbleelapsed_time = 0 bubbleelapsed_timetotal = 0 bubbleelapsed_timeaverage = 0 for run in sampleruns: bubblearr = sample bubblestart_time = time.time() # start time of the program count in nanosecond bubble_sort(bubblearr) # calls the bubble_sort function here bubbleend_time = time.time() # end time of the program count in nanosecond bubbleelapsed_time = round((bubbleend_time - bubblestart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places print("The elapsed time is: " ,bubbleelapsed_time) bubbleelapsed_timetotal = bubbleelapsed_timetotal + bubbleelapsed_time # calculate the total time of the all runs bubbleelapsed_timeaverage = round(bubbleelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places #elapsedtimesbubblesort.append(elapsed_time) #print("Elapsed times in ms are:" ,elapsedtimesbubblesort) print("Total elapsed times" , bubbleelapsed_timetotal ) print("Average running time is" , bubbleelapsed_timeaverage) elapsedtimesbubblesortall.append(bubbleelapsed_timeaverage) elapsedtimes.append(bubbleelapsed_timeaverage) # insert the average time in an Arr print("Elapsed time" , elapsedtimes) #print("Sample after sorting:" ,sample) # Runs through the Selection sorting function selectionelapsed_time = 0 selectionelapsed_timetotal = 0 selectionelapsed_timeaverage = 0 for run in sampleruns: selectionarr = sample selectionstart_time = time.time() # start time of the program count in nanosecond selection_sort(selectionarr) # calls the bubble_sort function here selectionend_time = time.time() # end time of the program count in nanosecond selectionelapsed_time = round((selectionend_time - selectionstart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places print("The elapsed time is: " ,selectionelapsed_time) selectionelapsed_timetotal = selectionelapsed_timetotal + selectionelapsed_time # calculate the total time of the all runs selectionelapsed_timeaverage = round(selectionelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places #elapsedtimesbubblesort.append(elapsed_time) #print("Elapsed times in ms are:" ,elapsedtimesbubblesort) print("Total elapsed times" , selectionelapsed_timetotal ) print("Average running time is" , selectionelapsed_timeaverage) elapsedtimesselectionsortall.append(selectionelapsed_timeaverage) elapsedtimes.append(selectionelapsed_timeaverage) # insert the average time in an Arr print("Elapsed time" , elapsedtimes) # Runs through the Insertion sorting function insertionelapsed_time = 0 insertionelapsed_timetotal = 0 insertionelapsed_timeaverage = 0 for run in sampleruns: insertionarr = sample insertionstart_time = time.time() # start time of the program count in nanosecond insertion_sort(insertionarr) # calls the bubble_sort function here insertionend_time = time.time() # end time of the program count in nanosecond insertionelapsed_time = round((insertionend_time - insertionstart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places print("The elapsed time is: " ,insertionelapsed_time) insertionelapsed_timetotal = insertionelapsed_timetotal + insertionelapsed_time # calculate the total time of the all runs insertionelapsed_timeaverage = round(insertionelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places #elapsedtimesbubblesort.append(elapsed_time) #print("Elapsed times in ms are:" ,elapsedtimesbubblesort) print("Total elapsed times" , insertionelapsed_timetotal ) print("Average running time is" , insertionelapsed_timeaverage) elapsedtimesinsertionsortall.append(insertionelapsed_timeaverage) elapsedtimes.append(insertionelapsed_timeaverage) # insert the average time in an Arr print("Elapsed time" , elapsedtimes) # Runs through the Quick sorting function quickelapsed_time = 0 quickelapsed_timetotal = 0 quickelapsed_timeaverage = 0 for run in sampleruns: quickarr = sample quickstart_time = time.time() # start time of the program count in nanosecond quick_sort(quickarr) # calls the quick_sort function here quickend_time = time.time() # end time of the program count in nanosecond quickelapsed_time = round((quickend_time - quickstart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places print("The elapsed quick sort time is: " ,quickelapsed_time) quickelapsed_timetotal = quickelapsed_timetotal + quickelapsed_time # calculate the total time of the all runs quickelapsed_timeaverage = round(quickelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places #elapsedtimesbubblesort.append(elapsed_time) #print("Elapsed times in ms are:" ,elapsedtimesbubblesort) print("Total elapsed quick sort times" , quickelapsed_timetotal ) print("Average running quick sort time is" , quickelapsed_timeaverage) elapsedtimesquicksortall.append(quickelapsed_timeaverage) elapsedtimes.append(quickelapsed_timeaverage) # insert the average time in an Arr print("Elapsed quick sort time" , elapsedtimes) # Runs through the Merge sorting function mergeelapsed_time = 0 mergeelapsed_timetotal = 0 mergeelapsed_timeaverage = 0 for run in sampleruns: mergearr = sample mergestart_time = time.time() # start time of the program count in nanosecond merge_sort(mergearr) # calls the quick_sort function here mergeend_time = time.time() # end time of the program count in nanosecond mergeelapsed_time = round((mergeend_time - mergestart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places print("The elapsed quick sort time is: " ,mergeelapsed_time) mergeelapsed_timetotal = mergeelapsed_timetotal + mergeelapsed_time # calculate the total time of the all runs mergeelapsed_timeaverage = round(mergeelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places #elapsedtimesbubblesort.append(elapsed_time) #print("Elapsed times in ms are:" ,elapsedtimesbubblesort) print("Total elapsed merge sort times" , mergeelapsed_timetotal ) print("Average running merge sort time is" , mergeelapsed_timeaverage) elapsedtimesmergesortall.append(mergeelapsed_timeaverage) elapsedtimes.append(mergeelapsed_timeaverage) # insert the average time in an Arr print("Elapsed merge sort time" , elapsedtimes) # Runs through the Count sorting function countelapsed_time = 0 countelapsed_timetotal = 0 countelapsed_timeaverage = 0 for run in sampleruns: countarr = sample countstart_time = time.time() # start time of the program count in nanosecond count_sort(countarr) # calls the quick_sort function here countend_time = time.time() # end time of the program count in nanosecond countelapsed_time = round((countend_time - countstart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places print("The elapsed quick sort time is: " ,countelapsed_time) countelapsed_timetotal = countelapsed_timetotal + countelapsed_time # calculate the total time of the all runs countelapsed_timeaverage = round(countelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places #elapsedtimesbubblesort.append(elapsed_time) #print("Elapsed times in ms are:" ,elapsedtimesbubblesort) print("Total elapsed merge sort times" , countelapsed_timetotal ) print("Average running merge sort time is" , countelapsed_timeaverage) elapsedtimescountsortall.append(countelapsed_timeaverage) elapsedtimes.append(countelapsed_timeaverage) # insert the average time in an Arr print("Elapsed merge sort time" , elapsedtimes) # Write a new column in the dataframe after every run df.insert(columnposition,str(samples[sampleindex]),elapsedtimes,True) sampleindex = sampleindex + 1 columnposition = columnposition + 1 elapsedtimes = [] # clear the elapsedtimes array print(df) print(elapsedtimesbubblesortall) print(elapsedtimesselectionsortall) print(elapsedtimesinsertionsortall) print(elapsedtimesquicksortall) print(elapsedtimesmergesortall) print(elapsedtimescountsortall) # plot the Time Results from the Dataframe #plt.plot(data=df) #sns.scatterplot(x="Sample Size",y="Running Times in (ms)",data=df,hue="Algoritms") #sns.scatterplot(x="2000",y="Algoritms",data=df,hue="Algoritms") #sns.scatterplot(x=samples,y="Bubble Sort",data=df,hue="Algoritms") #sns.scatterplot(data=df,hue="Algoritms") ##plt.scatter(samples,elapsedtimesbubblesortall,c="red",label="Bubble Sort") ##plt.scatter(samples,elapsedtimesselectionsortall,c="blue",label="Selection Sort") ##plt.scatter(samples,elapsedtimesinsertionsortall,c="green",label="Insertion Sort") plt.plot(samples,elapsedtimesbubblesortall,c="blue",label="Bubble Sort",marker = 'o',markersize=10) plt.plot(samples,elapsedtimesselectionsortall,c="orange",label="Selection Sort",marker = 'o',markersize=10) plt.plot(samples,elapsedtimesinsertionsortall,c="green",label="Insertion Sort",marker = 'o',markersize=10) plt.plot(samples,elapsedtimesquicksortall,c="red",label="Quick Sort",marker = 'o',markersize=10) plt.plot(samples,elapsedtimesmergesortall,c="grey",label="Merge Sort",marker = 'o',markersize=10) plt.plot(samples,elapsedtimescountsortall,c="yellow",label="Count Sort",marker = 'o',markersize=10) plt.xlabel("Samples") plt.ylabel("Running Time in ms") plt.legend() plt.show() plt #if __name__ == "__main__": # execute only if run from a script # main() # calls the main program at the start when python start to run ''' import random import time import pandas as pd import matplotlib.pyplot as plt # Start the Main program def main(): # Create a Dataframe df = pd.DataFrame({'Sample Size':["Bubble Sort","Selection Sort","Quick Sort","Merge Sort","Count Sort"]},index:=None) # Create an array with different sample sizes #samples = [100,200,500,1000] samples = [100,250,500,750,1000,1250,2500,3750,5000,10000,20000,40000,80000] #samples = [100,250,500,750,1000,1250,2500,3750,5000,10000,20000,30000,40000] # Create random numbers def random_array(n): array = [] for i in range(0,n,1): array.append(random.randint(0,100)) return array # Bubble Sort # Use the function from GMIT lecture and adopted this to my purpose def bubble_sort(bubblearr): n = len(bubblearr) for outer in range(n-1, 0, -1): # starts at the end of the array n-1 and goes to the start of the array 0 decrease every time by -1 for inner in range(0,outer,1):#so called bubbling up here if bubblearr[inner] > bubblearr[inner+1]:# if not in order swap in the next line temp = bubblearr[inner] bubblearr[inner] = bubblearr[inner+1]# if in order write value in temp variable in the next line bubblearr[inner+1] = temp # Selection Sort # Use the function from GMIT lecture and adopted this to my purpose def selection_sort(selectionarr): n = len(selectionarr) for outer in range(0,n,1):# the loop runs through each element of the data input array min = outer for inner in range(outer+1,n,1): # it increments by 1 (outer+1)and searches in every iteration for the smallest element if selectionarr[inner] < selectionarr[min]:# if the next element is smaller we write the value in min variable next line if not jump to temp line min = inner # and running through the rest of the array temp = selectionarr[outer] # we write the value of first array element in the temp variable selectionarr[outer] = selectionarr[min] # we swap write the minimum value of the array to the first element of the array selectionarr[min] = temp # we swap write the temp variable value as a minimum value in the array # Quick Sort #found this code on https://www.educative.io/edpresso/how-to-implement-quicksort-in-python and adopted this to my purpose def quick_sort(quickarr): elements = len(quickarr) #Base case if elements < 2: return quickarr current_position = 0 #Position of the partitioning element for i in range(1, elements): #Partitioning loop if quickarr[i] <= quickarr[0]: current_position += 1 temp = quickarr[i] quickarr[i] = quickarr[current_position] quickarr[current_position] = temp temp = quickarr[0] quickarr[0] = quickarr[current_position] quickarr[current_position] = temp #Brings pivot to it's appropriate position left = quick_sort(quickarr[0:current_position]) #Sorts the elements to the left of pivot right = quick_sort(quickarr[current_position+1:elements]) #sorts the elements to the right of pivot quickarr = left + [quickarr[current_position]] + right #Merging everything together return quickarr # Merge sort # found this code on https://www.geeksforgeeks.org/merge-sort/ and adopted this to my purpose def merge_sort(mergearr): if len(mergearr)>1: mid = len(mergearr)//2 # Finding the mid of the array left = mergearr[:mid] # Dividing the array elements into left from middle right = mergearr[mid:] # Dividing the array elements into right from middle merge_sort(left) # Sorting the left half merge_sort(right) # Sorting the right half i = j = k = 0 # set the array index i,j,k to 0 while i < len(left) and j < len(right):# Copy data to temp arrays left[] and right[] if left[i] < right[j]: mergearr[k] = left[i] i = i + 1 # increment the index i for the left side else: mergearr[k] = right[j] j = j + 1 # increment the index j for the right side k = k + 1 # increment the index k for the mergearr while i < len(left): # Checking if any element was on the left side mergearr[k] = left[i] # write the left index i value in the mergearr on the appropiate position i = i + 1 # increment the index i for the left side k = k + 1 # increment the index k for the mergearr while j < len(right): # Checking if any element was on the right side mergearr[k] = right[j] # write the right index j value in the mergearr on the appropiate position j = j + 1 # increment the index j for the right side k = k + 1 # increment the index k for the mergearr # Counting sort # https://www.geeksforgeeks.org/counting-sort/ and adopted this to my purpose def count_sort(countarr): max_element = int(max(countarr)) min_element = int(min(countarr)) range_of_elements = max_element - min_element + 1 count_arr = [0 for _ in range(range_of_elements)]# Create a count array to store count of individual elements and initialize count array as 0 output_arr = [0 for _ in range(len(countarr))]# Create a output array to store the count array of individual elements and initialize output array as 0 for i in range(0, len(countarr)): # Store count of each count array element count_arr[countarr[i]-min_element] += 1 for i in range(1, len(count_arr)): # Change count_arr[i] so that count_arr[i] now contains actual position of this element in output array count_arr[i] += count_arr[i-1] for i in range(len(countarr)-1, -1, -1): # Build the output array output_arr[count_arr[countarr[i] - min_element] - 1] = countarr[i] count_arr[countarr[i] - min_element] -= 1 for i in range(0, len(countarr)):# Copy the output array to arr, so that arr now contains sorted characters countarr[i] = output_arr[i] #elapsed_timetotal = 0 #elapsed_timeaverage = 0 elapsedtimes = [] elapsedtimesbubblesortall = [] elapsedtimesselectionsortall = [] elapsedtimesquicksortall = [] elapsedtimesmergesortall = [] elapsedtimescountsortall = [] sampleindex = 0 columnposition = 1 for i in samples: # loops through each sample size sample = random_array(i) # call the random_array function and pass in the array and shuffle around the numbers sampleruns = range(0,10,1) # runs 10 times through the samples # Runs through the Bubble sorting function bubbleelapsed_time = 0 bubbleelapsed_timetotal = 0 bubbleelapsed_timeaverage = 0 for run in sampleruns: bubblearr = sample bubblestart_time = time.time() # start time of the program count in nanosecond bubble_sort(bubblearr) # calls the bubble_sort function here bubbleend_time = time.time() # end time of the program count in nanosecond bubbleelapsed_time = round((bubbleend_time - bubblestart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places bubbleelapsed_timetotal = bubbleelapsed_timetotal + bubbleelapsed_time # calculate the total time of the all runs bubbleelapsed_timeaverage = round(bubbleelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places elapsedtimesbubblesortall.append(bubbleelapsed_timeaverage) elapsedtimes.append(bubbleelapsed_timeaverage) # insert the average time in an Arr #print("Elapsed time" , elapsedtimes) # Runs through the Selection sorting function selectionelapsed_time = 0 selectionelapsed_timetotal = 0 selectionelapsed_timeaverage = 0 for run in sampleruns: selectionarr = sample selectionstart_time = time.time() # start time of the program count in nanosecond selection_sort(selectionarr) # calls the bubble_sort function here selectionend_time = time.time() # end time of the program count in nanosecond selectionelapsed_time = round((selectionend_time - selectionstart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places selectionelapsed_timetotal = selectionelapsed_timetotal + selectionelapsed_time # calculate the total time of the all runs selectionelapsed_timeaverage = round(selectionelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places elapsedtimesselectionsortall.append(selectionelapsed_timeaverage) elapsedtimes.append(selectionelapsed_timeaverage) # insert the average time in an Arr #print("Elapsed time" , elapsedtimes) # Runs through the Quick sorting function quickelapsed_time = 0 quickelapsed_timetotal = 0 quickelapsed_timeaverage = 0 for run in sampleruns: quickarr = sample quickstart_time = time.time() # start time of the program count in nanosecond quick_sort(quickarr) # calls the quick_sort function here quickend_time = time.time() # end time of the program count in nanosecond quickelapsed_time = round((quickend_time - quickstart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places quickelapsed_timetotal = quickelapsed_timetotal + quickelapsed_time # calculate the total time of the all runs quickelapsed_timeaverage = round(quickelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places elapsedtimesquicksortall.append(quickelapsed_timeaverage) elapsedtimes.append(quickelapsed_timeaverage) # insert the average time in an Arr #print("Elapsed quick sort time" , elapsedtimes) # Runs through the Merge sorting function mergeelapsed_time = 0 mergeelapsed_timetotal = 0 mergeelapsed_timeaverage = 0 for run in sampleruns: mergearr = sample mergestart_time = time.time() # start time of the program count in nanosecond merge_sort(mergearr) # calls the quick_sort function here mergeend_time = time.time() # end time of the program count in nanosecond mergeelapsed_time = round((mergeend_time - mergestart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places mergeelapsed_timetotal = mergeelapsed_timetotal + mergeelapsed_time # calculate the total time of the all runs mergeelapsed_timeaverage = round(mergeelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places elapsedtimesmergesortall.append(mergeelapsed_timeaverage) elapsedtimes.append(mergeelapsed_timeaverage) # insert the average time in an Arr #print("Elapsed merge sort time" , elapsedtimes) # Runs through the Count sorting function countelapsed_time = 0 countelapsed_timetotal = 0 countelapsed_timeaverage = 0 for run in sampleruns: countarr = sample countstart_time = time.time() # start time of the program count in nanosecond count_sort(countarr) # calls the quick_sort function here countend_time = time.time() # end time of the program count in nanosecond countelapsed_time = round((countend_time - countstart_time),3) # calculate the time the program runs in milli seconds with 3 decimal places countelapsed_timetotal = countelapsed_timetotal + countelapsed_time # calculate the total time of the all runs countelapsed_timeaverage = round(countelapsed_timetotal / len(sampleruns) , 3) # calculate the average time of the all runs in milli seconds with 3 decimal places elapsedtimescountsortall.append(countelapsed_timeaverage) elapsedtimes.append(countelapsed_timeaverage) # insert the average time in an Arr print("Elapsed merge sort time" , elapsedtimes) # Write a new column in the dataframe after every run df.insert(columnposition,str(samples[sampleindex]),elapsedtimes,True) sampleindex = sampleindex + 1 columnposition = columnposition + 1 elapsedtimes = [] # clear the elapsedtimes array print(df) # Plot the Time Results from the Dataframe for Bubble Sort fig1, ax1 = plt.subplots(1) ax1.plot(samples,elapsedtimesbubblesortall,c="blue",label="Bubble Sort",marker = 'o',markersize=10) ax1.set_xlabel("Input Size n") ax1.set_ylabel("Running Time in ms (milliseconds)") ax1.legend() ax1.set_title("Bubble Sort \n Worst case O(n2)notation") ax1.grid(b=True,which='major',axis='both',linestyle='dotted', linewidth=1) fig1.savefig("Bubble sort.png") # Plot the Time Results from the Dataframe for Selection Sort fig2, ax2 = plt.subplots(1) ax2.plot(samples,elapsedtimesselectionsortall,c="orange",label="Selection Sort",marker = 'o',markersize=10) ax2.set_xlabel("Input Size n") ax2.set_ylabel("Running Time in ms (milliseconds)") ax2.legend() ax2.set_title("Selection Sort \n Worst case O(n2)notation") ax2.grid(b=True,which='major',axis='both',linestyle='dotted', linewidth=1) fig2.savefig("Selection sort.png") # Plot the Time Results from the Dataframe for Quick Sort fig3, ax3 = plt.subplots(1) ax3.plot(samples,elapsedtimesquicksortall,c="red",label="Quick Sort",marker = 'o',markersize=10) ax3.set_xlabel("Input Size n") ax3.set_ylabel("Running Time in ms (milliseconds)") ax3.legend() ax3.set_title("Quick Sort \n Worst case O(n2)notation") ax3.grid(b=True,which='major',axis='both',linestyle='dotted', linewidth=1) fig3.savefig("Quick sort.png") # Plot the Time Results from the Dataframe for Merge Sort fig4, ax4 = plt.subplots(1) ax4.plot(samples,elapsedtimesmergesortall,c="grey",label="Merge Sort",marker = 'o',markersize=12) ax4.set_xlabel("Input Size n") ax4.set_ylabel("Running Time in ms (milliseconds)") ax4.legend() ax4.set_title("Merge Sort \n Worst case O(n log n)notation") ax4.grid(b=True,which='major',axis='both',linestyle='dotted', linewidth=1) fig4.savefig("Merge sort.png") # Plot the Time Results from the Dataframe for Count Sort fig5, ax5 = plt.subplots(1) ax5.plot(samples,elapsedtimescountsortall,c="yellow",label="Count Sort",marker = 'o',markersize=10) ax5.set_xlabel("Input Size n") ax5.set_ylabel("Running Time in ms (milliseconds)") ax5.legend() ax5.set_title("Count Sort \n Worst case O(n + k)notation") ax5.grid(b=True,which='major',axis='both',linestyle='dotted', linewidth=1) fig5.savefig("Count sort.png") # Plot the Time Results from the Dataframe for Count Sort fig6, ax6 = plt.subplots(1) ax6.plot(samples,elapsedtimesbubblesortall,c="blue",label="Bubble Sort",marker = 'o',markersize=10) ax6.plot(samples,elapsedtimesselectionsortall,c="orange",label="Selection Sort",marker = 'o',markersize=10) ax6.plot(samples,elapsedtimesquicksortall,c="red",label="Quick Sort",marker = 'o',markersize=10) ax6.plot(samples,elapsedtimesmergesortall,c="grey",label="Merge Sort",marker = 'o',markersize=12) ax6.plot(samples,elapsedtimescountsortall,c="yellow",label="Count Sort",marker = 'o',markersize=10) ax6.set_xlabel("Input Size n") ax6.set_ylabel("Running Time in ms (milliseconds)") ax6.legend() ax6.set_title("Benchmark of time complexity for differnt\n Sorting algorithms") ax6.grid(b=True,which='major',axis='both',linestyle='dotted', linewidth=1) fig6.savefig("Sorting.png") plt.show() if __name__ == "__main__": # execute only if run from a script main() # calls the main program at the start when python start to run
5bfd688f204ec052eddb248a466c0df6918a1291
RedChlorine/DeskOne
/cookBook.py
1,803
3.65625
4
#Decimals################## import decimal from decimal import Decimal borderLine = "///"*10 taxRate = Decimal('7.25')/Decimal(100) purchaseAmount = Decimal('2.95') penny = Decimal('0.01') totalAmount = purchaseAmount+taxRate*purchaseAmount totalAmount.quantize(penny, decimal.ROUND_UP) print(totalAmount) print(borderLine) ##################Fractions################### from fractions import Fraction sugarCups = Fraction('2.5') scalingFactor = Fraction(5/8) print(sugarCups*scalingFactor) #the output is in fraction form n/d print(borderLine) #############################Simplification via Fraction()############## print(Fraction(24/16)) #output is simplified print(borderLine) ###############################Floating Point Approximations############ answer = (55/7)*(7/55) print (str(answer)+" float approximation") print ("--> "+str(round(answer, 3))+" rounded approximation, to 3 decimal places") print(borderLine) ################################f-strings############################### #first declair the array you want in the f-string id = "IAD" minTemp = 20 maxTemp = 28 location = "Dallas International Airport" precipitation = 0.6 print(f' {id} : {location} : {minTemp} / {maxTemp} / {precipitation})') print (borderLine) ##############adding optional data to as f-string####################### id = "IAD" minTemp = 20 maxTemp = 28 location = "Dallas International Airport" precipitation = 0.6 print(f' {id:s} : {location:s} : {minTemp:d} / {maxTemp:d} / {precipitation:f})') print (borderLine) ############Adding lengths to f-strings################################## id = "IAD" minTemp = 20 maxTemp = 28 location = "Dallas International Airport" precipitation = 0.6 print(f' {id:s} : {location:19s} : {minTemp:3d} / {maxTemp:3d} / {precipitation:5.2f})') print (borderLine)
7153f3aae6742f8c118b6b69bce672eb388f1592
someshmahule/DataStructures
/SimpleStk.py
823
3.59375
4
class Stk: def __init__(self,size): self.size = size self.stk = [] def printStk(self): print(self.stk) def isEmpty(self): if len(self.stk) == 0: return "Empty" else: return "Not Empty" def push(self,x): self.stk.append(x) def pop(self): l = len(self.stk) - 1 x = self.stk[l] self.stk = self.stk[:l] return x def isOverflow(self): if len(self.stk) == self.size : return "Overflown" else: return "Not Overflown" if __name__ == "__main__": a = Stk(3) #a.printStk() print(a.isEmpty()) a.push(1) a.push(2) a.push(3) print(a.isOverflow()) a.printStk() print(a.pop()) print(a.pop()) a.printStk()
2a7bfe5e36dd16489cd059749a3dead21d1b6016
thehummingbird/Machine-Learning-and-Deep-Learning
/Logistic Regression/LogisticRegression.py
1,238
3.5625
4
import numpy as np class LogisticRegression: def __init__(self,lr=0.02,iter=10000): self.lr = lr self.iter = iter def sigmoid(self, z): return (1/(1 + np.exp(-z))) def gradient_descent(self,y,x): for i in range(self.iter): yhat = self.sigmoid(np.dot(self.w.T,x) + self.c) dlw = (2/self.m)*np.dot(x, (yhat-y).T) dlc = (2/self.m)*np.sum(yhat-y) self.w = self.w - self.lr*dlw self.c = self.c - self.lr*dlc def run(self, y, x): self.m = x.shape[1] self.n = x.shape[0] self.w = np.zeros((self.n,1)) self.c = 0 self.gradient_descent(y,x) return self.w, self.c def predict(self,x): yhat = self.sigmoid(np.dot(self.w.T, x) + self.c) out = (yhat > 0.5).astype(int) return out def main(): # nxm (#n features, #m examples) x = np.random.rand(1, 10000)*10 # decision boundary at x=5 here y = (x > 5).astype(int) algorithm = LogisticRegression() algorithm.run(y, x) x = np.array([[8.0, 6.8, 3.3, 4.8, 4.85, 5.2]]) pred = algorithm.predict(x) print(pred) # expected output -> 1 1 0 0 0 1 if __name__ == '__main__': main()
c3cac605ba5a47da5cc7132d42a7976dc5fcdfa4
teqn0x/Polynomial_Classes
/Python/polynomial.py
2,880
3.578125
4
import os,sys,math,cmath class polynomial: def __init__(self,lcoeffs): self.lcoeffs = lcoeffs #Making it floats because of the division by 0 when doing the ABC formula for i in range(len(self.lcoeffs)): self.lcoeffs[i] = float(self.lcoeffs[i]) def __str__(self): outstring = '' N = len(self.lcoeffs) for i in range(N): if i == N-1: outstring += '%s' % self.lcoeffs[i] elif i == N-2: outstring += '%s x + ' % self.lcoeffs[i] else: outstring += '%s x^%s + ' % (self.lcoeffs[i],N-i-1) return outstring def __repr__(self): return str(self) def __add__(self,other): if not isinstance(other,polynomial): sys.exit('Cannot add a polynomial and a non-polynomial object, exiting!') N1 = len(self.lcoeffs) N2 = len(other.lcoeffs) #Make copies so that the original lists do not get adjusted lcoeffs1 = list(self.lcoeffs) lcoeffs2 = list(other.lcoeffs) if N1 < N2: lcoeffs1 = [0]*(N2-N1) + lcoeffs1 lcoeffs3 = [0]*N2 for i in range(N2): lcoeffs3[i] = lcoeffs1[i] + lcoeffs2[i] if N2 < N1: lcoeffs2 = [0]*(N1-N2) + lcoeffs2 lcoeffs3 = [0]*N1 for i in range(N1): lcoeffs3[i] = lcoeffs1[i] + lcoeffs2[i] return polynomial(lcoeffs3) def __mul__(self,other): if not isinstance(other,polynomial): sys.exit('Cannot multiply a polynomial and a non-polynomial object, exiting!') lcoeffs1 = list(self.lcoeffs) lcoeffs2 = list(other.lcoeffs) N1 = len(lcoeffs1) N2 = len(lcoeffs2) lcoeffs1.reverse() lcoeffs2.reverse() lcoeffs = [0]*(N1+N2-1) for i in range(len(lcoeffs1)): for j in range(len(lcoeffs2)): lcoeffs[i+j] += (lcoeffs1[i] * lcoeffs2[j]) lcoeffs.reverse() return polynomial(lcoeffs) def __call__(self,x): y = float(0) coeffs = list(self.lcoeffs) coeffs.reverse() N = len(coeffs) for i in range(N): y+= coeffs[i] * (x ** (i)) return y def add(self,other): return self + other def mul(self,other): return self * other def val(self,x): return self(x) def coeff(self,i): lcoeffs = list(self.coeffs) lcoeffs.reverse() return lcoeffs[i] def roots(self): if len(self.lcoeffs) == 1: print 'This is a constant, no polynomial' return [] elif len(self.lcoeffs) == 2: return [-1 * self.lcoeffs[1] / self.lcoeffs[0]] elif len(self.lcoeffs) == 3: a = self.lcoeffs[0] b = self.lcoeffs[1] c = self.lcoeffs[2] D = b*b - 4*a*c xp1 = -1 * b / (2*a) if D < 0: xp2 = complex( 0 , math.sqrt(-1*D) / (2*a) ) else: xp2 = math.sqrt(D) / (2*a) return [xp1+xp2,xp1-xp2] else: print 'Order is too high to solve for roots.' return [] def valHorner(self,x): y = 0 for n in self.lcoeffs: y = (y + n)*x return y
b7c7db07bc5758ab86b5c33967f2f62fd09a6bc6
nishmaj/DSAN-Projects
/project2/problem5/problem_5.py
1,542
3.796875
4
""" problem_5.py - BlockChain build a link list to store basic blockchain data the data in this example is just a random integer """ import hashlib import time class Block: def __init__(self, timestamp, data, previous_hash): self.timestamp = timestamp self.data = data self.previous_hash = previous_hash self.hash = self.calc_hash() def calc_hash(self): sha = hashlib.sha256() hash_str = str(self.data).encode('utf-8') sha.update(hash_str) return sha.hexdigest() def __str__(self): return ('Timestamp: {}\nData: {}\nPrevious Hash: {}\nHash: {}'.format(self.timestamp, self.data, self.previous_hash, self.hash)) class Blockchain: def __init__(self): self.current_block = None def add_block(self, value): timestamp = time.gmtime() data = value previous_hash = self.current_block.hash if self.current_block else 0 self.current_block = Block(timestamp, data, previous_hash) blockchain = Blockchain() blockchain.add_block('1) First String') print(blockchain.current_block) blockchain = Blockchain() blockchain.add_block('2) Second String to') print(blockchain.current_block) blockchain = Blockchain() blockchain.add_block('3) Third String to encode') print(blockchain.current_block) blockchain = Blockchain() blockchain.add_block('4) Forth String to encode in block') print(blockchain.current_block) # Edge Cases: blockchain = Blockchain() blockchain.add_block('') print(blockchain.current_block)
8d46c2db69ef57cce95058c8a484eb147fb82ab6
andyqu94/homework
/python-challange/PyBank/main.ipynb.py
850
3.515625
4
import pandas as pd import sys filepath = "Resources/budget_data.csv" df = pd.read_csv(filepath) total_month = len(df["Date"].unique()) total = df["Profit/Losses"].sum() df2 = df["Profit/Losses"].diff() average_change = df2.mean() greatest_increase = df2.max() greatest_decrease = df2.min() df3 = df2.sort_values(ascending=True) df4 = pd.concat([df,df3],axis=1) greatest_month = df4.iloc[44]["Date"] lowest_month = df4.iloc[25]["Date"] filename = open("analysis",'w') sys.stdout = filename print("Financial Analysis") print("-------------------------") print("Total Month:",total_month) print("Total: $",total) print("Average Change: $", average_change) print("Greatest Increase in Profits:" +str(greatest_month)+"($"+str(greatest_increase)+")") print("Greatest Decrease in Profits:" +str(lowest_month)+"($"+str(greatest_decrease)+")")
137a5ddac366c0fefbbae211c75f4e9a6ac2206a
Muhammadshamel/Investigating-Texts-and-Calls
/Task2.py
1,251
4.0625
4
""" Read file into texts and calls. It's ok if you don't understand how to read files """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 2: Which telephone number spent the longest time on the phone during the period? Don't forget that time spent answering a call is also time spent on the phone. Print a message: "<telephone number> spent the longest time, <total time> seconds, on the phone during September 2016.". """ result_dict = {} for line in calls: key = line[0] val = int(line[3]) if result_dict.get(key) == None: result_dict[key] = val else: result_dict[key] += val key = line[1] val = int(line[3]) if result_dict.get(key) == None: result_dict[key] = val else: result_dict[key] += val maxkey = '' maxval = 0 for key in result_dict: if maxval < result_dict[key]: maxkey = key maxval = result_dict[key] # Output print('%s spent the longest time, %d seconds, on the phone during September 2016.' % ( maxkey, maxval ))
28f0e5637cd7ca7d5b47451e27e6e1d0ac7db093
zlatnizmaj/GUI-app
/OOP/OOP-03-Variables.py
642
4.40625
4
# In python programming, we have three types of variables, # They are: 1. Class variable 2. Instance variable 3. Global variable # Class variable class Test(): class_var = "Class Variable" class_var2 = "Class Variable2" # print(class_var) --> error, not defined x = Test() print(x.class_var) print(x.class_var2) # Instance Variables # This variable is created within class in instance method class TestIns(): def __init__(self, name, age): self.name = name self.age = age y = TestIns('Y', 9) print(y.name) print(y.age) # Global variable: # It can be accessed anywhere in the project as it is assigned globally
1e45cfd30735bc93f3341bb6bfdec05603fa77fc
pravsp/problem_solving
/Python/BinaryTree/solution/invert.py
1,025
4.125
4
'''Invert a binary tree.''' import __init__ from binarytree import BinaryTree from treenode import TreeNode from util.btutil import BinaryTreeUtil # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Invert: def invertTree(self, root: TreeNode) -> TreeNode: if root: right = root.right left = root.left root.right = self.invertTree(left) root.left = self.invertTree(right) return root if __name__ == '__main__': print("Create a binary tree") bt = BinaryTree() btutil = BinaryTreeUtil() btutil.constructBinaryTree(bt) bt.printTree(traversal=BinaryTree.LevelOrder, verbose=True) bt.printTree(traversal=BinaryTree.InOrder) print("Height of the tree: ", bt.getHeight()) bt.printTree(traversal=BinaryTree.LevelOrder, verbose=True) bt.root = Invert().invertTree(bt.root) bt.printTree(traversal=BinaryTree.InOrder)
1d2132b560e493b2d001cea3c158580f31730080
pravsp/problem_solving
/Python/TrappingRainWater/TrapRainWater.py
969
4.03125
4
"""Solution to trap the rain water.""" """ Problem: ======= Given n Non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining """ class TrapRainWater: def trap(self, height): left_hieghest = 0 right_hieghest = 0 lmap = list() rmap = list() total_liters = 0 for map_v in height: left_hieghest = max(left_hieghest, map_v) lmap.append(left_hieghest) for map_v in height[::-1]: right_hieghest = max(right_hieghest, map_v) rmap.append(right_hieghest) for elem,l_h,r_h in zip(height,lmap,reversed(rmap)): total_liters = total_liters + (min(l_h, r_h) - elem) return total_liters if __name__ == '__main__': elv_map = [0,1,0,2,1,0,1,3,2,1,2,1] trapped_water = TrapRainWater().trap(elv_map) print("Amount of water trapped: ", trapped_water)
dd844a663563586ac649ede13dfe67b7472bbdba
pravsp/problem_solving
/Python/BinaryTree/solution/__init__.py
654
3.6875
4
import os import sys def AddSysPath(new_path): """ AddSysPath(new_path): adds a directory to python's sys.path Does not add the directory if it doesnt exists or if its already on sys.path. Return 1 if OK, -1 if new_path doesnt exists, 0 if it was already on sys.path """ # Avoid adding non existent of paths if not os.path.exists(new_path): return -1 for x in sys.path: x = os.path.abspath(x) if new_path in (x, x + os.sep): return 0 sys.path.append(new_path) return 1 MODULE_PATH = os.path.dirname(__file__) REPO_PATH = os.path.dirname(MODULE_PATH) AddSysPath(REPO_PATH)
6d6bbd9a42a4e427aae9db99827299d396363b83
pravsp/problem_solving
/Python/BinaryTree/util/btutil.py
518
3.765625
4
"""Binary Tree util.""" from binarytree import BinaryTree class BinaryTreeUtil: def constructBinaryTree(self, btree: BinaryTree): """Construct the binary tree based on user input. :param btree: Binary tree on which new nodes to be added :type btree: BinaryTree """ while True: data = input("Enter Node Data (Numeric), others if you are done:") if data.isdigit(): btree.addToTree(int(data)) else: return
42b8d9a128a7a5345ba2d1fd820489f4a7d13f27
BruceWang94/COMP9021-17S1
/Assignment/Assignment_1/superpower.py
2,245
3.6875
4
import sys try: superpower = input('Please input the heroes\' powers: ') superpower = superpower.split(' ') for i in range(len(superpower)): if not int(superpower[i]): raise ValueError except ValueError: print('Sorry, these are not valid power values.') sys.exit() try: nb_of_swiches = int(input('Please input the number of power flips: ')) if nb_of_swiches < 0 or nb_of_swiches > len(superpower): raise ValueError except ValueError: print('Sorry, this is not a valid number of power flips.') sys.exit() for i in range(len(superpower)): superpower[i] = int(superpower[i]) # def a fct to output num of negative number and a list of them position def find_num_of_negative(L): n = 0 length = len(L) l = [0] # save the postion of negative number, l[0] is the smallest one for i in range(length): if L[i] < 0: n += 1 l.append(i) if l[0] > L[i]: l[0] = i return n,l q1 = superpower.copy() q1.sort() for i in range(nb_of_swiches): q1[0] = -q1[0] q1.sort() print ('Possibly flipping the power of the same hero many times, the greatest achievable power is %d.' % sum(q1)) q2 = superpower.copy() q2.sort() for i in range(nb_of_swiches): q2[i] = -q2[i] print('Flipping the power of the same hero at most once, the greatest achievable power is %d.' % sum(q2)) q3 = superpower.copy() l = [0] * 2 # list save the inital and the sum for i in range(len(q3) - nb_of_swiches + 1): s = sum(q3[i: i + nb_of_swiches]) if l[1] > s: l[0] = i l[1] = s for i in range(nb_of_swiches): q3[l[0] + i] = -q3[l[0] + i] #print ('q3 is',q3) print ('Flipping the power of nb_of_flips many consecutive heroes, the greatest achievable power is %d.' % sum(q3)) q4 = superpower.copy() length = 0; add = 0; begin = 0 for l in range(1, nb_of_swiches + 1): for i in range(len(q4) - l + 1): if sum(q4[i: i + l]) < add: length = l add = sum(q4[i: i + l]) begin = i for i in range(begin, begin + length): q4[i] = -q4[i] print ('Flipping the power of arbitrarily many consecutive heroes, the greatest achievable power is %d.' % sum(q4))
66409873b4b58ebc8cec53c0caecc03266efa3a8
Arushi96/Python
/Recursions/multiply_rec.py
124
3.96875
4
def multiply(a,b): m=0 if b == 1: print a return a else: m=a+ multiply(a,b-1) print m return m multiply(6,3)
b6ff3bb38beaea248d13389d5246d449e8e8bf8a
Arushi96/Python
/Radical- Python Assignment Solutions/Loops and Conditions/Question 3.py
367
4.15625
4
#Assignment Questions #Q: Write a program which calculates the summation of first N numbers except those which are divisible by 3 or 7. n = int(input ("Enter the number till which you want to find summation: ")) s=0 i=0 while i<=n: if (i%3==0)or(i%7==0): #print(i) i+=1 continue else: s=s+i i=i+1 print("sum is: ", s)
069a8828e50772d06dacc74f25ec2a59ae4d4213
songtoan0201/algorithm
/leetCode/digitTreeSum.py
405
3.578125
4
def digitTreeSum(t): if not t: return 0 stack = [(t, 0)] sum = 0 while stack: cur, v = stack.pop() if cur.left or cur.right: if cur.left: stack.append((cur.left, cur.value + v * 10)) if cur.right: stack.append((cur.right, cur.value + v * 10)) else: sum += cur.value + v * 10 return sum
3f4c8365e98ee5b8558370e96d0a64ccdad2b1e2
songtoan0201/algorithm
/leetCode/longestCommonPrefix.py
460
4
4
# Write a function to find the longest common prefix string amongst an array of strings. # If there is no common prefix, return an empty string "". String sclicing String1[3:12]) def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ for i in range(len(strs) - 1): for j in range(i+1, len(strs)): if strs[i] == strs[j]: return print(longestCommonPrefix(["flower", "flow", "flight"]))
9c180882c5f24e44308eb281569ecc43556260f2
AxisAngeles/election-analysis
/3-1-Student-Resources/07-Evr_HobbyBook-Dictionaries/Unsolved/HobbyBook_Unsolved.py
490
3.53125
4
# @TODO: Your code here PetInfo = { "name":"Puchy", "age":8, "hobby":["eating","walking","sleeping"], "woke":{ "monday":"10am", "tuesday":"9am", "wednesday":"11am" } } print(f'My pet´s name is {PetInfo["name"]} and he is {PetInfo["age"]} years old.') print(f'My pet has {len(PetInfo["hobby"])} hobies and its favorite is {PetInfo["hobby"][1]}.') print(f'My dog, {PetInfo["name"]}, wakes up at {PetInfo["woke"]["wednesday"]} every wednesday.')
505449aa00c311562c2d9af0e9399f45d06476fd
kz-sera/python_study
/BMI.py
455
4
4
#BMI = 体重(kg) / 身長(m)^2 from decimal import Decimal as decimal kg = float(input('あなたの体重を入力してください')) height = (input('あなたの身長を入力してください')) if '.' not in height: height = int(height) / 100 elif '.' in height: height = float(height) print(kg) print(height) BMI = kg / (height ** 2) BMI = decimal(BMI).quantize(decimal('0.01')) print(BMI) BMI_round = round(BMI, 2) print(BMI_round)
e59d24fe7367404e53d997df5af8ca9db84156f1
kz-sera/python_study
/j_body_calculate.py
2,601
3.890625
4
from decimal import Decimal as decimal def base_body_data(): while True: try: print('性別を入力してください') gender = int(input('[0. 男性 1. 女性]')) if gender != 0 and gender != 1: print('適切な値を入力してください') continue break except: print('適切な値を入力してください') while True: try: age = int(input('年齢を入力してください')) break except: print('適切な値を入力してください') while True: try: weight = float(input('体重を入力してください')) break except: print('適切な値を入力してください') while True: try: height = input('身長を入力してください') if "." not in height: height = int(height) / 100 elif '.' in height: height = float(height) break except: print('適切な値を入力してください') if gender == 0: print('性別: 男性') elif gender == 1: print('性別: 女性') print('年齢: {age}歳'.format(age=age)) print('体重: {weight}kg'.format(weight=weight)) print('身長: {height}m'.format(height=height)) return gender, age, weight, height def BMI(weight, height): bmi = weight / (height ** 2) bmi = decimal(bmi).quantize(decimal('0.01')) print('BMI: {bmi}'.format(bmi=bmi)) def suitable_weight(weight, height): suitable_weight = (height ** 2) * 22 suitable_weight = decimal(suitable_weight).quantize(decimal('0.01')) print('適正体重: {suitable_weight}kg'.format(suitable_weight=suitable_weight)) print('適正体重より: +{over_weight}'.format(over_weight=decimal(weight) - suitable_weight)) def basa_metabolism(gender, age, weight, height): height = height * 100 #男性:66+13.7×体重kg+5.0×身長cm-6.8×年齢 #女性:665.1+9.6×体重kg+1.7×身長cm-7.0×年齢 if gender == 0: base_meta = 66 + 13.7 * weight + 5.0 * height - 6.8 * age elif gender == 1: base_meta = 665.1 + 9.6 * weight + 1.7 * height - 7.0 * age print('基礎代謝: {bs}kcal'.format(bs=base_meta)) if __name__ == '__main__': gender, age, weight, height = base_body_data() BMI(weight, height) suitable_weight(weight=weight, height=height) basa_metabolism(gender, age, weight, height)
35025370621c265eff6d02c68d4284525634f5e1
mtjhartley/codingdojo
/dojoassignments/python/fundamentals/find_characters.py
568
4.21875
4
""" Write a program that takes a list of strings and a string containing a single character, and prints a new list of all the strings containing that character. Here's an example: # input word_list = ['hello','world','my','name','is','Anna'] char = 'o' # output new_list = ['hello','world'] """ def find_characters(lst, char): new_list = [] for word in lst: if char in word: new_list.append(word) return new_list word_list = ['hello','world','my','name','is','Anna'] char = 'o' print find_characters(word_list, char)
52469f19f3f2c6691408e89d341ea7041fa5a38c
mtjhartley/codingdojo
/dojoassignments/python/python_oop/car.py
921
3.71875
4
class Car(object): def __init__(self, price, speed, fuel, mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage if self.price > 10000: self.tax = .15 else: self.tax = .12 def displayAll(self): print "Price:", self.price print "Speed:", str(self.speed) print "Fuel:", str(self.fuel) print "Mileage:", str(self.mileage) print "Tax:", self.tax car1 = Car(11000, "60mph", "Full", "20mpg") car2 = Car(8000, "40mph", "Half Full", "30mpg") car3 = Car(10000, "80mph", "Full", "50mpg") car4 = Car(120, "10mph", "Empty", "5mpg") car5 = Car(10000000, "120mph", "Full", "3mpg") car6 = Car(1000, "30mph", "Quarter Tank", "31mpg") car1.displayAll() print car2.displayAll() print car3.displayAll() print car4.displayAll() print car5.displayAll() print car6.displayAll()
ddef36fe897037d8094621e1a3bf6204cd34e334
mtjhartley/codingdojo
/dojoassignments/python/python_oop/hospital.py
1,896
3.53125
4
import random import itertools id = 0 class Patient(object): id_generator = itertools.count(1) def __init__(self, name, allergies, bedNum=None): self.id = next(self.id_generator) self.name = name self.allergies = allergies self.bedNum = bedNum class Hospital(object): bed_num_generator = itertools.count(1) def __init__(self, name, capacity=5): self.patients = [] self.name = name self.capacity = capacity def info(self): print "Num of patients:", len(self.patients) print "Hospital name:", self.name for patient in self.patients: print "Patient information" print "Id:", patient.id print "Name:",patient.name print "BedNumber:",patient.bedNum print "_____________" def admit(self, patient): if len(self.patients) < self.capacity: print "Adding the patient to the hospital" patient.bedNum = next(self.bed_num_generator) if patient.bedNum >= 10: self.bed_num_generator = itertools.count(1) self.patients.append(patient) else: print "Capacity max!" return self def discharge(self, name): for patient in self.patients: if patient.name == name: patient.bedNum = None self.patients.remove(patient) return self patient1 = Patient("Michael", "Cefloflexin") patient2 = Patient("Gary", "Anime") patient3 = Patient("David", "Sports") patient4 = Patient("Alex", "Freckles") sacred_heart = Hospital("Sacred Heart", 3) sacred_heart.admit(patient1) sacred_heart.admit(patient2) sacred_heart.admit(patient3) sacred_heart.admit(patient4) sacred_heart.info() sacred_heart.discharge("Michael") print print "After discharging..." print sacred_heart.info()
ac0c500a62196c5bf29fe013f86a82946fdb65b2
mtjhartley/codingdojo
/dojoassignments/python/fundamentals/list_example.py
854
4.28125
4
fruits = ['apple', 'banana', 'orange'] vegetables = ['corn', 'bok choy', 'lettuce'] fruits_and_vegetables = fruits + vegetables print fruits_and_vegetables salad = 3 * vegetables print salad print vegetables[0] #corn print vegetables[1] #bok choy print vegetables[2] #lettuce vegetables.append('spinach') print vegetables[3] print vegetables[2:] #[lettuce, spinach] print vegetables[1:3] #[bok choy, lettuce] for index, item in enumerate(vegetables): item = item.upper() vegetables[index] = item print vegetables index = 0 for food in vegetables: vegetables[index] = food.lower() index += 1 print vegetables #another enumerate example my_list = ['apple', 'banana', 'grapes', 'pear'] counter_list = list(enumerate(my_list, 1)) print counter_list numbers = [1,2,3,4] new_numbers = map(lambda x: x*3, numbers) print new_numbers
3389a2cb84c667ada3e41ec096592cfdbf6c2e07
mtjhartley/codingdojo
/dojoassignments/python/fundamentals/compare_array.py
2,432
4.3125
4
""" Write a program that compares two lists and prints a message depending on if the inputs are identical or not. Your program should be able to accept and compare two lists: list_one and list_two. If both lists are identical print "The lists are the same". If they are not identical print "The lists are not the same." Try the following test cases for lists one and two: """ list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] list_three = [1,2,5,6,5] list_four = [1,2,5,6,5,3] list_five = [1,2,5,6,5,16] list_six = [1,2,5,6,5] list_seven = ['celery','carrots','bread','milk'] list_eight = ['celery','carrots','bread','cream'] list_nine = ['a', 'b', 'c'] list_ten = ['a','b','z'] #assumes order matters. if order doesn't matter, would call sorted() or .sort on both lists before checking. def compare_array_order_matters(lst1, lst2): if len(lst1) != len(lst2): print "The lists are not the same" print "This is because the list lengths are not the same." else: for index in range(len(lst1)): if lst1[index] == lst2[index] and (index == len(lst1)-1): print lst1[index], lst2[index] print "The lists are identical" elif lst1[index] == lst2[index]: print lst1[index], lst2[index] continue else: print lst1[index], lst2[index] print "These items are not the same, thus: " print "The lists are not the same." break compare_array_order_matters(list_one, list_two) print compare_array_order_matters(list_three, list_four) print compare_array_order_matters(list_five, list_six) print compare_array_order_matters(list_seven, list_eight) print compare_array_order_matters(list_nine, list_ten) print def compare_array_order_doesnt_matter(lst1, lst2): sorted_lst1 = sorted(lst1) sorted_lst2 = sorted(lst2) if sorted_lst1 == sorted_lst2: print "The lists are equal" else: print "The lists are not equal" print "--------------------------------------------------" print "Now testing the lists when order doesn't matter" print compare_array_order_doesnt_matter(list_one, list_two) compare_array_order_doesnt_matter(list_three, list_four) compare_array_order_doesnt_matter(list_five, list_six) compare_array_order_doesnt_matter(list_seven, list_eight) compare_array_order_doesnt_matter(list_nine, list_ten)
cb31593423cb1972d4ab10cf798b4aeb70527719
premraj234/CSPP-Project-001
/tail.py
1,610
4.0625
4
"""Implementing the tail shell command in python.""" """The import statement the import sys imports the library sys from the module along with the functions and methods of the library system""" import sys """... from the lib.helper module we are importing the built in functions tail and readfile of the lib-helper module into our source code""" from lib.helper import tac, readfile, tail """text is a variable assigned with a non type value""" TEXT = None """ARG_CNT is a variable is assigned with int value len(sys.argv) - 1.len() takes one argument as input and returns length of given input""" ARG_CNT = len(sys.argv) - 1 """if statement is used to check the condition and execute it if the condition is true if ARG_CNT value is 0 then it reads the input using standard input function""" if ARG_CNT == 0: TEXT = sys.stdin.read() """The below if statement checks the condition of ARG_CNT is equals to 1 if it is satisfied it executes the the first line sys.argv[1] it returns the filename and stores data""" if ARG_CNT == 1: filename = sys.argv[1] TEXT = readfile(filename) """This below if statement checks the condition of ARG_CNT > 1 or not if condition is true it prints the current python file and the given text using print() function. print() function prints specified values to the output screen""" if ARG_CNT > 1: print("Usage: tail.py <file>") """the print() function is used to print the output to the terminal .in the below print () it first executes the tail() function which takes one argument is used to print the output of given function""" print(tail(TEXT))
9f0cc5968a6a9a9da8dbb826554c9ab15b7733ad
karybeca/Learning_Python
/Choosing a team.py
1,332
4
4
#!/bin/python3 from random import choice players = [] #Here Should be a Loop! players.append = (input ("Enter the name of the Player:")) players.append = (input ("Enter the name of the Player:")) players.append = (input ("Enter the name of the Player:")) players.append = (input ("Enter the name of the Player:")) players.append = (input ("Enter the name of the Player:")) players.append = (input ("Enter the name of the Player:")) players.append = (input ("Enter the name of the Player:")) players.append = (input ("Enter the name of the Player:")) players.append = (input ("Enter the name of the Player:")) players.append = (input ("Enter the name of the Player:")) print (players) #players = [] #file = open ('players.txt', 'r') #players = file.read().splitlines() #print (players) teamNames = [] file = open ('teamNames.txt', 'r') teamNames = file.read().splitlines() print (teamNames) teamA = [] teamB = [] while len(players) > 0: playerA = choice(players) teamA.append(playerA) players.remove(playerA) playerB = choice(players) teamB.append(playerB) players.remove(playerB) teamNameA = choice(teamNames) teamNames.remove(teamNameA) print (teamA) teamNameB = choice(teamNames) print (teamB) teamNames.remove(teamNameB) print ('Here are your teams:') print (teamNameA, teamA) print (teamNameB, teamB)
f0c2e0bd6418339b210f68efcf5f447e2baeea76
ccarterlandis/mathproblems
/brownNumbers.py
422
3.578125
4
import math allBrown = [] def brown(m,n): brownMid = [] nResult = math.factorial(n) + 1 mResult = pow(m,2) if mResult == nResult: brownMid.append(m) brownMid.append(n) if brownMid: allBrown.append(brownMid) for x in range(100): for y in range(100): brown(x,y) print(allBrown) print("The first {} pairs of Brown numbers are {}.".format(len(allBrown), allBrown))
20151461f8bfa4a1631fecd826518664bf00db41
ccarterlandis/mathproblems
/primesBelow.py
432
3.890625
4
userInt = input("Pick a number. ") counter, primality, lower = 0, 0, 0 primeList = [] for x in range(2, int(userInt)): primality = 1 for y in range(2, x+1): if (x % y == 0) & (x != y): primality = 0 break if (x == y) & (primality == 1): print("{} is prime.".format(y)) primeList.append(y) print("There are {} primes below {}.".format(len(primeList), userInt))
ec6b49ccbfef3f26f082b17f4c6ea67e9e7c8611
orlandod543/datalogger_filter
/pendrive.py
1,649
3.609375
4
__author__ = 'orlando' import os class pendrive(): filepath='' def __init__(self,filepath): self.filepath = filepath def write_append(self,filename,data): """ method that append a string to a file If there is an error, catches it and does nothing Input: str filename, str data Output: None """ try: with open(self.filepath+filename,"a") as file_descriptor: file_descriptor.write(data) file_descriptor.close() except IOError: pass return None def create_file_header(self,filename,header): """ Creates the file header. Raises IOError if it fails Input: str filename, str header Output: None """ try: with open(self.filepath+filename,'w') as file_descriptor: file_descriptor.write(header) #escribo el header en el archivo file_descriptor.close() except IOError: pass return None def file_exists(self,filename): """ Check if filename file_exists Input: str filename Output: bool """ return os.path.isfile(self.filepath+filename) #pregunto si el archivo existe def address(self): return self.filepath if __name__ == "__main__": p=pendrive('/home/orlando/dataloggerweb/') print p.address() if p.file_exists('holaprueba'): p.write_append('holaprueba','213123'+'\n') else: p.create_file_header('holaprueba','esto es una prueba para saber si esta funcionando todo'+'\n')
19aa6ef97da6fdbb4a2a11fd2e66060d8a04f72e
nmarriotti/PythonTutorials
/readfile.py
659
4.125
4
################################################################################ # TITLE: Reading files in Python # DESCRIPTION: Open a text file and read the contents of it. ################################################################################ def main(): # Call the openFile method and pass it Files/file1.txt openFile('Files/file1.txt') def openFile(filename): # Create variable and set it to the contents of the file fh = open(filename) # Output each line in the file for line in fh: print(line.strip()) if __name__ == "__main__": # Here we start the program by calling the main method main()
6a6034e699003b4a4ab0f11f7b2a9e89f235dc92
Eugene-Korneev/GB_01_Python_Basics
/lesson_03/task_01.py
822
4.25
4
# Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. # Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. def divide(number_1, number_2): if number_2 == 0: return None return number_1 / number_2 # num_1 = input("Введите первое число: ") num_1 = '5' # num_2 = input("Введите второе число: ") num_2 = '2' num_1, num_2 = float(num_1), float(num_2) result = divide(num_1, num_2) if result is None: print("Ошибка! Деление на 0") else: print(f"Результат деления: {f'{result:.2f}'.rstrip('0').rstrip('.')}")
3e38d9b9de1f9c09dfaea120317b09ff62e88bcf
Eugene-Korneev/GB_01_Python_Basics
/lesson_01/task_06.py
1,534
3.84375
4
# Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. # Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. # Например: a = 2, b = 3. # Результат: # 1-й день: 2 # 2-й день: 2,2 # 3-й день: 2,42 # 4-й день: 2,66 # 5-й день: 2,93 # 6-й день: 3,22 # Ответ: на 6-й день спортсмен достиг результата — не менее 3 км. # a = int(input("Введите результат пробежки в первый день, км: ")) a = int("2") # b = int(input("Введите желаемый результат, км: ")) b = int("3") day = 1 print("Результат:") while True: if day > 1: a += a * 0.1 print(f"{day}-й день: {f'{a:.2f}'.rstrip('0').rstrip('.')}") if a >= b: break day += 1 print(f"\nОтвет: на {day}-й день спортсмен достиг результата — не менее {b} км.")
157c97530b288bb7fbee706fb0a71ef56a4dfaa4
Eugene-Korneev/GB_01_Python_Basics
/lesson_05/task_02.py
641
3.84375
4
# Создать текстовый файл (не программно), сохранить в нем несколько строк, # выполнить подсчет количества строк, количества слов в каждой строке. import os FILE_PATH = os.path.join(os.path.curdir, 'files', 'task_02.txt') with open(FILE_PATH, 'r', encoding='utf-8') as f: file_lines = f.readlines() print(f"Количество строк в файле: {len(file_lines)}") for i, line in enumerate(file_lines): words = line.split() print(f"Количество слов в строке {i+1}: {len(words)}")
7b72749a9f1bbf33723e47ddd491529226a414d5
Eugene-Korneev/GB_01_Python_Basics
/lesson_03/task_06.py
1,205
4.4375
4
# Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, # но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. # Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. # Каждое слово состоит из латинских букв в нижнем регистре. # Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы. # Необходимо использовать написанную ранее функцию int_func(). def int_func(word): chars = list(word) chars[0] = chr(ord(chars[0]) - 32) return ''.join(chars) print(int_func('text')) string = 'hello world. python is the best!' words = string.split() capitalized_words = [] for w in words: capitalized_words.append(int_func(w)) capitalized_string = ' '.join(capitalized_words) print(capitalized_string)
1fa19b51df98ee3a68a0bf0838574d22a0cf39ba
Eugene-Korneev/GB_01_Python_Basics
/lesson_03/task_04.py
1,152
3.75
4
# Программа принимает действительное положительное число x и целое отрицательное число y. # Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). # При решении задания необходимо обойтись без встроенной функции возведения числа в степень. # Подсказка: попробуйте решить задачу двумя способами. Первый — возведение в степень с помощью оператора **. # Второй — более сложная реализация без оператора **, предусматривающая использование цикла. # Способ 1 def my_func_1(x, y): return x ** y print(my_func_1(2, -5)) # Способ 2 def my_func_2(x, y): denominator = x for _ in range(abs(y)-1): denominator *= x return 1 / denominator print(my_func_2(2, -5))
27307b91316cc3d130610aca1b0e3eecc6e74110
longpdm-teko/project1
/test intern 1.py
4,142
3.640625
4
class ChiTiet: def __init__(self, name): self.name = name def get_price(self): pass def get_weight(self): pass def __repr__(self): return "name: {0}, price: {1}, weight: {2} ".format(self.name, self.get_price(), self.get_weight()) class Chitietdon(ChiTiet): def __init__(self, name, weight, price): super(Chitietdon, self).__init__(name) self.weight = weight self.price = price def get_price(self): return self.price def get_weight(self): return self.weight class Chitietphuc(ChiTiet): def __init__(self, name, list_items=[]): super(Chitietphuc, self).__init__(name) self.list_items = list_items def get_price(self): total = 0 for item in self.list_items: total += item.get_price() return total def get_weight(self): total = 0 for item in self.list_items: total += item.get_weight() return total def add_items(self, item): if not self.list_items: self.list_items = [] self.list_items.append(item) # class Comaydon: # def __init__(self, ten_may, list_may_don=[]): # self.ten_may = ten_may # self.list_may_don = list_may_don # # def add_items(self, item): # if not self.list_may_don: # self.list_may_don = [] # self.list_may_don.append(item) # # def __repr__(self): # return "Ten may: {0}, " \ # "Cac chi tiet trong may: {1}".format(self.ten_may, self.list_may_don) # # # class Comayphuc: # def __init__(self, ten_may, list_may_phuc=[]): # self.ten_may = ten_may # self.list_may_phuc = list_may_phuc # # def add_items(self, item): # if not self.list_may_phuc: # self.list_may_phuc = [] # self.list_may_phuc.append(item) # # def __repr__(self): # return "Ten may: {0}, " \ # "Cac chi tiet trong may: {1}".format(self.ten_may, self.list_may_phuc) # _list_may_don = [ # Comaydon("A1", [Chitietdon("CT001", 56, 47000), Chitietdon("CT002", 74, 75000), Chitietdon("CT003", 83, 56000)]), # Comaydon("A2", [Chitietdon("CT004", 76, 88000), Chitietdon("CT005", 27, 38000), Chitietdon("CT006", 83, 93000)]) # ] # # num = 1 # print("List cac may toan chi tiet don: ") # for i in range(0, len(_list_may_don)): # print("%s)" % num, _list_may_don[i]) # num = num + 1 # if num <= len(_list_may_don): # continue # else: # break # # b = 0 # for i in _list_may_don: # for j in i.list_may_don: # a = j.price # b = a + b # print("Tong gia tri cua may {0}: {1} vnd".format(i.ten_may, b)) # # c = 0 # for i in _list_may_don: # for j in i.list_may_don: # d = j.weight # c = c + d # print("Tong trong luong cua may {0}: {1} kg".format(i.ten_may, c)) # # _list_may_phuc = [ # Comayphuc("B1", [Chitietdon("CT004", 73, 46000), Chitietphuc("PT2000", [Chitietdon("CT005", 47, 94000), # Chitietdon("CT006", 85, 35000)])]), # Comayphuc("B2", [Chitietphuc("PT3000", [Chitietdon("CT005", 83, 47000), Chitietdon("CT009", 73, 36000)]), # Chitietphuc("PT2000", [Chitietdon("CT005", 47, 94000), Chitietdon("CT006", 85, 35000)])]) # ] # # print("") # # num = 1 # print("List cac may gom chi tiet don va chi tiet phuc: ") # for i in range(0, len(_list_may_phuc)): # print("%s)" % num, _list_may_phuc[i]) # num = num + 1 # if num <= len(_list_may_phuc): # continue # else: # break d1 = Chitietdon("CT001", 73, 1000) d2 = Chitietdon("CT002", 73, 2000) d3 = Chitietdon("CT003", 73, 3000) d4 = Chitietdon("CT004", 73, 4000) p1 = Chitietphuc("B1", [d1, d2]) p2 = Chitietphuc("B2", [d3, p1]) p3 = Chitietphuc("B3", [p2, d4]) print(p3) # n = Chitietphuc("B1", [, Chitietphuc("PT2000", [Chitietdon("CT005", 47, 94000), # Chitietdon("CT006", 85, 35000)])]) # print(n.get_price())
2ac21404da9fac2574459957e1252625ab9a6a9d
Ravi-Rsankar/datascience-base
/numpy/ndarray_basics_indexing.py
1,995
3.921875
4
import numpy as np an_array = np.array([[3,33,333],[2,22,3]]) print("whole array ") print(an_array) print("elements ") print(an_array[0,0]) print("fill the array with the given value") ex1 = np.full((2,2), 9) print(ex1) print("create an array with ones in the diagonals") ex2 = np.eye(2,2) print(ex2) print("create an array with ones as element") ex3 = np.ones((2,2)) print(ex3) print("Shape of the matrices") print("an_array ",an_array.shape) print("ex1 ",ex1.shape) print("ex2 ",ex2.shape) print("ex3 ",ex3.shape) print("create an array with random values") ex4 = np.random.random((2,2)) print("ex4 ",ex4) #For a matrix with n rows and m columns, # shape will be (n,m). # The length of the shape tuple is therefore the rank, # or number of dimensions, ndim. ex5 = np.array([1,2,3]) print(ex5) print("ex5 ",ex5.shape) print("print the dimension of array ", ex5.ndim) # the total number of elements of the array. # This is equal to the product of the elements of shape. print("size of the array ", ex5.size) print("type of elements in array ",ex5.dtype) ex6 = np.array([[11,12,14,14], [21,22,23,24],[31,32,33,34]]) print("ex6 ") print(ex6) #This will create the slice of the existing array but not the copy. ex6_slice = ex6[:2,1:3] print("ex6_slice ",ex6_slice) print("change the value in ex6_slice ") ex6_slice[0,1] = 15 print("the value of ex6 also changes ", ex6) #This creates the copy of slice ex6_slice2 = np.array(ex6[:2,1:3]) print("This is a copy of ex6 array slice ",ex6_slice2) ex6_slice2[0,1] = 13 print("This will not change the ex6 array ", ex6) row_rank1 = ex6[1, :] print("using array indexing - single number ",row_rank1, row_rank1.shape) col_indices = np.array([0,1,2]) #the arange method is used to add values into the array. #it works similar to the python range function row_indices = np.arange(3) print(row_indices) for row,col in zip(col_indices,row_indices): print(row," , ",col) print("Values in ex6 at those indices ", ex6[row_indices, col_indices])
37caa40697854af77bae5e7e637f118d5b05918a
foreveryao/Leetcode
/leetcode/36/solution.py
1,013
3.671875
4
class Solution(object): def isValidSudoku(self, board): s=set() list=board for i in range(9): for j in range(9): if list[i][j] in s: return False if list[i][j]!='.': s.add(list[i][j]) s=set() for i in range(9): for j in range(9): if list[j][i] in s: return False if list[j][i]!='.': s.add(list[j][i]) s=set() for i in range(0,9,3): for j in range(0,9,3): for m in range(i,i+3): for n in range(j,j+3): if list[m][n] in s: return False if list[m][n]!='.': s.add(list[m][n]) s=set() return True
9ab7e4292c509b713daf778b97ad3f12433d6b9c
lasselb87/MC
/NeuralNet/NeuralNet_classification.py
5,040
3.734375
4
import csv import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler # Give name to features and target headers = ['age', 'sex','chest_pain','resting_blood_pressure', 'serum_cholestoral', 'fasting_blood_sugar', 'resting_ecg_results', 'max_heart_rate_achieved', 'exercise_induced_angina', 'oldpeak',"slope of the peak", 'num_of_major_vessels','thal', 'heart_disease'] heart_df = pd.read_csv('heart.dat', sep=' ', names=headers) # Drop target from data and replace target class with 0 and 1 # 0 means "have heart disease" and 1 means "do not have heart disease" X = heart_df.drop(columns=['heart_disease']) heart_df['heart_disease'] = heart_df['heart_disease'].replace(1,0) heart_df['heart_disease'] = heart_df['heart_disease'].replace(2,1) y_label = heart_df['heart_disease'].values.reshape(X.shape[0], 1) # Split data into train and test X_train, X_test, y_train, y_test = train_test_split(X, y_label, test_size = 0.2, random_state = 2) # Let us standardize the dataset sc = StandardScaler() sc.fit(X_train) X_train = sc.transform(X_train) X_test = sc.transform(X_test) # Define the neural network class class NeuralNetwork(): # This is a two layer neural network with 13 input nodes, 8 nodes in hidden layer # and 1 output node def __init__(self, layers = [13,8,1], learning_rate = 0.001, iterations = 100): self.params = {} self.learning_rate = learning_rate self.iterations = iterations self.loss = [] self.sample_size = None self.layers = layers self.X = None self.y = None def init_weights(self): # We initialize the weights from a random normal distribution np.random.seed(1) # Seed the random number generator self.params['W1'] = np.random.randn(self.layers[0], self.layers[1]) self.params['b1'] = np.random.randn(self.layers[1],) self.params['W2'] = np.random.randn(self.layers[1], self.layers[2]) self.params['b2'] = np.random.randn(self.layers[2],) # Let us add activation functions to our class def relu(self,Z): return np.maximum(0,Z) def sigmoid(self,Z): return 1.0/(1+np.exp(-Z)) # We will also need a loss function. # For a classification problem we use the cross-entropy loss def entropy_loss(self, y, yhat): nsample = len(y) loss = -1/nsample * (np.sum(np.multiply(np.log(yhat),y)+np.multiply((1-y),np.log(1-yhat)))) return loss # Forward propagation def forward(self): Z1 = self.X.dot(self.params['W1'])+self.params['b1'] A1 = self.relu(Z1) Z2 = A1.dot(self.params['W2'])+self.params['b2'] yhat = self.sigmoid(Z2) loss = self.entropy_loss(self.y,yhat) # Save the calculated params to be used for backpropagation self.params['Z1'] = Z1 self.params['Z2'] = Z2 self.params['A1'] = A1 return yhat, loss # Backward propagation def backward(self, yhat): # Abbreviation: Differentiate loss with respect to -> dl_wrt_... # Derivative of Relu def d_Relu(x): x[x<=0] = 0 x[x>0] = 1 return x dl_wrt_yhat = -(np.divide(self.y,yhat)-np.divide((1-self.y),(1-yhat))) dl_wrt_sig = yhat*(1-yhat) dl_wrt_Z2 = dl_wrt_yhat*dl_wrt_sig dl_wrt_A1 = dl_wrt_Z2.dot(self.params['W2'].T) dl_wrt_W2 = self.params['A1'].T.dot(dl_wrt_Z2) dl_wrt_b2 = np.sum(dl_wrt_Z2, axis = 0) dl_wrt_Z1 = dl_wrt_A1*d_Relu(self.params['Z1']) dl_wrt_W1 = self.X.T.dot(dl_wrt_Z1) dl_wrt_b1 = np.sum(dl_wrt_Z1, axis = 0) # Update weights and biases self.params['W1'] = self.params['W1']-self.learning_rate*dl_wrt_W1 self.params['b1'] = self.params['b1']-self.learning_rate*dl_wrt_b1 self.params['W2'] = self.params['W2']-self.learning_rate*dl_wrt_W2 self.params['b2'] = self.params['b2']-self.learning_rate*dl_wrt_b2 def fit(self, X, y): self.X = X self.y = y self.init_weights() # initialize weights and bias for i in range(self.iterations): yhat, loss = self.forward() self.backward(yhat) self.loss.append(loss) def predict(self, X): Z1 = self.X.dot(self.params['W1'])+self.params['b1'] A1 = self.relu(Z1) Z2 = A1.dot(self.params['W2'])+self.params['b2'] prediction = self.sigmoid(Z2) return np.round(prediction) def accuracy(self, y, yhat): acc = int(sum(y==yhat)/len(y)*100) return acc def plot_loss(self): plt.plot(self.loss) plt.xlabel("Iterations") plt.ylabel("logloss") plt.title("Loss curve") plt.savefig('Logloss.pdf') plt.show() # Create the neural network model nn = NeuralNetwork() nn.fit(X_train,y_train) nn.plot_loss()
63960b50812134ed7286b8288e51bbf90c46d011
bovard/advent_of_code_2016
/09/part_two.py
859
3.859375
4
with open('input.txt') as f: instructions = f.readlines()[0].strip() def expand_string(string): # base case if string == '': return 0 # find all the characters as the beginning of the string chrs = 0 while chrs < len(string) and string[chrs] != '(': chrs += 1 # if it's only characters, return the length if chrs == len(string): return chrs # find the instructions j = chrs while j < len(string) and string[j] != ")": j += 1 # break apart instructions command = string[chrs+1:j] chars = int(command.split('x')[0]) repeat = int(command.split('x')[1]) to_repeat = string[j+1:j+chars+1] # recurse on characters to repeat, and tail return chrs + repeat * expand_string(to_repeat) + expand_string(string[j+chars+1:]) print expand_string(instructions)