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
d6c8b62d75d43f23f079223c80a3869e3c10a6b6
SyuW/phys_363_classical_mech
/restricted_3BP_motion.py
2,238
3.59375
4
import numpy as np import matplotlib.pyplot as plt ''' Plot test mass trajectories in the restricted three-body problem ''' # Constants a = 1 G = 1 m = 1 M_2 = 1 delta_t = 0.001 mass_ratios = {"i": 1, "ii": 0.041, "iii": 0.039, "iv": 19/20000} def determine_mass_of_M_1(mass_ratio, M_2): return mass_ratio * M_2 def compute_acceleration(velocity, position, M_1, M_2, M): x, y = position x_dot, y_dot = velocity omega = np.sqrt(G * M / a**3) helper_x_1 = a*M_2/M - x helper_x_2 = a*M_1/M + x helper_y_1 = a*M_2/M - x helper_y_2 = a*M_1/M + x #Terms: Coriolis Centrifugal Gravitational Potential x_double_dot = -2*omega*(y_dot) + (omega**2)*x + (G*M_1*helper_x_1)/((helper_x_1**2 + y**2)**(3/2)) - (G*M_2*helper_x_2)/((helper_x_2**2 + y**2)**(3/2)) y_double_dot = 2*omega*(x_dot) + (omega**2)*y - (G*M_1*y) /((helper_y_1**2 + y**2)**(3/2)) - (G*M_2*y) /((helper_y_2**2 + y**2)**(3/2)) return np.array([x_double_dot, y_double_dot]) def main(): # Set masses for part in mass_ratios: M_1 = determine_mass_of_M_1(mass_ratios[part], M_2) M = M_1 + M_2 delta = (M_2 - M_1) / M # Lagrange Points L_4 = (a / 2) * np.array([delta, np.sqrt(3)]) L_5 = (a / 2) * np.array([delta, -np.sqrt(3)]) # Initial conditions perturbation = np.array([0, 0.001*a]) positions = [L_4 + perturbation] velocities = [np.array([0, 0])] # For comparing nature of eigenfrequencies to observed trajectory eigenfreqs_disc = 27*delta**2 - 23 print(f"Eigenfrequencies discriminant: {eigenfreqs_disc}") # Solve DE using Euler's Method for n in range(1, 100000): velocities += [velocities[-1] + delta_t*compute_acceleration(velocities[-1], positions[-1], M_1, M_2, M)] positions += [positions[-1] + delta_t*velocities[-1]] x = [coords[0] for coords in positions]; y = [coords[1] for coords in positions] plt.plot(x, y) plt.xlabel(r"$y_{x}^{\prime}$") plt.ylabel(r"$y_{y}^{\prime}$", rotation=0) plt.show() main()
258a26f57623ce51cd70dd66295ce40993ddc481
iCeterisParibus/analytics-vidhya-essentials-of-machine-learning-algorithms
/AV_gradient_boost.py
1,265
3.71875
4
# Python code for Gradient Boosting & AdaBoost provided by Analytics Vidhya print '-' * 85 print """ Gradient Boosting & AdaBoost GBM & AdaBoost are boosting algorithms used when we deal with plenty of data to make a prediction with high prediction power. Boosting is an ensemble learning algorithm which combines the prediction of several base estimators in order to improve robustness over a single estimator. It combines multiple weak or average predictors to a build strong predictor. These boosting algorithms always work well in data science competitions like Kaggle, AV Hackathon, CrowdAnalytix. """ print '-' * 85 print """ Code provided by Analytics Vidhya article: #Import Library from sklearn.ensemble import GradientBoostingClassifier #Assumed you have, X (predictor) and Y (target) for training data set and # x_test(predictor) of test_dataset # Create Gradient Boosting Classifier object model= GradientBoostingClassifier(n_estimators=100, learning_rate=1.0, max_depth=1, random_state=0) # Train the model using the training sets and check score model.fit(X, y) #Predict Output predicted= model.predict(x_test) """ print '-' * 85
a65178b09ef727b96992dc3d20820e07afcc9bfc
bingx1/python-examples
/lru_cache.py
947
3.859375
4
#Lru Cache implemented using python's built-in OrderedDict # OrderedDict stores the order keys were added to the dictionary class LruCache: def __init__(self, capacity) -> None: self.capacity = capacity self.price_table = {} def lookup(self, isbn): if isbn not in self.price_table: return -1 # Key is popped so that we can re-insert the (key,value) to the back of the queue price = self.price_table.pop(isbn) self.price_table[isbn] = price def insert(self, isbn, price): if isbn in self.price_table: price = self.price_table.pop(isbn) # Pop even when the item is present so we can update the order of the queue elif len(self.price_table == self.capacity): self.price_table.popitem(last=False) self.price_table[isbn] = price def erase(self, isbn): return self.price_table.pop(isbn, None) is not None
43716fe322cd9e307b98cefa32a1e35a1d387b87
omvikram/python-ds-algo
/dynamic-programming/longest_increasing_subsequence.py
2,346
4.28125
4
# Dynamic programming Python implementation of LIS problem # lis returns length of the longest increasing subsequence in arr of size n def maxLIS(arr): n = len(arr) # Declare the list (array) for LIS and # initialize LIS values for all indexes lis = [1]*n # Compute optimized LIS values in bottom up manner for i in range (1 , n): for j in range(0 , i): if arr[i] > arr[j] and lis[i] < lis[j] + 1 : lis[i] = lis[j]+1 # Initialize maximum to 0 to get # the maximum of all LIS maximum = 0 # Pick maximum of all LIS values for i in range(n): maximum = max(maximum , lis[i]) return maximum # end of lis function # Driver program to test above function arr = [10, 22, 9, 33, 21, 50, 41, 60] arr1 = [16, 3, 5, 19, 10, 14, 12, 0, 15] arr2 = [10, 8, 6, 4, 2, 0] print ("LIS length of arr is ", maxLIS(arr)) print ("LIS length of arr1 is ", maxLIS(arr1)) print ("LIS length of arr2 is ", maxLIS(arr2)) ############################################################################################## # Given a list of N integers find the longest increasing subsequence in this list. # Example # If the list is [16, 3, 5, 19, 10, 14, 12, 0, 15] # one possible answer is the subsequence [3, 5, 10, 12, 15], another is [3, 5, 10, 14, 15]. # If the list has only one integer, for example: [14], the correct answer is [14]. # One more example: [10, 8, 6, 4, 2, 0], a possible correct answer is [8]. # Function to print the longest increasing subsequence def lisNumbers(arr): n = len(arr) # Declare the list (array) for LIS and # initialize LIS values for all indexes by 1 lis = [1]*n # Compute optimized LIS values in bottom up manner for i in range (1 , n): for j in range(0 , i): if arr[i] > arr[j] and lis[i] < lis[j] + 1 : lis[i] = lis[j]+1 # print(arr) # print(lis) myLISlist = [] # Print the LIS sequence from all LIS values for i in range(0, len(lis)): if(i == 0): myLISlist.append(arr[0]) elif(i > 0 and lis[i] == lis[i-1]): if(arr[i] > arr[i-1]): myLISlist.append(arr[i-1]) else: myLISlist.remove(arr[i-1]) myLISlist.append(arr[i]) elif(i > 0 and lis[i] > lis[i-1]): myLISlist.append(arr[i]) print myLISlist lisNumbers([10, 22, 9, 33, 21, 50, 41, 60]) lisNumbers([16, 3, 5, 19, 10, 14, 12, 0, 15]) lisNumbers([10, 8, 6, 4, 2, 0])
b4c01ca063d09ba24aff1bfe44c719043d24d1c3
omvikram/python-ds-algo
/dynamic-programming/pattern_search_typo.py
1,035
4.28125
4
# Input is read from the standard input. On the first line will be the word W. # On the second line will be the text to search. # The result is written to the standard output. It must consist of one integer - # the number of occurrences of W in the text including the typos as defined above. # SAMPLE INPUT # banana # there are three bananas on the tree and one banano on the ground # SAMPLE OUTPUT # 2 def findTyposCount(): txt = input("Please enter the searching text here:") pat = input("Please enter the searchable pattern here:") pat_len = len(pat) txt_arr = txt.split(" ") counter_list = [] for each in txt_arr: counter = 0 txt_len = len(each) if(txt_len >= pat_len): ## Call a function to check the max possible match between each text and pattern ## If matching count > 1 then we can consider it as typo (ideally matching count > pat_len/2) counter_list.append(each) print(counter_list) findTyposCount()
a3ca34db407b81382afc3e61e6abbc74eed86c3a
omvikram/python-ds-algo
/dynamic-programming/bit_count.py
568
4.3125
4
# Function to get no of bits in binary representation of positive integer def countBits(n): count = 0 # using right shift operator while (n): count += 1 n >>= 1 return count # Driver program i = 65 print(countBits(i)) ########################################################################## # Python3 program to find total bit in given number import math def countBitsByLog(number): # log function in base 2 take only integer part return int((math.log(number) / math.log(2)) + 1); # Driver Code num = 65; print(countBitsByLog(num));
5fff518a9ffe783632b8d28920772fbc7ab54467
omvikram/python-ds-algo
/data-strucutres/linked_list.py
1,483
4.4375
4
# Python program to create linked list and its main functionality # push, pop and print the linked list # Node class class Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None # LinkedList class class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Remove an item from the LinkedList def pop(self, key): temp = self.head # If head node itself holds the key to be deleted if(self.head.data == key): self.head = temp.next temp = None return # this loop is to just set the prev node while (temp is not None): if(temp.data == key): break else: prev = temp temp = temp.next #after the loop just change the next node if(temp == None): return prev.next = temp.next temp = None # Utility function to print it the linked LinkedList def printList(self): temp = self.head while(temp): print(temp.data) temp = temp.next # Driver program for testing llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(10) llist.printList() llist.pop(4) llist.printList()
6b4f8c75cf2425bac0d93784b1ceb53707af7db8
omvikram/python-ds-algo
/dynamic-programming/jump_over_numbers.py
1,191
3.984375
4
# You are given a list of non-negative integers and you start at the left-most integer in this list. # After that you need to perform the following step: # Given that the number at the position where you are now is P you need to jump P positions to the right in the list. # For example, if you are at position 6 and the number at position 6 has the value 3, you need to jump to position 6 + 3 = 9. # Repeat this operation until you reach beyond the right-side border of the list. # Your program must return the number of jumps that it needs to perform following this logic. # Note that the list may contain the number 0, which mean that you can get stuck at a this position forever. # In such cases you must return the number -1. # The length N of the input list will be in the range [1, 1000]. # SAMPLE INPUT # 3 4 1 2 5 6 9 0 1 2 3 1 # SAMPLE OUTPUT # 4 def jump_over_numbers(mylist): index = 0 maxjump = 0 while(index < len(mylist)): if(mylist[index] == 0): return -1 index = index + mylist[index] maxjump = maxjump + 1 return maxjump mylist = [3, 4, 1, 2, 5, 6, 9, 0, 1, 2, 3, 1] print(jump_over_numbers(mylist))
8ac6c88830679c6fb29732e283ec1884d30fdaa8
omvikram/python-ds-algo
/data-strucutres/heap.py
742
4.125
4
import heapq ## heapify - This function converts a regular list to a heap. In the resulting heap the smallest element ## gets pushed to the index position 0. But rest of the data elements are not necessarily sorted. ## heappush – This function adds an element to the heap without altering the current heap. ## heappop - This function returns the smallest data element from the heap. ## heapreplace – This function replaces the smallest data element with a new value supplied in the function. H = [21,1,45,78,3,5] # Use heapify to rearrange the elements heapq.heapify(H) print(H) # Add element heapq.heappush(H,8) print(H) # Remove element from the heap heapq.heappop(H) print(H) # Replace an element heapq.heapreplace(H,6) print(H)
dd09b6396367705c2bb81a94711f220d212e94af
vipulyadav150/Python-OOP
/src/closureFunctions.py
252
3.53125
4
def outer_function(): message = 'Hi' def inner_function(): print(message) return inner_function #removed Paranthesis my_func = outer_function() #MY func is = inner_function(){ready to be executed} my_func() my_func() my_func()
ecdabecb200fb8066e266509c39ab0fa4307b580
Deo-07/python-work
/deo10.py
633
4.09375
4
#Pyhon IF , Else and Elif statements age=int(input("Enter Your Age:")) if(age>28): print("Yes U can Drink Alcohol") elif( age>15): print("You can take Only soft Drinks") else: print("You can only drink Water") #Sort Hand If OR Else it is Also known as ternary operaters if(12>6):print("hello ") #Nested IF Statements x=50 if(x>40): print("Above Ten") if(x>30): print("and also greater than 30") if(x>20): print("also greater than 20") else: print("But not above than 20") #The Pass Statements - If statements can not be empty its only happen when u use pass statatements if(2>4): pass
0ac2e2f67a2ccd09efcb2375af529d5758732cd9
Deo-07/python-work
/prac5.py
186
3.671875
4
#Make ATM concept print("Welcome To Deovano Bank\n") chanses=3 balance=900 while chanses>=0: pin=int(input("Plese Enter your Pin\n")) if (pin==1234): print("Welcome") break
759c43ae5db67cb5badfa6eded41722aa3cf218c
theod0sis/AFDEmp
/Maze/mazeprob.py
8,862
3.75
4
import random import sys sys.version n = input('Enter the size of the graph :') n= int(n) i=0 walls=[] while i==0 : wall_x = input ('Enter the walls of the graph(x)[if you want to stop enter "exit"] :') if (wall_x=="exit"): i=1 else: wall_y = input ('Enter the walls of the graph(y):') wall_x=int(wall_x) wall_y=int(wall_y) walls.append([wall_x,wall_y]) #print (walls) graph1 = {} test=[] k=0 print (walls) for i in range(0,n): for j in range(0, n): neighbours = [] test.append([i,j]) #print (test, walls) #Isagogi gitonon goniakon komvon kai aferesi walls apo tixous if (i == 0 and j == 0): flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([0,1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([1,0]) graph1[(i,j)] = neighbours elif (i == 0 and j == n-1): flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([0,j-1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([1,j]) graph1[(i,j)] = neighbours elif (i == n-1 and j == 0): flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i-1,0]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i,1]) graph1[(i,j)] = neighbours elif (i == n-1 and j == n-1): flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i,j-1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i-1,j]) graph1[(i,j)] = neighbours #Isagogi gitonon perimetrikon komvon kai aferesi walls apo tixous elif (i == 0 and not(j == 0) and not(j == n-1)): flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i,j-1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i,j+1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i+1,j]) graph1[(i,j)] = neighbours elif (j == 0 and not(i == 0) and not(i == n-1)): flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i-1,j]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i,j+1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i+1,j]) graph1[(i,j)] = neighbours elif (i == n-1 and not(j == 0) and not(j == n-1)): flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i,j-1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i,j+1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i-1,j]) graph1[(i,j)] = neighbours elif (j == n-1 and not(i == 0) and not(i == n-1)): flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i,j-1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i+1,j]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i-1,j]) graph1[(i,j)] = neighbours #Isagogi gitonon kentrikon komvon kai aferesi walls apo tixous else: flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i,j+1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i,j-1]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i+1,j]) flag="false" for p in range(0,len(walls)): if (test[k]== walls[p]): flag="true" if (flag=="false"): neighbours.append ([i-1,j]) graph1[(i,j)] = neighbours k+=1 #print (neighbours,walls) #Isagogi metavliton ekinisis kai goal start_x = input('Enter the starting x coordinate ): ') start_x= int(start_x) while (start_x<0 or start_x>=n): start_x = input('Enter again the the starting x coordinate: ') start_x= int(start_x) start_y = input('Enter the starting y coordinate ): ') start_y= int(start_y) while (start_y<0 or start_y>=n): start_y = input('Enter again the the starting y coordinate: ') start_y= int(start_y) end_x = input('Enter the goal x coordinate ): ') end_x= int(end_x) while (end_x<0 or end_x>=n): end_x = input('Enter again the the goal x coordinate: ') end_x= int(end_x) end_y = input('Enter the goal y coordinate ): ') end_y= int(end_y) while (end_y<0 or end_y>=n): end_y = input('Enter again the the goal y coordinate: ') end_y= int(end_y) #To visited hrisimopiite gia na elenghoume an ehoume episkefthei ton ekastote komvo visited = {} for i in range(0,n): for j in range(0,n): visited[(i,j)] = 0 #ston maze katagrafoume tous komvous pou diashizoume kata tin anazitisi tou grafou maze = [] def DFS(sx,sy,fx,fy): visited[(sx,sy)] = 1 #vazw stn maze ts komvous maze.append((sx,sy)) #stin AdjacencyList katagrafonte oi gitones tou ekastote komvou AdjacencyList = graph1[(sx,sy)] random_neighbour = random.sample(AdjacencyList, len(AdjacencyList)) #print (random_neighbour) #gia kathe stihio tis anakatemenis listas elenghoume to visited kai an den ehoume episkefti ton komvo ksanakaloume tin methodo for index in range(len(random_neighbour)): a = random_neighbour[index] sx = a[0] sy = a[1] if (visited[(sx,sy)]==0): if (sx==fx and sx==sy): maze.append((sx,sy)) break else: DFS(sx,sy,fx,fy) #kaloume tin methodo me tis metavlites ekinisis DFS(start_x,start_y,end_x,end_y) #tipono ton maze gia na do tin poria pou akolouthisame kata tin anazitisi tou grafou print(maze)
f667d642e7b5d4d23665265c5d82301503ef43e5
LinvernSS/daily_assignments
/week1/day4/day10.py
631
3.859375
4
#!/usr/bin/env python # coding: utf-8 # Lucas Invernizzi Day 10 Assignment # 1) # In[16]: def bmi(in_data): in_data = in_data.split('\n') out = '' for i in range(1, int(in_data[0]) + 1): person = in_data[i].split() weight = int(person[0]) height = float(person[1]) bmi = weight / (height ** 2) if bmi >= 30: out += 'obese ' elif bmi >= 25: out += 'over ' elif bmi >= 18.5: out += 'normal ' else: out += 'under ' return out.strip() # In[17]: data = '3\n80 1.73\n55 1.56\n49 1.91' # In[18]: bmi(data)
1aa3316e636bfcc2f6880ebb8f910e85d6913fa3
MandilKarki/RabbitMQ
/Python/Hello world /receive.py
978
3.765625
4
""" Receiver which receives the message from the queue. """ import pika """Create a connection to the RabbitMQ server and establish a channel""" connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost", port=5672)) channel = connection.channel() """ - Create or get the existing channel from the Queue - So far we have already created a channel in send.py so it won't be created again. """ channel.queue_declare(queue="hello") def callback(ch, method, properties, body): """Function to be called by Pika Library on receiving message""" # %r -> converts to representation print("[X] Received %s" % body) channel.basic_consume( queue="hello", # subscribe to hello queue on_message_callback=callback, # call function on receiving a message auto_ack=True ) print('[*] Waiting for messages. To exit press CTRL+C') """enter a never-ending loop that waits for data and runs callbacks""" channel.start_consuming()
ae3ea608877c02a2c481bc3c43c8f9bbaa423ba2
MandilKarki/RabbitMQ
/Python/Hello world /send.py
954
3.71875
4
""" A producer to send the message to the RabbitMQ server. """ import pika """Create a connection to the RabbitMQ server and channel""" connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost',port=5672)) channel = connection.channel() """Create a queue named 'hello'. If no queue name is defined, message may drop.""" channel.queue_declare(queue='hello') """ - Now ready to send message - Point to Note: RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange exchange='' uses default exchange in AMQP """ channel.basic_publish( exchange='', # use default exchange routing_key='hello', # queue name to which message needs to be enqued body='Hello world' # message content ) """ Make sure network buffer is cleared. i.e make sure to close the connection """ connection.close() """ Note: List the queues available: sudo rabbitmqctl list_queues """
cd638f4db8cfb8a929fe2461230f6ac8949655ce
Swetapadma94/simple-linear-regression
/simple linear regression-udemy.py
1,733
3.984375
4
#!/usr/bin/env python # coding: utf-8 # # Importing Libraries # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt # # Importing the dataseet # In[2]: df=pd.read_csv(r'E:\Udemy\Machine Learning A-Z (Codes and Datasets)\Part 2 - Regression\Section 4 - Simple Linear Regression\Python\Salary_Data.csv',encoding='latin1') # In[3]: df.head() # In[28]: X=df.iloc[:,:-1] # In[29]: X # In[30]: Y=df.iloc[:,-1] # # Splitting Data set into train and test # In[31]: from sklearn.model_selection import train_test_split # In[32]: X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0) # In[33]: X_train # # Training simple linear regression on Training data # In[34]: from sklearn.linear_model import LinearRegression # In[35]: sl=LinearRegression() # In[36]: sl.fit(X_train,Y_train) # In[48]: # print the coefficients print(sl.intercept_) print(sl.coef_) # # Predicting the test result # In[37]: predict=sl.predict(X_test) # In[38]: predict # In[41]: dt = pd.DataFrame({'Actual': Y_test, 'Predicted': predict}) dt # In[ ]: from # # Visualising the training set result # In[43]: plt.scatter(X_train,Y_train,color='red') plt.plot(X_train,sl.predict(X_train),color='blue') plt.title("Regression implementation") plt.xlabel("years of experince") plt.ylabel("salary") # In[ ]: # In[47]: plt.scatter(X_test,Y_test,color='red') plt.plot(X_train,sl.predict(X_train),color='blue') plt.title("Regression implementation") plt.xlabel("years of experince") plt.ylabel("salary") # In[51]: # to predict a single value print(sl.predict([[12]])) # In[52]: print(sl.predict([[35]])) # In[57]: # In[ ]:
8f183f613c8faee3b9cc680a4649e0a27a854c44
tjhoward/Discord-Quiz-Bot
/quizbot.py
7,646
3.703125
4
import discord #discord.py library #import os #from replit import db client = discord.Client() #create client instance to discord class quiz(discord.Client): def __init__(self, user_name): self.user_name = user_name #self.quizzes = [["1$quizname", "Question ***", "Answer *** "], ["2$quizname", "Question ***", "Answer **"]] #list will have quesitons, answers, and name, so mult by 2 and 1 to length *((numQuestions*2) + 1 self.quizzes = [] self.new_quiz_questions = [] #used to store questions that are being created self.quizCount = 0 self.has_quiz = False self.creating_questions = False self.creating_index = 0 self.creating_qnum = 0 self.takingQuiz = False self.choosingQuiz = False self.current_quiz = 0 # the quiz user is currently taking self.current_quiz_quest = 0 #used to self.quizing_index = 0 #used to loop through quiz quesitons def getName(self): return self.user_name def settName(self, new_name): self.user_name = new_name def printQuiz(self): count = 1 q = self.quizzes #print(q) if len(q) > 0: for i in range(len(q)): print(q[i][0]) if q[i][0].find(str(count) + "$") != -1: #count occurences in form quiznum$ #print("found") print(q[i][0].replace("$", ". ")) count += 1 return True else: return False @client.event #Notify when bot is ready async def on_ready(): print('Bot {0.user}'.format(client) + 'is ready') #if Permissions(read_message_history,client.user) == TRUE: print("Success logging in") users = [] q = quiz("") # store username and quiz questions @client.event async def on_message(message): #Called whenever a message is sent on a channel if message.author == client.user: #ignore if message is from bot return currentQuizTaker = q.user_name #print("CURRENT QUIZ TAKER " + q.user_name) m = message.content #get message m_auth = message.author # the Member that sent the message a = str(m_auth) name_split = a.split("#") name = name_split[0] prev_message = "" counter = 0 async for message in message.channel.history(limit=3): #get the PREVIOUS message of the user #print(message.content) if message.author == m_auth and prev_message == "" and counter >= 1: prev_message = message.content counter += 1 if m.startswith('$greeting'): #have bot say hello await message.channel.send('Hello!') if m.startswith('$quiz') and currentQuizTaker == "": #user initiates quiz bot print("entered45") #TODO check if they a quiz session is already active # check if user has a quiz in database and create a quiz object with that info if so q.user_name = a await message.channel.send('Hello ' + name + ', it\'s Quiz Time! Do you want to start a quiz, or create one? Type: $create or $start') elif currentQuizTaker == a and (prev_message == "$quiz" or q.creating_questions == False) and q.choosingQuiz == False and q.takingQuiz == False: print("entered78") if m.startswith('$create'): await message.channel.send('What should the name of the quiz be? Type: $<quiz name>') q.creating_questions = True if m.startswith('$start'): if q.printQuiz() == True: #if has quizzes on file, print out a list q.has_quiz = True count = 1 output = "" for i in range(len(q.quizzes)): #print(q.quizzes[i][0] + "FOUND-") if q.quizzes[i][0].find(str(count) + "$") != -1: #count occurences in form quiznum$ #print("found") #print(q[i][0].replace("$", ". ")) output = output + q.quizzes[i][0].replace("$", ". ") + " " count += 1 await message.channel.send(output) await message.channel.send("Here are a list of your quizzes.\nEnter $ <quiz number> to choose one ") q.choosingQuiz = True else: await message.channel.send("You do not have any quizzes!!!!") elif currentQuizTaker == a and (prev_message == "$create" or q.creating_questions == True) and q.takingQuiz == False: #where user can create questions, ###BUG, FIX CONDITIONALS print("entered") if q.creating_index == 0: q.new_quiz_questions.clear() q.quizCount += 1 q.new_quiz_questions.append(str(q.quizCount) + "$" + m) q.creating_index += 1 if m.startswith("$X") and q.creating_index == 2: # stop entering questions await message.channel.send("Quiz Saved!! Use $start command to start quiz!") q.quizCount += 1 q.creating_questions = False q.creating_index = 0 q.quizzes.append(q.new_quiz_questions) if q.creating_index == 1: # go back and forth with asking questions / getting answers until done await message.channel.send("Enter a Question or enter $X if done ") q.creating_index = 2 elif q.creating_index == 2: q.new_quiz_questions.append("Question: " + m) await message.channel.send("Enter the answer to the Question ") q.creating_index = 3 elif q.creating_index == 3: q.new_quiz_questions.append("ANSWER: " + m) q.creating_index = 2 await message.channel.send("Enter a Question or enter $X if done ") #TODO add method in quiz object that checks that parses $num and checks if there is a quiz with that number elif currentQuizTaker == a and m.startswith("$") and q.has_quiz == True and q.creating_questions == False and q.choosingQuiz == True: # When user is choosing the questions #print("entered24") try: s = m.split("$") q.current_quiz = int(s[1]) await message.channel.send("Starting Quiz") await message.channel.send(q.quizzes[int(q.current_quiz) - 1][q.current_quiz_quest + 1]) q.takingQuiz = True q.choosingQuiz = False except: await message.channel.send("Invalid Quiz Number. Enter choice as $<quiz number>") elif currentQuizTaker == a and q.has_quiz == True and q.creating_questions == False and q.takingQuiz == True: #when user is answering the question print("Quiz" + str(q.current_quiz) + "chosen") questions = len(q.quizzes[int(q.current_quiz) - 1]) - 1 # minus one since we show list starting at 1 and also since index 0 is for name only if questions != q.current_quiz_quest: if q.quizing_index == 0: q.current_quiz_quest = 0 await message.channel.send(q.quizzes[int(q.current_quiz) - 1][q.current_quiz_quest+ 2] ) # first answer await message.channel.send( "Enter $next to continue") q.current_quiz_quest += 2 q.quizing_index = 1 elif q.quizing_index == 1: await message.channel.send(q.quizzes[int(q.current_quiz) - 1][q.current_quiz_quest + 1]) #question q.quizing_index = 2 elif q.quizing_index == 2: await message.channel.send(q.quizzes[int(q.current_quiz) - 1][q.current_quiz_quest + 2]) #answer await message.channel.send( "Enter $next to continue") q.quizing_index = 1 q.current_quiz_quest += 2 else: await message.channel.send("Finished Quiz!!") await message.channel.send("Good Job!!") q.takingQuiz = False q.new_quiz_questions.clear() q.creating_index = 0 q.current_quiz = 0 q.current_quiz_quest = 0 #DEBUG-- #msg = await message.channel.history(limit = 5).get(author__name= name) #get the last message from user #print(msg.content) #print("PREVIOUS MESSAGE " + prev_message) #print("create index " + str(q.creating_index)) #Enter the bots key here. I removed mine here as it should not be public :) client.run("key") #run bot #discord.py docs https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.author
ae02115fe8dcf8601be35b9eb282d7a2088bd67e
recaedo/CTFs
/picoCTF/picoCTF_2019/Cryptography/The_Numbers/analysis.py
192
3.65625
4
flag = [16, 9, 3, 15, 3, 20, 6, 20, 8, 5, 14, 21, 13, 2, 5, 18, 19, 13, 1, 19, 15, 14] result = [] for n in flag: result.append(n % 26) if flag == result: print("Hello, world!")
c4871ea3c60a561260b3dcdf807fcf29d8739dd6
recaedo/CTFs
/picoCTF/picoCTF_2018/Cryptography/Crypto_Warmup_1/solve.py
1,734
3.875
4
text = "llkjmlmpadkkc" key = "thisisalilkey" def encrypt(plain, key): plain = list(plain) j = 0 for i in range(len(plain)): j %= len(key) if plain[i].islower(): if key[j].islower(): plain[i] = (ord(plain[i]) - 97 + ord(key[j]) - 97) % 26 elif key[j].isupper(): plain[i] = (ord(plain[i]) - 97 + ord(key[j]) - 65) % 26 plain[i] += 97 elif plain[i].isupper(): if key[j].islower(): plain[i] = (ord(plain[i]) - 65 + ord(key[j]) - 97) % 26 elif key[j].isupper(): plain[i] = (ord(plain[i]) - 65 + ord(key[j]) - 65) % 26 plain[i] += 65 else: plain[i] = ord(plain[i]) j += 1 return ''.join(map(chr, plain)) def decrypt(cipher, key): cipher = list(cipher) j = 0 for i in range(len(cipher)): j %= len(key) if cipher[i].islower(): if key[j].islower(): cipher[i] = (ord(cipher[i]) - ord(key[j])) % 26 elif key[j].isupper(): cipher[i] = (ord(cipher[i]) - 97 - ord(key[j]) + 65) % 26 if cipher[i] < 0: cipher[i] += 26 cipher[i] += 97 j += 1 elif cipher[i].isupper(): if key[j].islower(): cipher[i] = (ord(cipher[i]) - 65 - ord(key[j]) + 97) % 26 elif key[j].isupper(): cipher[i] = (ord(cipher[i]) - ord(key[j])) % 26 if cipher[i] < 0: cipher[i] += 26 cipher[i] += 65 j += 1 else: cipher[i] = ord(cipher[i]) return ''.join(map(chr, cipher)) print(decrypt(text, key))
c578023e68884af5ba50f88161e1d4f7c06ac81d
recaedo/CTFs
/picoCTF/picoCTF_2018/Cryptography/caesar_cipher_1/solve.py
1,018
3.875
4
text = "vgefmsaapaxpomqemdoubtqdxoaxypeo" def encrypt(plain, key): plain = list(plain) for i in range(len(plain)): if plain[i].islower(): plain[i] = (ord(plain[i]) - 97 + key) % 26 + 97 elif plain[i].isupper(): plain[i] = (ord(plain[i]) - 65 + key) % 26 + 65 else: plain[i] = ord(plain[i]) return ''.join(map(chr, plain)) def decrypt(cipher, key): cipher = list(cipher) for i in range(len(cipher)): if cipher[i].islower(): cipher[i] = (ord(cipher[i]) - 97 - key) % 26 if cipher[i] < 0: cipher[i] += 26 cipher[i] += 97 elif cipher[i].isupper(): cipher[i] = (ord(cipher[i]) - 65 - key) % 26 if cipher[i] < 0: cipher[i] += 26 cipher[i] += 65 else: cipher[i] = ord(cipher[i]) return ''.join(map(chr, cipher)) for key in range(1, 26): print("%2d: " % key + "picoCTF{"+encrypt(text, key)+"}")
5b09f190c2d6abad62be8ce900bddd9cf9103087
YovieYulian/aassdw
/class atribute.py
333
3.578125
4
class persons(): def __init__ (self,nama,umur): self.nama = nama self.umur = umur def setname(self,namabaru) : self.nama=namabaru def getnama(self) : return self.nama orang1=persons('aki',17) print(orang1.nama) print(orang1.umur) orang1.setname('sujo') print(orang1.getnama())
7c26da8af224c3c6452198be5a2228fac2a84117
ezequielfrias20/exam-mutant
/src/mutant.py
3,210
3.796875
4
''' Funcion que permite ver si una persona es mutante o no, tiene como parametro una lista y devuelve True si es mutante o False si no lo es ''' def Mutant(adn): try: ''' Funcion que permite verificar si la matriz es correcta siendo NxN y que solo tenga las letras A T C G. Devuelve True si todo esta correcto ''' def check(adn): contador=0 verificacion=0 for elemento in adn: for letra in elemento: if letra=="A" or letra=="T" or letra=="C" or letra=="G": contador+=1 if contador!=len(adn): raise Exception else: verificacion+=1 contador=0 return verificacion==len(adn) ''' Esta funcion permita verificar si es mutante de manera horizontal ''' def is_mutant_horizontal(adn): mutacion=False for elemento in adn: for letra in elemento: if elemento.count(letra)>=4: mutan=letra+letra+letra+letra if mutan in elemento: mutacion= True break return mutacion ''' Esta funcion permite crear una nueva lista con los valores verticales y se aplica la funcion is_mutant_horizontal ''' def is_mutant_vertical(adn): vertical="" new_adn=[] for i in range(len(adn)): for a in range(len(adn)): vertical+=adn[a][i] new_adn.append(vertical) vertical="" return is_mutant_horizontal(new_adn) ''' funcion que permite encontrar las diagonales de la matriz ''' def get_diagonals(matrix): n = len(matrix) # diagonals_1 = [] # lower-left-to-upper-right diagonals # diagonals_2 = [] # upper-left-to-lower-right diagonals for p in range(2*n-1): yield [matrix[p-q][q] for q in range(max(0, p - n + 1), min(p, n - 1) + 1)] yield [matrix[n-p+q-1][q] for q in range(max(0, p - n + 1), min(p, n - 1) + 1)] ''' Esta funcion permite crear una nueva lista con los valores de todas las diagonales y se aplica la funcion is_mutant_horizontal para ver si es mutante ''' def is_mutant_oblicua(adn): new=[] new_word="" for i in get_diagonals(adn): for element in i: new_word+=element new.append(new_word) new_word="" return is_mutant_horizontal(new) check(adn) if is_mutant_horizontal(adn): return True elif is_mutant_oblicua(adn): return True elif is_mutant_vertical(adn): return True else: return False except Exception: return None
291ce4c80a528eebc116dee6feff782222c5ecef
444aman/Nmd_vpn-Automatic-Update
/Nmd_vpn.py
1,302
3.59375
4
import urllib2 import os response = urllib2.urlopen('https://twitter.com/vpnbook') html = response.read() #reads whole page in html format and save it to html variable def blank_lines(): #for removing blank lines Lines1=open("Data.txt").readlines() Lines=[x for x in Lines1 if x.strip()] open("Data.txt","w").writelines(Lines) f=open("Data.txt",'w') f.write(html) #save html format in txt file blank_lines() f.close() search='Password:' f=open("Data.txt",'r') for i in f.readlines(): if search in i: #will match string Password: in file temp=i.strip() #if string Found will store those line in temp variable break #as we want the latest Password Updated so as soon it is found we break the loop temp=temp.replace('</p>','') #at the end of the line it will remove tht temp1=temp.index(search) temp2=temp[temp1:] temp3=temp2.index(':') temp3+=1 temp4=temp2[temp3:] final=temp4.strip() print final #here we will get the Final Password We have been looking For raw_input("Press Any Key To Update Password ") f.close() f=open('C:\Program Files (x86)\NMDVPN\config\pass.txt','w') f.write('vpnbook') f.write('\n') f.write(final) f.close() print 'Password Updated Sucessfully ' raw_input("Press Any Key To Quit This Application ") os.remove('Data.txt')
e136f84abb4f0e9070fb7ae254ec1390ee53ef22
RuzannaKusikyan/Intro-to-Python
/Lecture 1/Practical/Problem4.py
106
3.890625
4
AB = 3 AC = 4 import math BC = int(math.sqrt(AB**2+AC**2)) print("The hypotenuse of the triangle ABC:",BC)
43486f405621613de5d973ecfa3dfed21356969f
Adil-Anzarul/VSC-codes-c-cpp-python
/python_language/W11p2.py
1,257
4.75
5
# Give a string, remove all the punctuations in it and print only the words # in it. # Input format : # the input string with punctuations # Output format : # the output string without punctuations # Example # input # “Wow!!! It’s a beautiful morning” # output # Wow Its a beautiful morning # # Python Program for # # Creation of String # # Creating a String # # with single Quotes # String1 = 'Welcome to the Geeks World' # print("String with the use of Single Quotes: ") # print(String1) # # Creating a String # # with double Quotes # String1 = "I'm a Geek" # print("\nString with the use of Double Quotes: ") # print(String1) # # Creating a String # # with triple Quotes # String1 = '''I'm a Geek and I live in a world of "Geeks"''' # print("\nString with the use of Triple Quotes: ") # print(String1) # # Creating String with triple # # Quotes allows multiple lines # String1 = '''Geeks # For # Life''' # print("\nCreating a multiline String: ") # print(String1) string=input() punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' for x in string.lower(): if x in punctuations: string = string.replace(x, "") print(string,end="")
ddce169af5d2b344a2d3ce1e4e90a8c381f767af
Adil-Anzarul/VSC-codes-c-cpp-python
/python_language/W9p2.py
949
4.1875
4
# Panagrams # Given an English sentence, check whether it is a panagram or not. # A panagram is a sentence containing all 26 letters in the English alphabet. # Input Format # A single line of the input contains a stirng s. # Output Format # Print Yes or No # Example: # Input: # The quick brown fox jumps over a lazy dog # Output: # Yes # Input: # The world will be taken over by AI # Output: # No l = input().lower() s = 'abcdefghijklmnopqrstuvwxyz' for i in s: if i not in l: print('No',end='') break else: print('Yes',end='') # import string as st # s=list(input().upper()) # if list(st.ascii_uppercase) == sorted(list(set(sorted(s)[sorted(s).index('A'):]))): # print("Yes",end="") # else: # print('No',end="") # # import string library function # import string # # Storing the value in variable result # result = string.ascii_uppercase # # Printing the value # print(result) # print(type(result))
d7303089dc5042589ae42bd13cb1d726dadff9c3
Adil-Anzarul/VSC-codes-c-cpp-python
/python_language/W6p1.py
822
3.875
4
# Number Triangle-2 # Given an integer input 'n', print a palindromic number triangle # of n lines as # shown in the example. # Input Format # The input contains a number n (n < 10) # Output Format # Print n lines corresponding to the number triangle # Example: # Input: # 5 # Output: # 1 # 121 # 12321 # 1234321 # 123454321 # Explanation: n th line of the triangle contains a palindromic number # of length 2n-1 a=int(input()) for i in range(1,a+1): for j in range(1,i+1): print(j,end="") for k in range(i-1,0,-1): print(k,end="") print() # n=int(input()) # for i in range(0,n): # for j in range(0,i+1): # print(j+1,end="") # for k in range(0,i): # print(i-k,end="") # print() # n = int(input()) # for i in range(1,n+1): print((((10**i)-1)//9)**2)
0bb8e4550ae5e032beb28daceb741bbe6834bfda
Adil-Anzarul/VSC-codes-c-cpp-python
/python_language/W4p1.py
1,000
3.84375
4
#Two friends Suresh and Ramesh have m red candies and n green candies #respectively. They want to arrange the candies in such a way that each #row contains equal number of candies and also each row should have only red #candies or green candies. Help them to arrange the candies in such a way # that there are maximum number of candies in each row. #The first line contains m number of red candies Suresh has #The second line contains n number of green candies Ramesh has #Print maximum number of candies that can be arranges in each row. def compute_hcf(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf num1 = int(input()) num2 = int(input()) print(compute_hcf(num1, num2)) """ (m,n,pro)=(int(input()),int(input()),1) vmin=min(m,n) for i in range(1 ,vmin+1): if m% i==0 and n% i ==0: pro=i print(pro,end="") """
fbc33061f8d425faf946cd9cf51b1fce77e52c5f
ahmed-abdulaal/docstr-md
/docstr_md/src_href/github.py
1,439
3.578125
4
class Github(): """ Compiles a hyperlink for source code stored in a Github repository. Parameters ---------- root : str Path to the root directory of the source code. e.g. `'https://github.com/<username>/blob/master'`. Attributes ---------- root : str Set from the `root` parameter. Examples -------- ```python from docstr_md.python import PySoup, compile_md from docstr_md.src_href import Github src_href = Github('https://github.com/my-username/my-package/blob/master') soup = PySoup(path='path/to/file.py', src_href=src_href) md = compile_md(soup) ``` `md` is a string of compiled markdown with source code links in the class and function headers. """ def __init__(self, root): if not root.endswith('/'): root += '/' self.root = root def __call__(self, obj): """ Compile the hyperlink for the source code of the input object. Parameters ---------- obj : docstr_md.soup_objects.FunctionDef or ClassDef Soup object to whose souce code we are linking. Returns ------- href : str Hyperlink of the form `'<root>/<src_path>#L<lineno>'`. """ return '{root}{src_path}#L{lineno}'.format( root=self.root, src_path=obj.src_path, lineno=obj.lineno, )
b17e385011d88d48869af98706b12b924d46fca4
jachsu/Tower-of-Hanoi
/tour.py
4,589
3.734375
4
""" functions to run TOAH tours. """ # Copyright 2013, 2014, 2017 Gary Baumgartner, Danny Heap, Dustin Wehr, # Bogdan Simion, Jacqueline Smith, Dan Zingaro # Distributed under the terms of the GNU General Public License. # # This file is part of Assignment 1, CSC148, Winter 2017. # # This is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this file. If not, see <http://www.gnu.org/licenses/>. # Copyright 2013, 2014 Gary Baumgartner, Danny Heap, Dustin Wehr # you may want to use time.sleep(delay_between_moves) in your # solution for 'if __name__ == "main":' import time from toah_model import TOAHModel def tour_of_four_stools(model, delay_btw_moves=0.5, animate=False): """Move a tower of cheeses from the first stool in model to the fourth. @type model: TOAHModel TOAHModel with tower of cheese on first stool and three empty stools @type delay_btw_moves: float time delay between moves if console_animate is True @type animate: bool animate the tour or not """ n = model.get_number_of_cheeses() for move in move_of_four(n, 0, 1, 2, 3): if animate: model.move(move[0], move[1]) print(model) time.sleep(delay_btw_moves) else: model.move(move[0], move[1]) def m(n): """ return the minimum number of moves needed to move n cheeses from stool 0 to stool 3. @type n: int @rtype: int """ l = [] if n <= 2: return 2**n-1 else: for i in range(1, n): l.append(2*m(n - i) + 2**i - 1) return min(l) def get_i(n): """ return the special number i so that m(n) is the minimum. precondition: n >= 2 @type n: int @rtype: int """ l = [] for i in range(1, n): l.append(2*m(n - i) + 2**i - 1) if min(l) == m(n): return i def move_of_four(n, source, inter1, inter2, dest): """ return a list of moves which takes the least steps to move n cheeses from source to dest through inter1 and inter2. @type n: int @type source: int @type inter1: int @type inter2: int @type dest: int @rtype: list """ l = [] if n == 1: l.append([source, dest]) elif n == 2: l.append([source, inter1]) l.append([source, dest]) l.append([inter1, dest]) elif n == 3: if l == []: # 2 inters l.append([source, inter1]) l.append([source, inter2]) l.append([source, dest]) l.append([inter2, dest]) l.append([inter1, dest]) else: l += move_of_three(n, source, inter2, dest) if n > 3: # move n-i cheeses from src to inter1 l += move_of_four(n - get_i(n), source, dest, inter2, inter1) # move i cheeses from src to dest, stool 1 occupied l += move_of_three(get_i(n), source, inter2, dest) # move n-i cheeses from inter 1 to dest l += move_of_four(n - get_i(n), inter1, source, inter2, dest) return l # credit to prof Danny Heap def move_of_three(n, source, intermediate, destination): """Move n cheeses from source to destination in the model of three stools @param int n: @param int source: @param int intermediate: @param int destination: @rtype: None """ l = [] if n > 1: l += move_of_three(n - 1, source, destination, intermediate) l += move_of_three(1, source, intermediate, destination) l += move_of_three(n - 1, intermediate, source, destination) else: l.append([source, destination]) return l if __name__ == '__main__': num_cheeses = 8 delay_between_moves = 0.5 console_animate = True four_stools = TOAHModel(4) four_stools.fill_first_stool(number_of_cheeses=num_cheeses) tour_of_four_stools(four_stools, animate=console_animate, delay_btw_moves=delay_between_moves) print(four_stools.number_of_moves()) # File tour_pyta.txt must be in same folder import python_ta python_ta.check_all(config="tour_pyta.txt")
cb5dfa15e842564de905077495ef235aa2393145
Prudhvi-raj/embl
/Coding_python_Q_1.py
2,119
3.953125
4
# Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. import xml.etree.ElementTree as ET import pandas as pd import numpy as np xml = '''<?xml version="1.0" encoding="UTF-8"?> <MedlineCitationSet> <Article> <ArticleTitle>Title 1</ArticleTitle> <AuthorList> <Author> <LastName>Public</LastName> <ForeName>J Q</ForeName> <Initials>JQ</Initials> </Author> <Author> <LastName>Doe</LastName> <ForeName>John</ForeName> <Initials>J</Initials> </Author> </AuthorList> </Article> <Article> <ArticleTitle>Title 2</ArticleTitle> <AuthorList> <Author> <LastName>Doe</LastName> <ForeName>John</ForeName> <Initials>J</Initials> </Author> <Author> <LastName>Doe</LastName> <ForeName>Jane</ForeName> <Initials>J</Initials> </Author> </AuthorList> </Article> <Article> <ArticleTitle>Title 3</ArticleTitle> <AuthorList> <Author> <LastName>Doe</LastName> <ForeName>Jane</ForeName> <Initials>J</Initials> </Author> <Author> <LastName>Public</LastName> <ForeName>J Q</ForeName> <Initials>JQ</Initials> </Author> </AuthorList> </Article> <Article> <ArticleTitle>Title 4</ArticleTitle> <AuthorList> <Author> <LastName>Smith</LastName> <ForeName>John</ForeName> <Initials>J</Initials> </Author> <Author> <LastName>Doe</LastName> <ForeName>John</ForeName> <Initials>J</Initials> </Author> </AuthorList> </Article> </MedlineCitationSet> ''' tree = ET.fromstring(xml) list_names = [] for node in tree.iter('AuthorList'): author_names = [] for each_author in node.iter('Author'): author_names.append(each_author[0].text+" "+each_author[1].text) list_names.append(author_names) u = (pd.get_dummies(pd.DataFrame(list_names), prefix='', prefix_sep='') .groupby(level=0, axis=1) .sum()) v = u.T.dot(u) # df_names = pd.DataFrame(list_names, columns = ['Name_1', 'Name_2']) print(v)
13d065bf569f9e553556c9372059031d044cf713
mattkjames7/FieldTracing
/FieldTracing/RK4/RK4Step.py
777
3.625
4
import numpy as np def RK4Step(x0,dt,fv,direction=1.0): ''' This Function returns the step taken along the field provided by the function 'fv' using the Runge-Kutta 4th order method. Inputs ====== x0 : float Initial location vector. dt : float Step size. fv : callable Callable function which provides a field vector given a positional vector. direction : float Direction in which to trace, +1.0 will trace along the field direction, -1.0 will trace in the opposite direction. Returns ======= x1 : float New positional vector of the same form as x0. ''' v0 = direction*fv(x0) v1 = direction*fv(x0 + 0.5*dt*v0) v2 = direction*fv(x0 + 0.5*dt*v1) v3 = direction*fv(x0 + dt*v1) x1 = x0 + dt*(v0 + 2.0*v1 + 2.0*v2 + v3)/6.0 return x1
525d09b9016cef48b3a332c19759ce116dcd4121
chokpisit/pist
/month2016.py
443
3.515625
4
import pandas as pd data = pd.read_csv("bakery_update.csv") dictmonth = {} for i in range(len(data)): check = data['Date'][i] if '2016' in check: if len(check) == 10: month = check[3:5] if month not in dictmonth: dictmonth[month] = 1 else: dictmonth[month] += 1 else: month = check[2:4] if month not in dictmonth: dictmonth[month] = 1 else: dictmonth[month] += 1 print(dictmonth)
bd9c25fa4e68dbe602ea0dd62ac339ef8568c96f
simvisage/bmcs
/simulator/demo/interaction_scripts.py
766
3.65625
4
''' Created on Jan 9, 2019 @author: rch ''' import time def run_rerun_test(s): # Start calculation in a thread print('\nRUN the calculation thread from t = 0.0') s.run_thread() print('\nWAIT in main thread for 3 secs') time.sleep(3) print('\nPAUSE the calculation thread') s.pause() print('\nPAUSED wait 1 sec') time.sleep(1) print('\nRESUME the calculation thread') s.run_thread() print('\nWAIT in the main thread for 3 secs again') time.sleep(3) print('\nSTOP the calculation thread') s.stop() print('\nRUN a new calculation thread from t = 0.0') s.run_thread() print('\nJOIN the calculation thread into main thread to end simultaneously') s.join_thread() print('END all threads')
5152604c575032c3175edd9cfdd719eff002acdb
ArpanMahatra1999/NewsAnalysis
/news/emotion_counter/remove_special_characters.py
208
3.953125
4
import re # input: string of characters # output: string of characters without special characters def remove_special_characters(text): new_text = re.sub(r"[^a-zA-Z0-9\s]", "", text) return new_text
60f5ab2d39a8249b25f74e0e10601a05aaa09b7d
adamrodger/google-foobar
/4-1.py
1,195
3.75
4
from itertools import combinations def solution(num_buns, num_required): """ approach: - you have n bunnies - you require exactly r bunnies in order to open the doors (i.e. there are that many consoles) - r choose k is combinatorics - learned that in Project Euler :) - so, k = n-r+1 - e.g. n=2 and r=2 == 1 copy of each key, which makes sense becaue it's [[0], [1]] - the example with n=5, r=3 makes that clearer - each key appears exactly 3 times (5-3+1) - 5 choose 3 == 10 so the keys are 0-9 - so, for each combination of k bunnies, make sure that combination has a key that no other combination has """ bunnies = [[] for bunny in xrange(num_buns)] # divide the bunnies into combinations of k size - i.e. each bunny will appear in multiple groups k = num_buns - num_required + 1 groups = combinations(bunnies, k) # everyone in a group gets a key matching the group ID for key, group in enumerate(groups): for bunny in group: bunny.append(key) # fortunately this is already formatted properly for the required output return bunnies if __name__ == "__main__": print solution(5, 3)
24759baf978403b0711b4e45834bd24cd8d2be13
okorchevaya/infa_2020_okorchevaya
/catch_the_ball_2.py
2,990
3.65625
4
import pygame from pygame.draw import * from random import randint pygame.init() FPS = 40 screen = pygame.display.set_mode((1200, 800)) length=1200 height=800 change = [-4, -3, -2, -1, 1, 2, 3, 4] RED = (255, 0, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) GREEN = (0, 255, 0) MAGENTA = (255, 0, 255) CYAN = (0, 255, 255) BLACK = (0, 0, 0) COLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN] points = 0 def new_balls(x,y,r, color): circle(screen, color, (x, y), r) clock = pygame.time.Clock() finished = False click = False click1 = False def running_ball(): finished=False score = 0 while not finished: x = randint(1, 500) y = randint(1, 500) r = randint(10, 50) color = COLORS[randint(0, 5)] del_x = change[randint(1, 5)] del_y = change[randint(1, 5)] x1 = randint(1, 500) y1 = randint(1, 500) r1 = randint(10, 50) color1 = COLORS[randint(0, 5)] del_x1 = change[randint(1, 5)] del_y1 = change[randint(1, 5)] click = False click1 = False while (finished == False) and (click == False or click1 == False): if click == False: new_balls(x, y, r, color) x +=del_x y +=del_y if click1 == False: new_balls(x1, y1, r1, color1) x1 += del_x1 y1 += del_y1 clock.tick(FPS) #отталкивание от стен if y+r >= height or y-r <= 0: del_y = del_y * (-1) if x+r >= length or x-r <= 0: del_x = del_x*(-1) if y1+r1 >= height or y1-r1 <= 0: del_y1= del_y1 * (-1) if x1+r1 >= length or x1-r1 <= 0: del_x1 = del_x1*(-1) pygame.display.update() screen.fill(BLACK) for event in pygame.event.get(): if event.type == pygame.QUIT: finished = True elif event.type == pygame.MOUSEBUTTONDOWN: print('Click') if (x - event.pos[0]) ** 2 + (y - event.pos[1]) ** 2 <= r ** 2: score += 1 x = randint(1, 500) y = randint(1, 500) r = randint(10, 50) color = COLORS[randint(0, 5)] del_x = change[randint(1, 5)] del_y = change[randint(1, 5)] if (x1 - event.pos[0]) ** 2 + (y1 - event.pos[1]) ** 2 <= r1 ** 2: score += 1 x1 = randint(1, 500) y1 = randint(1, 500) r1 = randint(10, 50) color1 = COLORS[randint(0, 5)] del_x1 = change[randint(1, 5)] del_y1 = change[randint(1, 5)] running_ball() running_ball1() pygame.quit()
880f5e82814c5b2bf94504b3cfd787178392c591
okorchevaya/infa_2020_okorchevaya
/labs_1-3/lesson2.12.py
283
3.6875
4
import turtle as tur import numpy as np tur.shape('turtle') tur.speed(9) tur.left(90) def arch(halfr): ag=6 n=(np.pi*halfr**2/180*ag) for i in range(180//ag): tur.left(ag) tur.forward(n) while 2>1: arch(10) arch(5)
188f0afaf07e30c9ae7be8d478babe302eda49b8
sandro272/Data_Structure_with_Python
/03_double_link_list.py
4,238
3.859375
4
#! /usr/bin/env python # _*_coding:utf-8_*_ # project: Data_Structure_with_Algorithm_python # Author: zcj # @Time: 2019/11/12 11:42 class DoubleNode(object): '''双向链表的节点''' def __init__(self, item): self.elem = item self.next = None self.prior = None class DoubleLinkList(object): '''双向链表''' def __init__(self, double_node = None): self.__head = double_node def is_empty(self): '''链表是否为空''' return self.__head is None def length(self): '''链表长度''' cur = self.__head count = 0 while cur != None: count += 1 cur = cur.next return count def travel(self): '''遍历链表''' cur = self.__head while cur != None: print(cur.elem, end = " ") cur = cur.next print("") def add(self, item): '''链表头部添加''' node = DoubleNode(item) if self.is_empty(): # 如果是空链表,将_head指向node self.__head = node else: # 将node的next指向_head的头节点 node.next = self.__head # 将_head的头节点的prev指向node self.__head.prior = node # 将_head 指向node self.__head = node def append(self, item): '''链表尾部添加''' node = DoubleNode(item) if self.is_empty(): # 如果是空链表,将_head指向node self.__head = node else: cur = self.__head # 移动到链表尾部 while cur.next != None: cur = cur.next # 将尾节点cur的next指向node cur.next = node # 将node的prev指向cur node.prior = cur def insert(self, pos, item): '''指定位置添加 :param pos从0开始 ''' if pos <= 0: self.add(item) elif pos > (self.length() - 1): self.append(item) else: node = DoubleNode(item) cur = self.__head count = 0 # 移动到指定位置的前一个位置 while count < pos: count += 1 cur = cur.next node.next = cur node.prior = cur.prior cur.prior.next = node cur.prior = node def remove(self, item): '''删除节点''' cur = self.__head while cur != None: if cur.elem == item: #如果要删除的是链表的第一个节点 if cur == self.__head: self.__head = cur.next # 判断链表是否仅有一个节点 if cur.next: cur.next.prior = None else: cur.prior.next = cur.next if cur.next: cur.next.prior = cur.prior break else: cur = cur.next def search(self, item): '''查找节点是否存在''' cur = self.__head while cur != None: if cur.elem == item: return True else: cur = cur.next return False if __name__ == "__main__": link = DoubleLinkList() print(link.is_empty()) # True print(link.length()) # 0 link.append(1) print(link.is_empty()) # False print(link.length()) # 1 link.append(2) link.add(8) link.insert(-1, 10) link.travel() # 10 8 1 2 link.insert(0, 15) link.travel() # 15 10 8 1 2 link.insert(4, 20) link.travel() # 15 10 8 1 20 2 link.insert(9, 25) link.travel() # 15 10 8 1 20 2 25 link.insert(7, 30) link.travel() # 15 10 8 1 20 2 25 30 link.append(3) link.append(4) link.append(5) link.travel() # 15 10 8 1 20 2 25 30 3 4 5 print(link.search(100)) # False print(link.search(20)) # True link.remove(5) link.travel() link.remove(15) link.travel() link.remove(1) link.travel()
b49ba0c8e5015a86efe80a932459d52fb733828f
ashwindasr/Jet-Brains-Academy
/Python/Simple-Chatty-Bot/Stage_3/code.py
870
3.984375
4
# write your code here class SimpleChattyBot: user_name = None user_age = None def __init__(self, name, birth_year): self.name = name self.birth_year = birth_year def greeting(self): print(f"""Hello! My name is {self.name}. I was created in {self.birth_year}.""") def get_user_name(self): self.user_name = input("Please, remind me your name.\n") print(f"What a great name you have, {self.user_name}!") def guess_age(self): print("Let me guess your age.\nEnter remainders of dividing your age by 3, 5 and 7.") self.user_age = (int(input()) * 70 + int(input()) * 21 + int(input()) * 15) % 105 print(f"Your age is {self.user_age}; that's a good time to start programming!") bot = SimpleChattyBot("Jarvis", 2020) bot.greeting() bot.get_user_name() bot.guess_age()
d5fad4bc865112b86a3d80e07b06fef4b2dd71c9
ashwindasr/Jet-Brains-Academy
/Python/Coffee-Machine/Stage_4/code.py
1,899
4.0625
4
# Write your code here water_current = 400 milk_current = 540 coffee_current = 120 money_current = 550 cups_current = 9 def take(): global money_current print("I gave you ${}".format(money_current)) money_current = 0 def buy(): global water_current, milk_current, coffee_current, money_current, cups_current choice = int(input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino:\n")) if choice == 1: water_current -= 250 coffee_current -= 16 money_current += 4 elif choice == 2: water_current -= 350 milk_current -= 75 coffee_current -= 20 money_current += 7 else: water_current -= 200 milk_current -= 100 coffee_current -= 12 money_current += 6 cups_current -= 1 def fill(): global water_current, milk_current, coffee_current, money_current, cups_current water_current += int(input("Write how many ml of water do you want to add:\n")) milk_current += int(input("Write how many ml of milk do you want to add:\n")) coffee_current += int(input("Write how many grams of coffee beans do you want to add:\n")) cups_current += int(input("Write how many disposable cups of coffee do you want to add:\n")) print("The coffee machine has:") print(str(water_current) + " of water") print(str(milk_current) + " of milk") print(str(coffee_current) + " of coffee beans") print(str(cups_current) + " of disposable cups") print(str(money_current) + " of money") action = input("Write action (buy, fill, take):\n") if action == 'buy': buy() elif action == 'fill': fill() else: take() print("The coffee machine has:") print(str(water_current) + " of water") print(str(milk_current) + " of milk") print(str(coffee_current) + " of coffee beans") print(str(cups_current) + " of disposable cups") print(str(money_current) + " of money")
336ec37e4eca607217d7d91b9ac4fe0ce89ec079
ashwindasr/Jet-Brains-Academy
/Python/Rock-Paper-Scissors/Stage_2/code.py
589
3.921875
4
# Write your code here import random def check(player_move_): disadvantage = {"paper": "scissors", "rock": "paper", "scissors": "rock"} moves = ["rock", "paper", "scissors"] computer_move = random.choice(moves) if disadvantage[player_move_] == computer_move: print(f"Sorry, but computer chose {computer_move}") elif player_move_ == computer_move: print(f"There is a draw ({computer_move})") else: print(f"Well done. Computer chose {computer_move} and failed") if __name__ == '__main__': player_move = input() check(player_move)
6f95a955b620917840231a1df936faa9276e5e2d
tamasgal/python_project_template
/foo/tests/test_bar.py
1,339
3.59375
4
#!usr/bin/env python # -*- coding: utf-8 -*- # Filename: test_bar.py from unittest import TestCase from foo.bar import whats_the_meaning_of_life, calculate_mean __author__ = "Your Name" __credits__ = [] __license__ = "MIT" __maintainer__ = "Jürgen" __email__ = "yname@km3net.de" class TestMeaningOfLife(TestCase): """Tests for the bar module""" def test_meaning_of_life(self): assert 42 == whats_the_meaning_of_life() def test_meaning_of_life_with_one_core(self): assert 42 == whats_the_meaning_of_life(n_cores=1) class TestCalculateMean(TestCase): """Tests for the calculate_mean function""" def test_calculate_mean_of_a_single_number_returns_the_number_itself(self): assert 0 == calculate_mean([0]) assert 1 == calculate_mean([1]) assert 2 == calculate_mean([2]) assert -1 == calculate_mean([-1]) assert 1.5 == calculate_mean([1.5]) def test_calculate_mean_returns_mean_of_a_list_of_numbers(self): assert 2 == calculate_mean([1, 2, 3]) assert 3 == calculate_mean([1, 2, 3, 4, 5]) def test_calculate_mean_returns_correct_value_for_negative_numbers(self): assert -3 == calculate_mean([-1, -2, -3, -4, -5]) def test_calculate_mean_of_some_other_numbers(self): self.assertAlmostEqual(2.5, calculate_mean([1, 2, 3, 4]))
f24199e1370b17f6ba250e31db0c817228f1e33d
marysom/stepik
/adaptive python/2_159.py
169
3.78125
4
''' Write a program: input of this program has a single line with integers. The program must output the sum of these numbers. ''' print(sum(map(int, input().split())))
6395703c2fc90856fe635294a7a00467c3221df6
marysom/stepik
/adaptive python/2_4.py
594
3.703125
4
'''MKAD The length of the Moscow Ring Road (MKAD) is 109 kilometers. Biker Vasya starts from the zero kilometer of MKAD and drives with a speed of V kilometers per hour. On which mark will he stop after T hours? Input data format The program gets integers V and T as input. If V > 0, then Vasya moves in a positive direction along MKAD, if the value of V < 0 – in the negative direction. 0 ≤ T ≤ 1000, -1000 ≤ V ≤ 1000. Output data format The program should output an integer from 0 to 108 - the mark on which Vasya stops. ''' V = int(input()) T = int(input()) print(T*V % 109)
60ef604f4946af95f38f5fe00cb47f2d35d1ea77
michal-swiatek/Checkers
/board.py
4,090
3.734375
4
""" Authors: Michal Swiatek, Jan Wasilewski Github: https://github.com/michal-swiatek/Checkers """ import itertools from pieces import Piece, Man class Board: """ Represents current board state Board holds all currently active pieces and generates representation of current game state """ def __init__(self): """ Initializes board with predefined set of pieces """ self.white_pieces = [] self.black_pieces = [] # White pieces for y in range(3): for x in range(8): if (x + y) % 2 == 0: self.white_pieces.append(Man(Piece.WHITE, x, y)) # Black pieces for y in range(5, 8): for x in range(8): if (x + y) % 2 == 0: self.black_pieces.append(Man(Piece.BLACK, x, y)) def getPieces(self, color): """ Returns list of pieces of specified color """ if color == Piece.WHITE: return self.white_pieces else: return self.black_pieces def generateBitmap(self): """ Generates bitmap representation of current board state Bitmap consists of True/False values representing WHITE and BLACK pieces as well as None values that represent empty tile :return: 8x8 matrix """ bitmap = [[None for columns in range(8)] for rows in range(8)] for white_piece, black_piece in itertools.zip_longest(self.white_pieces, self.black_pieces): if white_piece is not None: if not white_piece.captured: bitmap[white_piece.x][white_piece.y] = white_piece.white else: bitmap[white_piece.x][white_piece.y] = not white_piece.white if black_piece is not None: if not black_piece.captured: bitmap[black_piece.x][black_piece.y] = black_piece.white else: bitmap[black_piece.x][black_piece.y] = not black_piece.white return bitmap def generateBoardState(self): """ Generates current board representation that holds all board info Builds an 8x8 grid holding pieces at their positions and None values representing empty tiles :return: 8x8 matrix """ grid = [[None for i in range(8)] for i in range(8)] for white_piece, black_piece in itertools.zip_longest(self.white_pieces, self.black_pieces): if white_piece is not None: grid[white_piece.x][white_piece.y] = white_piece if black_piece is not None: grid[black_piece.x][black_piece.y] = black_piece return grid def display(self): """ Draws the board in console """ grid = self.generateBoardState() row = 7 print(" ###################", end='') while row >= 0: column = 0 print("\n", row, "#", end='') while column < 8: if grid[column][row] is None: if (row + column) % 2 == 0: print(" +", end='') else: print(" .", end='') elif grid[column][row].captured: print(" @", end='') else: print(' ', grid[column][row].displayCharacter(), sep='', end='') column = column + 1 print(" #", end='') row = row - 1 print("\n", " ###################", "\n", " 0 1 2 3 4 5 6 7") def clearCaptured(self): """ Removes captured pieces from the board """ for i in range(len(self.white_pieces) - 1, -1, -1): if self.white_pieces[i].captured: self.white_pieces.remove(self.white_pieces[i]) for i in range(len(self.black_pieces) - 1, -1, -1): if self.black_pieces[i].captured: self.black_pieces.remove(self.black_pieces[i])
e18ff86e0a36fedea4fea3e8079e2c75bd92be40
jfhiguita/Retos-Python
/password_generator.py
780
3.84375
4
import random import string def _pass_generator(n): upper_letters = [random.choice(string.ascii_uppercase) for _ in range(int(n*0.3))] lower_letters = [random.choice(string.ascii_lowercase) for _ in range(int(n*0.3))] digits = [random.choice(string.digits) for _ in range(int(n*0.2))] special = [random.choice(string.punctuation) for _ in range(int(n*0.2))] contrasena = upper_letters + lower_letters + digits + special random.shuffle(contrasena) contrasena = "".join(contrasena) return contrasena def run(): n = 0 while (n < 5): n = int(input("How many characters? (minimiun 5 characters): ")) contrasena = _pass_generator(n) print(contrasena) if __name__ == '__main__': run()
16e9fea85b75f97f53cdc6a057b527aa80263fcf
jfhiguita/Retos-Python
/ejer23.py
885
3.609375
4
def file_txt(filename): lista = [] with open(filename) as f: line = f.readline() while line: lista.append(int(line)) line = f.readline() return lista def run(): list1 = file_txt('lista1_exe23.txt') list2 = file_txt('lista2_exe23.txt') overlap = [item for item in list1 if item in list2] print(overlap) # list1 = [] # with open('lista1_exe23.txt', 'r') as lista1: # line = lista1.readline() # while line: # list1.append(int(line)) # line = lista1.readline() # list2 = [] # with open('lista2_exe23.txt', 'r') as lista2: # line = lista2.readline() # while line: # list2.append(int(line)) # line = lista2.readline() if __name__ == '__main__': run()
2b567d87483eee160ca326be15ea086c52ff95a3
jfhiguita/Retos-Python
/ejer6.py
679
4.09375
4
def _palindrome(text): text = text.lower() text = text.replace(' ', '') left, right = 0, len(text)-1 while left < right: if text[left] != text[right]: return False left += 1 right -= 1 return True # reverse_text = text[::-1] # if text == reverse_text: # return True # else: # return False def run(): text = input('Tell me a string: ') palindrome = _palindrome(text) if palindrome: message = print('YES...it\'s a palindrome!!!') else: message = print('NOOOOOooo...it\'s not a palindrome!!!') return message if __name__ == '__main__': run()
ae8af934709defb6386c1ecc93423fec0d92f3d7
camilacvieira/Sorting-Algorithms-Analysis
/algorithms/bogoSort.py
698
3.921875
4
import random # Sorts array a[0..n-1] using Bogo sort def bogoSort(arr): count = 0 result, count = isSorted(arr) while (result == False): shuffle(arr) result, comparisons = isSorted(arr) count = count + comparisons return count # To check if array is sorted or not def isSorted(arr): n = len(arr) count = 0 for i in range(0, n - 1): count = count + 1 if (arr[i] > arr[i+1] ): return [False, count] return [True, count] # To generate permutation of the array def shuffle(arr): n = len(arr) for i in range (0,n): r = random.randint(0,n-1) arr[i], arr[r] = arr[r], arr[i]
aea50fb6f8be9c7e0df30010831eb079ca003fe6
DEEKSHANT-123/Compititive-Coding
/Heackerearth/Basic of IO/Zoos.py
97
3.671875
4
s = input() x = s.count('z') y = s.count('o') if 2*x == y: print("YES") else: print("NO")
d0f779e9a8c0f669d769e6e810e6b0ab033306e2
RaisaAkter/Online_judge_Problem
/python_programming/uri1019.py
209
3.734375
4
N=int(input()) hour=0 minute=int(N/60) if minute>60: hour=int(N/3600) secnd=N%3600 minute=int(secnd/60) secnd=secnd%60 else: secnd=N%60 print(str(hour)+':'+str(minute)+':'+str(secnd))
44d0c33f54ca1e79af869e5ea8d2eab352d9e5d4
RaisaAkter/Online_judge_Problem
/python_programming/py1.py
343
3.96875
4
class ListNode: def __init__(self,data): self.data=data self.next=None Node1=ListNode(11) Node2=ListNode(21) Node3=ListNode(31) head=Node1 Node1.next=Node2 Node2.next=Node3 def traversal(head): fNode=head while fNode is not None: print (fNode,fNode.data) fNode=fNode.next traversal(head)
8b56ac366700b926c2b3468b6c4fb9b9811acad2
RaisaAkter/Online_judge_Problem
/python_programming/subeen1.py
229
3.859375
4
def find_fib(n): if n <=2: return 1 fib_x,fib_next=1,1 i=3 while i<=n: i=i+1 fib_x , fib_next=fib_next,(fib_x + fib_next) return fib_next for x in range(1,11): print(find_fib(x))
621f34791ed34311df6cd56e0c53a91e68670da2
Rabeet-Syed/TABLES-using-Loop
/Table of -4 (2 methods).py
205
3.578125
4
print('TABEL OF -ve 4') for A in range(0,-100,-1) : print('4 x ' + str(A) + " = " + str( A * 4)) print('TABEL OF -ve 4') for A in range(100) : print('-4 x ' + str(A) + " = " + str( A * -4))
814601a978204d25789ea9aba8bdb01aeb3286b7
uggi121/Problem-Solving
/Strings/spreadsheet.py
316
3.515625
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 21 20:36:37 2019 @author: Sudharshan """ def spreadsheet_encoding(x): def conv(y): return ord(y) - ord('A') + 1 power, res = 0, 0 for i in reversed(range(len(x))): res += conv(x[i]) * 26 ** power power += 1 return res
49584d54e0c5caf5803ccce17905ed6f87713de5
uggi121/Problem-Solving
/Arrays/plus_one.py
454
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 21 21:19:56 2019 @author: Sudharshan """ def plus_one(digits): carry = 0 for i in reversed(range(len(digits))): if carry == 0 and i != len(digits) - 1: break value = digits[i] + 1 if value > 9: carry = 1 else: carry = 0 digits[i] = value % 10 if carry == 1: digits.insert(0, 1) return digits
1de93371a6aa6b58c47daa9f15377e2e0f7e88ec
yudzhi/001_Drones.Python
/grid.py
10,562
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 1 12:32:56 2018 @author: yudzhi """ """ create a configuration space given a map of the world and setting a particular altitude for your drone. You'll read in a .csv file containing obstacle data which consists of six columns x, y, z and δx, δy, δz. You can look at the .csv file here. The first line gives the map center coordinates and the file is arranged such that: x -> NORTH y -> EAST z -> ALTITUDE (positive up, note the difference with NED coords) Each (x,y,z) coordinate is the center of an obstacle. δx, δy, δz are the half widths of the obstacles, meaning for example that an obstacle with (x=37,y=12,z=8)and (δx=5,δy=5,δz=8) is a 10 x 10 m obstacle that is 16 m high and is centered at the point (x,y)=(37,12)at a height of 8 m. Given a map like this, the free space in the (x,y) plane is a function of altitude, and you can plan a path around an obstacle, or simply fly over it! You'll extend each obstacle by a safety margin to create the equivalent of a 3 dimensional configuration space. Your task is to extract a 2D grid map at 1 metre resolution of your configuration space for a particular altitude, where each value is assigned either a 0 or 1 representing feasible or infeasible (obstacle) spaces respectively. """ import numpy as np import matplotlib.pyplot as plt from scipy.spatial import Voronoi, voronoi_plot_2d import math from Bresenham import bres def create_voxmap(data, voxel_size=5): """ Returns a grid representation of a 3D configuration space based on given obstacle data. The `voxel_size` argument sets the resolution of the voxel map. """ # minimum and maximum north coordinates north_min = np.floor(np.amin(data[:, 0] - data[:, 3])) north_max = np.ceil(np.amax(data[:, 0] + data[:, 3])) # minimum and maximum east coordinates east_min = np.floor(np.amin(data[:, 1] - data[:, 4])) east_max = np.ceil(np.amax(data[:, 1] + data[:, 4])) alt_max = np.ceil(np.amax(data[:, 2] + data[:, 5])) alt_min = 0 print("N") print("min = {0}, max = {1}\n".format(north_min, north_max)) print("E") print("min = {0}, max = {1}\n".format(east_min, east_max)) print("Z") print("min = {0}, max = {1}".format(alt_min, alt_max)) print() # given the minimum and maximum coordinates we can # calculate the size of the grid. north_size = int(np.ceil((north_max - north_min))) // voxel_size east_size = int(np.ceil((east_max - east_min))) // voxel_size alt_size = int(alt_max) // voxel_size voxmap = np.zeros((north_size, east_size, alt_size), dtype=np.bool) # Given an interval, values outside the interval are clipped to the interval # edges. For example, if an interval of [0, 1] is specified, values smaller # than 0 become 0, and values larger than 1 become 1 for i in range(data.shape[0]): north, east, alt, d_north, d_east, d_alt = data[i,:] obstacle = [ int(np.clip((north - d_north - north_min)// voxel_size, 0, north_size-1)), int(np.clip((north + d_north - north_min)// voxel_size, 0, north_size-1)), int(np.clip((east - d_east - east_min)// voxel_size, 0, east_size-1)), int(np.clip((east + d_east - east_min)// voxel_size, 0, east_size-1)), int(alt + d_alt)//voxel_size ] voxmap[obstacle[0]:obstacle[1], obstacle[2]:obstacle[3], 0:obstacle[4]] = True # TODO: fill in the voxels that are part of an obstacle with `True` # # i.e. grid[0:5, 20:26, 2:7] = True return voxmap def create_grid(data, drone_altitude, safety_distance): """ Returns a grid representation of a 2D configuration space based on given obstacle data, drone altitude and safety distance arguments. Input: data, drone_altitude, safety_distance """ # minimum and maximum north coordinates north_min = np.floor(np.amin(data[:, 0] - data[:, 3])) north_max = np.ceil(np.amax(data[:, 0] + data[:, 3])) #print(north_min) #print(north_max) # minimum and maximum east coordinates east_min = np.floor(np.amin(data[:, 1] - data[:, 4])) east_max = np.ceil(np.amax(data[:, 1] + data[:, 4])) # given the minimum and maximum coordinates we can # calculate the size of the grid. north_size = int(np.ceil(north_max - north_min)) east_size = int(np.ceil(east_max - east_min)) # Initialize an empty grid grid = np.zeros((north_size, east_size)) # Center offset for grid # north_min_center = np.min(data[:, 0]) # east_min_center = np.min(data[:, 1]) # print(north_min_center,east_min_center) ###########Like this one more##########3 # Populate the grid with obstacles for i in range(data.shape[0]): north, east, alt, d_north, d_east, d_alt = data[i, :] if alt + d_alt + safety_distance > drone_altitude: obstacle = [ int(np.clip(north - d_north - safety_distance - north_min, 0, north_size-1)), int(np.clip(north + d_north + safety_distance - north_min, 0, north_size-1)), int(np.clip(east - d_east - safety_distance - east_min, 0, east_size-1)), int(np.clip(east + d_east + safety_distance - east_min, 0, east_size-1)), ] grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = 1 return grid # Here you'll modify the `create_grid()` method from a previous exercise # In this new function you'll record obstacle centres and # create a Voronoi graph around those points def create_grid_and_edges(data, drone_altitude, safety_distance): """ Returns a grid representation of a 2D configuration space along with Voronoi graph edges given obstacle data and the drone's altitude. """ # minimum and maximum north coordinates north_min = np.floor(np.min(data[:, 0] - data[:, 3])) north_max = np.ceil(np.max(data[:, 0] + data[:, 3])) # minimum and maximum east coordinates east_min = np.floor(np.min(data[:, 1] - data[:, 4])) east_max = np.ceil(np.max(data[:, 1] + data[:, 4])) # given the minimum and maximum coordinates we can # calculate the size of the grid. north_size = int(np.ceil((north_max - north_min))) east_size = int(np.ceil((east_max - east_min))) # Initialize an empty grid grid = np.zeros((north_size, east_size)) # Center offset for grid north_min_center = np.min(data[:, 0]) east_min_center = np.min(data[:, 1]) # Define a list to hold Voronoi points points = [] # Populate the grid with obstacles for i in range(data.shape[0]): north, east, alt, d_north, d_east, d_alt = data[i, :] if alt + d_alt + safety_distance > drone_altitude: obstacle = [ int(north - d_north - safety_distance - north_min_center), int(north + d_north + safety_distance - north_min_center), int(east - d_east - safety_distance - east_min_center), int(east + d_east + safety_distance - east_min_center), ] grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = 1 # add center of obstacles to points list points.append([north - north_min, east - east_min]) # TODO: create a voronoi graph based on # location of obstacle centres graph = Voronoi(points) voronoi_plot_2d(graph) plt.show() #print(points) # TODO: check each edge from graph.ridge_vertices for collision edges = [] for v in graph.ridge_vertices: p1 = graph.vertices[v[0]] p2 = graph.vertices[v[1]] p1_gr = [int(round(x)) for x in p1] p2_gr = [int(round(x)) for x in p2] p = [p1_gr,p2_gr] #print(p1, p1_grid, p2, p2_grid) in_collision = True if np.amin(p) > 0 and np.amax(p[:][0]) < grid.shape[0] and np.amax(p[:][1]) < grid.shape[1]: track = bres(p1_gr,p2_gr) for q in track: #print(q) q = [int(x) for x in q] if grid[q[0],q[1]] == 1: in_collision = True break else: in_collision = False if not in_collision: edges.append((p1,p2)) return grid, edges """ # Populate the grid with obstacles for i in range(data.shape[0]): north, east, alt, d_north, d_east, d_alt = data[i, :] grid = obstacle_formation(grid, north_min_center, east_min_center, drone_altitude, safety_distance, north, east, alt, d_north, d_east,d_alt) # TODO: Determine which cells contain obstacles # and set them to 1. #print('cicle',np.nonzero(grid)) return grid def obstacle_formation(grid, gr_north, gr_east, drone_alt, safe_dist, c_north, c_east, c_alt, d_north, d_east, d_alt): if (c_alt + d_alt + safe_dist - drone_alt) > 0: gr_row = int(np.ceil(c_north - gr_north)) gr_col = int(np.ceil(c_east - gr_east)) dN = int(np.ceil(d_north + safe_dist)) dE = int(np.ceil(d_east + safe_dist)) #print(gr_row - dN, gr_row+dN, gr_col-dE, gr_col-dE) grid[(gr_row - dN):(gr_row + dN), (gr_col-dE):(gr_col+dE)] = 1 #print(np.nonzero(grid)) return grid """ if __name__ == "__main__": #%matplotlib inline plt.rcParams["figure.figsize"] = [16, 16] filename = 'colliders.csv' # Read in the data skipping the first two lines. # Note: the first line contains the latitude and longitude of map center # Where is this?? data = np.loadtxt(filename,delimiter=',',dtype='Float64',skiprows=2) #print(data) # Static drone altitude (metres) drone_altitude = 15 # Minimum distance required to stay away from an obstacle (metres) # Think of this as padding around the obstacles. safe_distance = 3 grid = create_grid(data, drone_altitude, safe_distance) # equivalent to # plt.imshow(np.flip(grid, 0)) # NOTE: we're placing the origin in the lower lefthand corner here # so that north is up, if you didn't do this north would be positive down plt.imshow(grid, origin='lower') plt.xlabel('EAST') plt.ylabel('NORTH') plt.show()
4eab4617d62d9673cdaef3e3054eda88ddd30a10
oeg1n18/learning-python
/Learning-python-Oreilly/Statements.py
433
4
4
#================ if/elif/else/while/for ======================= x = True if (x): print('statement entered') elif (x): print('Statment not printed') else: print('statement not enetered') q=0 while x: print('still true') q += 1 if q==10: x = False print('not true') x = ['banana', 'strawberry', 'orange'] for y in x: if y=='orange': print('found the orange') break
0f460b9585e9fe668cd99117c9dfd9deb2555a22
oeg1n18/learning-python
/Learning-python-Oreilly/Numpy_testing.py
1,873
3.703125
4
import numpy as np a=np.array([0,1,2,3,4]) type(a) #returns numpy.ndarray #as the data in the numpy.ndarry is all of one type then it is a.dtype #returns dtype('int32') a.size #returns 5 a.ndim #returns the number of dimensions or rank of array print(a.shape) # returns a tuple of the size of the array in each dimention (col, row) #============== indexing and slicing =============== c=np.array([20,1,2,3,4]) c[0] = 100 #sets first value in array to 100 d = c[1:4] #slicing availible. #============== Basic Operations ================== #vector addition u=np.array([1,0]) v=np.array([0,1]) z = u + v #vector addition z = array([1,1] this would not be so simple using regular array's z = u - v #vector subtraction #vector multiplication with a scalar z = 2*u #only requires one line of code. u = np.array([1,2]) v = np.array([3,2]) z = u*v #hattenberg product result = np.dot(u,v) #returns the dot product of u and v z = u+1 # scalar addition. Adds to all values in the array (broadcasting) mean_a=a.mean() #returns the average of all the elements in the array max_b = a.max() #returns largest value int he array np.pi # returns pi np.linspace(-2,2,num=5) #returns a evenly spaced array from -2 - 2 in 5 steps #=============== Ploting sine wave ========================== x = np.linspace(0,2*np.pi,100) y=np.sin(x) import matplotlib.pyplot as plt plt.plot(x,y) #plots the graph plt.show() #============== Numpy in 2d a = [[11,12,13,14], [21,22,23],[31,32,33]] A = np.array(a) A.ndim(a) #ndim obtains the number of dimensions (rank of an array) in this case it is 2 A.shape #returns a tuple returns (3,3) (num of nested arrays, number of items per list) A.size #returns 9, the number of elements B = np.array(a) Y = A + B #matrix addition Y = 2*Y #multiplying matrix by a scalar H = A * B #hattemard product C = np.dot(A,B) # dot product matrix multiplication
7a2bda2ce8776be14af22a7945733902554b56a2
KemengXu/Othello
/othello/board.py
5,843
3.640625
4
class Board: def __init__(self, size): self.occupy = { "black": [], "white": [], "empty": [(i, j)for j in range(size) for i in range(size)] } self.size = size def initial_tile(self): """to put 4 initial tiles in the middle""" center = self.size//2 w1 = (center - 1, center - 1) w2 = (center, center) b1 = (center - 1, center) b2 = (center, center - 1) del_set = {w1, w2, b1, b2} self.occupy["white"] += [w1, w2] self.occupy["black"] += [b1, b2] for i in del_set: self.occupy["empty"].remove(i) def is_empty(self): """check if there are spaces for more tiles""" if len(self.occupy["empty"]) == 0: return True return False def put_tile(self, name, tran_pos): """alter the occupy dictionary with the mouse_clicked positon""" self.occupy[name].append(tran_pos) self.occupy["empty"].remove(tran_pos) def flip(self, name, tran_pos, opp_name): """ flip after every put_tile, the input is already legal check all tiles around the new tile wheter they should flip and call the flip_execute function """ length_directions = 8 flip_flag = [False] * length_directions checked_direction = [] can_flip = [0] * length_directions for i in range(1, self.size): if len(checked_direction) == length_directions: break d = self.directions_generator(i, tran_pos) curr = [] for j in range(len(d)): if j not in checked_direction: if d[j][0] in range(0, self.size) and\ d[j][1] in range(0, self.size): # on board if d[j] in self.occupy["empty"]: checked_direction.append(j) elif not flip_flag[j] and d[j] in self.occupy[name]: checked_direction.append(j) elif d[j] in self.occupy[opp_name]: flip_flag[j] = True elif flip_flag[j] and d[j] in self.occupy[name]: self.execute_flip(d[j], name, tran_pos, opp_name) checked_direction.append(j) can_flip[j] += 1 def execute_flip(self, curr, name, tran_pos, opp_name): """execute the flip in different situatoions""" diff_x = curr[0] - tran_pos[0] diff_y = curr[1] - tran_pos[1] step_x = 0 if diff_x == 0 else int(diff_x / abs(diff_x)) step_y = 0 if diff_y == 0 else int(diff_y / abs(diff_y)) if step_x == 0: x = curr[0] for y in range(tran_pos[1] + step_y, curr[1], step_y): self.occupy[name].append((x, y)) self.occupy[opp_name].remove((x, y)) elif step_y == 0: y = curr[1] for x in range(tran_pos[0] + step_x, curr[0], step_x): self.occupy[name].append((x, y)) self.occupy[opp_name].remove((x, y)) else: x = tran_pos[0] + step_x y = tran_pos[1] + step_y while x != curr[0]: # should not use for{for}, because # we want (0,0) -> (1, 1), not (0, 0)->(0,1)->(1, 0)->(1, 1) self.occupy[name].append((x, y)) self.occupy[opp_name].remove((x, y)) x += step_x y += step_y def check_who_wins(self): """check who wins according to the number of tiles""" res = [] if self.is_empty() is True: r1 = len(self.occupy["black"]) r2 = len(self.occupy["white"]) if r1 > r2: res.append("You win") elif r1 == r2: res.append("Tie!!!!!") else: res.append("AI wins!") res += [r1, r2] return res return def display(self, p1, p2): """draw tiles on board""" p1.display(self) p2.display(self) def is_legal(self, pos, name, opp_name): """ decide if the input position is legal by checking if there will be at least one flip after the tile """ length_directions = 8 opp_flag = [False] * length_directions impossible_direction = set() for i in range(1, self.size): if len(impossible_direction) == length_directions: break d = self.directions_generator(i, pos) for j in range(length_directions): if j not in impossible_direction: if d[j][0] in range(0, self.size) and\ d[j][1] in range(0, self.size): if d[j] in self.occupy[name] and opp_flag[j]: return True elif d[j] in self.occupy[name] and not opp_flag[j]: impossible_direction.add(j) elif d[j] in self.occupy["empty"]: impossible_direction.add(j) elif d[j] in self.occupy[opp_name]: opp_flag[j] = True return False def directions_generator(self, i, pos): """generate a list of all positions around the input position""" w = (pos[0], pos[1] - i) e = (pos[0], pos[1] + i) n = (pos[0] - i, pos[1]) s = (pos[0] + i, pos[1]) nw = (pos[0] - i, pos[1] - i) ne = (pos[0] - i, pos[1] + i) sw = (pos[0] + i, pos[1] - i) se = (pos[0] + i, pos[1] + i) directions = [w, e, n, s, nw, ne, sw, se] return directions
0f33046da4c87c3f23339de7b7407a217370b62c
AvigailKoll/matala0
/add.py
155
3.8125
4
firstNumber=input('put in first int number') secondNumber=input('put in second int number') sumNumbers=int(firstNumber)+int(secondNumber) print(sumNumbers)
b3afda1168d2fa7d84b1c1bc01405722e7c5ca9d
Shehbab-Kakkar/Waronpython
/arch1/index1.py
310
3.78125
4
#!/usr/bin/python #Filname is index1.py number = [3, 7, 1, 4, 2, 8, 5, 6] print(number.index(5)) number *= 2 # number = number * 2 print(number) print(number.index(5,7)) #start counting index position #of 5 start from the 7 means second 5 print(number.index(7,0, 4)) #index of 7 inbetween 0 and 4 position
cb9cc0d3b499881d0b8798dd39ec38906eeaaf28
Shehbab-Kakkar/Waronpython
/arch1/indexexp.py
305
3.84375
4
#!/usr/bin/python #Filname is indexexp.py list = [67, 12, 46, 43, 13] key1 = 43 key2 = 44 if key1 in list: print(f'{key1} is present at {list.index(key1)}') else: print(f'{key1} not found') if key2 in list: print(f'{key2} is present at {list.index(key2)}') else: print(f'{key2} not found')
b4567494d3606a3c2af0e0fa6f0ab7a8d79f6002
Shehbab-Kakkar/Waronpython
/arch1/dict1.py
205
3.890625
4
#!/usr/bin/python #Filname is dict1.py dict1 = {'A':'aa','B':'bb','C':'cc'} for i in dict1.values(): print(i) for i in dict1.keys(): print(i) for i, j in dict1.items(): print(f'{i} {j}')
7e21b51ec88b79191088614971bbc325fff0fabf
AhhhHmmm/Programming-HTML-and-CSS-Generator
/exampleInput.py
266
4.15625
4
import turtle # This is a comment. turtle = Turtle() inputs = ["thing1", "thing2", "thing3"] for thing in inputs: print(thing) # comment!!! print(3 + 5) # little comment print('Hello world') # commmmmmmm 3 + 5 print("ahhhh") # ahhhh if x > 3: print(x ** 2)
637ae867ecf3e7998e59a27a21d3931b14532927
phyrenight/caesar
/testunit.py
924
3.75
4
from main import shift, convertToList import unittest class testfunctions(unittest.TestCase): def testConvertTolist(self): self.assertEqual(convertToList(None), "No string entered.") self.assertEqual(convertToList(""), "No string entered.") self.assertEqual(convertToList(" "), [" "]) sentence = "The rain in Spain falls mainly in the plains." lst = list(sentence) self.assertEqual(convertToList(sentence), lst) def testShift(self): self.assertEqual(shift(None), "No string entered.") sentence = "The rain in Spain falls mainly in the plains." lst = list(sentence) encrypt = 'Uif sbjo jo Tqbjo gbmmt nbjomz jo uif qmbjot.' self.assertEqual(shift(lst), encrypt) self.assertEqual(shift(sentence), "No string entered.") self.assertEqual(shift(""), "No string entered.") if __name__ == '__main__': unittest.main()
80a36a5d806378611e71176bd3e34097c0b902d5
mahendrathapa/python-basic-ml
/Coursera-ML-AndrewNg/linear-regression/gradiet-descent.py
1,212
3.53125
4
import numpy as np def load_dataset(): dataset = np.genfromtxt('ex1data2.txt', delimiter=',') X = dataset[:,:-1] y = dataset[:, [-1]] X = np.insert(X, 0, 1, axis=1) return X, y def feature_standardization(X): for col in range(1, X.shape[1]): mean = np.mean(X[:, col]) sigma = np.std(X[:, col]) X_ = (X[:, col] - mean) / sigma X[:, col] = X_ return X def calculate_output(X, theta): return X.dot(theta) def calculate_cost(X,y, theta): m = y.size output = calculate_output(X, theta) return np.sum(np.square(output - y)) / (2 * m) def gradient_descent(X, y, alpha, iteration_number): theta = np.zeros([X.shape[1],1]) m = y.size for i in range(iteration_number): output = calculate_output(X,theta) theta = theta - ((alpha / m) * (np.dot(X.T, (output - y)))) if i % 1000 == 0: print("i: {}, Cost: {}".format(i, calculate_cost(X, y, theta))) return theta def main(): X, y = load_dataset() X = feature_standardization(X) theta = gradient_descent(X, y, 0.001, 10000) print("Theta's: {}".format(theta)) if __name__ == "__main__": main()
0dff840349408c41a0b51d96577dc4d0b5bd9c32
TSechrist/Codewars
/src/find_missing_letter.py
180
3.71875
4
def find_missing_letter(chars): for i in range(len(chars) - 1): if ord(chars[i]) - ord(chars[i + 1]) != -1: res = chr(ord(chars[i]) + 1) return res
851a08f4d1580cde6c19fb9dbc3dd939d0a7b6f3
vdmitriv15/DZ_Lesson_1
/DZ_5.py
1,604
4.125
4
# Запросите у пользователя значения выручки и издержек фирмы. # Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). # Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). # Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника revenue = int(input("введите значение выручки: ")) cost = int(input("введите значение издержек: ")) profit = revenue - cost if revenue > cost: print(f"ваша прибыль {profit}") profitability = profit / revenue number_of_employees = int(input("введите количество сотрудников: ")) profit_to_employee = profit / number_of_employees print(f"рентабельность выручки {profitability}") print(f"прибыль фирмы в расчете на одного сотрудника {profit_to_employee}") elif revenue < cost: print(f"ваш убыток {profit*-1}") else: print("выручка равна издержкам. вы отработали в ноль")
df7282d45332baf2d25d9ca1794b55cd802aac6c
evab19/verklegt1
/Source/models/Airplane.py
1,156
4.25
4
class Airplane: '''Module Airplane class Module classes are used by the logic layer classes to create new instances of Airplane gets an instance of a Airplane information list Returns parameters if successful --------------------------------- ''' def __init__(self, name = "", model = "", producer = "", number_of_seats = "", plane_status = "A"): self.name = name self.model = model self.producer = producer self.number_of_seats = number_of_seats self.plane_status = plane_status def __str__(self): return "{}{:20}{}{:20}{}{:25}{}{:20}{}{:10}{}".format('| ', self.name, '| ', self.model, '| ', self.producer, '| ', str(self.number_of_seats), '| ', str(self.plane_status), '|') def get_name(self): return str(self.name) def get_model(self): return str(self.model) def get_producer(self): return str(self.producer) def get_number_of_seats(self): return str(self.number_of_seats) def get_plane_status(self): return str(self.plane_status)
905df9bcdb837b6e0692e1b2033aff9f72619a45
DrakeDwornik/Data2-2Q1
/quiz1/palindrome.py
280
4.25
4
def palindrome(value: str) -> bool: """ This function determines if a word or phrase is a palindrome :param value: A string :return: A boolean """ result = True value_rev = value[::-1] if value != value_rev: result = False return result
24ce60696eaccae9667d238e13cb3a59d8bcc732
wanf425/MyPython
/com/wt/practice/Collection.py
634
3.921875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #list alist = [1,'2',['3','4']] print 'alist',alist print 'length',len(alist) print 'index 1 value',alist[1] print 'last value',alist[-1] print 'append',alist.append(5) print 'after append',alist print 'insert',alist.insert(1,6) print 'after insert',alist print 'pop',alist.pop(1) print 'after pop',alist #tuple atuple = (1,2,'3') print atuple atuple = (1,) print atuple #dict adict = {'wt':20,'lff':19,'dc':18,10:17} print 'adict',adict print 'get key wt',adict['wt'] print 'key kdc is in adict', 'kdc' in adict #set aset = ([1,2,3]) print 'aset',aset print 'index 1 value',aset[1]
2c69df7cf69081ec3e100034c4e7b53c0f01f5e1
NathanKr/pandas-playground
/insert_column.py
278
4.09375
4
import pandas as pd df = pd.DataFrame([] , columns=['col0' , 'col1' , 'col2']) #choose columns df['col0'] = [1,2,3] # set values to existing column df['col1'] = [4,5,6] # set values to existing column df['col2'] = [7,8,9] # set values to existing column print (f'df\n{df}')
b90d2d9aba147a4e71f39610e2ba7ad73f426ede
NathanKr/pandas-playground
/insert_row_at_index.py
717
3.890625
4
from typing import List import pandas as pd def insert_row_to_new_df(i_row : int, df : pd.DataFrame, row : List)->pd.DataFrame: # Slice the upper half of the dataframe # use copy because df[0:i_row] is a view which we update and it is NOT allowed df1 = df[0:i_row].copy() # Store the result of lower half of the dataframe df2 = df[i_row:] # Inser the row in the upper half dataframe df1.loc[i_row]=row # Concat the two dataframes new_df = pd.concat([df1, df2]) # Reassign the index labels # new_df.index = [*range(new_df.shape[0])] new_df.reset_index(inplace=True,drop=True) # drop prev index # Return the updated dataframe return new_df
703fe2fe6574d8e38204d238afee5327720345a9
NathanKr/pandas-playground
/compare_dfs.py
598
3.75
4
import pandas as pd df1 = pd.DataFrame([[1, 2, 3, 4], [4, 5, 6 , 7], [7, 8, 9 , 10]], columns=['col1', 'col2', 'col3' , 'col4']) df2 = pd.DataFrame([[1, 2, 3, 4], [4, 5, 6 , 7], [7, 8, 9 , 10]], columns=['col1', 'col2', 'col3' , 'col4']) df3 = pd.DataFrame([[11, 2, 3, 4], [4, 5, 6 , 7], [7, 8, 9 , 10]], columns=['col1', 'col2', 'col3' , 'col4']) df_compare_result : pd.DataFrame = df1 == df2 print(df_compare_result == True) df_compare_result : pd.DataFrame = df1 == df3 print(df_compare_result.all(axis=None) == True)
15250c4e99d8133175c5956444b1473f70f194bb
Steven98788/Ch.03_Input_Output
/3.1_Temperature.py
446
4.5
4
''' TEMPERATURE PROGRAM ------------------- Create a program that asks the user for a temperature in Fahrenheit, and then prints the temperature in Celsius. Test with the following: In: 32 Out: 0 In: 212 Out: 100 In: 52 Out: 11.1 In: 25 Out: -3.9 In: -40 Out: -40 ''' print("Welcome to my Fahrenheit to Celsius converter!") Fahrenheit=int(input("What is your Fahrenheit?")) Celsius=(Fahrenheit-32)*5/9 print("Your Celsius is",Celsius)
6fbce57e72e72e2260039c0b9089bc505f3539ad
geekprateek/cs101
/Unit 7/1 Longest repitition.py
1,585
4.03125
4
# Question 8: Longest Repetition # Define a procedure, longest_repetition, that takes as input a # list, and returns the element in the list that has the most # consecutive repetitions. If there are multiple elements that # have the same number of longest repetitions, the result should # be the one that appears first. If the input list is empty, # it should return None. def longest_repetition(i_list): if i_list == []: return None v_result = [i_list[0], 1] v_curr = ['', 0] for v_val in i_list: if v_val == v_curr[0]: v_curr[1] += 1 if v_curr[1] > v_result[1]: v_result = v_curr else: v_curr = [v_val, 1] return v_result[0] def new_longest_repetition(input_list): best_element = None length = 0 current = None current_length = 0 for element in input_list: if current != element: current = element current_length = 1 else: current_length += 1 if current_length > length: best_element = current length = current_length return best_element #For example, print longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1]) print new_longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1]) # 3 print longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd']) print new_longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd']) # b print longest_repetition([1,2,3,4,5]) print new_longest_repetition([1,2,3,4,5]) # 1 print longest_repetition([]) print new_longest_repetition([]) # None
d0131f70c30f32dcca2bab05dd8852d38376e50a
geekprateek/cs101
/Unit 3/Sum list.py
553
3.90625
4
# Define a procedure, sum_list, # that takes as its input a # list of numbers, and returns # the sum of all the elements in # the input list. def sum_list(in_val): v_sum = 0 for test in in_val: v_sum = v_sum + test return v_sum def new_sum_list(p): result = 0 for e in p: result = result + e return result print sum_list([1, 7, 4]) print new_sum_list([1, 7, 4]) #>>> 12 print sum_list([9, 4, 10]) print new_sum_list([9, 4, 10]) #>>> 23 print sum_list([44, 14, 76]) print new_sum_list([44, 14, 76]) #>>> 134
cc4d9d7f9567124a453c6fb1ae894d5996e20e4f
geekprateek/cs101
/Unit 6/Faster Fibo.py
247
3.875
4
#Define a faster fibonacci procedure that will enable us to computer #fibonacci(36). def fibonacci(n): v_n1 = 0 v_n2 = 1 for i in range(0, n): v_n1, v_n2 = v_n2, v_n1 + v_n2 return v_n1 print fibonacci(36) #>>> 14930352
27963142d7ea42c015716c2b879ac2c049e4afa9
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Ersan/soru6.py
99
3.515625
4
a = int(input("A:")) b = int(input("B:")) c = ((a ** 2 + b ** 2) ** 0.5) print("Hipotenüs:",c)
086827ea32ce78e70e1fa31ab62861b34cb941ae
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Alpertolgadikme/soru15.py
314
3.921875
4
sayi1 = int(input("1. Sayı: ")) sayi2 = int(input("2. Sayı: ")) sayi3 = int(input("3. Sayı: ")) if (sayi1 >= sayi2) and (sayi1 >= sayi3): buyuk = sayi1 elif (sayi2 >= sayi1) and (sayi2 >= sayi3): buyuk = sayi2 else: buyuk = sayi3 print(sayi1,",",sayi2,"ve",sayi3,"içinde büyük olan sayı",buyuk)
d22159d6574cad9ffeb39abfb57fbf4ce4694614
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Haydar/soru4.py
184
4.0625
4
yakıt=float (input ("Aracın ne kadar yaktığını girin:")) km= float (input ("Aracın kaç kilometre yol yaptığını girin:")) print("Toplam ödenmesi gereken ücret:",yakıt*km)
1b3b2de13de22e7829b0715935ef9e7e0df89c4d
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Ersan/mukemmel.py
323
3.921875
4
print("""\nMükemmel Sayıyı Bulma Programı --------------------------------------""") sayi = int(input("Lütfen bir sayı giriniz: ")) toplam = 0 for i in range(1,sayi): if (sayi %i == 0): toplam += i if (sayi == toplam): print("Bu Mükemmel Sayıdır") else: print("Bu Mükemmel Sayı Değildir")
17c5b3c6316bc38c01ed66167428f58b9d05c4b0
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Alpertolgadikme/Ödev1.py
119
3.75
4
km=int(input("Kaç km yol gidildi:")) yakit=float(input("Araç km kaç kuruş yaktı:")) print("Toplam tutar",km*yakit)
47f01032f8856736e2676954ac227c00bd018947
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Alpertolgadikme/soru13h.py
845
3.84375
4
print(""" HESAP MAKİNESİ TOPLAMA İŞLEMİ YAPMAK İÇİN 1 'e BASIN. ÇIKARMA İŞLEMİ YAPMAK İÇİN 2 'e BASIN. ÇARPMA İŞLEMİ YAPMAK İÇİN 3 'e BASIN. BÖLME İŞLEMİ YAPMAK İÇİN 4 'e BASIN. """) islem = input("İşlem seçiniz: ") if islem == "1": sayi1 = int(input("sayi1 giriniz: ")) sayi2 = int(input("sayi2 giriniz: ")) print("Sonuç:", sayi1 + sayi2) elif islem == "2": sayi1 = int(input("sayi1 giriniz: ")) sayi2 = int(input("sayi2 giriniz: ")) print("Sonuç:", sayi1 - sayi2) elif islem == "3": sayi1 = int(input("sayi1 giriniz: ")) sayi2 = int(input("sayi2 giriniz: ")) print("Sonuç:", sayi1 * sayi2) elif islem == "4": sayi1 = int(input("sayi1 giriniz: ")) sayi2 = int(input("sayi2 giriniz: ")) print("Sonuç:", sayi1/sayi2) else: print("geçersiz işlem girdiniz...")
3069ea9d425a72d8cdf497a084b6e227fae4ebc6
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Ersan/faktoriyel.py
148
3.921875
4
while(True): sayi = int(input("Bir sayı Giriniz: ")) fak = 1 for i in range(2,sayi+1): fak*= i print("Faktöriyel= ", fak)
50994b599b3c8928274159261d63a727e050bf0d
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Burcu/02DONGULER/dongulerspru6.py
139
3.65625
4
#1'den 100'e kadar olan çift sayıları listeye atalım. even=[] for n in range(1,101): if n%2==0: even.append(n) print(even)
34e8040dfc5102fd1d34f74e25c74424cb80bd14
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Ekrem/kullanıcıgirişi.py
568
3.703125
4
print("-------Kullanıcı Girişi---------") kullaniciAdi="Ekrem" parola="369258" username=input("Kullanıcı Adınızı Giriniz") password=input("Parolanızı Giriniz") if username==kullaniciAdi and password==parola: print("Tebrikler başarılı giriş yaptınız.") elif username!=kullaniciAdi and password==parola: print("kullanıcı adını yanlış girdiniz.") elif username==kullaniciAdi and password!=parola: print("Şifreyi yanlış girdiniz.") elif username==kullaniciAdi and password!=parola: print("Kullanıcı ve Şifreyi yanlış Girdiniz.")
8d4a16a3b136c2a3180ee6ebdb71a9b8f17ed7b9
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Varol/dongulersoru4.py
164
3.84375
4
toplam=0 while True: sayi=input("Bir sayı giriniz:") if (sayi=="q"): break toplam+=int(sayi) print("Girdiğiniz sayıların toplamı:",toplam)
be691b15a1b6ae664498d24c31017fe143536ab1
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Eren/soru3.py
212
3.578125
4
a=int(input("1. Sayıyı giriniz : ")) b=int(input("2. Sayıyı giriniz : ")) sonuc=a,b = b,a print("----Yeni Hali------") print("a =",a) print("b =",b) print("-----Eski Hali-----") print("a =",b) print("b =",a)
ab9b570ae1bcba6c3f6c6a4d4e1eb98bbbd6d083
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Ersan/armstrong.py
472
3.765625
4
while True: sayi=input("LÜtfen Bir Sayı Giriniz. (Çıkmak için 'q' ya basın.) : ") if sayi.lower()=="q": print("Oyundan çıktınız. Yine bekleriz.") break uzunluk=len(sayi) toplam=0 for i in range(uzunluk): toplam = toplam + int(sayi[i])**uzunluk if(toplam==int(sayi)): print("Girdiğiniz Sayı Bir Armstrong Sayıdır!") else: print("Girdiğiniz Sayı Armstrong Bir Sayı Değildir!")
e326533c4fb3975831b1caa28928e996e1c99dcc
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Varol/whiledonugusu.py
56
3.53125
4
x=0 while (x<10): print("x'nin değeri:",x) x+=1
1d0d0313e1a5adcc857596138cd236ed6dd7298e
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Fatih/init.py
850
3.5
4
class Yazilimci(): def __init__(self,isim,soyisim,sicil,maas,diller): self.isim=isim self.soyisim=soyisim self.sicil=sicil self.maas=maas self.diller=diller def bilgileriGoster(self): print(""" Çalışan Bilgisi: İsim: {} Soyisim: {} Sicil No: {} Maaş: {} Bilgiği Diller: {} """.format(self.isim,self.soyisim,self.sicil,self.maas,self.diller)) def dilEkle(self,yenidil): print ("dil ekleniyor...") self.diller.append(yenidil) def maasZammi(self,zam): print("Maaşa Zam Yapılıyor...") self.maas+=zam yazilimci1=Yazilimci ("Ali", "Aktaş",123456, 15000,["Python","C"]) yazilimci1.dilEkle("Go") yazilimci1.maasZammi(500) yazilimci1.bilgileriGoster()
9ab10061e29fc0601bda77d55c2686f1644465e6
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Alpertolgadikme/Ödev3.py
101
3.703125
4
a=int(input("a kenarı :")) b=int(input("b kenarı :")) c=(a**2+b**2) print("Hipotenüs Uzunluğu",c)
03e0469f883183238c9ae49103dd5f7a2074c694
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Burcu/02DONGULER/kullaniciadidöngü.py
578
3.734375
4
print(""" -------------KULLANICI GİRİŞ EKRANI---------- """) Kullaciadi_ID = "Kullanici" Kullaciadi_PW= "123" kullanici_adi = input("Kullanıcı Adını Giriniz: ") sifre = input("Şifre'yi Giriniz: ") if (kullanici_adi == Kullaciadi_ID) and (sifre != Kullaciadi_PW): print("Dikkat Şifre Yanlış..!!") elif (kullanici_adi != Kullaciadi_ID) and (sifre == Kullaciadi_PW): print("Dikkat Kullanıcı Adı Yanlış..") elif (kullanici_adi != Kullaciadi_ID) and (sifre != Kullaciadi_PW): print("Dikkat Kullanıcı Adı Ve Şifre yanlış..") else: print("Giriş yapıldı!")
97e19b265205e7ef2959534256af4b6c05bac251
ProEgitim/Python-Dersleri-BEM
/Ogrenciler/Eren/soru5.py
331
3.859375
4
print("Kullanıcıdan İstenilen Bilgileri(Ad,SoyAd,Numara) Bilgilerini Alt Alta Yazdırma İşlemi.") print("---------------------------------------------------------------------------------------") a=input("Adınızı Giriniz : ") b=input("Soy Adınızı Giriniz : ") c=int(input("Numaranızı Giriniz : ")) print(a,b,c,sep="\n")
f7612c53c7f064899443a632a91bf62123c37814
jmoehler/CityDistance
/distanceEx.py
932
3.53125
4
from distance import distance, tempDiff def distExample(): from City import City stg = City("Stg", 48.7758459, 9.1829321, 22) #Stuttgart ber = City("Ber", 52.521918, 13.413215, 21) #Berlin ham = City("Ham", 53.551085, 9.993682, 24) #Hamburg nür = City("Nür", 49.452030, 11.076750, 22) #Nürnberg fra = City("Fra", 50.110922, 8.682127, 23) #Frankfurt düs = City("Düs", 51.2277411, 6.7734556, 20) #Düsseldorf cities = [stg, ber, ham, nür, fra, düs] for c in cities: c.describe() for i in range(0,len(cities)): for j in range(i +1, len(cities)): c1 = cities[i] c2 = cities[j] dist = distance(c1, c2) tDiff = tempDiff(c1, c2) if dist == 0: continue print("De Luftlinie %s, %s ist %.2fKm TempDiff:%.1fC" % (c1.name, c2.name, dist, tDiff)) distExample()
d1d750a8f2b2d0ce135a2e35856ca292a48caa6a
akashggupta/Nueral-Networks
/bill_authentication.py
5,240
3.640625
4
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split # 4 layered nueral network (3 hidden layer +1 output layer) # getting the data data = pd.read_csv("bill_authentication.csv") x = data.drop(data.columns[-1], axis=1, inplace=False) y = data.drop(data.columns[range(4)], axis=1, inplace=False) # splitting into training and testing data set X_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size=0.20) nx = 4 # no. of nuerons in input layer ny = 1 # no. of nuerons in output layer layer_dims = np.array([4, 5, 5, 5, 1]) # no. of nuerons in each layer of network m=X_train.shape[0] #no. of training examples # initializing weights and bias of every layer def initialize_parameter(layer_dims): np.random.seed(3) parameters = {} L = len(layer_dims) for l in range(1, L): parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l - 1]) * 0.01 parameters['b' + str(l)] = np.zeros((layer_dims[l], 1)) return parameters """# for checking the dimensions of weight and bias matrices parameters=initialize_parameter(layer_dims) for i in parameters: print(parameters[i].shape)""" def sigmoid(z): s = 1 / (1 + np.exp(-1 * z)) return s def relu(z): s = np.maximum(0, z) return s def relu_derivative(Z): Z[Z<=0]=0 Z[Z>0]=1 return Z # Forward Propagation def forward_prop(parameters, X_train): cache = {} L = len(layer_dims) for l in range(1, L): if l == 1: cache['Z' + str(l)] = np.dot(parameters['W' + str(l)], X_train.T) + parameters['b' + str(l)] cache['A' + str(l)] = relu(cache['Z' + str(l)]) elif l == L - 1: cache['Z' + str(l)] = np.dot(parameters['W' + str(l)], cache['A' + str(l-1)]) + parameters['b' + str(l)] cache['A' + str(l)] = sigmoid(cache['Z' + str(l)]) else: cache['Z' + str(l)] = np.dot(parameters['W' + str(l)], cache['A' + str(l-1)]) + parameters['b' + str(l)] cache['A' + str(l)] = relu(cache['Z' + str(l)]) return cache # for checking the dimensions of Z value """parameters=initialize_parameter(layer_dims) cache=forward_prop(parameters,X_train) for i in cache: print(cache[i].shape)""" # cost function def cost_func(cache,Y_train): L=len(layer_dims) J=np.sum(np.multiply(Y_train,np.log(cache['A'+str(L-1)]).T))+np.sum(np.multiply(1-Y_train,np.log(1-cache['A'+str(L-1)]).T)) J=-J/m return J # Back prop def back_prop(cache,Y_train,parameters,X_train): L=len(layer_dims) grad={} for l in reversed(range(1,L)): if l==L-1: grad['dz'+str(l)]=cache['A'+str(l)]-Y_train.T else: grad['dz'+str(l)]=np.multiply(np.dot(parameters['W'+str(l+1)].T,grad['dz'+str(l+1)]),relu_derivative(cache['Z'+str(l)])) if l!=1: grad['dw' + str(l)] = (np.dot(grad['dz' + str(l)], cache['A' + str(l - 1)].T)) / m grad['db' + str(l)] = (np.sum(grad['dz' + str(l)], axis=1)) / m grad['db' + str(l)] = np.array(grad['db' + str(l)]) grad['db' + str(l)] = grad['db' + str(l)].reshape(layer_dims[l],1) elif l==1: grad['dw' + str(l)] = (np.dot(grad['dz' + str(l)], X_train)) / m grad['db' + str(l)] = (np.sum(grad['dz' + str(l)], axis=1)) / m grad['db' + str(l)] = np.array(grad['db' + str(l)]) grad['db' + str(l)] = grad['db' + str(l)].reshape(layer_dims[l], 1) return grad # for checking dimension of dz,dw,db """grad=back_prop(cache,Y_train,parameters,X_train) for i in grad: print(grad[i].shape)""" def update(grad,parameters,alpha): L=len(layer_dims) for l in range(1,L): parameters['W' + str(l)]= parameters['W'+str(l)]-np.multiply(alpha,grad['dw'+str(l)]) parameters['b' + str(l)]=parameters['b'+ str(l)]-np.multiply(alpha,grad['db'+str(l)]) return parameters # for checking the dimension of W and b """temp=update(grad,parameters,0.1) for i in temp: print(temp[i].shape)""" # for prediction on test set def predict(X_test,parameters): temp=forward_prop(parameters,X_test) L=len(layer_dims) prediction=temp['A'+str(L-1)] prediction[prediction < 0.5] = 0 prediction[prediction >= 0.5] = 1 return prediction # Model def model(X_train,Y_train,epoch,learning_rate): parameters=initialize_parameter(layer_dims) for i in range(epoch): cache=forward_prop(parameters,X_train) print(cost_func(cache,Y_train)) grad=back_prop(cache, Y_train, parameters, X_train) parameters=update(grad, parameters, learning_rate) return parameters def accuracy(prediction,Y_test): total=len(prediction.T) temp=np.array(prediction-Y_test.T) temp=temp.T correct=0 for i in temp: if i==0: correct+=1 print((correct/total)*100) # evaluating the nueral network parameters=model(X_train,Y_train,10000,0.3) prediction=predict(X_test,parameters) #print(prediction.shape) accuracy(prediction,Y_test)