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
5dc0ca50f55cc6967821f52336deffda5530ad04
airuchen/python_practice
/raise_error.py
444
3.8125
4
import sys def displaySalary(salary): if salary<0: raise ValueError('positive') print('Salary = '+str(salary)) while True: try: Salary = float(input('enter Salary:')) displaySalary(Salary) break except OSError as err: print('OS Error: {0}'.format(err)) except ValueError: print('Error: Enter positive value') except: print('Unexpected error:', sys.exc_info()[0])
feefbfb35b341b204fddcbe7dbd8d31acbc13b89
adpoe/CupAndChaucerSim
/INITIAL_EXPERIMENT/time_advance_mechanisms.py
28,390
3.8125
4
import Queue as q import cupAndChaucArrivs as cc """ Discrete time advance mechanisms for airport simulation project. This class will generate 6 hours worth of passenger arrivals, and store the data in two arrays: - One for commuters passengers - One for international passengers For each passenger, also need to generate their wait times for each queue. Or is that done when a passenger queues up? """ """ Goals ------ Generalize this code so it can be used for ANY queuing system. Need to account for: - How many steps? :: Spawn a Server-Queue System for each of these.... link these all together o How many servers at each step? o How many queues at each step? -- Make a class that holds each of these "single step" systems -- interface between these classes -- glue them all together with a start and end point -- make them each a member of the overall system and use the same time advance mechanisms I've already got in place. """ ########################### ### ARRIVAL GENERATION #### ########################### class CupChaucArrivals(): """ Class used to generate one hour of arrivals at a time """ def __init__(self): self.cashier_arrivals = [] self.barista_arrivals = [] def get_arrivals(self): """ Get all the arrivals to the system in the next six hours. Store the values in instance vars. """ hourly_arrivals = cc.generate_hourly_arrivals() arrivals_by_type = cc.gen_customer_type_distribution(hourly_arrivals) self.cashier_arrivals = cc.create_array_of_cashier_arrivals(arrivals_by_type) self.barista_arrivals = cc.create_array_of_barista_arrivals(arrivals_by_type) ########################## #### CHECK-IN QUEUES ##### ########################## #------------------# # C&C Queues # #------------------# class RegisterQueue: """ Class used to model a register line Queue """ def __init__(self): self.queue = q.Queue() self.customers_added = 0 def add_customer(self, new_customer): self.queue.put_nowait(new_customer) self.customers_added += 1 def get_next_customer_in_line(self): if not self.queue.empty(): next_customer = self.queue.get_nowait() self.queue.task_done() else: next_customer = None return next_customer class BaristaQueue: """ Class used to model a register line Queue """ def __init__(self): self.queue = q.Queue() self.customers_added = 0 def add_customer(self, new_customer): self.queue.put_nowait(new_customer) self.customers_added += 1 def get_next_customer_in_line(self): if not self.queue.empty(): next_customer = self.queue.get_nowait() self.queue.task_done() else: next_customer = None return next_customer # # # End C&C Queues # # # ########################### ###### C&C SERVERS ###### ########################### class CashierServer: """ Class used to model a server at the Check-in terminal """ def __init__(self): """ Initialize the class variables """ self.service_time = 0.0 self.busy = False self.customer_being_served = q.Queue() self.customers_added = 0 self.customers_served = 0 self.idle_time = 0.00 def set_service_time(self): """ Sets the service time for a new passenger :param passenger_type: either "commuter" or "international" """ self.service_time = cc.gen_cashier_service_time() self.busy = True def update_service_time(self): """ Updates the service time and tells us if the server is busy or not """ self.service_time -= 0.01 if self.service_time <= 0: self.service_time = 0 self.busy = False if not self.is_busy(): self.idle_time += 0.01 def is_busy(self): """ Call this after updating the service time at each change in system time (delta). Tells us if server is busy. :return: True if server is busy. False if server is NOT busy. """ return self.busy def add_customer(self, new_passenger): """ Adds a customer to the sever and sets his service time :param new_passenger: the passenger we are adding """ # get the type of flight his passenger is on # add the passenger to our service queue self.customer_being_served.put_nowait(new_passenger) # set the service time, depending on what type of flight the customer is on self.set_service_time() # update the count of customers added self.customers_added += 1 def complete_service(self): """ Models completion of our service :return: the customer who has just finished at this station """ if not self.is_busy() and not self.customer_being_served.empty(): next_customer = self.customer_being_served.get_nowait() self.customer_being_served.task_done() self.customers_served += 1 else: next_customer = None return next_customer class BaristaServer: """ Class used to model a server at the Security terminal """ def __init__(self): """ Initialize the class variables """ self.service_time = 0.0 self.busy = None # self.customer = None self.customer_being_served = q.Queue() self.is_barista_class = False self.customers_added = 0 self.customers_served = 0 self.idle_time = 0.0 def set_service_time(self): """ Sets the service time for a new passenger :param passenger_type: either "commuter" or "international" """ self.service_time = cc.gen_barista_service_time() self.busy = True def update_service_time(self): """ Updates the service time and tells us if the server is busy or not """ self.service_time -= 0.01 if self.service_time <= 0: self.service_time = 0 self.busy = False if not self.is_busy(): self.idle_time += 0.01 def is_busy(self): """ Call this after updating the service time at each change in system time (delta). Tells us if server is busy. :return: True if server is busy. False if server is NOT busy. """ return self.busy def add_customer(self, new_customer): """ Adds a customer to the sever and sets his service time :param new_passenger: the passenger we are adding """ # add the passenger to our service queue self.customer_being_served.put_nowait(new_customer) # set the service time, depending on what type of flight the customer is on self.set_service_time() # update the count of customers added self.customers_added += 1 def complete_service(self): """ Models completion of our service :return: the customer who has just finished at this station """ next_customer = None # only try to pull a customer from the queue if we are NOT busy # AND the queue isn't empty # else we just return a None if not self.is_busy() and not self.customer_being_served.empty(): next_customer = self.customer_being_served.get_nowait() self.customer_being_served.task_done() self.customers_served += 1 else: next_customer = None return next_customer ############################# ###### C&C CUSTOMERS ###### ############################# class Customer: """ Class used to model a passenger in our simulation """ def __init__(self, system_time, customer_class, system_iteration, relative_time): self.system_time_entered = system_time self.customer_class = customer_class self.system_iteration = system_iteration self.relative_time = relative_time #--------DEBUGGING------- #if flight_type == "international" and system_time > 1490: # print "here" # #confirm_system_time = (system_time / system_iteration) #confirm_relative_time = str(relative_time) #relative_system_time = system_time / (system_iteration * 360.0) #if not str(math.floor((system_time / system_iteration))) == str(math.floor(relative_time)): # print "something's off." #------------------------ def __eq__(self, other): """Override the default Equals behavior""" if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return NotImplemented def __ne__(self, other): """Define a non-equality test""" if isinstance(other, self.__class__): return not self.__eq__(other) return NotImplemented def __hash__(self): """Override the default hash behavior (that returns the id or the object)""" return hash(tuple(sorted(self.__dict__.items()))) ########################## #### SIMULATION CLASS #### ########################## class Simulation: """ Class used to house our whole simulation """ def __init__(self): """ Sets up all the variables we need for the simulation """ #----TIME---- # Time variables self.system_time = 0.00 self.delta = 0.01 self.hours_passed = 0 # = number of system iterations self.system_iteration = 0 self.relative_global_time = 0.00 self.time_until_next_arrival_generation = 60.0 #-----ARRIVALS----- # Arrival list self.barista_ARRIVALS = [] self.cashier_ARRIVALS = [] # All arrivals self.arrivals = [self.barista_ARRIVALS, self.cashier_ARRIVALS] #----QUEUES----- # Check-in Queues - separate for first and coach self.register_QUEUE = RegisterQueue() # Security Queues - also separate for first and coach self.barista_QUEUE = BaristaQueue() # All Queues self.queues = [self.register_QUEUE, self.barista_QUEUE] #------SERVERS------- # Register Servers self.CASHIER_server01 = CashierServer() self.check_in_servers = [self.CASHIER_server01] # Barista Servers self.BARISTA_server01 = BaristaServer() # self.BARISTA_server02 = BaristaServer() self.barista_servers = [self.BARISTA_server01] # All servers self.servers = [self.CASHIER_server01, self.BARISTA_server01] #----INTERNAL_DATA COLLECTION----- self.total_cashier_customers_arrived = 0 self.total_cashier_customers_serviced = 0 self.total_barista_customers_arrived = 0 self.total_barista_customers_serviced = 0 self.customers_combined = 0 # Then counters to see how far people are making it in the system.... # Averaged data self.time_in_system = [] self.time_in_system_CASHIER = [] self.avg_time_in_system = 0 self.avg_time_in_system_CASHIER = [] self.time_in_system_BARISTA = [] #-----INTERNAL MECHANISMS------ self.data_users_added_to_REGISTER_QUEUE = 0 self.data_users_added_to_BARISTA_QUEUE = 0 self.data_users_added_to_FIRSTCLASS_SECURITY_QUEUE = 0 self.data_CASHIER_customers_moved_to_EXIT = 0 self.data_BARISTA_customers_moved_to_EXIT = 0 self.data_users_currently_in_system = 0 self.total_server_idle_time = 0.0 self.data_num_customers_wait_over_one_min = 0 def generate_ONE_HOUR_of_arrivals(self): """ Generates six hours of arrivals and stores in our ARRIVAL LIST instance variables. """ # Create instance of arrival class new_arrivals = CupChaucArrivals() # Generate new arrivals new_arrivals.get_arrivals() # Add one to the system iteration (denoted by international flight number) self.hours_passed += 1 # Transfer those values into our simulation, as arrivals for next six hours self.barista_ARRIVALS = new_arrivals.barista_arrivals self.cashier_ARRIVALS = new_arrivals.cashier_arrivals # clean up arrivals, so nothing greater 60, because we'll never reach it for arrival in new_arrivals.cashier_arrivals: if arrival > 59.99999999: new_arrivals.cashier_arrivals.remove(arrival) for arrival in new_arrivals.barista_arrivals: if arrival > 59.99999999: new_arrivals.barista_arrivals.remove(arrival) # Count our arrivals for data collection self.total_cashier_customers_arrived += len(new_arrivals.cashier_arrivals) self.total_barista_customers_arrived += len(new_arrivals.barista_arrivals) print "arrivals generated for hour: " + str(self.hours_passed) def update_servers(self): """ Updates servers after a change of DELTA in system time """ for server in self.servers: server.update_service_time() def collect_and_create_passengers_from_arrivals(self): """ Looks at all arrival lists, and if there is new arrival at the current system time, creates a passenger object for use in the system, and places it in the check-in queue """ relative_time = self.relative_global_time # make sure we're not checking an array that's empty if not len(self.barista_ARRIVALS) == 0: # Then get next available item from INTL FIRST CLASS ARRIVALS if self.barista_ARRIVALS[0] <= relative_time: # create passenger, put it in first class check in queue new_customer = Customer(self.system_time, "barista", self.hours_passed, self.barista_ARRIVALS[0]) self.register_QUEUE.add_customer(new_customer) # pop from the list self.barista_ARRIVALS.pop(0) # make sure we're not checking an array that's empty if not len(self.cashier_ARRIVALS) == 0: # Then get next available item from COMMUTER COACH CLASS ARRIVALS if self.cashier_ARRIVALS[0] <= relative_time: # create passenger, put it in coach class check in queue new_customer = Customer(self.system_time, "cashier", self.hours_passed, self.cashier_ARRIVALS[0]) self.register_QUEUE.add_customer(new_customer) # pop from the list self.cashier_ARRIVALS.pop(0) def move_to_CASHIER_server(self): """ Look at check in servers, and if they are not busy, advance the first item in the correct queue to the correct (and open) check in server """ #>>>>>> Later, change this go through all checkin servers in a loop and do same action. # This code can be very much condensed # If first class check-in server is NOT busy if not self.CASHIER_server01.is_busy(): # de-queue from the FIRST class check-in queue if not self.register_QUEUE.queue.empty(): next_passenger = self.register_QUEUE.queue.get() self.register_QUEUE.queue.task_done() # and move next passenger to server, since it isn't busy self.CASHIER_server01.add_customer(next_passenger) def update_register_queues(self): """ Updates queues after a change of DELTA in system time """ # then check the servers, and if they're free move from queue to server self.move_to_CASHIER_server() # Check all arrivals and if the arrival time matches system time... # Create a passenger and ADD the correct queue self.collect_and_create_passengers_from_arrivals() def update_barista_queues(self): """ Updates queues after a change of DELTA in system time """ # Check all check-in servers... and if they are NOT busy, take their passenger... # Take the passenger, add the correct security queue # First, look at all servers for server in self.check_in_servers: # and if the server is NOT busy # if not server.is_busy(): #if not server.last_customer_served.empty(): # Take the passenger, who must have just finished being served my_customer = server.complete_service() # and move them to the correct security queue if not my_customer == None: # but first make sure that the passenger does not == None if my_customer.customer_class == "cashier": # add to end of simulation self.data_CASHIER_customers_moved_to_EXIT += 1 # data collection for coach time_in_system = self.system_time - my_customer.system_time_entered self.time_in_system.append(time_in_system) self.time_in_system_CASHIER.append(time_in_system) # data collection for commuters self.time_in_system_CASHIER.append(time_in_system) self.total_cashier_customers_serviced += 1 # else, add to barista queue else: # because if they are NOT cashier customers, they must be barista customers self.barista_QUEUE.add_customer(my_customer) def move_to_BARISTA_server(self): """ If servers are not busy, advance next passenger in the security queue to to security server """ # step through all the security servers and check if they are busy for server in self.barista_servers: # if the server isn't busy, we can take the next passenger from security queue # and put him in the server if not server.is_busy(): # first make sure it's not empty if not self.barista_QUEUE.queue.empty(): # and if it's not, grab the next passenger out of it next_customer = self.barista_QUEUE.queue.get() self.barista_QUEUE.queue.task_done() # And move that passenger into the available security server server.add_customer(next_customer) def move_to_EXIT(self): """ Look at Security servers, and if they are NOT busy, someone just finished security screening. This means they've completed the queuing process. --- Once through queuing, go to GATE. Commuters --> Go straight to gate waiting area International --> First check if they missed their flight. - If yes: They leave - If no: They go to international gate """ # step through all the security servers for server in self.barista_servers: # if the server is NOT busy #if not server.is_busy(): #if not server.last_customer_served.empty(): # passenger has completed queuing phase, and can move to gate. # but first, we need to check if they are commuters or international flyers # and in each case, need to handle that accordingly next_customer = server.complete_service() # first make sure that the passenger isn't a NONE if not next_customer == None: # if the passenger is a commuter, they just go to gate if next_customer.customer_class == "barista": self.data_BARISTA_customers_moved_to_EXIT += 1 # data collection for coach time_in_system = self.system_time - next_customer.system_time_entered self.time_in_system.append(time_in_system) self.time_in_system_BARISTA.append(time_in_system) # data collection for commuters self.time_in_system_BARISTA.append(time_in_system) self.total_barista_customers_serviced += 1 def advance_system_time(self): """ Advances the system time by delta --> .01 of a minute - Looks for arrivals at current time - If an arrival is valid, create a passenger object and place it in the proper Queue - Needs to update EVERY QUEUE and SERVER, advance wherever needed """ # every six hours, generate new arrivals, # and perform accounting procedures on ticket # for those arrivals #if self.time_until_international_flight <= 0.0: # self.generate_SIX_HOURS_of_arrivals() # self.collect_revenue() # self.every_six_hours_deduct_operating_costs() # increment the system time by delta self.system_time += self.delta self.time_until_next_arrival_generation -= self.delta # keep track of relative global time self.relative_global_time += self.delta if self.relative_global_time >= 60.0: self.relative_global_time = 0.0 #print "gets system time update" # skip these on the first iteration because we don't have data yet if not self.hours_passed == 0: #DO IT IN REVERSE ORDER # start by updating the servers self.update_servers() # then, if we can pull someone FROM a sever, while not busy, do it self.move_to_EXIT() self.update_barista_queues() # then get passengers from arrivals, and fill the queues self.collect_and_create_passengers_from_arrivals() # then move people into any empty spots in the servers self.move_to_BARISTA_server() self.move_to_CASHIER_server() # every six hours, generate new arrivals, # and perform accounting procedures on ticket # for those arrivals if self.time_until_next_arrival_generation <= 0: self.generate_ONE_HOUR_of_arrivals() self.time_until_next_arrival_generation = 60.0 #print "checks if planes depart" # print self.system_time def run_simulation(self, simulation_time_in_days): """ Use this to run simulation for as long as user has specified, in days While the counter < # of days, keep generating the arrivals every 6 hours and stepping through the simulation """ simulation_time_in_minutes = simulation_time_in_days * 24.0 * 60.0 + 60.0 # = days * 24 hours in a day * 60 minutes in an hour while self.system_time < simulation_time_in_minutes: # then, advance system time by delta: 0.01 self.advance_system_time() print "SIMULATION COMPLETE:" ############################################# ####### DATA REPORTING AND ANALYSIS ######### ############################################# def print_simulation_results(self): """ prints the results of our simulation to the command line/console """ print "###################################" print "####### SIMULATION RESULTS ########" print "###################################" print "#-----System Info-----" print "Total CASHIER customers ARRIVED="+str(self.total_cashier_customers_arrived) print "Total CASHIER customers SERVICED="+str(self.total_cashier_customers_serviced) print "Total BARISTA customers ARRIVED="+str(self.total_barista_customers_arrived) print "Total BARISTA customers SERVICED="+str(self.total_barista_customers_serviced) total_customers_serviced = self.total_barista_customers_serviced + self.total_cashier_customers_serviced print "Total CUSTOMERS (all types) SERVICED="+str(total_customers_serviced) print "-------Averages-------" #sum_time_in_system = sum(self.time_in_system) length_of_time_in_system_list = len(self.time_in_system) #length_of_time_in_system_list = float(length_of_time_in_system_list) #print "SUM OF TIME IN SYSTEM: "+str(sum_time_in_system) #print "LENGTH OF TIME IN SYSTEM: "+str(length_of_time_in_system_list) self.avg_time_in_system = sum(self.time_in_system)/len(self.time_in_system) print "AVG Time In System for ALL CUSTOMERS (who make make it to EXIT)="+str(self.avg_time_in_system) self.time_in_system.sort(reverse=True) longest_time_in_system = self.time_in_system.pop(0) print "Longest time in system="+str(longest_time_in_system) average_time_in_system_cashier = sum(self.time_in_system_CASHIER) / len(self.time_in_system_CASHIER) print "AVG Time in system CASHIER="+str(average_time_in_system_cashier) average_time_in_system_barista = sum(self.time_in_system_BARISTA) / len(self.time_in_system_BARISTA) print "AVG Time in system all BARISTA="+str(average_time_in_system_barista) print "------Internal Mechanisms-------" print ".......Stage 1......" print "Customers added to RegisterQueue="+str(self.register_QUEUE.customers_added) print "......Stage 2......." print "Customers added to BaristaQueue="+str(self.barista_QUEUE.customers_added) print "......Stage 3......." print "CASHIER customers who make it to EXIT="+str(self.data_CASHIER_customers_moved_to_EXIT) print "BARISTA customers who make it to EXIT="+str(self.data_BARISTA_customers_moved_to_EXIT) print ". . . . didn't make it . . . . ." still_in_system = 0 for queue in self.queues: still_in_system += queue.queue.qsize() print "Users STILL in SYSTEM="+str(still_in_system) print "======= GOALS ========" self.total_server_idle_time = 0.0 for server in self.check_in_servers: self.total_server_idle_time += server.idle_time print "AGENTS' Total Idle Time="+str(self.total_server_idle_time) server_count = len(self.servers) print "AGENTS AVG IDLE TIME="+str(self.total_server_idle_time/server_count) print "TIMES GREATER THAN 1 MIN:" wait_times_longer_than_min = [] wait_times_longer_than_2mins = [] wait_times_longer_than_3mins = [] wait_times_longer_than_5mins = [] for time in self.time_in_system: if time > 1.0: # print time wait_times_longer_than_min.append(time) if time > 2.0: wait_times_longer_than_2mins.append(time) if time > 3.0: wait_times_longer_than_3mins.append(time) if time > 5.0: wait_times_longer_than_5mins.append(time) print "TOTAL WAIT TIMES LONGER THAN 1 MINUTE: " + str(len(wait_times_longer_than_min)) print "TOTAL WAIT TIMES LONGER THAN 2 MINUTES: " + str(len(wait_times_longer_than_2mins)) print "TOTAL WAIT TIMES LONGER THAN 3 MINUTES: " + str(len(wait_times_longer_than_3mins)) print "TOTAL WAIT TIMES LONGER THAN 5 MINUTES: " + str(len(wait_times_longer_than_5mins)) print "Percentage of Barista Customers who waited longer than 1 minute: " + str(float(float(len(wait_times_longer_than_min))/self.total_barista_customers_serviced)) print "Percentage of Barista Customers who waited longer than 2 minutes: " + str(float(float(len(wait_times_longer_than_2mins))/self.total_barista_customers_serviced)) print "Percentage of Barista Customers who waited longer than 3 minutes: " + str(float(float(len(wait_times_longer_than_3mins))/self.total_barista_customers_serviced)) print "Percentage of Barista Customers who waited longer than 5 minutes: " + str(float(float(len(wait_times_longer_than_5mins))/self.total_barista_customers_serviced)) print ""
261a80f5080e6ad40aacc3f4921d7e140d19fedd
imran436/Projects-Portfolio-master
/Tech Academy/python projects/#13.py
555
3.9375
4
import time X = 5 print(X) X = X**5 print(X) if X<10: print("our number X is a small value") elif X<100: print("The number is an average value") else: print("the number holds a big value") counter = 0 for counter in range(0, 100,5): print(counter) time.sleep(.25) counter = 0 while counter < X: print(counter*5) time.sleep(.25) if(counter<1): counter = 1; counter = counter *5 dictionary={'orange':'Fruit','milk':'dairy','carrots':'vegitable'} print(dictionary) dictionary['chicken']='Poltry' print(dictionary)
70c66c6ddb26d1ddad9409d84c4932e7dfd718af
Sasithorn04/Python
/ตารางหมากฮอส.py
604
3.9375
4
#โปรแกรมจำลองตารางหมากฮอส #ปรับจากสร้างภาพวาด4เหลี่ยมจตุรัส number = int(input("ป้อนขนาด :")) for row in range(1,number+1) : for column in range(1,number+1) : if (column%2 == 0) & (row%2 == 0) : print("o",end='') elif (column%2 != 0) & (row%2 != 0): print("o",end='') else : print("x",end='') print(" ") ''' oxoxoxox xoxoxoxo oxoxoxox xoxoxoxo oxoxoxox xoxoxoxo oxoxoxox xoxoxoxo '''
ebcd50508c0690db480ba215a31c764c84db3988
harshit-tiwari/Python-Codes
/Simple Calculator/addition.py
689
4.09375
4
import calculate def addFunc(): print("You have chosen Addition") operands = [] number = 0 while True: try: number = int(input("How many numbers do you want to add? : ")) break except ValueError: print("Please enter a number as your input") for i in range(0, number): while True: try: value = int(input("Enter the number %s here : "%(i+1))) break except ValueError: print("Please enter a number as your input") operands.append(value) total = calculate.add(*operands) print("The sum of these numbers is : ", total)
e978a7977ddfd0f0e7559618d3aa1f5282f8ab91
chrissowden14/bank
/FileStore.py
1,592
3.90625
4
class FileStore: def __init__(self): # This creates an open list everytime the program is opened self.cusnames = [] self.cusspaswords = [] self.cusbalance = [] # opening the stored file that collects the old data from customer self.namefile = open("cusnamesfile.txt", "r") self.passfile = open("cuspassfile.txt", "r") self.balancefile = open("cusbalancefile.txt", "r") # this will input the date into the empty list from the stored FileExistsError for line in self.namefile: self.cusnames.append(line[:-1]) self.namefile.close() # check the list of customers passwords for line in self.passfile: self.cusspaswords.append(line[:-1]) self.passfile.close() # checks customer balance for line in self.balancefile: self.cusbalance.append(line[:-1]) self.balancefile.close() # this function will write new date into stored files when its called up def filewrite(self, item): if item == self.cusnames: text = open("cusnamesfile.txt", "w") for i in item: text.write(i + "\n") text.close() elif item == self.cusspaswords: text = open("cuspassfile.txt", "w") for i in item: text.write(i + "\n") text.close() elif item == self.cusbalance: text = open("cusbalancefile.txt", "w") for i in item: text.write(str(i) + "\n") text.close()
b58ef87371085284143fbb0d28d9251d8d97b01f
Subhashriy/python
/11-07-19/substitute.py
200
3.5
4
import re n=int(input("Enter no. of lines:")) a=[] for i in range(n): a.append(input()) str1=re.sub(r'&&','and',a[i]) str1=re.sub(r'\|\|','or',a[i])
0de46d21ae522160a24e89e11919f60365b32288
Subhashriy/python
/17-07-19/tcpclient.py
752
3.5625
4
import socket def main(): host='127.0.0.1' port=5000 #Creting a socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print("Socket Created.") #connect to the server s.connect((host,port)) print('Connected to server.') #send msg to the server data=input('Enter the number to find the factorial: ') print('Enter q to terminate connection.') while data!='q': print(data) #s.send(str.encode(data,'utf-8')) s.send(str.encode(data,'utf-8')) data=s.recv(1024).decode('utf-8') print(data) data=input('Enter the number to find the factorial: ') s.close() if __name__=='__main__': main()
07617bf9783632e43ce3e5e585bc5d844e29f8e1
Subhashriy/python
/17-07-19/avg.py
128
3.90625
4
lst=[int(x) for x in input('Enter the list: ').split(' ')] print('The average of the list is : {}'.format((sum(lst)/len(lst))))
1687e6c73055cb78bb5399468addc38065edfc4f
Subhashriy/python
/17-07-19/random.py
199
3.75
4
import random def randomnum(i,n): print(random.randint(i,n+1)) #print(random.randint(1,100)) i=int(input('Enter the start range:')) n=int(input('Enter the end range:')) randomnum(i,n)
70b744b963b558041e7e60fb910eaa3260c619e9
zacharymollenhour/Fitness_Tracker
/test.py
2,323
3.984375
4
import numpy as np import pandas as pd import csv from datetime import date #Get User Name class Person: "This is a persons data class" def __init__(self): self.userData = [] self.name = '' self.age = 0 self.weight = 0 #Greet User for data about the individual def greet(self): #User Data self.name = input("Enter in your name: ") print(self.name) self.age = input("Enter in your age: ") print(self.age) self.weight = input("Enter in your weight: ") print(self.weight) #Write Inital Data of individual being tracked def updateCSV(self): with open('user_statistics.csv', mode='w') as csv_file: csv_reader = csv.writer(csv_file) csv_reader.writerow(self.name) csv_reader.writerow(self.age) csv_reader.writerow(self.weight) #Class for tracking workout data class Workout: "This is a class to track workout data" def __init__(self): self.date = '' self.workoutType = '' self.weight = 0 self.duration = 0 #Function to get workout information def workoutData(self): today = date.today() self.date = today.strftime("%m/%d/%y") self.workoutType = input("Please enter the workout type:") print(self.workoutType) self.updateWorkoutData() #Class that writes workout data to a csv def updateWorkoutData(self): with open('workout_data.csv', mode='a+',newline='') as csv_file: csv_reader = csv.writer(csv_file) csv_reader.writerow([self.date]) csv_reader.writerow([self.workoutType]) #Menu def menu(self): ans = True while ans: print(""" 1.Add a Workout 2.Delete a Workout """) ans=input("What would you like to do?") if ans == "1": self.workoutData() if ans == "2": "comeback" #Main Function def main(): #Declare a object person1 = Person() workoutObject = Workout() #Call object functions """ person1.greet() person1.updateCSV() """ workoutObject.menu() #workoutObject.workoutData() #workoutObject.updateWorkoutData() main()
ce0dada2eadce554808ced1d97e1c8b88e2a9b7e
devsben/Neopets-Multi-Tool
/classes/__init__.py
288
3.5
4
import sys if sys.version_info[0] < 3: """ If a Python version less than 3 is detected prevent the user from running this program. This will be removed once the final tweaking is completed for Python 2. """ raise Exception("Python 3 is required to run this program.")
39c5729b31befc2a988a0b3ac2672454ae99ea9a
krsatyam20/PythonRishabh
/cunstructor.py
1,644
4.625
5
''' Constructors can be of two types. Parameterized/arguments Constructor Non-parameterized/no any arguments Constructor __init__ Constructors:self calling function when we will call class function auto call ''' #create class and define function class aClass: # Constructor with arguments def __init__(self,name,id): self.name=name self.id=id #print(self.id) #print(self.name) #simple function def show(self): print("name=%s id= %d "%(self.name,self.id)) #call a class and passing arguments obj=aClass("kumar",101) obj2=aClass("rishave",102) obj.show() obj2.show() #second ExAMPLE class Student: def __init__(self,name,id,age): self.name = name; self.id = id; self.age = age #creates the object of the class Student s = Student("John",101,22) #s = Student() TypeError: __init__() missing 3 required positional arguments: 'name', 'id', and 'age' print("*************befoer set print***********") print(getattr(s,'name')) print(getattr(s,'id')) print(getattr(s,'age')) print("**********After set print***********") setattr(s,'age',23) print(getattr(s,'age')) setattr(s,'name','kumar') print(getattr(s,'name')) # Constructor - non parameterized print("************ Non parameters ***********") class Student: def __init__(self): print("This is non parametrized constructor") def show(self,name): print("Hello",name) student = Student() #student.show("Kuldeep")
bcde27b2f96aff6d73cf8cb2836416b57c3e0e56
krsatyam20/PythonRishabh
/filehandling.py
1,001
3.734375
4
''' open(mode,path) mode r :read read() => read all file at a time readline() => line by line read readlines() => line by line read, but line convert into list w :write write() a :append open(path,'a') write() path(file location with file name) ''' x=open(r"C:\Users\User\Desktop\Java.advance.txt") print(x) #print(x.read()) '''print(x.readline()) print(x.readline()) print(x.readline()) print(x.readline()) ''' #print(x.readlines()) readFileandconvertIntoList=x.readlines() '''for rf in readFileandconvertIntoList: print(rf)''' #count line print(len(readFileandconvertIntoList)) wf=open(r"C:\Users\User\Desktop\output.txt",'w') wf.write('Hello\n') wf.write('Hello\n') wf.write('Hello\n') wf.write('Hello\n') wf.write('Hello\n') wf.write('Hello\n') wf.write('Hello\n') wf.close() ''' count word and char in any file'''
5be464d262f21413b369dc140cae381540470ef0
krsatyam20/PythonRishabh
/forloop.py
590
4.09375
4
''' loop : loop is a reserved keyword it`s used for repetaion of any task types of loop 1. For loop 2.while loop ''' for i in range(0,10): print("Rishab %d " %(i)) for i in range(1,21): print(i) #use break keyword print("===========break keyword=================") for i in range(1,21): if(i==8): break; print(i) #continue print("===========continue keyword=================") for d in range(1,21): if(d==12): continue; print(d)
fa517e9e021b1d701a23211c569e6fd201bdb42c
gsingh84/Adventure-Game
/Adventure-game.py
10,666
4.25
4
#All functions call at the end of this program import random treasure = ['pieces of gold!', 'bars of silver!', 'Diamonds!', 'bottles of aged Rum!'] bag = ['Provisions'] #yorn function allow user to enter yes or no. def yorn(): yinput = "" while True: yinput = input("Please Enter Yes or No (Y/N): ") if yinput == 'Y' or yinput == 'y' or yinput == 'n' or yinput == 'N': return yinput #find_treasure function find the random treasure from given list. def find_treasure(ref): new = random.sample(set(treasure),1) from random import randint qty_tr = (randint(1,50), new[0], '%s.'%ref) print() print ('You Found', ' '.join(str(x) for x in qty_tr)) print('---------------------------------') bag.append(qty_tr) show_treasure() print('---------------------------------') #show_treasure function shows the items that available in the bag. def show_treasure(): print('your bag of holding contains:') for list in bag: print (' '.join(str(x) for x in list)) #This is strating point of program, this function gives the intro. def intro(): print("Time for a little adventure!") print() print("You're for a hike, you have a walking stick, backpack, and some provisions") print() print("You have been following a stream bed through a forest, when you see a") print("small stone building. Around you is a forest. A small stream flows out of the") print("building and down a gully.") print() print("Just outside of the small building, by a warm, inviting fire, is an old,") print("possibly ancient man, with long rather mangy beard. He sees you and says:") print() print("\t 'Hello my friend, stay a while and listen...'") print() print("You're not sure why, but you decide to stay and listen as he tells you stories") print("of strange and magical lands of adventure and Treasure!") print() print("After what seems like hours, the old man admits to being a bit hungry. He asks,") print("pointing at your backpack, if you have food in your 'bag of Holding', that") print("you might be willing to share.") print() print("Do you share your provisions?") print("-------------------------------------------------------------------------------") fun_input = yorn() #call the yorn function here to get input from user. if fun_input == "y" or fun_input == "Y": print("The old man hungrily devours all of your provisions with barely a crumb in sight") print() print("He leans close to you and whispers 'Besides gold, silver, and diamonds, if you") print("chosse wisely, there could also be other valuable GEMS!'") print() print('He slips you something of great value...') treasure.insert(0, 'bags of GEMS!') #if user Enter 'y' then it will add (bags of GEMS!) into the treasure list other wise not. print() print("your possible treasures are:") bag.remove(bag[0]) #after sharing provison with old man, this statement will remove provisions from bag other wise provisions remain in the bag. for list in treasure: ge = list.strip() print(ge) find_treasure("from old man") #call the find_treasure function here and pass the argument for where the item found from and also show the items in the bag. elif fun_input == 'N' or fun_input == "n": print("He looks at you wistfully ... for a moment,") print(" then eats the last few crumbs.") print() print('your possible treasures are:') for list in treasure: ge = list.strip() print(ge) #potion function allow user to choose between two potions. def potion(): print("-------------------------------------------------------------------------------") print("The old man stands up and waves his hand towards a rather ornate table close to") print("the building. you didn't notice the table before, but it's really quite out of") print("place in this forest.") print() print("On the ornate table is two bottles of potion, one is blue, and the other is red.") print() print("There is also a note, the note says,") print() print("\t Drink the BLUE potion and believe whatever you want to believe.") print() print("The rest of the note is destroyed and can't be read.") print() print("You turn to the old man, he seems to look much taller and a bit forbidding ...") print() print("\t He points at the table and says 'CHOOSE' ") print() red = ('RED') blue = ('BLUE') pinput = input('Do you choose the RED potion or the BLUE potion (R/B)? ') if pinput == "r" or pinput == "R": print() print('you guzzle the contents of the bottle with the red potion.') print() print("you feel like you're on fire! smoke is pouring out of your nose and ears!") print("when the thick red billowy smoke subsides, the old man is gone and there is a") print("narrow cobblestone trail leading from the small building.") print() print("you follow the cobblestone trail.") return (red) elif pinput == "b" or pinput == "B": print() print("you drink the BLUE potion. Nothing seems to happen ... at first. Then") print("strangely your body tingles , an old man bids you farewell as he leaves the park.") print("you wonder vaguely about something regarding a hike or a forest ...") return (blue) else: print() print("you fail to drink a potion, the old man leaves and you wonder aimlessly though") print("the forest, hopelessly lost!") def dwarf(): max = 6 for counter in range(max): from random import randint dwarfappear = (randint(1,2)) dwarf_r = (randint(1,2)) if dwarfappear == 1: #Here you can see if dwarfappear variable or random number = 1 then dwarf will appear print("-------------------------------------------------------------------------------") print("As you procees along the trail, you encounter a wicked looking") print("dwarf with a long black beard.") print() print("He has a large rusty knife in his hand!") print() print("He seems to be laughing at you as you're trying to decide to attack or to just") print("run away ...") print() print("Do you attack?") print("-------------------------------------------------------------------------------") dwarfinput = yorn() #Here I call the yorn function for asking "do you want to attack" on dwarf if dwarfinput == 'y' or dwarfinput == 'Y' and dwarf_r == 2: #Here I used another random number, you can see above with the name dwarf_r which is for mighty swing print("You take a mighty swing at the dwarf with your stick") print() print("C R A C K ! ! ... you hit the dwarf, it's dead") print() print("Do you want to loot the body?") loot = yorn() #call yorn() function to get input from user. if loot == 'y' or loot == 'Y': find_treasure("from Dwarf") elif dwarfinput == 'y' or dwarfinput == 'Y' and dwarf_r == 1: #If dwarf_r variable or random number = 1 then you will miss the target other wise you hit the dwarf print() print("You take a mighty swing at the dwarf with your stick") print("Whoosh! ... you miss the dwarf, but he runs away") elif dwarfinput == 'n' or dwarfinput == 'N': print("You let out a blood curdling scream, and run very fast!") elif dwarfappear == 2: #Here you can see if dwarfappear variable = 2 then dwarf will not appear print("-------------------------------------------------------------------------------") print("You continue to follow the cobblestone trail.") print() def elves(): from random import randint elves_r = (randint(1,2))# Here again I used randint for elf. print() print("You come to what looks like the end of the 'road'. The trail splits and") print("there appears to be two strange looking houses here.") print() print("The first one, the left, is a very large and elaborate house. There") print("is a very 'fancy' elf standing in front!") print() print("The second house is very small and looks like it's about to fall over. There") print("is a very short elf standing in front!") print() print("Both seem to be beckoning you closer. which elf do you approach? The one by") print("the first house or the one by the second house?") print() while True: try: elves_input = int(input("Choose an elf to approach (1 or 2)? ")) print() if elves_r == 1 and elves_input == 1 or elves_r == 2 and elves_input == 2: #if user enter 1 and random number also 1 or user enter 2 and random number also 2 then elf invites you in. print("you have chosen wisely!") print("... The elf invites you in for a cup of tea (and a gift) ") print() find_treasure('from elf') print("You have had a great adventure and found some amazing treasure") elif elves_r == 1 and elves_input == 2 or elves_input == 1 and elves_r == 2: # other then that if you input value not matched with random number then you choosed the bad elf. print() print("The elf starts to cackle, and begins to incant a spell") print() print("P O O F ! ! he turns you into a giant TOAD!!") print() print("You have had a great adventure and found some amazing treasure") print("... if you're not a giant toad!") if elves_input == 1 or elves_input == 2: break except ValueError: print('Please Enter 1 or 2') intro() print() input('Press Enter to continue..') potion = potion() print(potion) print() input('Press Enter to continue..') dwarf() print() input('Press Enter to continue..') elves() print() print('Thanks for playing')
34f5750734878b8d0d100a5882e2b4a70fbb13f9
nicklip/Google_Python_Developers_Course
/copyspecial.py
4,485
3.828125
4
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import sys import re import os import shutil import commands """Copy Special exercise The copyspecial.py program takes one or more directories as its arguments. We'll say that a "special" file is one where the name contains the pattern __w__ somewhere, where the w is one or more word chars. The provided main() includes code to parse the command line arguments, but the rest is up to you. Write functions to implement the features below and modify main() to call your functions. Suggested functions for your solution(details below): get_special_paths(dir) -- returns a list of the absolute paths of the special files in the given directory copy_to(paths, dir) given a list of paths, copies those files into the given directory zip_to(paths, zippath) given a list of paths, zip those files up into the given zipfile """ def get_special_paths(the_dir): ''' returns a list of the absolute paths of the special files in the given directory ''' the_paths = [] # Getting the filenames from the directory filenames = os.listdir(the_dir) for filename in filenames: # Finding all of the "special" files special = re.findall(r'__\w+__', filename) if special: # Putting all special files in a list abs_path = os.path.abspath(os.path.join(the_dir, filename)) the_paths.append(abs_path) # Returning list of special files return the_paths def copy_to(paths, to_dir): ''' given a list of paths, copies those files into the given directory ''' # If the directory to copy the files to doesn't exist, create it if not os.path.exists(to_dir): os.mkdir(to_dir) for path in paths: # Getting the files to be copied from each path filenames = os.listdir(path) for filename in filenames: # Getting the full path of each file abs_path = os.path.abspath(os.path.join(path, filename)) # Copying each file to the desired directory if os.path.isfile(abs_path): shutil.copy(abs_path, to_dir) def zip_to(paths, to_zip): ''' given a list of paths, zip those files up into the given zipfile ''' files = [] for path in paths: # Getting the filenames from each path filenames = os.listdir(path) for filename in filenames: # Putting each joined path + filename into a list files.append(os.path.join(path,filename)) # Command to zip the files into a zipfile with the desired name/path cmd = 'zip -j' + ' ' + to_zip + ' ' + ' '.join(files) # A warning to the user of what command is about to run print 'Command to run:', cmd # Running the zip command (status, output) = commands.getstatusoutput(cmd) # If an error happens, print it to the terminal if status: sys.stderr.write(output) sys.exit(1) def main(): # This basic command line argument parsing code is provided. Add code to call your functions below. # Make a list of command line arguments, omitting the [0] element which is the script itself. args = sys.argv[1:] if not args: print "usage: [--todir dir][--tozip zipfile] dir [dir ...]"; sys.exit(1) # todir and tozip are either set from command line or left as the empty string. # The args array is left just containing the directories (paths) todir = '' if args[0] == '--todir': todir = args[1] del args[0:2] tozip = '' if args[0] == '--tozip': tozip = args[1] del args[0:2] # If no arguments, print an error if len(args) == 0: print "error: must specify one or more dirs" sys.exit(1) # +++your code here+++ ## Call your functions # If '--todir' command is called in the args, run the function to copy all of the # files from all the paths to the desired directory. if todir: copy_to(args[0:len(args)], todir) # If '--tozip' command is called in the args, run the function to create a zip file, # with the desired name, of all of the files from all the paths. elif tozip: zip_to(args[0:len(args)], tozip) # Run the function to print all special files from all paths, if no '--todir' or # '--to zipfile' command is included in the args else: paths = [] for dirname in args: paths.extend(get_special_paths(dirname)) print '\n'.join(paths) if __name__ == "__main__": main()
5bd5df1910a6c6765dfeff536eba03ca4878dc6e
TiwariSimona/Hacktoberfest-2021
/g-animesh02/cartoon3.py
2,243
4.0625
4
import cv2 class Cartoonizer: """Cartoonizer effect A class that applies a cartoon effect to an image. The class uses a bilateral filter and adaptive thresholding to create a cartoon effect. """ def __init__(self): pass def render(self, img_rgb): img_rgb = cv2.imread(img_rgb) img_rgb = cv2.resize(img_rgb, (1366, 768)) numDownSamples = 2 # number of downscaling steps numBilateralFilters = 50 # number of bilateral filtering steps # -- STEP 1 -- # downsample image using Gaussian pyramid img_color = img_rgb for _ in range(numDownSamples): img_color = cv2.pyrDown(img_color) # cv2.waitKey(0) # repeatedly apply small bilateral filter instead of applying # one large filter for _ in range(numBilateralFilters): img_color = cv2.bilateralFilter(img_color, 9, 9, 7) # cv2.waitKey(0) # upsample image to original size for _ in range(numDownSamples): img_color = cv2.pyrUp(img_color) # cv2.waitKey(0) # -- STEPS 2 and 3 -- # convert to grayscale and apply median blur img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY) img_blur = cv2.medianBlur(img_gray, 3) # cv2.waitKey(0) # -- STEP 4 -- # detect and enhance edges img_edge = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11,11) # cv2.waitKey(0) # -- STEP 5 -- # convert back to color so that it can be bit-ANDed with color image (x, y, z) = img_color.shape img_edge = cv2.resize(img_edge, (y, x)) img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB) cv2.waitKey(0) (x, y, z) = img_color.shape img_edge = cv2.resize(img_edge, (y, x)) return cv2.bitwise_and(img_color, img_edge) tmp_canvas = Cartoonizer() file_name = input() # File_name will come here res = tmp_canvas.render(file_name) cv2.imwrite("Cartoon version.jpg", res) cv2.imshow("Cartoon version", res) cv2.waitKey(0) cv2.destroyAllWindows()
5152927f8f259d1d78645fdec94330753225833a
TiwariSimona/Hacktoberfest-2021
/Aryan810/new_search_algorithm.py
1,268
3.71875
4
from threading import Thread import time class SearchAlgorithm1: def __init__(self, list_data: list, element): self.element = element self.list = list_data self.searching = True self.index = None def search(self): Thread(self.forward()) self.reverse() return self.index def reverse(self): len_all = len(self.list) for i in range(len(self.list) - 1): try: if not self.searching: break i = len_all - i if self.list[i] == self.element: self.searching = False self.index = i break except Exception: pass def forward(self): for i in range(len(self.list) - 1): try: if not self.searching: break if self.list[i] == self.element: self.searching = False self.index = i break except Exception: pass list_i = [i for i in range(800, 9800)] print("Searching by my algorithm...") index_element = SearchAlgorithm1(list_i, 8999).search() print(index_element)
f2744631653064a83857180583c831b187a8f53c
TiwariSimona/Hacktoberfest-2021
/ajaydhoble/euler_1.py
209
4.125
4
# List for storing multiplies multiplies = [] for i in range(10): if i % 3 == 0 or i % 5 == 0: multiplies.append(i) print("The sum of all the multiples of 3 or 5 below 1000 is", sum(multiplies))
bbfe214cd8be2137032f9f2fa056302865a9ada2
TiwariSimona/Hacktoberfest-2021
/akashrajput25/Some_py_prog/count_alphabet.py
178
3.671875
4
name=input("Enter your name\n") x=len(name) i=0 temp="" for i in range(x) : if name[i] not in temp: temp+=name[i] print(f"{name[i]}:{name.count(name[i])}")
16ad6fbbb5ab3f9a0e638a1d8fd7c4469d349c11
TiwariSimona/Hacktoberfest-2021
/parisheelan/bmi.py
957
4.15625
4
while True: print("1. Metric") print("2. Imperial") print("3. Exit") x=int(input("Enter Choice (1/2/3): ")) if x==1: h=float(input("Enter height(m) : ")) w=float(input("Enter weight(kg) : ")) bmi=w/h**2 print("BMI= ",bmi) if bmi<=18.5: print("Underweight") elif bmi>=25: if bmi>=30: print("Obese") else: print("Overweight") else: print("Normal") elif x==2: h=float(input("Enter height(in) : ")) w=float(input("Enter weight(lbs) : ")) bmi=(w*703)/h**2 print("BMI= ",bmi) if bmi<=18.5: print("Underweight") elif bmi>=25: if bmi>=30: print("Obese") else: print("Overweight") else: print("Normal") elif x==3: break else: print("wrong input")
c5a68da4e7ffdc1ddc86d247e3092c5eb7d09699
TiwariSimona/Hacktoberfest-2021
/CharalambosIoannou/doubly_linked_list_helper.py
2,632
4
4
class DListNode: """ A node in a doubly-linked list. """ def __init__(self, data=None, prev=None, next=None): self.data = data self.prev = prev self.next = next def __repr__(self): return repr(self.data) class DoublyLinkedList: def __init__(self): """ Create a new doubly linked list. Takes O(1) time. """ self.head = None def __repr__(self): """ Return a string representation of the list. Takes O(n) time. """ nodes = [] curr = self.head while curr: nodes.append(repr(curr)) curr = curr.next return '[' + ', '.join(nodes) + ']' def prepend(self, data): """ Insert a new element at the beginning of the list. Takes O(1) time. """ new_head = DListNode(data=data, next=self.head) if self.head: self.head.prev = new_head self.head = new_head def append(self, data): """ Insert a new element at the end of the list. Takes O(n) time. """ if not self.head: self.head = DListNode(data=data) return curr = self.head while curr.next: curr = curr.next curr.next = DListNode(data=data, prev=curr) def find(self, key): """ Search for the first element with `data` matching `key`. Return the element or `None` if not found. Takes O(n) time. """ curr = self.head while curr and curr.data != key: curr = curr.next return curr # Will be None if not found def remove_elem(self, node): """ Unlink an element from the list. Takes O(1) time. """ if node.prev: node.prev.next = node.next if node.next: node.next.prev = node.prev if node is self.head: self.head = node.next node.prev = None node.next = None def remove(self, key): """ Remove the first occurrence of `key` in the list. Takes O(n) time. """ elem = self.find(key) if not elem: return self.remove_elem(elem) def reverse(self): """ Reverse the list in-place. Takes O(n) time. """ curr = self.head prev_node = None while curr: prev_node = curr.prev curr.prev = curr.next curr.next = prev_node curr = curr.prev self.head = prev_node.prev
1c7ecdea2b8d027f39b67355f76a7b6e9c7fce47
SiyandzaD/analysehackathon
/tests/test.py
494
3.875
4
from analysehackathon.recursion import sum_array from analysehackathon.recursion import fibonacci def test_sum_array(): """ make sure sum_aray works correctly """ assert sum_array([1,2,3]) == 6, 'incorrect' print(sum_array([1,2,3])) assert sum_array([1,2,3,4]) == 10, 'incorrect' def test_fibonacci(): """ make sure sum_aray works correctly """ assert fibonacci(7) == 13, 'incorrect' assert fibonacci(12) == 144, 'incorrect'
932042d87adfba2bdb8d437b2c20d98d2afd7c22
VinayagamD/PythonBatch3
/hello.py
74
3.5
4
a = 10 b = 20 sum = a +b print(sum) print('Hello to python programming')
b6d05ea933a068a2a1716aee977af795764eeaa7
quirosnv/PROYECTO
/Proyecto Buscador en proceso/Buscador.py
5,085
3.890625
4
data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: ")) cantante = ['KALEO', 'kaleo', 'Coldplay', 'COLDPLAY', 'The Beatles', 'beatles'] contador = 0 while data != -1: if data == 1: print("Eligio buscar por cantante:") cant= input("Ingrese el nombre de un cantante o banda, para ser buscado: ") if cant == 'kaleo': print("Cancion: Way Down we go") if cant == 'beatles': print("Cancion: Let It Be\n","Cancion: Love Me Do") if cant == 'lp': print("Cancion: Lost On You") if cant == 'status quo': print("Cancion: In the Army Now") if cant == 'coldplay': print("Cancion: Yellow") if cant == 'depeche mode': print("Enjoy The Silence") if cant == 'the cure': print("Cancion: LoveSong\n","Cancion: Friday im in love") contador = contador +1 data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: ")) #else: # print("ARTISTA NO ENCONTRADO") if data == 2: print("\n***Eligio buscar por cancion***\n") music = input("\nIngrese el nombre de la cancion para ver su informacion:\n") if music == 'in the army now': print("Artista: Status Quo\n", "Album: In the Army Now\n", "Fecha de lanzamineto: 1986") if music == 'army': print("Cacion relacionada") print("Artista: Status Quo\n", "Album: In the Army Now\n", "Fecha de lanzamineto: 1986") if music == 'lovesong': print("Artist: The Cure\n", "Album: Japanese Whispers\n", "Year: 1989") if music== 'friday im in love' and 'friday': print("Artist: The Cure\n", "Album: Wish\n", "Year: 1992") if music == 'love me do' and 'love': print("Artist: The Beatles\n", "Album: Please Please Me\n" "Year: 1963") if music == 'let it be': print("Artist: The Beatles\n" "Format: MP3\n" "Album: Parachutes\n", "Year: 1970") if music == 'yellow': print("Artist: Coldplay\n" "Title: Yellow\n" "Album: Parachutes\n" "Year: 2000") if music == 'way down we go': print("Artist: KALEO\n", "Album: A/B\n", "Year: 2017") if music == 'lost on you': print("Artist: LP\n", "Album: Lost On You\n", "Year: 2016") contador = contador + 1 data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: ")) #else: # print("\nCANCION NO ENCONTRADA\n") if data == 3: print("***Eligio buscar por album***") albu = input("\nIngrese el nombre del album\n") if albu == 'ab': print("Artist: KALEO\n", "Year: 2017") if albu == 'lost on you': print("Artist: LP\n", "Year: 2016") if albu == 'in the army now': print("Artist; Status Quo\n", "Year: 1986") if albu == 'parachutes': print("Artist: Coldplay\n", "Year: 2000") if albu == 'the singles': print("Artist: The Peche Mode\n", "Year: 1990") if albu == 'japanese whisper': print("Artist: The Cure\n", "Year: 1989") if albu == 'wish': print("Artist: The Cure\n", "Year: 1992") if albu == 'please please me': print("Artist: The Beatles\n", "Year: 1970") contador = contador + 1 data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: ")) #else: # print("ALBUM NO ENCONTRADO") if data == 4: print("***ELIGIO BUSCAR POR AÑO") year = int(input("Ingrese un año para buscar informacion\n")) if year == 2017: print("Artist: KALEO\n", "Title: Way Down We Go\n", "Album: A/B") if year == 2016: print("Artist: LP\n", "Title: Lost On You\n", "Album: Lost On You") if year == 1986: print("Artist: Status Quo\n", "Title: In The Army Now\n", "Album: In The Army Now") if year == 2000: print("Artist: Coldplay\n", "Title: Yellow\n", "Format: MP3\n","Album: Parachutes") if year == 1990: print("Artist: Depeche Mode\n", "Title: Emjoy the Silence\n", "Album: The Singles") if year == 1989: print("Artist: The Cure\n" "Title: LoveSong\n","Album: Japanese Whispers") if year == 1992: print("Artist: The Cure\n", "Title: Friday Im In Love\n","Album: Wish") if year == 1963: print("Artist: The Beatles\n", "Title: Love Me Do\n", "Album: Please Please Me") if year == 1970: print("Artist: The Beatles\n", "Title: Let It Be\n", "Album: Parachutes") #else: # print("NO SE ENCONTRO INFORMACION POR AÑO") contador = contador +1 data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: "))
169e431b852089fcda8a72114582cba0f847afbe
whyalwaysmeee/Machine-Learning-Sklearn-Linear-Model
/Linear Model(Least Square Mothod).py
1,274
4.03125
4
import matplotlib.pyplot as plt from sklearn import datasets, linear_model import numpy as np from sklearn.metrics import mean_squared_error, r2_score # Load the diabetes dataset price = datasets.load_boston() # Use only one feature price_x = price.data[:,np.newaxis,5] # Split the data into training/testing sets price_x_train = price_x[:-20] price_x_test = price_x[-20:] # Split the targets into training/testing sets price_y_train = price.target[:-20] price_y_test = price.target[-20:] # Create linear regression object regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(price_x_train, price_y_train) # Make predictions using the testing set price_y_pred = regr.predict(price_x_test) # The coefficients print('Coefficients: \n', regr.coef_) # The mean squared error print("Mean squared error: %.2f" % mean_squared_error(price_y_test, price_y_pred)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % r2_score(price_y_test, price_y_pred)) # Plot outputs plt.scatter(price_x_test, price_y_test, color='black') plt.plot(price_x_test, price_y_pred, color='blue', linewidth=3) plt.xticks(()) plt.yticks(()) #display the plot graph plt.show()
08947ee21f916756c6edf64e0f1d1ad5730b59bd
LiangChen204/pythonApi_Test
/runoob/baseException.py
1,868
3.921875
4
#!//usr/local/bin python # -*- coding:utf-8 -*- # 走try try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!") except IOError: print("Error: 没有找到文件或读取文件失败") else: print("内容写入文件成功") fh.close() # 捕获异常 try: fh = open("testfile", "r") fh.write("这是一个测试文件,用于测试异常!") except IOError: print("Error1: 没有找到文件或读取文件失败") else: print("内容写入文件成功") fh.close() # finally try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!") finally: print("Error2: 没有找到文件或读取文件失败") try: fh = open("testfile", "w") try: fh.write("这是一个测试文件,用于测试异常!!") finally: print("关闭文件") fh.close() except IOError: print("Error3: 没有找到文件或读取文件失败") # 定义函数 def temp_convert(var): try: return int(var) except (ValueError) as Argument: print("参数没有包含数字\n", Argument) # 调用函数 temp_convert('oo') # 定义异常:使用 raise 语句抛出一个指定的异常 class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) try: raise MyError(2*2) except MyError as e: print("My exception occurred, value:", e.value) # raise MyError('oops!!') # 稍复杂的抛出异常例子 def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") except TypeError: print("division unsupported!") else: print("result is", result) finally: print("executing finally clause") divide(2, 1) divide(2, 0) divide("2", "1")
5f285c43fbeb0489a57c0c703201abfb2df3a575
andfanilo/streamlit-sandbox
/archives/app_styling.py
567
3.734375
4
import pandas as pd import streamlit as st # https://stackoverflow.com/questions/43596579/how-to-use-python-pandas-stylers-for-coloring-an-entire-row-based-on-a-given-col df = pd.read_csv("data/titanic.csv") def highlight_survived(s): return ['background-color: green']*len(s) if s.Survived else ['background-color: red']*len(s) def color_survived(val): color = 'green' if val else 'red' return f'background-color: {color}' st.dataframe(df.style.apply(highlight_survived, axis=1)) st.dataframe(df.style.applymap(color_survived, subset=['Survived']))
00eb68cef452b9026f89936170f6c21e7ef09e2c
TeenaThmz/List
/list2.py
64
3.5
4
list2=[12,14,-95,3] list=[i for i in list2 if i>=0] print(list)
18785e22dbae3eed4affb39e74eaf9aaffadf949
kooose38/pytools_table
/xai/eli5.py
1,384
3.578125
4
from typing import Any, Dict, Union, Tuple import eli5 from eli5.sklearn import PermutationImportance import numpy as np import pandas as pd class VizPermitaionImportance: def __doc__(self): """ package: eli5 (pip install eli5) support: sckit-learn xgboost lightboost catboost lighting purpose: Visualize the importance of each feature quantity by giving a big picture explanation using a model """ def __init__(self): pass def show_weights(self, model: Any, importance_type: str="gain"): return eli5.show_weights(model, importance_type=importance_type) def show_feature_importance(self, model: Any, x_train: pd.DataFrame, y_train: Union[pd.DataFrame, pd.Series, np.ndarray], x_val: pd.DataFrame, y_val: Union[pd.DataFrame, pd.Series]) -> Tuple[object, object]: ''' warnings: support sklearn model only! By trying both the training data and the validation data, you can lyric whether there is a difference in the distribution of the data. x_train, y_train -> x_val, y_val ''' perm_train = PermutationImportance(model).fit(x_train, y_train) fig1 = eli5.show_weights(perm_train, feature_names=x_train.columns.tolist()) perm_val = PermutationImportance(model).fit(x_val, y_val) fig2 = eli5.show_weights(perm_val, feature_names=x_val.columns.tolist()) return fig1, fig2
c6ea76ace41ca74098a6562ee75c1e6216cb6fe2
plukis/merge_sort
/controllers/merge_sort.py
1,177
3.84375
4
# -*- coding: utf-8 -*- class MergeSort: a_list = [] def _merge_work(self, alist): print("delimito ", alist) if len(alist) > 1: mid = len(alist) // 2 lefthalf = alist[:mid] righthalf = alist[mid:] self._merge_work(lefthalf) self._merge_work(righthalf) i = 0 j = 0 k = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: alist[k] = lefthalf[i] i = i + 1 else: alist[k] = righthalf[j] j = j + 1 k = k + 1 while i < len(lefthalf): alist[k] = lefthalf[i] i = i + 1 k = k + 1 while j < len(righthalf): alist[k] = righthalf[j] j = j + 1 k = k + 1 print("Mezclando ", alist) return (alist) def run_merge(self): list_new = self._merge_work(self.a_list) return list_new def __init__(self, a_list): self.a_list = a_list
42a76e11702d791ddbff3b132710144b3d684323
qqinxl2015/leetcode
/112. Path Sum.py
1,036
3.859375
4
#https://leetcode.com/problems/path-sum/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if not root: return False queue = {} queue[root] = root.val while not len(queue) == 0: queueOneLevel = {} for q, v in queue.items(): if q.left == None and q.right == None: if v == sum: return True if not q.left == None: queueOneLevel[q.left] = v + q.left.val if not q.right == None: queueOneLevel[q.right] = v + q.right.val queue = queueOneLevel return False
91ac4bcae6d6e1ba52e2145bdc158800e31d5d6e
qqinxl2015/leetcode
/009. Palindrome Number.py
470
3.796875
4
#https://leetcode.com/problems/palindrome-number/ class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x ==0: return True if x < 0: return False if int(x%10) == 0 and x !=0: return False ret = 0 while x > ret: ret = ret*10 + int(x%10) x = int(x/10) return x == ret or x== int(ret/10)
0e5abd4e1435664f4b626bc96a4d57fd2b5f2374
susanpinch/Read-and-Process-Data-Python
/pinchiaroli_susan_assign9_fileioio.py
1,952
3.96875
4
""" file_io_nested.py Write data from a set of nested lists to a file, then read it back in. By: Susan Pinchiaroli Date: 28 Nov 2018 """ data = []#empty list # This is our data data.append(['Susan','Davis',23,7])#append data data.append(['Harold','Humperdink',76,9]) data.append(['Lysistrata','Jones',40,12]) data.append(['Stan','Laurel',60]) data.append(['Rose','Harris',56,9,'Ambassador']) # filename is a string fname = "people.txt"#create file name ffirstobj=open(fname,'w')#open file name to write, so that once we complete the file it will be rewritten each time we code ffirstobj.write('')#write nothing ffirstobj.close()3close file # open file for actual writing fobj = open(fname, "w") line_text='' # write the data file # iterate through the list of people for i in range(len(data)): line = "" # iterate through each datum for the person for j in range(len(data[i])): # convert this datum to a string and append it to our line # NOTE: change this so it doesn't add ',' if this is last datum if j==(len(data[i])-1):#this separates so we know when to add comma and when not to line += str(data[i][j]) else: line += str(data[i][j]) + "," # NOTE: now, write this line to the data file line_text += line +'\n'#write linebreak after each line fobj.write(line_text)#write line_text into code # Don't forget to close the file! fobj.close() print("Done writing the file.") # Now, read the data back # Open the file for reading fobj = open("people.txt","r") # read the whole file into a string raw_dat = fobj.read() print("Read:",raw_dat) # break the string into a list of lines data_list = raw_dat.split("\n") # NOW: process your list of lines, so that you can put the # data back into a new list of lists, called data2 # this should have the exact same format as your original data structure data2 = [] # process data here print("Final data list:") print(data2)
0211584a0d5087701ee07b79328d4eb6c101e962
pintugorai/python_programming
/Basic/type_conversion.py
438
4.1875
4
''' Type Conversion: int(x [,base]) Converts x to an integer. base specifies the base if x is a string. str(x) Converts object x to a string representation. eval(str) Evaluates a string and returns an object. tuple(s) Converts s to a tuple. list(s) Converts s to a list. set(s) Converts s to a set. dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples. and So on ''' x="5" xint = int(x); print("xint = ",xint)
ac7016757e19991066147e75b923b1ef734beb6d
zags4life/tableformatters
/tableformatters/tabledataprovider.py
776
3.75
4
# table_formatters/data_provider.py from abc import ABC, abstractproperty class TableFormatterDataProvider(ABC): '''An ABC that defines the interface for objects to display by a table formatter. Any object displayed by a TableFormatters must implement this ABC. Classes that implement this ABC can using this interface to define what data contained in its class to display ''' @abstractproperty def header_values(self): '''Must return a list of strings, containing the table header values. Note: order of this list is the order that headers will appear''' pass @abstractproperty def row_values(self): '''Must return a list of data to be output by a table formatter.''' pass
22c30808220f095b21eca67c444dc2b46b4026b0
gmayock/kaggle_titanic_competition
/gs-titanic-7-final-submission-code.py
11,102
3.515625
4
# # Load data # Ignore warnings to clean up output after all the code was written import warnings warnings.filterwarnings("ignore") import numpy as np import pandas as pd import os print(os.listdir("../input")) ['train.csv', 'gender_submission.csv', 'test.csv'] # Step 1 is to import both data sets training_data = pd.read_csv("../input/train.csv") testing_data = pd.read_csv("../input/test.csv") # Step two is to create columns which I will add to the respective datasets, in order to know which row came from which dataset when I combine the datasets training_column = pd.Series([1] * len(training_data)) testing_column = pd.Series([0] * len(testing_data)) # Now we append them by creating new columns in the original data. We use the same column name training_data['is_training_data'] = training_column testing_data['is_training_data'] = testing_column # # Combine and process # Now we can merge the datasets while retaining the key to split them later combined_data = training_data.append(testing_data, ignore_index=True, sort=False) # Encode gender (if == female, True) combined_data['female'] = combined_data.Sex == 'female' # Split out Title title = [] for i in combined_data['Name']: period = i.find(".") comma = i.find(",") title_value = i[comma+2:period] title.append(title_value) combined_data['title'] = title # Replace the title values with an aliased dictionary title_arr = pd.Series(title) title_dict = { 'Mr' : 'Mr', 'Mrs' : 'Mrs', 'Miss' : 'Miss', 'Master' : 'Master', 'Don' : 'Formal', 'Dona' : 'Formal', 'Rev' : 'Religious', 'Dr' : 'Academic', 'Mme' : 'Mrs', 'Ms' : 'Miss', 'Major' : 'Formal', 'Lady' : 'Formal', 'Sir' : 'Formal', 'Mlle' : 'Miss', 'Col' : 'Formal', 'Capt' : 'Formal', 'the Countess' : 'Formal', 'Jonkheer' : 'Formal', } cleaned_title = title_arr.map(title_dict) combined_data['cleaned_title'] = cleaned_title # Fill NaN of Age - first create groups to find better medians than just the overall median and fill NaN with the grouped medians grouped = combined_data.groupby(['female','Pclass', 'cleaned_title']) combined_data['Age'] = grouped.Age.apply(lambda x: x.fillna(x.median())) #add an age bin age_bin_conditions = [ combined_data['Age'] == 0, (combined_data['Age'] > 0) & (combined_data['Age'] <= 16), (combined_data['Age'] > 16) & (combined_data['Age'] <= 32), (combined_data['Age'] > 32) & (combined_data['Age'] <= 48), (combined_data['Age'] > 48) & (combined_data['Age'] <= 64), combined_data['Age'] > 64 ] age_bin_outputs = [0, 1, 2, 3, 4, 5] combined_data['age_bin'] = np.select(age_bin_conditions, age_bin_outputs, 'Other').astype(int) # Fill NaN of Embarked combined_data['Embarked'] = combined_data['Embarked'].fillna("S") # Fill NaN of Fare, adding flag for boarded free, binning other fares combined_data['Fare'] = combined_data['Fare'].fillna(combined_data['Fare'].mode()[0]) combined_data['boarded_free'] = combined_data['Fare'] == 0 fare_bin_conditions = [ combined_data['Fare'] == 0, (combined_data['Fare'] > 0) & (combined_data['Fare'] <= 7.9), (combined_data['Fare'] > 7.9) & (combined_data['Fare'] <= 14.4), (combined_data['Fare'] > 14.4) & (combined_data['Fare'] <= 31), combined_data['Fare'] > 31 ] fare_bin_outputs = [0, 1, 2, 3, 4] combined_data['fare_bin'] = np.select(fare_bin_conditions, fare_bin_outputs, 'Other').astype(int) # Fill NaN of Cabin with a U for unknown. Not sure cabin will help. combined_data['Cabin'] = combined_data['Cabin'].fillna("U") # Counting how many people are riding on a ticket from collections import Counter tickets_count = pd.DataFrame([Counter(combined_data['Ticket']).keys(), Counter(combined_data['Ticket']).values()]).T tickets_count.rename(columns={0:'Ticket', 1:'ticket_riders'}, inplace=True) tickets_count['ticket_riders'] = tickets_count['ticket_riders'].astype(int) combined_data = combined_data.merge(tickets_count, on='Ticket') # Finding survival rate for people sharing a ticket # Note that looking at the mean automatically drops NaNs, so we don't have an issue with using the combined data to calculate survival rate as opposed to just the training data combined_data['ticket_rider_survival'] = combined_data['Survived'].mean() # # Finding survival rate for people sharing a ticket (cont'd) # This groups the data by ticket # And then if the ticket group is greater than length 1 (aka more than 1 person rode on the ticket) # it looks at the max and min of the _other_ rows in the group (by taking the max/min after dropping the current row) # and if the max is 1, it replaces the default survival rate of .3838383 (the mean) with 1. This represents there being # at least one known member of the ticket group which survived. If there is no known survivor on that ticket, but there # is a known fatality, the value is replaced with 0, representing there was at least one known death in that group. If # neither, then the value remains the mean. for ticket_group, ticket_group_df in combined_data[['Survived', 'Ticket', 'PassengerId']].groupby(['Ticket']): if (len(ticket_group_df) != 1): for index, row in ticket_group_df.iterrows(): smax = ticket_group_df.drop(index)['Survived'].max() smin = ticket_group_df.drop(index)['Survived'].min() if (smax == 1.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'ticket_rider_survival'] = 1 elif (smin==0.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'ticket_rider_survival'] = 0 # Finding survival rate for people with a shared last name (same method as above basically) combined_data['last_name'] = combined_data['Name'].apply(lambda x: str.split(x, ",")[0]) combined_data['last_name_group_survival'] = combined_data['Survived'].mean() for last_name_group, last_name_group_df in combined_data[['Survived', 'last_name', 'PassengerId']].groupby(['last_name']): if (len(last_name_group_df) != 1): for index, row in last_name_group_df.iterrows(): smax = last_name_group_df.drop(index)['Survived'].max() smin = last_name_group_df.drop(index)['Survived'].min() if (smax == 1.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'last_name_group_survival'] = 1 elif (smin==0.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'last_name_group_survival'] = 0 # Finding survival rate for people with a shared last name _and_ fare combined_data['last_name_fare_group_survival'] = combined_data['Survived'].mean() for last_name_fare_group, last_name_fare_group_df in combined_data[['Survived', 'last_name', 'Fare', 'PassengerId']].groupby(['last_name', 'Fare']): if (len(last_name_fare_group_df) != 1): for index, row in last_name_fare_group_df.iterrows(): smax = last_name_fare_group_df.drop(index)['Survived'].max() smin = last_name_fare_group_df.drop(index)['Survived'].min() if (smax == 1.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'last_name_fare_group_survival'] = 1 elif (smin==0.0): combined_data.loc[combined_data['PassengerId'] == row['PassengerId'], 'last_name_fare_group_survival'] = 0 # Finding cabin group cabin_group = [] for i in combined_data['Cabin']: cabin_group.append(i[0]) combined_data['cabin_group'] = cabin_group # Adding a family_size feature as it may have an inverse relationship to either of its parts combined_data['family_size'] = combined_data.Parch + combined_data.SibSp + 1 # Mapping ports to passenger pickup order port = { 'S' : 1, 'C' : 2, 'Q' : 3 } combined_data['pickup_order'] = combined_data['Embarked'].map(port) # Encode childhood combined_data['child'] = combined_data.Age < 16 # One-Hot Encoding the titles combined_data = pd.concat([combined_data, pd.get_dummies(combined_data['cleaned_title'], prefix="C_T")], axis = 1) # One-Hot Encoding the Pclass combined_data = pd.concat([combined_data, pd.get_dummies(combined_data['Pclass'], prefix="PClass")], axis = 1) # One-Hot Encoding the cabin group combined_data = pd.concat([combined_data, pd.get_dummies(combined_data['cabin_group'], prefix="C_G")], axis = 1) # One-Hot Encoding the ports combined_data = pd.concat([combined_data, pd.get_dummies(combined_data['Embarked'], prefix="Embarked")], axis = 1) # # Import Classifier (only KNN in the end, see previous notebooks for exploration) new_train_data=combined_data.loc[combined_data['is_training_data']==1] new_test_data=combined_data.loc[combined_data['is_training_data']==0] from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score k_fold = KFold(n_splits = 10, shuffle=True, random_state=0) from sklearn.model_selection import cross_val_predict from sklearn.metrics import confusion_matrix # # Define features # Here are the features features = ['Pclass', 'Age', 'SibSp', 'Parch', 'Fare', 'female', 'child', 'C_T_Master', 'C_T_Miss', 'C_T_Mr', 'C_T_Mrs', 'C_T_Formal','C_T_Academic', 'C_T_Religious','C_G_A', 'C_G_B', 'C_G_C', 'C_G_D', 'C_G_E', 'C_G_F', 'C_G_G', 'C_G_T', 'C_G_U', 'family_size', 'ticket_riders', 'ticket_rider_survival', 'last_name_group_survival', 'last_name_fare_group_survival'] target = 'Survived' cvs_train_data = new_train_data[features] cvs_test_data = new_test_data[features] cvs_target = new_train_data['Survived'] # # Scale them from sklearn.preprocessing import MinMaxScaler mm_scaler = MinMaxScaler() mms_train_data = mm_scaler.fit_transform(cvs_train_data) mms_test_data = mm_scaler.transform(cvs_test_data) mms_target = new_train_data['Survived'] mms_train_data.shape, mms_test_data.shape, mms_target.shape # # GridSearchCV for KNN from sklearn.model_selection import GridSearchCV # on all features n_neighbors = [14, 16, 17, 18, 19, 20, 22] algorithm = ['auto'] weights = ['uniform', 'distance'] leaf_size = list(range(10,30,1)) hyperparams = {'algorithm': algorithm, 'weights': weights, 'leaf_size': leaf_size, 'n_neighbors': n_neighbors} gd=GridSearchCV(estimator = KNeighborsClassifier(), param_grid = hyperparams, verbose=True, cv=k_fold, scoring = "accuracy") gd.fit(mms_train_data, mms_target) print(gd.best_score_) print(gd.best_estimator_) gd.best_estimator_.fit(mms_train_data, mms_target) prediction = gd.best_estimator_.predict(mms_test_data) submission = pd.DataFrame({ "PassengerId" : new_test_data['PassengerId'], "Survived" : prediction.astype(int) }) submission_name = 'knn_all_feat.csv' submission.to_csv(submission_name, index=False)
f172ed025705f196ebe0c394595dee382a415ccf
jaaaaaaaaack/zalgo
/zalgo.py
1,428
3.96875
4
# zalgo.py # Jack Beal, June 2020 # A small module to give any text a flavor of ancient doom from random import random def validCharacter(char, stoplist): """ Helps to prevent unwanted manipulation of certain characters.""" if char in stoplist: return False else: return True def uniformMangle(s, additives, n=1, p=1, stoplist=[]): """ Convenience function for uniformly mangling longer strings.""" mangled = "" for c in s: mangled += mangle(c, additives, n, p, stoplist) return mangled def mangle(char, additives, n=1, p=1, stoplist=[]): """ Accumulate additive characters from the list of possible additives, up to a maximum n and with average density p, and join them to the input character.""" mangled = "" if validCharacter(char, stoplist): joiners = "" for i in range(int(n)): if random() <= p: joiners += additives[int(random()*len(additives))] mangled += char+joiners return mangled else: return char def main(): testString = "ZALGO.py" additives = ["\u0300","\u0301","\u0302","\u0315","\u031b","\u0327","\u0316","\u0317","\u0318"] stoplist = ["."] greeting = uniformMangle(testString, additives, n=3, p=1, stoplist=stoplist) print(greeting, "- a salt shaker for your text, filled with anxiety and foreboding!") if __name__ == "__main__": main()
cf37344075ac3ebcd091fcfe24de0444742a01be
elliotgreenlee/advent-of-code-2019
/day10/day10_puzzle1.py
2,365
3.734375
4
import math def read_puzzle_file(filename): with open(filename, 'r') as f: points = set() for y, line in enumerate(f): for x, point in enumerate(line): if point is '#': points.add((x, y)) return points def number_slopes(starting_point, other_points): slopes = set() for point in other_points: try: slope = str((point[1] - starting_point[1]) / (point[0] - starting_point[0])) except ZeroDivisionError: slope = str(math.inf) if point[0] > starting_point[0]: slope = 'right' + slope elif point[0] < starting_point[0]: slope = 'left' + slope if point[1] > starting_point[1]: slope = 'above' + slope elif point[1] < starting_point[1]: slope = 'below' + slope slopes.add(slope) if len(slopes) == 278: print(starting_point) return len(slopes) def find_best_station(asteroids): # whichever starting point has the maximum number of slopes is the best all_slope_counts = [] for station_asteroid in asteroids: working_copy_asteroids = asteroids.copy() working_copy_asteroids.remove(station_asteroid) all_slope_counts.append(number_slopes(station_asteroid, working_copy_asteroids)) return max(all_slope_counts) def solve_day10puzzle1(): asteroids = read_puzzle_file("day10_data.txt") return find_best_station(asteroids) def tests_day10puzzle1(): asteroids = read_puzzle_file("day10_test1.txt") if find_best_station(asteroids) != 8: return False asteroids = read_puzzle_file("day10_test2.txt") if find_best_station(asteroids) != 33: return False asteroids = read_puzzle_file("day10_test3.txt") if find_best_station(asteroids) != 35: return False asteroids = read_puzzle_file("day10_test4.txt") if find_best_station(asteroids) != 41: return False asteroids = read_puzzle_file("day10_test5.txt") if find_best_station(asteroids) != 210: return False return True def main(): if tests_day10puzzle1(): print("Day 10 Puzzle 1 answer: ", solve_day10puzzle1()) if __name__ == "__main__": main()
5976699fa85e8eb7237467f8732bdca6df5d350d
jasoncwells/Test_2
/scraper.py
230
3.578125
4
myvar = 'What is happening today' myage = 46 mylist = ['how','now','brown','cow'] mynumlist = [1,2,3,4,5] print myvar print myage print mylist listlength = len(mylist) print listlength stringlength = len(myvar) print stringlength
dd793f5d7f0d88d1a6446c8ce2025904144c2136
cybera/data-science-for-entrepreneurs-workshops
/helpers/color.py
820
3.640625
4
def hex2rgb(color): return tuple(int(color.lstrip('#')[i:i+2], 16) for i in (0, 2 ,4)) # Decimal number to HEX str def dec2hex(n): n = int(n) if (n > 16): return str(hex(n).split('x')[-1]) else: return "0" + str(hex(n).split('x')[-1]) # Gradient starting at color "start" to color "stop" with "steps" colors # Not include start and stop colors to result def gradient(start, stop, steps): out = [] r = hex2rgb(start)[0] g = hex2rgb(start)[1] b = hex2rgb(start)[2] r_step = (hex2rgb(stop)[0] - r) / steps g_step = (hex2rgb(stop)[1] - g) / steps b_step = (hex2rgb(stop)[2] - b) / steps for i in range(steps): r = r + r_step g = g + g_step b = b + b_step out.append("#" + dec2hex(r) + dec2hex(g) + dec2hex(b)) return out
ca8162f61acd25fc40f57615225c78c2d1ad0623
sambapython/batch53
/modules/file1.py
199
3.546875
4
print("name:",__name__) a=100 b=200 c=a+b d=a-b def fun(): print("this is fun in file1") if __name__=="__main__": def fun1(): print("this is fun1") print("this is file1") fun() print(a,b,c,d)
38da743b5276b4924cc7e40aa237daef479aaed8
sambapython/batch53
/app.py
89
3.515625
4
a=raw_input("Enter a value:") b=raw_input("Enter b value:") a=int(a) b=int(b) print (a+b)
b483de5c6c42f4c9234be3dacd50c8828437b260
aishraj/slow-learner
/python/pythonchallenge/001.py
614
3.53125
4
import string import collections def decrypt(cyphertext): values = '' keys = '' for i in range(ord('a'),ord('z')+1): keys += chr(i) j = i - ord('a') values += chr(ord('a') + (j + 2) % 26) transtable = string.maketrans(keys,values) return string.translate(cyphertext,transtable) if __name__ == "__main__": mycyphertext = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr\'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." print decrypt(mycyphertext)
cdb57be6cb1e664d937ecc44efcd00095bdb7407
azbrainiac/PyStudy
/third.py
702
3.953125
4
for item in [1, 3, 7, 4, "qwerty", [1, 2, 4, 6]]: print(item) for item in range(5): print(item ** 2) wordlist = ["hello", "ass", "new", "year"] letterlist = [] for aword in wordlist: for aletter in aword: if aletter not in letterlist: letterlist.append(aletter) print(letterlist) sqlist = [] for x in range(4, 20): sqlist.append(x**2) print(sqlist) sqlist = [x**2 for x in range(1, 9)] print(sqlist) sqlist = [x**2 for x in range(1, 10) if x % 3 == 0] print(sqlist) letterlist = [ch.upper() for ch in "asshole" if ch not in "eloh"] print(letterlist) print(list(set([ch for ch in "".join(wordlist)]))) print(list(set(s[i] for s in wordlist for i in range(len(s))))) #input("Press Enter")
ad94bc21b8b6a213a11e455e666325fdcf95d890
patpalmerston/Algorithms-1
/making_change/making_change.py
2,323
4.0625
4
#!/usr/bin/python import sys def making_change(amount, denominations=[1, 5, 10, 25, 50]): # base case if amount <= 2: return 1 # starting a cache equal to the size of the amount, plus an initial default of 1 for index of zero cache = [1] + [0] * amount # loop through the coins in our list for coin in denominations: # loop through the range of the outer loop coin and our amount + 1 # first outer loop iteration starts at index of 1, then 5, then 10, then 25, then 50, as our index starts in the range dictated by the value of our denominations outer loop. for i in range(coin, amount + 1): # print('coin:', coin, f'amount: {amount} + 1 = ', amount +1) # print("i: ", i, "i - coin = ", i-coin) # inner loop index starts from the index equal to the value of coin and will iterate however many times that that index can be subtracted from 'amount + 1'. Our Cache indexes will be given a value every time the current index(1-11) minus the coin value from the denominations list, is less than our original amount of '10'. Each iteration of the outer loop will start our inner loop at the index equal to the value of the the outer loop coin. cache[i] += cache[i - coin] # default value of cache[0] = 1 # then we cycle through cache[1]-cache[11] subtracting the coin value of "1 cent", from the current loop index # giving each loop that is able complete this task a value of 1 in the cache index # when we hit cache[11] and minus the coin of '1', we return the value of amount and restart the loop # print(cache, cache[amount]) # print('cache amount', cache[amount]) # this counts how many times the loop was able to generate the value of amount return cache[amount] if __name__ == "__main__": # Test our your implementation from the command line # with `python making_change.py [amount]` with different amounts if len(sys.argv) > 1: denominations = [1, 5, 10, 25, 50] amount = int(sys.argv[1]) print("There are {ways} ways to make {amount} cents.".format( ways=making_change(amount, denominations), amount=amount)) else: print("Usage: making_change.py [amount]")
5f89f65fa211fff9288edd96e534a90baaca6919
hklgit/PythonStudy
/pythonCodes/com/coocaa/study/类/Student.py
885
3.9375
4
class Student(object): # 把一些我们认为必须绑定的属性强制填写进去。 # 通过定义一个特殊的__init__方法,在创建实例的时候,就把name,score等属性绑上去: # 特殊方法“__init__”前后分别有两个下划线!!! # 注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。 # 这个跟构造器很类似 def __init__(self, name, age): self.name = name self.age = age # Student的一个对象 # stu = Student() # 注意: 我竟然犯了一个错误,__int__ 然后就是报错: # TypeError: object() takes no parameters stu = Student('kerven',20) print(stu.age) # print(stu) # <__main__.Student object at 0x00000000026A8128>
becc6a966f455b1d32d7633c9f7cfb53e110b033
kelvinng2017/chat1
/test2.py
225
3.890625
4
while True: print("請輸入密碼:", end='') password = input() if int(password) == 1234567: print("歡迎光臨!敬請指教") break else: print("密碼錯誤!請在重新輸入")
c538c8864abefaab9f3e97af43283c2bc0efc63f
randeeppr/fun
/desired_days.py
1,188
4.0625
4
#!/usr/bin/python # # This program prints the desired day(s) in between start date and end date # import datetime,sys,getopts def getDesiredDay(start_date,end_date,desired_day): v1 = value_of_start_day = weekdays[start_date.strftime("%a")] v2 = value_of_desired_day = weekdays[desired_day] #print(v1) #print(v2) if v1 == v2: return start_date else: start_date = start_date + datetime.timedelta(days=(abs(v2-v1))) return start_date weekdays = { "Mon" : 1, "Tue" : 2, "Wed" : 3, "Thu" : 4, "Fri" : 5, "Sat" : 6, "Sun" : 7 } start_date = datetime.datetime(2019, 04, 8, 00, 00) end_date = datetime.datetime(2019, 04, 30, 00, 00) desired_day = sys.argv[1] #print(start_date.strftime("%Y-%m-%d")) #print(start_date.strftime("%a")) start_date = getDesiredDay(start_date,end_date,desired_day) print("Next {0} is {1}".format(desired_day,start_date.strftime("%Y-%m-%d"))) while start_date <= end_date: print(start_date.strftime("%Y-%m-%d")) start_date= start_date + datetime.timedelta(days=7) sys.exit(0) #output example ''' [root@4a178e708f64 fun]# ./desired_days.py Thu Next Thu is 2019-04-11 2019-04-11 2019-04-18 2019-04-25 ''' [root@4a178e708f64 fun]#
0d261b64fc0fee1629ebb3e24483ea4ecd89ad07
Jav10/Matplotlib-Plotting
/UNO/backToBackBarCharts.py
488
3.59375
4
#Matplotlib Plotting #Autor: Javier Arturo Hernández Sosa #Fecha: 30/Sep/2017 #Descripcion: Ejecicios Matplotlib Plotting - Alexandre Devert - (18) #Gráficas de barras espalda con espalda import numpy as np import matplotlib.pyplot as plt women_pop=np.array([5., 30., 45., 22.]) men_pop=np.array([5., 25., 50., 20.]) X=np.arange(4) plt.barh(X, women_pop, color='r') #Hacemos negativos los valores de la población de hombres para que #se vea el efecto plt.barh(X, -men_pop, color='b') plt.show()
1e618d71d615ae0f419c6d78f9684f028d8f4aa6
jip174/cs362--Software-Eng-2
/week4/test/teststring_testme.py
480
3.765625
4
import testme from unittest import TestCase import string class teststring(TestCase): def test_input_string(self): ts = testme.inputString() count = 0 for x in ts: if x.isalpha() == True or x == '\0': count += 1 print(x) else: print("Invalid input") break self.assertEqual(count, 6) #self.assertTrue(ts.isalpha() == True)
b74c84a5554423d4fcb488945748ebbe64bdd716
jip174/cs362--Software-Eng-2
/week4/test/tester_testme.py
864
3.8125
4
import testme from unittest import TestCase import string class testchar(TestCase): def test_input_char(self): tc = testme.inputChar() letters = string.ascii_letters if (tc.isalpha() == True): #print(tc) self.assertTrue(tc.isalpha() == True) else: temp = " " for temp in tc: if tc in string.punctuation: temp = tc self.assertEqual(tc, temp) class teststring(TestCase): def test_input_string(self): ts = testme.inputString() count = 0 for x in ts: if x.isalpha() == True or x == '\0': count += 1 print(x) else: print("Invalid input") break self.assertEqual(count, 6)
4891587a4606af3b4d6e284ac033185117abbf14
peluche/mooc_algo2
/graphs/dfs_topological_search.py
1,058
3.875
4
#!/usr/bin/env python3 explored = {} current_label = 0 def is_explored(vertex): return explored.get(vertex) != None def explore(vertex): explored[vertex] = True def tag(vertex): global current_label explored[vertex] = current_label current_label -= 1 def dfs(graph, vertex): explore(vertex) for node in graph[vertex]: if not is_explored(node): dfs(graph, node) tag(vertex) def dfs_loop(graph): """ generate a topological order of the directed graph /!\ graph must be directed, graph shouldn't have any cycle """ for vertex, _ in graph.items(): if not is_explored(vertex): dfs(graph, vertex) def main(): """ A--->B--->D `-->C--´ E--´ """ graph = { 'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': [], 'E': ['C'], } global current_label global explored explored = {} current_label = len(graph) dfs_loop(graph) print(explored) if __name__ == '__main__': main()
d902702bc0e0c3168d745fdf7dfda52fbff1c3d0
Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1
/Programas da 3a week/Tarefa de programação/Exercícios 2 - FizzBuzz parcial, parte 1.py
100
4.1875
4
num = int(input("Digite um número inteiro: ")) if num % 3 == 0: print ("Fizz") else: print (num)
29781302370b185924aca0e0384ab49f4af4764c
Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1
/Programas da 7a week/Tarefa de programação Lista de exercícios - 6/Exercício 2 - Retângulos 2.py
456
4
4
larg = int(input("Digite o número da largura do retângulo: ")) alt = int(input("Digite o número da altura do retângulo: ")) x=larg y=alt cont=larg while y > 0: while x > 0 and x <= larg: if y==1 or y==alt: print ("#", end="") else: if x==1 or x==cont: print ("#", end="") else: print(" ", end="") x = x - 1 print () y = y - 1 x = larg
1d326577cedbfe93c61026649efd049a720ded66
Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1
/Programas da 3a week/Praticar tarefa de programação Exercícios adicionais (opcionais)/Exercício 1 - Distância entre dois pontos.py
277
3.828125
4
import math x1 = int(input("Digite o primeiro x: ")) y1 = int(input("Digite o primeiro y: ")) x2 = int(input("Digite o segundo x: ")) y2 = int(input("Digite o segundo y: ")) dis = math.sqrt ((x1 - x2)**2 + (y1 - y2)**2) if dis > 10: print("longe") else: print ("perto")
2c6eb6b2fbcc6a1cd440d3c0fff85fdb58e0d72f
maimoonmaimu/codeketa
/set1-5.py
104
3.546875
4
m,a,i=input().split() if(m>a): if(m>i): print(m) elif(a>i): print(a) else: print(i)
91cbaa9c8b92230b76a14a687875b71358fe260f
lx36301766/AtlanLeetCode
/src/pl/atlantischi/leetcode/medium/Medium486.py
2,964
3.78125
4
""" 给定一个表示分数的非负整数数组。 玩家1从数组任意一端拿取一个分数,随后玩家2继续从剩余数组任意一端拿取分数,然后玩家1拿,……。 每次一个玩家只能拿取一个分数,分数被拿取之后不再可取。直到没有剩余分数可取时游戏结束。最终获得分数总和最多的玩家获胜。 给定一个表示分数的数组,预测玩家1是否会成为赢家。你可以假设每个玩家的玩法都会使他的分数最大化。 示例 1: 输入: [1, 5, 2] 输出: False 解释: 一开始,玩家1可以从1和2中进行选择。 如果他选择2(或者1),那么玩家2可以从1(或者2)和5中进行选择。如果玩家2选择了5,那么玩家1则只剩下1(或者2)可选。 所以,玩家1的最终分数为 1 + 2 = 3,而玩家2为 5。 因此,玩家1永远不会成为赢家,返回 False。 示例 2: 输入: [1, 5, 233, 7] 输出: True 解释: 玩家1一开始选择1。然后玩家2必须从5和7中进行选择。无论玩家2选择了哪个,玩家1都可以选择233。 最终,玩家1(234分)比玩家2(12分)获得更多的分数,所以返回 True,表示玩家1可以成为赢家。 注意: 1 <= 给定的数组长度 <= 20. 数组里所有分数都为非负数且不会大于10000000。 如果最终两个玩家的分数相等,那么玩家1仍为赢家。 """ import numpy as np class Solution: # 递归 def PredictTheWinner(self, nums): """ :type nums: List[int] :rtype: bool """ return self.winnter(nums, 0, len(nums) - 1) >= 0 def winnter(self, nums, start, end): if start == end: return nums[start] else: pick_first = nums[start] - self.winnter(nums, start + 1, end) pick_last = nums[end] - self.winnter(nums, start, end - 1) return max(pick_first, pick_last) # 二阶动态规划 def PredictTheWinner2(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) dp = np.zeros([n, n]) # dp = [[0] * n for i in range(n)] for i in range(0, n - 1)[::-1]: for j in range(i + 1, n): a = nums[i] - dp[i + 1][j] b = nums[j] - dp[i][j - 1] dp[i][j] = max(a, b) # print("%s %s" % (i, j)) print(dp) return dp[0][n - 1] >= 0 # 一阶动态规划 def PredictTheWinner3(self, nums): """ print("%s %s" % (i, j)) :type nums: List[int] :rtype: bool """ def main(): nums = [1, 5, 2, 4, 6] # nums = [2, 4, 3, 4, 55, 1, 2, 3, 1, 2, 4, 3, 4, 5, 1] solution = Solution() ret = solution.PredictTheWinner2(nums) print(ret) if __name__ == '__main__': main() # print(__name__)
0b241bfd9a912c87ef304cb43ace9ffb90cce82c
cyro809/trabalho-tesi
/sentimusic/distance_utils.py
1,284
4
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import math # --------------------------------------------------------------------------- # Função calculate_distance(): Calcula a distancia euclidiana entre dois pontos # - vec1: Vetor 1 # - vec2: Vetor 2 # - num: Número de dimensões espaciais # --------------------------------------------------------------------------- def calculate_distance(p1,p2, num): result = 0 for i in range(0,num): result += (p1[i] - p2[i])**2 return math.sqrt(result) # --------------------------------------------------------------------------- # Função get_minimum_distance_label(): Calcula a menor distancia entre a # musica e os centroides retornando o # grupo a qual ela pertence # - centers: Centroides de cada grupo # - music: Coordenadas da musica no espaço # --------------------------------------------------------------------------- def get_minimum_distance_label(centers, music): min_distance = 1000 label = 0 for i in range(0, len(centers)): distance = calculate_distance(music, centers[i], len(centers[i])) if distance < min_distance: min_distance = distance label = i return label
7faefdd7192a19669f3b7a0e73e08b2b769ed15c
chulhee23/today_ps
/hanbit/dfs_bfs/ice_frame.py
810
3.640625
4
# 얼음 틀 모양 주어졌을 때 # 생성되는 최대 아이스크림 수 # 2차원 배열 # 1은 막힘 -> 방문. # 0은 열림 -> 아직 방문X. # 0 인접한 0들 묶음 갯수를 파악 def dfs(x, y): # 범위 벗어나면 종료 if x <= -1 or x >= n or \ y <= -1 or y >= m: return False # 방문 전 if graph[x][y] == 0: # 방문 처리 graph[x][y] = 1 # 상하좌우 재귀 호출 dfs(x-1, y) dfs(x, y-1) dfs(x+1, y) dfs(x, y+1) return True return False n, m = map(int, input()) graph = [] for i in range(n): graph.append(list(map(int, input().split()))) result = 0 for i in range(n): for j in range(m): if dfs(i, j) == True: result += 1 print(result)
3b05df07dcddc639466ba683231cfeff56ba44d8
chulhee23/today_ps
/data_structure/stack/stack.py
547
3.921875
4
class Stack: def __init__(self): self.top = [] def __len__(self): return len(self.top) def __str__(self): return str(self.top[::1]) def push(self, item): self.top.append(item) def pop(self): if not self.isEmpty(): return self.top.pop(-1) else: print("stack underflow") exit() def isEmpty(self): return len(self.top) == 0 stack = Stack() stack.push(2) stack.push(1) stack.push(3) print(stack) stack.pop() print(stack)
101eea3d60903038cf55472c0ef04b5591e0190e
chulhee23/today_ps
/BOJ/15000-19999/17413.py
1,793
3.515625
4
from collections import deque import sys word = list(sys.stdin.readline().rstrip()) i = 0 start = 0 while i < len(word): if word[i] == "<": # 열린 괄호를 만나면 i += 1 while word[i] != ">": # 닫힌 괄호를 만날 때 까지 i += 1 i += 1 # 닫힌 괄호를 만난 후 인덱스를 하나 증가시킨다 elif word[i].isalnum(): # 숫자나 알파벳을 만나면 start = i while i < len(word) and word[i].isalnum(): i += 1 tmp = word[start:i] # 숫자,알파벳 범위에 있는 것들을 tmp.reverse() # 뒤집는다 word[start:i] = tmp else: # 괄호도 아니고 알파,숫자도 아닌것 = 공백 i += 1 # 그냥 증가시킨다 print("".join(word)) # nums = list(str(i) for i in range(10)) # stacking = False # queueing = False # for c in s: # if c.isalpha() or c in nums: # if queueing: # queue.append(c) # else: # stacking = True # stack.append(c) # elif c == '<': # stacking = False # queueing = True # while stack: # tmp = stack.pop() # ans += tmp # queue.append(c) # elif c == '>': # queueing = False # queue.append(c) # while queue: # ans += queue.popleft() # else: # # 공백 # if stacking: # stacking = False # while stack: # ans += stack.pop() # ans += c # elif queueing: # queue.append(c) # else: # ans += c # if stacking: # while stack: # tmp = stack.pop() # ans += tmp # print(ans)
3597f00172708154780a6e83227a7930e034d166
csu100/LeetCode
/python/leetcoding/LeetCode_225.py
1,792
4.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/31 10:37 # @Author : Zheng guoliang # @Version : 1.0 # @File : {NAME}.py # @Software: PyCharm """ 1.需求功能: https://leetcode-cn.com/problems/implement-stack-using-queues/ 使用队列实现栈的下列操作: push(x) -- 元素 x 入栈 pop() -- 移除栈顶元素 top() -- 获取栈顶元素 empty() -- 返回栈是否为空 2.实现过程: """ from queue import Queue class MyStack: def __init__(self): """ Initialize your data structure here. """ self.stack = Queue() def push(self, x): """ Push element x onto stack. """ if self.stack.empty(): self.stack.put(x) else: temp = Queue() temp.put(x) while not self.stack.empty(): temp.put(self.stack.get()) while not temp.empty(): self.stack.put(temp.get()) def pop(self): """ Removes the element on top of the stack and returns that element. """ if self.stack.empty(): raise AttributeError("stack is empty!") return self.stack.get() def top(self): """ Get the top element. """ if self.stack.empty(): raise AttributeError("stack is empty!") a=self.stack.get() self.push(a) return a def empty(self): """ Returns whether the stack is empty. """ return True if self.stack.empty() else False if __name__ == '__main__': mystack = MyStack() print(mystack.empty()) for i in range(4): mystack.push(i * i) print(mystack.empty()) while not mystack.empty(): print(mystack.pop())
0efc9e2b00e3c6ad7251b21c0dbdda5fe5a748ff
csu100/LeetCode
/python/leetcoding/LeetCode_206.py
994
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/24 14:42 # @Author : Zheng guoliang # @Site : # @File : LeetCode_206.py # @Software: PyCharm """ 1.需求功能: https://leetcode.com/problems/reverse-linked-list/description/ 2.实现过程: """ from leetcoding.ListNode import ListNode class Solution: def reverseList(self, head): if head is None or head.next is None: return head head_node = None while head: node = head.next head.next = head_node head_node = head head = node return head_node def printList(head): while head: print(head.val) head = head.next if __name__ == '__main__': a1 = ListNode(1) a2 = ListNode(2) a3 = ListNode(3) a4 = ListNode(4) a5 = ListNode(5) a1.next = a2 a2.next = a3 a3.next = a4 a4.next = a5 solution = Solution() result = solution.reverseList(a1) printList(result)
0768a12697cd31a72c3d61ecfa4eda9a1aa0751e
csu100/LeetCode
/python/leetcoding/LeetCode_232.py
1,528
4.46875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/31 17:28 # @Author : Zheng guoliang # @Version : 1.0 # @File : {NAME}.py # @Software: PyCharm """ 1.需求功能: https://leetcode-cn.com/problems/implement-queue-using-stacks/submissions/ 使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。 2.实现过程: """ class MyQueue: def __init__(self): """ Initialize your data structure here. """ self._myqueue = [] def push(self, x): """ Push element x to the back of queue. """ if len(self._myqueue) < 1: self._myqueue.append(x) else: temp = self._myqueue[::-1] temp.append(x) self._myqueue = temp[::-1] def pop(self): """ Removes the element from in front of queue and returns that element. """ if len(self._myqueue) < 1: raise AttributeError("queue is empty!") return self._myqueue.pop() def peek(self) -> int: """ Get the front element. """ if len(self._myqueue) < 1: raise AttributeError("queue is empty!") return self._myqueue[-1] def empty(self) -> bool: """ Returns whether the queue is empty. """ return True if len(self._myqueue) < 1 else False
0341229309f1cf0e9add85b69c248e2f13e9f819
ZhouYzzz/TF-CT-ResCNN
/test/test_decorator.py
328
3.734375
4
def print_args(func): def wrapped_func(*args, **kwargs): print(func.__name__, func.__doc__) for a in args: print(a) for k, v in kwargs: print(k, v) return func(*args, **kwargs) return wrapped_func @print_args def add(x: int, y: int): """:Add two integers""" return x + y print(add(1, 2))
71a23a3ac6f35438be6d943dad386d2f33c01c84
DenisoDias/python-password-generator
/password_gen.py
1,181
3.734375
4
from random import choice import argparse import string arg = argparse.ArgumentParser(add_help=True) arg.add_argument('-s', '--size', default=20, nargs="?", type=int, help='Parameter to set size of password you will generate') arg.add_argument('-q', '--quantity', default=10, nargs="?", type=int, help="Parameter to set how much passwords you want to generate each time you run the script") arg.add_argument('-n', '--numbers', nargs="?", const=True, default=False, help='Parameter to set just numbers in the password') arg.add_argument('-l', '--letters', nargs="?", const=True, default=False, help='Parameter to set just letters in the password') arguments = arg.parse_args() def password_generator(args): if args.numbers: password_chars = (list(string.digits)) elif args.letters: password_chars = (list(string.ascii_letters)) else: password_chars = (list(string.digits) * 3) + (list(string.ascii_letters) * 3) + list(string.punctuation) password = "" for char in range(args.size): password += choice(password_chars) return password for passwd_number in range(arguments.quantity): print(password_generator(arguments))
ef0de30520dcecfae1031318a469f4202c02091c
jeanjoubert10/Atwood-machine
/atwood machine1.py
3,357
3.5
4
# Simple atwood machine in python on osX import turtle from math import * import time win = turtle.Screen() win.bgcolor('white') win.setup(500,900) win.tracer(0) win.title("Atwood machine simulation") discA = turtle.Turtle() discA.shape('circle') discA.color('red') discA.shapesize(3,3) discA.up() discA.goto(0,300) pen1 = turtle.Turtle() pen1.ht() pen1.color('black') pen1.up() pen1.goto(-200,380) # Ceiling pen1.down() pen1.pensize(10) pen1.goto(200,380) pen1.up() pen1.goto(-200,-300) #Floor pen1.down() pen1.goto(200,-300) pen1.pensize(1) pen1.up() pen1.goto(0,380) pen1.down() pen1.color('blue') # Rope to pulley pen1.goto(0,300) pen = turtle.Turtle() pen.ht() pen.up() starty = 0 massA = 2 # CHANGE MASS OF BOXES massB = 1 boxA = turtle.Turtle() boxA.shape('square') boxA.color('green') boxA.shapesize(massA,massA) boxA.up() boxA.goto(-100,starty) boxA.down() boxA.goto(100,starty) boxA.goto(-30,starty) boxA.up() boxB = turtle.Turtle() boxB.shape('square') boxB.color('green') boxB.shapesize(massB,massB) boxB.up() boxB.goto(30,starty) top_rope = 300 start_time = time.time() g = -9.8 vA = 0 uA = 0 vB = 0 uB = 0 net_force = massA*g - massB*g # if positive A will drop print("Net force: ",net_force) aA = net_force/(massA+massB) print("a for box A = ",aA) aB = -aA pen2 = turtle.Pen() pen2.ht() pen2.up() Game_over = False count = 0 while not Game_over: t = time.time() - start_time count+=1 vA = aA*t vB = aB*t yA = (uA*t + 1/2*aA*t*t + starty)*5 # start height or s0 yB = (uB*t + 1/2*aB*t*t + starty)*5 boxA.goto(boxA.xcor(),yA) boxB.goto(boxB.xcor(),yB) # Draw rope pen.clear() pen.up() pen.goto(boxA.xcor(),boxA.ycor()) pen.down() pen.goto(boxA.xcor(),top_rope) pen.lt(90) pen.goto(boxB.xcor(),top_rope) pen.goto(boxB.xcor(),boxB.ycor()) #Write Data: if count%40==0: pen2.clear() pen2.goto(0,400) pen2.write("time: {:.2f}s".format(t),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-330) pen2.write("mass A: {}kg\tmass B: {}kg".format(massA,massB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-360) pen2.write("Va: {:.2f}m/s\tVb: {:.2f}m/s".format(vA,vB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-390) pen2.write("Aa: {:.2f}m/s^2\tAb: {:.2f}m/s^2".format(aA,aB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-420) pen2.write("distance: {:.2f}m".format((yA-starty)/5),align='center',font = ('Courier',15, 'normal')) win.update() if boxA.ycor()<=-250 or boxB.ycor()<=-250: print('done') Game_over = True #Final figures: pen2.clear() pen2.goto(0,400) pen2.write("time: {:.2f}s".format(t),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-330) pen2.write("mass A: {}kg\tmass B: {}kg".format(massA,massB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-360) pen2.write("Va: {:.2f}m/s\tVb: {:.2f}m/s".format(vA,vB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-390) pen2.write("Aa: {:.2f}m/s^2\tAb: {:.2f}m/s^2".format(aA,aB),align='center',font = ('Courier',15, 'normal')) pen2.goto(0,-420) pen2.write("distance: {:.2f}m".format((yA-starty)/5),align='center',font = ('Courier',15, 'normal'))
708e40f6392f05d6e0b04e32c600328e052d153e
IracemaLopes/Data_Visualiazation_with_Matplotlib
/annotating_a_plot_of_time_series_data.py
444
3.984375
4
import pandas as pd import matplotlib.pyplot as plt fig, ax = plt.subplots() # Read the data from file using read_csv climate_change = pd.read_csv("climate_change.csv", parse_dates=["date"], index_col=["date"]) # Plot the relative temperature data ax.plot(climate_change.index, climate_change["relative_temp"]) # Annotate the date at which temperatures exceeded 1 degree ax.annotate(">1 degree", xy=[pd.Timestamp('2015-10-06'), 1]) plt.show()
995c55f01fcece72677e88b3518bcce98e8f4522
yassir-23/Algebre-application
/Systemes.py
1,765
3.703125
4
from os import * from Fonctions import * def Systemes(): while True: system('cls') print(" #-----------------------------# Menu #-----------------------------#") print(" 1 ==> Système de n équations et n inconnus.") print(" 0 ==> Quitter.") print(" #------------------------------------------------------------------#") choix = input(" Entrer votre choix : ") if choix == '1': n = int(input(" Entrer le nombre n : ")) print(" Entrer les coefficients : ") A = Matrice(n, n) print(" Entrer les nombres de la partie à droite : ") b = Matrice(n, 1) if n > 0: resultat(Multiplication_Matrice(Matrice_Inv(A, n), b, n, 1, n), n) else: print(" Le système n'est pas un système de Cramer") system('PAUSE') elif choix == '0': break #------------------------------------------------------------------------------# '''def Elimination_gauss(X, n): det = 1 pivot = 0 for i in range(n): if X[i][i] == 0: for j in range(n): if X[j][i] != 0: X[i], X[j] = X[j], X[i] pivot = X[i][i] break if pivot != 0: for ligne in range(i, n): a = X[ligne][i] for j in range(i, n+1): X[ligne][j] -= (a * X[i][j] / pivot) else: break Xn = [] for i in range(n, 0, i-1): for j in range(n-1): if j = 0: x = X[n-1][n] x -= X[i][j] x /= X[i][n-1] X.append(x)'''
3a9a3220f024406f7120421cb00e17427810bb09
devdw98/TIL
/Language/Python/파이썬으로 배우는 알고리즘 트레이딩/lesson05.py
913
3.546875
4
#5-1 def myaverage(a,b): return (a+b)/2 #5-2 def get_max_min(data_list): return (max(data_list), min(data_list)) #5-3 def get_txt_list(path): import os org_list = os.listdir(path) ret_list = [] for x in org_list: if x.endswith("txt"): ret_list.append(x) return ret_list #5-4 def BMI(kg, cm): m = cm * 0.01 result = kg / (m*m) if result < 18.5 : print('마른 체형') elif (18.5 <= result) and (result < 25.0): print('표준') elif (25.0 <= result) and (result < 30.0): print('비만') else: print('고도비만') #5-5 while 1: height = input("Height (cm): ") weight = input("Weight (kg): ") BMI(float(height), float(weight)) #5-6 def get_triangle_area(width, height): return width * height / 2 #5-7 def add_start_to_end(start, end): result = 0 for i in range(start,end+1,1): result += i return result
6e42680389e94466abc769aec4e8eba49d9a853d
hexavi42/eye-see-u
/proofOfConcept/grayscale.py
782
3.546875
4
import argparse from os import path from PIL import Image def main(): parser = argparse.ArgumentParser(description='Grayscale an Image') parser.add_argument('-p', '--path', type=str, default=None, help='filepath of image file to be analyzed') parser.add_argument('-o', '--outFile', type=str, default=None, help='filepath to save new image at') args = parser.parse_args() filename, file_extension = path.splitext(args.path) img = Image.open(args.path) newImg = img.convert("L") if args.outFile is not None: filename, file_extension = path.splitext(args.outFile) else: filename, file_extension = path.splitext(args.path) filename+="_Gray" newImg.save(filename,"PNG") return if __name__ == "__main__": main()
0be7bc8211b56c825d410b76816af2d89eb19f6d
Alb4tr02/holbertonschool-higher_level_programming
/0x03-python-data_structures/10-divisible_by_2.py
318
3.984375
4
#!/usr/bin/python3 def divisible_by_2(my_list=[]): new_list = [] if my_list is None or len(my_list) == 0: return (None) else: for i in my_list: if (i % 2) == 0: new_list.append(True) else: new_list.append(False) return (new_list)
c537a01c9337f80af03e9209217d1a7dd25fbad9
Alb4tr02/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
221
3.625
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): if matrix is None: return newm = matrix.copy() for i in range(0, len(newm)): newm[i] = list(map(lambda x: x*x, newm[i])) return newm
2003141f132187e8281b81d69561fe78131a948a
Alb4tr02/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/6-print_sorted_dictionary.py
216
4.03125
4
#!/usr/bin/python3 def print_sorted_dictionary(a_dictionary): if a_dictionary is None: return list = (sorted(a_dictionary.items())) for i in list: print("{}{} {}".format(i[0], ":", i[1]))
cc43bddce55b547f89fb76b6636a278204121d0f
Alb4tr02/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
194
4.09375
4
#!/usr/bin/python3 def uppercase(str): for a in str: c = ord(a) if c >= ord('a') and c <= ord('z'): c -= 32 print("{:c}".format(c), end="") print("")
74c99c3b0c9b9bd9adc3d84ec71d466169be8a1f
PuchatekwSzortach/convolutional_network
/examples/mnist.py
2,112
3.546875
4
""" A simple MNIST network with two hidden layers """ import tqdm import numpy as np import sklearn.utils import sklearn.datasets import sklearn.preprocessing import net.layers import net.models def main(): print("Loading data...") mnist = sklearn.datasets.fetch_mldata('MNIST original') X_train, y_train = mnist.data[:60000].reshape(-1, 28, 28).astype(np.float32), mnist.target[:60000].reshape(-1, 1) X_test, y_test = mnist.data[60000:].reshape(-1, 28, 28).astype(np.float32), mnist.target[60000:].reshape(-1, 1) encoder = sklearn.preprocessing.OneHotEncoder(sparse=False).fit(y_train) y_train = encoder.transform(y_train) y_test = encoder.transform(y_test) # Stack images so they are 3D, scale them to <0, 1> range X_train = np.stack([X_train], axis=-1) X_test = np.stack([X_test], axis=-1) layers = [ net.layers.Input(sample_shape=(28, 28, 1)), net.layers.Convolution2D(filters=20, rows=14, columns=14), net.layers.Convolution2D(filters=10, rows=15, columns=15), net.layers.Flatten(), net.layers.Softmax() ] model = net.models.Model(layers) batch_size = 128 epochs = 2 X_test, y_test = sklearn.utils.shuffle(X_test, y_test) print("Initial accuracy: {}".format(model.get_accuracy(X_test, y_test))) for epoch in range(epochs): print("Epoch {}".format(epoch)) X_train, y_train = sklearn.utils.shuffle(X_train, y_train) batches_count = len(X_train) // batch_size for batch_index in tqdm.tqdm(range(batches_count)): x_batch = X_train[batch_index * batch_size: (batch_index + 1) * batch_size] y_batch = y_train[batch_index * batch_size: (batch_index + 1) * batch_size] model.train(x_batch, y_batch, learning_rate=0.01) print("Accuracy: {}".format(model.get_accuracy(X_test, y_test))) model.save("/tmp/model.p") loaded_model = net.models.Model.load("/tmp/model.p") print("Loaded model's accuracy: {}".format(loaded_model.get_accuracy(X_test, y_test))) if __name__ == "__main__": main()
9003c2fc01c18745533b9995186de30fc99f4fc4
KulaevaNazima/files
/files4.py
1,348
3.859375
4
#Cоздайте текстовый файл python.txt и запишите в него текст #1 из Classroom: #Затем, считайте его. Пробежитесь по всем его словам, и если слово содержит #букву “t” или “T”, то запишите его в список t_words = [ ]. После окончания списка, #выведите на экран все полученные слова. Подсказка: используйте for. python = open ('/home/nazima/python.txt', 'w') python.writelines ("""PyThon is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991. An interpreted language, PyThon has a design philosophy that emphasizes code readability (notably using whitespace indentation to delimit code blocks rather than curly brackets or keywords), and a syntax that allows programmers to express concepts in fewer lines of code than might be used in languages such as C++ or Java.""") python.close () python = open ('/home/nazima/python.txt', 'r') letter1= "t" letter2= "T" for line in python.readlines (): for words in line.split (): t_words= [] if letter1 in words: t_words.append (words) print (t_words) if letter2 in words: t_words.append (words) print (t_words)
5cb813598d9e52af2c1f514da781de4d22285190
singediguess/my-python-note
/using_str/using_str.py
495
4.0625
4
str1 = 'I am {}, I love {}' str2 = str1.format('k1vin', 'coding') print (str2) print('---') #using index str3 = '{0:10} : {1:3d}' table = {'c++':16, 'html':15, 'python':17} for name, nmb in table.items(): print (str3.format(name, nmb)) print('---') #using '%' import math print ('pi = %6.4f' % math.pi) print('---') #dictionary problems print (table.items()) print (table['c++']) print (table['html']) print('---') #input name= input('Give me your name: ') print ('Welcome,', name, '!!')
d57b48fe6ebac8c1770886f836ef17f3cadf16c7
alma-frankenstein/Grad-school-assignments
/montyHall.py
1,697
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #to illustrate that switching, counterintuitively, increases the odds of winning. #contestant CHOICES are automated to allow for a large number of test runs, but could be #changed to get user input import random DOORS = ['A', 'B', 'C'] CHOICES = ["stay", "switch"] def main(): num_runs = 100 monty(num_runs) def monty(num_runs): switchAndWin = 0 #times winning if you switch stayAndWin = 0 #times winning if you stay runs = 0 while runs <= num_runs: prize = random.choice(DOORS) picked_door = random.choice(DOORS) #Monty open a door that was neither chosen nor containing the prize for door in DOORS: if door != prize and door != picked_door: openedDoor = door break #the contestant can either stay with picked_door or switch to the other unopened one stayOrSwitch = random.choice(CHOICES ) if stayOrSwitch == "stay": final = picked_door if final == prize: stayAndWin += 1 else: #switch for door in DOORS: if door != openedDoor and door != picked_door: final = door if final == prize: switchAndWin += 1 break runs += 1 percentSwitchWin = (switchAndWin/num_runs) * 100 percentStayWin = (stayAndWin/num_runs) * 100 print("Odds of winning if you stay: " + str(percentStayWin)) print("Odds of winning if you switch: " + str(percentSwitchWin)) if __name__ == '__main__': main()
050b97bea9846acccb6ec7abafbab7505c6fd462
ColinSidberry/Learning-to-Code
/KS2.py
1,208
3.6875
4
import csv with open('Santee-Surrounding-Cities.csv','w',newline = '') as f: thewriter = csv.writer(f) file = input('Please enter raw.csv: ') opened = open(file) file2 = input('Please enter new.txt: ') opened2 = open(file2) s = str() old = ['san diego','santee','del mar','carlsbad','san marcos','encinitas','pendleton'] new = list() x = list() #Creating List of New Cities that will replace old cities for line in opened2: new.append(line.rstrip()) #Creating File where completed date will be printed to with open('Santee-Surrounding-Cities.csv','w',newline = '') as f: thewriter = csv.writer(f) thewriter.writerow(['Keyword','Ad Group']) for line in opened: x = line.split(',') s = x[1] count = 0 for old_city in old: count = count + 1 if old_city in s: for new_city in new: thewriter.writerow([s.replace(old_city, new_city),x[2]]) count = count + 1 #if old_city is old[0] or old[1]: # thewriter.writerow([s,x[2]]) elif count is 7: thewriter.writerow([s,x[2]]) else: continue
141011f37de069a56eb23f0aa5cf9b1c18fa6c72
JMR96/Ciclo2LP
/PalavraContraria.py
263
4.0625
4
# -*- coding: latin1 -*- def fraseInvert(frase): invert = frase.split() for i in xrange(len(invert)): invert[i] = invert[i][::-1] return ' '.join(invert) frase = 'Estou no ciclo 2 fazendo Linguagem de Programacao' print fraseInvert(frase)
b36cc808695e667d53ed0d274ee5faec1dd139ba
skluzada/school_projects
/Image Editor/image_editor/image_editor.py
8,324
3.84375
4
import numpy as np from PIL import Image MIRROR_VERTICAL = 0 MIRROR_HORIZONTAL = 1 # coefficients by which the corresponding channels are multiplied when converting image from rgb to gray TO_GRAY_COEFFICIENTS = { 'RED': 0.2989, 'GREEN': 0.5870, 'BLUE': 0.1140 } class ImageEditor: """ A class used to perform some basic operations on images Attributes: image_data (np.array): Current state of the image, without brightness and contrast applied brightness and contrast are not applied, because information could be lost and we want to be able to keep all the information after for example setting brightness to maximum image_data_og (np.array): Serves as a backup to get to the original image brightness (int): Amount of brightness added to the image, default = 0, should be between -255 and 255 contrast (float): Amount of contrast added to the image, default = 1, should be higher than 0 """ def __init__(self): self.image_data = None self.image_data_og = None self.brightness = 0 self.contrast = 1 def load_data(self, image_path): """ Method used to load the image data :param image_path: (str) Absolute path of an image file :return: (bool) True for success, False otherwise """ try: self.image_data = np.asarray(Image.open(image_path).convert('RGB')) except (OSError, AttributeError): return False self.image_data.setflags(write=True) self.image_data_og = self.image_data.copy() self.brightness = 0 self.contrast = 1 return True def get_data(self): """ Method used to get the image data, with brightness and contrast applied :return: (np.array) Image data """ return self.apply_contrast(self.apply_brightness(self.image_data.copy())) def save_image(self, image_path): """ Method used to save the image data :param image_path: (string) Absolute path to which the image will be saved :return: (bool) True for success, False otherwise """ try: Image.fromarray(self.get_data()).save(image_path) except ValueError: return False return True def reset(self): """ Method used to set the image data back to the original """ self.image_data = self.image_data_og.copy() self.brightness = 0 self.contrast = 1 def rotate(self, angle): """ Method used to rotate the image by multiples of 90 :param angle: (int) Angle to rotate the image by - has to be a multiple of 90 """ assert angle % 90 == 0 # GUI shouldn't let this happen self.image_data = np.rot90(self.image_data, k=angle / 90) def mirror(self, axis=MIRROR_HORIZONTAL): """ Method used to mirror the image either vertically or horizontally :param axis: (int) Specify the axis around which the mirroring will be performed has to be either MIRROR_HORIZONTAL (=1) or MIRROR_VERTICAL (=0) """ self.image_data = np.flip(self.image_data, axis=axis) def negative(self): """ Method used to transform the image data to negative """ self.image_data = 255 - self.image_data def rgb_to_gray(self): """ Method used to transform the image data from rgb to gray """ if self.image_data.ndim != 3: # the image contains only one channel return if self.image_data.shape[2] < 3: # the image contains less than three channels return self.image_data = TO_GRAY_COEFFICIENTS['RED'] * self.image_data[:, :, 0] \ + TO_GRAY_COEFFICIENTS['GREEN'] * self.image_data[:, :, 1] \ + TO_GRAY_COEFFICIENTS['BLUE'] * self.image_data[:, :, 2] def set_brightness(self, new_brightness): """ Method use to set the brightness attribute :param new_brightness: (int) New brightness value, should be between -255 and 255 """ self.brightness = new_brightness def apply_brightness(self, image_data): """ Method to apply brightness to the passed image data (not the class's image_data attribute!) :param image_data: (np.array) Image data on which the brightness will be applied :return: (np.array) Image data with brightness applied """ # convert to int16 as uint8 values could overflow image_data = np.clip(np.int16(image_data) + self.brightness, 0, 255) # convert back to uint8 image_data = np.uint8(image_data) return image_data def set_contrast(self, new_contrast): self.contrast = new_contrast def apply_contrast(self, image_data): """ Method to apply contrast to the passed image data (not the class's image_data attribute!) :param image_data: (np.array) Image data on which the contrast will be applied :return: (np.array) Image data with contrast applied """ # convert to int16 as uint8 values could overflow image_data = np.clip(np.int16(image_data) * self.contrast, 0, 255) # convert back to uint8 image_data = np.uint8(image_data) return image_data @staticmethod def convolve2d(channel, kernel): """ Static method used to perform 2D convolution using Convolution theorem source: BI-SVZ, Lecture 7 proof: https://en.wikipedia.org/wiki/Convolution_theorem :param channel: (np.array) 2D channel of an image :param kernel: (np.array) 2D filter to be applied :return: (np.array) result of convolution of params channel and kernel, with same size as param channel """ assert channel.ndim == 2 assert kernel.ndim == 2 # we need to transform channel and kernel to same size, otherwise we wouldn't be able to get a dot product # size includes padding (np.fft.fft2 function will insert zero padding) size = np.array(channel.shape) + np.array(kernel.shape) - 1 dtft_channel = np.fft.fft2(channel, size) dtft_kernel = np.fft.fft2(kernel, size) new_channel = np.fft.ifft2(dtft_channel * dtft_kernel) # get convolution new_channel = np.real(new_channel) # get back to the real world new_channel = np.clip(new_channel, 0, 255) # there might be some overflows new_channel = np.uint8(new_channel) # np.real returned float type values # we used padding, so we won't return the first and last row and column return new_channel[1:-1, 1:-1] def highlight_edges(self): """ Method used to highlight edges using either laplacian filter or sharpen filter """ # laplacian filter # sharpen_filter = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]]) # this looks a lot better, than laplacian filter sharpen_filter = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]]) if self.image_data.ndim == 2: # gray image self.image_data = self.convolve2d(self.image_data, sharpen_filter) elif self.image_data.shape[2] == 3: # rgb image # for each channel: for i in range(3): self.image_data[:, :, i] = self.convolve2d(self.image_data[:, :, i], sharpen_filter) def blur(self): """ Method used to blur the image using either box blur filter or gaussian blur filter """ # box blur filter # blur_filter = 1/9 * np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) # gaussian blur filter blur_filter = 1 / 16 * np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]]) if self.image_data.ndim == 2: # gray image self.image_data = self.convolve2d(self.image_data, blur_filter) elif self.image_data.shape[2] == 3: # rgb image # for each channel: for i in range(3): self.image_data[:, :, i] = self.convolve2d(self.image_data[:, :, i], blur_filter)
31188f137dc8be0688b2a3042f04226bca65e202
mamorales10/Python-Guide-for-Beginners
/SortingAlgorithms/merge_sort.py
674
4.03125
4
def mergeSort(listToSort): if(len(listToSort) > 1): mid = len(listToSort)//2 lower = listToSort[:mid] upper = listToSort[mid:] mergeSort(lower) mergeSort(upper) i = 0 j = 0 k = 0 while(i < len(lower) and j < len(upper)): if(lower[i] < upper[j]): listToSort[k] = lower[i] i = i + 1 else: listToSort[k] = upper[j] j = j + 1 k = k + 1 while(i < len(lower)): listToSort[k] = lower[i] i = i + 1 k = k + 1 while(j < len(upper)): listToSort[k] = upper[j] j = j + 1 k = k + 1 print "Enter numbers to be sorted (separated by space)" userList = map(int, raw_input().split()) mergeSort(userList) print userList
f8096a50065547373b754f7c3c3ea43367434d88
psykid/computational-physics
/romberg.py
664
3.5
4
import math import numpy as np fun="1.0/x" lb, ub=1, 2 def f(x): return eval(fun) def T(m,k): if k==0: return T_0(m) return def T_0(m): N=2**m step=(ub-lb)*1.0/N i, summ=lb+step,0 while i<ub: summ+=f(i) i+=step summ+=0.5*(f(lb)+f(ub)) return summ*step #0.69314718055994529 def main(): #_n=int(raw_input("enter k, for degree of accuracy h^2k: ")) #_m=int(raw_input("enter initial m, for 2^m starting points: ")) _k=5 _m=3 T=np.zeros((_k+1,_k+1)) for m in range(_k+1): for k in range(m+1): print m,k if k==0: T[m][k]=T_0(_m+m) continue T[m][k]=((2**(2*k))*T[m,k-1]-T[m-1,k-1])/(2**(2*k)-1) print T main()
ffdba064734aa4cb7193f7121fa5c28cd06a32cc
Shio3001/koneta
/99.py
619
3.6875
4
import random print("九九計算して") def loop(): i1 = random.randint(0, 9) i2 = random.randint(0, 9) m = random.randint(0, 2) correct = 0 if m == 0: correct = i1 * i2 print("{0} x {1}".format(i1, i2)) if m == 1: correct = i1 + i2 print("{0} + {1}".format(i1, i2)) if m == 2: correct = i1 - i2 print("{0} - {1}".format(i1, i2)) correct_str = str(correct) ans_str = input().rstrip() correct_f = correct_str[-1] ans_f = ans_str[-1] if correct_f != ans_f: return loop() loop() print("おわり")
8b8644a5fbc3a44baff3a5ad1156c5a644b60f56
drod1392/IntroProgramming
/Lesson1/exercise1_Strings.py
1,026
4.53125
5
## exercise1_Strings.py - Using Strings # # In this exercise we will be working with strings # 1) We will be reading input from the console (similar to example2_ReadConsole.py) # 2) We will concatenate our input strings # 3) We will convert them to upper and lowercase strings # 4) Print just the last name from the "name" variable # 5) EXTRA - Use proper capitalization on first and last name print("Section 1 - Read input\n") # Prompt the user to enter first and last name seperately # Use two input() commands to read first and last name seperately. # Use variable names "first" and "last" to store your strings print("\nSection 2 - Concatenate") # Concatenate first and last name together in variable "name" # Print out the result print("\nSection 3 - Upper and Lower") # Print "name" in all uppercase # Print "name" in all lowercase print("\nSection 4 - Only Last Name") # Print just the last name from "name" print("\nSection 5 - Capitalization") # Extra - use proper capitalization on first and last name
df9cea82395dfc4c540ffe7623a0120d2483ea9e
imyogeshgaur/important_concepts
/Python/Exercise/ex4.py
377
4.125
4
def divideNumber(a,b): try: a=int(a) b=int(b) if a > b: print(a/b) else: print(b/a) except ZeroDivisionError: print("Infinite") except ValueError: print("Please Enter an Integer to continue !!!") num1 = input('Enter first number') num2 = input('Enter second number ') divideNumber(num1,num2)
abcb2f242d5b48cae08848eba99bec9249cd7f98
servemoseslake/serve
/sml/sml/serve/utils.py
873
3.5
4
from datetime import datetime, date def date_from_string(value, format='%Y-%m-%d'): if type(value) == date: return value return datetime.strptime(value, format).date() def datetime_from_string(value, format='%Y-%m-%dT%H:%M'): alternate_formats = ( '%Y-%m-%dT%H:%M:%S', ) all_formats = set((format,) + alternate_formats) for fmt in all_formats: try: return datetime.strptime(value, fmt) except ValueError: pass raise ValueError def date_to_age(value, now=None): now = now if now else datetime.now() if value > now.date().replace(year = value.year): return now.date().year - value.year - 1 else: return now.date().year - value.year def datetime_round(value): return datetime(value.year, value.month, value.day, value.hour, tzinfo=value.tzinfo)
c9586c078a3bd35ebab6a145de6b6a0a934f501f
zmadil/Random_snippets_2019
/bubblesort.py
242
4.0625
4
list1=[5,3,7,22,5,9,1] def bubblesort(list1): for i in range(len(list1)): for j in range(i+1,len(list1)): if list1[j] < list1[i]: temp=list1[j] list1[j]=list1[i] list1[i]=temp return list1 bubblesort(list1) print(list1)
4b8332d14517a5e339ea61207ed710d8e7cd7e78
zmadil/Random_snippets_2019
/fibonacci.py
214
3.8125
4
#0,1,1,2,3,5,8,13,21 print('Please enter how many numbers you want ') user=int(input()) print('----------------------------') a=0 b=1 print(a) print(b) for i in range(2,user): c=a+b a=b b=c print(c)
0953e7600c11fb8059e602fb948107fbc801065b
makstar1/low
/pro4.py
329
3.8125
4
from random import randint as ri a = int(input( "введите длину списка: ")) b = int(input("введите максимальное значение элемента списка: ")) def listFunc (x,y): list = [] for i in range(x): list.append(ri(0,y+1)) return list print(listFunc(a,b))
e822856efebb234650fa9d22e4e233757ec01acb
liweiwei1419/Algorithms-Learning-Python
/binary-search/binary-search-4.py
549
3.890625
4
# 查找最后一个小于等于给定值的元素 def binary_search_4(nums, target): size = len(nums) # 注意,right 向左边减了 1 位,因为 target 可能比 nums[0] 还要小 left = -1 right = size - 1 while left < right: mid = left + (right - left + 1) // 2 if nums[mid] <= target: left = mid else: right = mid - 1 return left if __name__ == '__main__': nums = [1, 3, 3, 3, 3, 4, 5] target = 9 result = binary_search_4(nums, target) print(result)
8c83a11c95c69da1e3d09e44130af2457d4bf91b
liweiwei1419/Algorithms-Learning-Python
/unweighted-graph/DenseGraph.py
1,211
3.578125
4
from iterator import DenseGraphIterator class DenseGraph: def __init__(self, n, directed): assert n > 0 # 结点数 self.n = n # 边数 self.m = 0 # 是否是有向图 self.directed = directed # 图的具体数据 self.g = [[False for _ in range(n)] for _ in range(n)] def add_edge(self, v, w): assert 0 <= v < self.n assert 0 <= w < self.n # 如果已经有了结点 v 到结点 w 的边 # 就直接返回,不再添加邻边,和 m + 1 if self.has_edge(v, w): return self.g[v][w] = True # 如果是无向图,维护无向图的对称性 if not self.directed: self.g[w][v] = True self.m += 1 def has_edge(self, v, w): assert 0 <= v < self.n assert 0 <= w < self.n return self.g[v][w] def show(self): for i in range(self.n): for j in range(self.n): if self.g[i][j]: print('1', end=' ') else: print('0', end=' ') print() def iterator(self, v): return DenseGraphIterator(self, v)
7a6ce3a681aeabe5b7758972546666d6be3ef641
2KNG/old_freshman
/python_source/수업/문제1.py
518
4
4
def calc(a, op, b): x = a y = b if op == "+": print("{:.2f}{}{:.2f}={:.2f}".format(a, op, b, a+b)) elif op == "-": print("{:.2f}{}{:.2f}={:.2f}".format(a, op, b, a-b)) elif op == "*": print("{:.2f}{}{:.2f}={:.2f}".format(a, op, b, a*b)) elif op == "/": print("{:.2f}{}{:.2f}={:.2f}".format(a, op, b, a/b)) else : print('올바른 정수 및 연산자를 입력하세요') calc(10,'+',2) calc(10.5,'-',2.1) calc(10,'*',5) calc(12,'/',5) calc(12,12,2)
f092c8017f618eb44d2c6c5a48248909b067eb68
2KNG/old_freshman
/python_source/수업/엑셀입출력.py
835
3.71875
4
import csv # in_file = open("excel_data.csv", "r") # data = csv.reader(in_file) # for i in data : # print(i) # in_file.close() # with open("aa/excel_data2.csv", "w", encoding="utf-8-sig", newline="") as out_file: # newlinee 을 안박으면 개손해 # data = csv.writer(out_file, delimiter=",") # data.writerow([i for i in range(1,3)]) # data.writerow([i*10 for i in range(1,3)]) with open("aa/excel_data3.csv", "w", encoding="utf-8", newline="") as out_file : data = csv.DictWriter(out_file, fieldnames = ['name', 'age']) data.writeheader() data.writerow({"name":"hong", "age":10}) data.writerow({"name":"kim", "age":18}) # # 읽기 # with open("aa/excel_data3.csv", "r", encoding="utf-8-sig") as in_file: # data = csv.DictReader(in_file) # for line in data: # print(line)
6885e4e26929aae57d69b5db41ca2971aacbf0fd
2KNG/old_freshman
/python_source/수업/문제3.py
198
3.828125
4
def plus(f, t): # from 으로 함수를 작성할 수 없어 f, t로 변경 sum = 0 for i in range(f, t+1): sum += i return sum print(plus(1,10)) print(plus(1, 3) + plus(5, 7))
094c36fab0d52ecac6cdee01896f54c1ec414c10
2KNG/old_freshman
/python_source/딥러닝/문제 210630.py
1,320
3.5
4
import random i = random.randint(1,15) print(i) while x != i : x = int(input('줘요')) k = x if x == i : print('정답띠') elif i < 7 : if 7 < x: print("i는 7보다 작다") elif x < i < 7 : print("i는 7보다 작고 {}보다 커욤".format(x)) elif i < x < 7 : print("i는 {}보다 작습니당".format(x)) elif 7 <= i : if x < 7 : print("i는 7보다 크다") elif 7 < i < x : print("i는 7보다 크고 {}보다 작아욤".format(x)) elif 7 <= x < i : print("i는 {}보다 큽니당".format(x)) else : print('이게머선129') print('i는 {}가 맞다'.format(i)) # 7보다 큰지 작은지 # 2진분류 # 랜덤값을 물어보면서 찾을 수 있게 # # # elif i < 7: # if 7 < x: # print("i는 7보다 작다") # elif x < i < 7: # print("i는 7보다 작고 {}보다 커욤".format(x)) # elif i < x < 7: # print("i는 {}보다 작습니당".format(x)) # elif 7 <= i: # if x < 7: # print("i는 7보다 크다") # elif 7 < i < x: # print("i는 7보다 크고 {}보다 작아욤".format(x)) # elif 7 <= x < i: # print("i는 {}보다 큽니당".format(x)) # else: # print('이게머선129')
f2e6ca8c1e4b7f263d07c18e437f7b376498d4c3
jky007/py_learn
/test3-12.py
274
3.78125
4
a = 'hello,world' # hello,world b = 1.414 # 1.414 c = (1 != 2) # True d = (True and False) # False e = (True or False) # True #1 print(a,b,c,d,e) #2 print("a:%s; b:%.2f; c:%s; d:%s; e:%s" % (a,b,c,d,e)) #3 s="\'hello,world\'\n\\\"hello,world\"" print(s)