blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
398b2c5fc86987fa9332c3b2d4ac23a8d1ff7a1d
ToxicMushroom/bvp-python
/oefenzitting 3/exercise3.py
264
4.15625
4
number = int(input("Enter a number: ")) total = 0 flipper = True while number != 0: if flipper: total += number flipper = False else: total -= number flipper = True number = int(input("Enter a number: ")) print(total)
false
ff983f0996b4abffdfa420f9449f95aa47097011
xXPinguLordXx/py4e
/exer11.py
234
4.125
4
def count (word, char): char_count = 0 for c in word: if c == char: char_count += 1 return char_count # occurences inp_word = input ("Enter word: ") inp_char = input ("Enter char: ") print (count)
true
2b2260baa8a63839a1d3feeabfc645cf52ef7761
xXPinguLordXx/py4e
/exer8.py
768
4.28125
4
#declare this shit outside the loop because if you put it inside it will just get looped forever #declare this outside so that it is accessible by the entire program outside and not just within the loop sum = 0 count = 0 while True: number = input ("Enter a number: ") if number == 'done': break try: number = float(number) except: print('Invalid input') continue sum += number #this is shorthand for sum = sum + number count = count + 1 #or you can write count += 1 #write this here so that program tries to do this before moving on to invalidating ## to protect the code from breaking when someone inputs 'done' at the start: if count == 0: print(sum,count, None) else: print(sum,count,sum/count)
true
e3d5c813c35e2ba8683d5404fa936e862a7e35f3
mileuc/breakout
/paddle.py
725
4.1875
4
# step 2: create paddle class from turtle import Turtle class Paddle(Turtle): # paddle class is now effectively the same as a Turtle class def __init__(self, paddle_position): super().__init__() # enable Turtle methods to be used in Ball class self.shape("square") self.color("white") self.shapesize(stretch_len=5, stretch_wid=1) self.penup() self.goto(paddle_position) # initial position of the paddle center def move_left(self): # move paddle left new_x = self.xcor() - 20 self.goto(x=new_x, y=self.ycor()) def move_right(self): # move paddle right new_x = self.xcor() + 20 self.goto(x=new_x, y=self.ycor())
true
b5b34dd6187ea0358c49522a15939bfa5a2367a7
karuneshgupta/python-prog
/patterns.py
1,569
4.1875
4
#squares for row in range (1,5): for column in range (1,5): print("*",end=" ") print() #triangle pyramid for row in range (1,5): for column in range(1,row+1): print("*",end=" ") print() # reverse triangle pyramid for row in range(1,5): for column in range(row,5): print("*",end=" ") print() #hollow square for row in range(1,5): for column in range(1,5): if(row==1 or row==4 or column==1 or column==4 ): print("*",end=" ") else: print(" ",end=" ") print() #plus for row in range(1,6): for column in range(1,6): if(row==3 or column==3 ): print("*",end=" ") else: print(" ",end=" ") print() #right angle triangle for row in range(1,4): for column in range(1,4): if(row==3 or column==1 ): print("*",end=" ") else: print(" ",end=" ") print() # reverse right angle triangle for row in range(1,4): for column in range(1,4): if(row==1 or column==1 ): print("*",end=" ") else: print(" ",end=" ") print() # cross for row in range(1,6): for column in range(1,6): if( row==column or row+column==6): print("*",end=" ") else: print(" ",end=" ") print() # reverse pyramid k=1 for row in range(1,7): for column in range(1,k): print(end=" ") for column in range(1,7-row): print("*",end=" ") k=k+1; print() pyramid
false
6ff3d2c4c52c4ed4c0543b81eb97a4e59e6babeb
vishalkmr/Algorithm-And-Data-Structure
/Searching/Binary Search(Ascending Order).py
1,134
4.15625
4
''' Binary Search on Ascending order Lists Assume that list is in Ascending order Note : Binary search is aplicable only when list is sorted ''' def binary_search(list,item): ''' funtion for binary search of element in list synatx: binary_search( list,item) retrun index of element where the item is found return -1 when item is not found in list Time Complexity: O(logn) ''' beg=0 length=len(list) end=length-1 while(beg<=end): mid=(beg+end)//2 #finding middle element index #if item is mathched with middle element if(list[mid]==item): return mid #if item is less than the middle element than consider only left portion of list elif(list[mid]>item): end=mid-1 #if item is greater than the middle element than consider only right portion of list elif(list[mid]<item): beg=mid+1 if(beg>end ): return -1 list=[0,1,2,3,4,5,6,7] item=6 result=binary_search(list,item) if result== -1: print("Not Found !") else: print(result)
true
edd37b42b381dfc85b5f443b79e151f7225b9201
vishalkmr/Algorithm-And-Data-Structure
/Arrays & Strings/Array Pair Sum.py
2,761
4.40625
4
''' Given an integer array, output all the unique pairs that sum up to a specific value k. Example pair_sum([1,2,3,4,5,6,7],7) Returns: (3, 4), (2, 5), (1, 6) ''' #using Sorting def pair_sum(list,k): ''' Funtion return all the unique pairs of list elements that sum up to k Syntax: insert(list,k) Time Complexity: O(nlogn) ''' list.sort() #sorting the list length=len(list) pairs=[] #for storing the list of pairs that sum up to k i=0 #pointing to begining of the list (Smallest number in the list) j=length-1 #pointing to ending of the list (Largest number in the list) #making iterations until i and j points to the same element while i<=j: #if sum of list[i] & list[j] is equal to k that means it is one of the desired pair if list[i]+list[j]==k: pairs.append((list[i],list[j])) i+=1 j-=1 #if these pair sum is less than k #we know that the list is sorted and hence j is pointing to Largest number in the list #so it is due to value of number pointed by i that is causes there sum to be lesser than k #Thus we increment the pointer i so that the sum of values pointed by i and j may gets equal to k elif list[i]+list[j]<k: i+=1 #if these pair sum is greater than k #we know that the list is sorted and hence i is pointing to Smallest number in the list #so it is due to value of number pointed by j that is causes there sum to be greater than k #Thus we dicrement the pointer j so that the sum of values pointed by i and j may gets equal to k else: j-=1 return pairs #using Set def pair_sum(list,k): ''' Funtion return all the unique pairs of list elements that sum up to k Syntax: insert(list,k) Time Complexity: O(n) ''' pairs=[] #for storing the list of pairs that sums up to k seen=set() #for storing the elements of the list which are alredy seened for current in list: target=k-current #stores the desiered value or target value ( which when added to current element of the list yiedls to the sum k ) #if target value is found in the seen set #then the sum of target and list current element is equal to k #Thus we add target & current element touple onto the pairs list if target in seen: pairs.append((min(target,current),max(target,current))) #formating the pairs touple so like (min_value_of_pairs,max_value_of_pairs) #if target value is not found in the seen set #means the sum of any element of seen set with the current element doesnot yields to k #Thus we simply add current element of the list to the seen set in a hop that may be this added_current_element_values can be summed up with upcomming element to produce k else: seen.add(current) return pairs list=[1,2,3,4,5,6,7] pairs=pair_sum(list,7) print(pairs)
true
aba4633ded621a38d9a0dd4a6373a4b70ee335d9
vishalkmr/Algorithm-And-Data-Structure
/Linked Lists/Rotate Right.py
1,755
4.40625
4
''' Rotates the linked-list by k in right side Example: link-list : 1,2,3,4,5,6 after 2 rotation to right it becomes 5,6,1,2,3,4 ''' from LinkedList import LinkedList def rotate_right(linked_list,k): """ Rotates the linked-list by k in right side Syntax: rotate_right(linked_list,k) Time Complexity: O(n) """ #for circular rotation if k>=len(linked_list): k=k%len(linked_list) if len(linked_list)==0 or k==0: return count=0 current=linked_list.head previous=None #break the linked_list into two portion while current and count!=(len(linked_list)-k): previous=current current=current.next count=count+1 previous.next=None #previous represent new likedlist last element linked_list.tail=previous #update the new linked_list tail #now list is splited into two portion #1st contains node form begining of original linked_list to previous node (left list) #2nd contains from current node to last node (right list) #for rotation we just have to append 1st linked-list after 2nd linked-list if count==(len(linked_list)-k): ptr=current while ptr.next: ptr=ptr.next #ptr points to 2nd linked_list last node #joining the 1st linked_list at the end of 2nd linked_list ptr.next=linked_list.head linked_list.head=current #update the new linked_list head linked_list=LinkedList() linked_list.insert_end(1) linked_list.insert_end(2) linked_list.insert_end(3) linked_list.insert_end(4) linked_list.insert_end(5) linked_list.insert_end(6) print(linked_list) result=rotate_right(linked_list,2) print(linked_list)
true
bac0d9c2b34bf891722e468c11ff0f615faef1fc
vishalkmr/Algorithm-And-Data-Structure
/Arrays & Strings/Missing element.py
1,576
4.28125
4
''' Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array. Example : The first array is shuffled and the number 5 is removed to construct the second array then missing_element([1,2,3,4,5,6,7],[3,7,2,1,4,6]) Returns: 5 ''' #using Soting def missing_element(arr1,arr2): ''' Funtion return missing element Syntax: missing_element(arr1,arr2) Time Complexity: O(nlogn) ''' # Sort the arrays arr1.sort() arr2.sort() # Compare elements in the sorted arrays for num1, num2 in zip(arr1,arr2): if num1!= num2: return num1 #using Dictionary def missing_element1(arr1,arr2): ''' Funtion return missing element Syntax: missing_element(arr1,arr2) Time Complexity: O(n) ''' count={} #Storing the element count of array2 in Dictionary for i in arr2: if i in count: count[i]+=1 else: count[i]=1 #Compairing the element count of array1 with Dictionary elements for i in arr1: if i not in count: return i elif count[i]==0: return i else: count[i]-=1 #using EXOR-Logic def missing_element(arr1,arr2): ''' Funtion return missing element Syntax: missing_element(arr1,arr2) Time Complexity: O(n) ''' result=0 # Perform an XOR between the numbers in the concatnated arrays (arr1+arr2) for num in arr1+arr2: result^=num return result arr1 = [1,2,3,4,5,6,7] arr2 = [3,7,2,1,4,6] output=missing_element1(arr1,arr2) print(output)
true
23ad168cebd9f937871f8ef52f0822387308dbc5
vishalkmr/Algorithm-And-Data-Structure
/Trees/Mirror Image.py
1,639
4.34375
4
''' Find the Mirror Image of a given Binary tree Exapmle : 1 / \ 2 3 / \ / \ 4 5 6 7 Mirror Image : 1 / \ 3 2 / \ / \ 7 6 5 4 ''' from TreeNode import Node def mirror_image(root): """ Return Mirror Image of the given Tree Syntax: mirror_image(root) Time Complexity: O(n) Recurrence Relation : Best Case : T(n)=2T(n/2)+C (C represents constant) Worst Case : T(n)=T(n-1)+C (C represents constant) """ # if Tree is empty if not root: return root #if leaf node if root.left==None and root.right==None: return root temp=root.right root.right=mirror_image(root.left) root.left=mirror_image(temp) return root #to display mirror image def preorder(root): """ Function to find Preorder traversal of the given Tree Syntax: inorder(root) Time Complexity: O(n) Recurrence Relation : Best Case : T(n)=2T(n/2)+C (C represents constant) Worst Case : T(n)=T(n-1)+C (C represents constant) """ # if Tree is empty if not root: return print(root.data) #root preorder(root.left) #left preorder(root.right) #right a=Node(1) b=Node(2) c=Node(3) d=Node(4) e=Node(5) f=Node(6) g=Node(7) a.left=b a.right=c b.left=d b.right=e c.left=f c.right=g print('Preorder Traversal Before Mirroring') preorder(a) root=mirror_image(a) print('Preorder Traversal After Mirroring') preorder(root)
true
8f8ba9c1a6e13d1527f0c3ac5c2a72dc330a0321
vishalkmr/Algorithm-And-Data-Structure
/Sorting/Bubble Sort.py
2,203
4.5625
5
''' SORT the given array using Bubble Sort Example: Let us take the array of numbers "5 1 4 2 8", and sort the array in ascending order using bubble sort. First Pass ( 5 1 4 2 8 ) -> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1 5 4 2 8 ) -> ( 1 4 5 2 8 ), Swap since 5 > 4 ( 1 4 5 2 8 ) -> ( 1 4 2 5 8 ), Swap since 5 > 2 ( 1 4 2 5 8 ) -> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. Second Pass ( 1 4 2 5 8 ) -> ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) -> ( 1 2 4 5 8 ), Swap since 4 > 2 ( 1 2 4 5 8 ) -> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) -> ( 1 2 4 5 8 ) Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. Third Pass ( 1 2 4 5 8 ) -> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) -> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) -> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) -> ( 1 2 4 5 8 ) Simmilarly other Passes yields same Sorted Array..... ''' #Conventional Bubble Sort def bubble_sort(list): ''' Funtion to sort the list using Bubble Sort Syntax: bubble_sort(list) Time Complexity: O(n^2) [Every Case] ''' for elements in list: for index in range(len(list)-1): #check the adjecent elements are in increasing order or not if list[index]>list[index+1]: #if not then perform pairwise swaps list[index],list[index+1]=list[index+1],list[index] #Efficient Bubble Sort def bubble_sort(list): ''' Funtion to sort the list using Bubble Sort Syntax: bubble_sort(list) Time Complexity: Worst Case : O(n^2) Best Case : O(n) ''' swapped = True #Flag to monitor that swaping ocuured or not while swapped: swapped = False for index in range(len(list)-1): #check the adjecent elements are in increasing order or not if list[index] > list[index+1]: #if not then perform pairwise swaps list[index],list[index+1]=list[index+1],list[index] swapped = True list=[7, 6, 5, 4, 3, 2, 1] bubble_sort(list) print(list)
true
30a98b2f034a60422a2faafbd044628cd1011e43
vishalkmr/Algorithm-And-Data-Structure
/Arrays & Strings/Max and Min(Recursion).py
1,108
4.40625
4
''' Find the maximum and minimum element in the given list using Recursion Example max_min([11,-2,3,6,14,8,16,10]) Returns: (-2, 16) ''' def max_min(list,index,minimum,maximum): ''' Funtion to return maximum and minimum element in the given list Syntax: max_min(list,index,minimum,maximum) Time Complexity: O(n) Space Complexity: O(n) Recurence Relation : T(n)=T(n-1)+C (C represents constant) ''' if index <len(list): #if current element is lesser than minimum then make the current element as the minimum element if list[index]<minimum: minimum=list[index] #if current element is greater than maximum then make the current element as the maximum element if list[index]>maximum: maximum=list[index] #recursively compute the maximum and minimum element of the remaining list return max_min(list,index+1,minimum,maximum) #if all element of list are encountered #return the current maximum and minimum element else : return (minimum ,maximum) list=[11,-2,3,6,14,8,16,10] minimum=9999 maximum=-9999 result=max_min(list,0,minimum,maximum) print(result)
true
4106cc2dccfacb7322a9e00a440321b30d224e30
vishalkmr/Algorithm-And-Data-Structure
/Searching/Ternary Search.py
1,860
4.46875
4
''' Ternary Search on lists Assume that list is already in Ascending order. The number of Recursive Calls and Recisrion Stack Depth is lesser for Ternary Search as compared to Binary Search ''' def ternary_search(list,lower,upper,item): ''' Funtion for binary search of element in list Synatx: ternary_search(list,lower,upper,item) Return index of element where the item is found Time Complexity: O(logn) Space Complexity: O(logn) Recurence Relation : T(n)=T(n/3)+C (C represents constant) ''' if lower<=upper: first_middle=lower+((upper-lower)//3) #finding 1st middle element which is at (n/3)rd index of list second_middle=lower+(((upper-lower)*2)//3) #finding 2nd middle element which is at (2n/3)rd index of list #if item is mathched with first_middle element then first_middle is the required index if list[first_middle]==item : return first_middle #if item is mathched with second_middle element then second_middle is the required index elif list[second_middle]==item: return second_middle #if item is less than the first_middle element then apply Ternary Search on Left portion of list elif list[first_middle]>item: return ternary_search(list,lower,first_middle-1,item) #if item is between than the first_middle and second_middle then apply Ternary Search on Middle portion of list elif list[first_middle]<item and item<list[second_middle]: return ternary_search(list,first_middle+1,second_middle-1,item) #if item is greater than the second_middle then apply Ternary Search on Right portion of list elif list[second_middle]<item : return ternary_search(list,second_middle+1,upper,item) list=[0,1,2,3,4,5,6,7] item=5 result=ternary_search(list,0,len(list)-1,item) if result!=None: print(result) else: print('Not Found !')
true
29c60efe0b91a9c74c2eebe4d9ce599a8c52ba7f
vishalkmr/Algorithm-And-Data-Structure
/Linked Lists/Cyclic.py
1,733
4.21875
4
''' Check the given limked-list is cyclic or not ''' from LinkedList import LinkedList #using Set def is_cyclic(linked_list): """ Returns True if linked-list is cyclic Syntax: is_cyclic(linked_list) Time Complexity: O(n) """ # if linked-list is empty if not linked_list.head or not linked_list.head.next: return False visited=set() current=linked_list.head while current: #if the node is already in visited set that mean linked-list is cyclic if current.data in visited: return True #if the node is not visited set that means it appears 1st time so add it on the visited set else: visited.add(current.data) #incement the loop counter current=current.next return False def is_cyclic(linked_list): """ Returns True if linked-list is cyclic Syntax: is_cyclic(linked_list) Time Complexity: O(n) """ # if linked-list is empty if not linked_list.head or not linked_list.head.next: return False slow = fast =linked_list.head while fast and fast.next: slow=slow.next #slow takes one step at a time fast= fast.next.next #fast takes two step at a time #if slow meets with fast that means linked-list is cyclic if fast==slow: return True return False linked_list=LinkedList() linked_list.insert_end(1) linked_list.insert_end(2) linked_list.insert_end(3) linked_list.insert_end(4) linked_list.insert_end(5) linked_list.insert_end(6) #making the linked-list cyclic linked_list.tail.next=linked_list.head result=is_cyclic(linked_list) print(result)
true
ea402428794a71e381266fdac172b0f6a2e5b105
prpratheek/Interview-Problem-Statements-HacktoberFest2020
/Power_Function.py
417
4.34375
4
def power(x, y): res = 1 while (y > 0): # If y is odd, multiply # x with result if ((y & 1) == 1) : res = res * x # n must be even # now y = y/2 y = y >> 1 # Change x to x^2 x = x * x return res # Driver Code x = 3 y = 5 print("Power is ", power(x, y))
false
967ac148b13a59295b9c16523e6e046ffd000950
PdxCodeGuild/Full-Stack-Day-Class
/practice/solutions/ttt-interface/list_board.py
1,184
4.1875
4
"""Module containing a list of lists tic-tac-toe board implementation.""" class ListListTTTBoard: """Tic-Tac-Toe board that implements storage as a list of rows, each with three slots. The following board results in the following data structure. X| | |X|O | | [ ['X', ' ', ' '], [' ', 'X', 'O'], [' ', ' ', ' '], ] """ def __init__(self): """Initialize an empty board.""" self.rows = [ [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '], ] def place_token(self, x, y, player): """Place a token on the board at some given coordinates. x is horizontal position, y is vertical position. 0, 0 is the top-left. `player` is either 'X' or 'O' """ pass def calc_winner(self): """Return which token type won ('X' or 'O') or None if no one has won yet. """ pass def __str__(self): """Return a string representation of the board. Should be three rows with each cell separated by a '|'. X| | |X|O | | """ pass
true
dcc6eac9a830867df9b8bf1dbc28c592c4458990
priyankamadhwal/MCA-101-OOP
/14- bubbleSort.py
1,139
4.28125
4
def swap(lst, lowerIndex=0, pos=0): ''' OBJECTIVE : To swap the elements of list so that the largest element goes at the lower index. INPUT : lst : A list of numbers. lowerIndex : The lower index upto which swapping is to be performed. OUTPUT : List, with the correct element at lowerIndex. ''' #APPROACH : Compare the 2 list elements: If lst[up] is greater than lst[low], then swap them. length = len(lst) up=length-1-pos low=up-1 if low < lowerIndex: return if lst[up] > lst[low]: temp = lst[up] lst[up] = lst[low] lst[low] = temp swap(lst, lowerIndex, pos+1) def bubbleSort(lst, lowerIndex=0): ''' OBJECTIVE : To sort the given list using bubble sort. INPUT : lst : A list of numbers. lowerIndex : The lower index from which sorting should begin. OUTPUT : List, sorted in descending order. ''' #APPROACH : Make use of the swap() function. length = len(lst) if lowerIndex > length-2: return swap(lst, lowerIndex) bubbleSort(lst, lowerIndex+1)
true
16bc2814112b7bd4fad04457af0ba79ccf21e68a
soumilk91/Algorithms-in-Python
/Mathematical_algorithms/calculate_fibo_number.py
1,414
4.21875
4
""" @ Author : Soumil Kulkarni This file contains various methods related to problems on FIBO Series """ import sys # Method to calculate the fibo number recursively def calculate_fibo_number_recursive(num): if num < 0: print "Input incorrect" elif num == 0 : return 0 elif num == 1 : return 1 else : return (calculate_fibo_number_recursive(num - 1) + calculate_fibo_number_recursive(num -2 )) # Method to calculate fibo number using a list def calculate_fibo_number_with_list(num): num_list =[0,1] if num < 0: print "Input incorrect" elif num == 0: return 0 elif num == 1: return 1 else: n = num - 2 pointer_1 = 0 poniter_2 = 1 for i in range(n): num_list.append(num_list[pointer_1] + num_list[poniter_2]) pointer_1 += 1 poniter_2 += 1 return (num_list[pointer_1] + num_list[poniter_2]) # Method to reduce the space complexity in the previous soultion. # Hint : All you need is the last 2 digits, so just store the last 2 digits and neglect the others. Space complexity will be reduced from O(N) to O(1) def calulate_fibo_number_with_list_improved(num): num_list = [0,1] if num < 0: print "Input incorrect" elif num == 0: return 0 elif num == 1: return 1 else: n = num - 2 pointer_1 = 0 poniter_2 = 1 for i in range (n): temp = num_list[0] + num_list[1] num_list[0] = num_list[1] num_list[1] = temp return (num_list[0] + num_list[1])
true
8358b7abc87c5062eeb4b676eb1091b5d6d897ba
abhijit-nimbalkar/Python-Assignment-2
/ftoc.py
530
4.125
4
#Author-Abhijit Nimbalkar & Sriman Kolachalam import Functions #importing Functions.py file having multiple functions temp_in_F=Functions.check_temp_input_for_F("Enter the Temperature in Fahrenheit: ") #Calling function check_temp_input_for_F() for accepting the valid input from User temp_in_C=Functions.FtoC(temp_in_F) #Calling function to convert temperature from Fahrenheit to Celsius print("{0}{1:0.2f}".format("Temperature in Celsius is: ", temp_in_C)) #printing the output in right format
true
685d18829d1197fa5471cfed83446b14af65789e
hsuvas/FDP_py_assignments
/Day2/Q6_FibonacciRecursion.py
263
4.25
4
#6. fibonacci series till the Nth term by using a recursive function. def fibo(n): if n<=1: return n else: return (fibo(n-1)+fibo(n-2)) n=int(input("How many numbers: ")) print("Fibonacci series: ") for i in range(n): print(fibo(i))
true
99bb6059454cf462afbe9bfc528b8ea6d9d84ecb
hsuvas/FDP_py_assignments
/Day2/Q3_areaCircumference.py
279
4.5
4
#3.compute and return the area and circumference of a circle. def area(r): area=3.14*r*r return area def circumference(r): c=2*3.14*r return c r=float(input("enter the radius")) a=area(r) print("area is: ",a) cf=circumference(r) print("Circumference is: ",cf)
true
db52166c1da16e74c737522bf01ccbc2e3a5331b
jared0169/Project_Euler_Code
/PE_Problem4.py
563
4.1875
4
# File: PE_Problem4.py # # Finds the largest palindrome that results from the multiplication # of two three digit numbers. import string def main(): i = 100 j = 101 largest_palindrome = 0 for i in range(100,999): for j in range(100,999): ## print "Forwards: " + str(i*j) ## print "Backwards: " + str(i*j)[::-1] ## break if str(i*j) == str(i*j)[::-1] and i*j > largest_palindrome: largest_palindrome = i * j print largest_palindrome if __name__ == "__main__": main()
false
edb63793a549bf6bf0e4de33f86a7cefb1718b57
onionmccabbage/python_april2021
/using_logic.py
355
4.28125
4
# determine if a number is larger or smaller than another number a = int(float(input('first number? '))) b = int(float(input('secomd number? '))) # using 'if' logic if a<b: # the colon begins a code block print('first is less than second') elif a>b: print('second is less than first') else: print('probably the same number')
true
ee715cb90cf4724f65c0f8d256be926b66dc1ddb
onionmccabbage/python_april2021
/fifo.py
1,739
4.1875
4
# reading adnd writing files file-input-file-output # a simple idea is to direct printout to a file # fout is a common name for file output object # 'w' will (over)write the file 'a' will append to the file. 't' is for text (the default) fout = open('log.txt', 'at') print('warning - lots of interesting loggy stuff', file=fout) fout.close() # clean up when done # we can write to a file a bit at a time long_str = '''we can use a while loop to automatically close any open file access objects This saves us doing it explicitly''' try: fout = open('other.txt', 'xt') # 'a' to append, 'x' for exclusive access size = len(long_str) offset = 0 chunk = 24 while True: if offset > size: fout.write('\n') # we need to put our own new line at the end of the file (if needed) break else: fout.write(long_str[offset:offset+chunk]) offset+=chunk except FileExistsError as err: print('the file already exists', err.errno) except Exception as err: print(err) finally: print('all done') # next we read content in from text files via a file access object fin = open('other.txt', 'r') # 'r' for read ('t' is the default) # received = fin.read() # reads the entire file received = fin.readline()+'---'+fin.readline() # reads TWO lines! fin.close() # tidy up print(received) # writing and reading byte files # we need some bytes b = bytes( range(0, 256) ) print(b) fout = open('bfile', 'wb') # 'wb' to (over)write bytes fout.write(b) fout.close() # now read them back in fin = open('bfile', 'rb') # 'rb' to read bytes retrieved_b = fin.read() # read the whole file fin.close() print(retrieved_b)
true
4417ee4d4251854d55dd22522dfef83a0f55d396
VadymGor/michael_dawson
/chapter04/hero's_inventory.py
592
4.40625
4
# Hero's Inventory # Demonstrates tuple creation # create an empty tuple inventory = () # treat the tuple as a condition if not inventory: print("You are empty-handed.") input("\nPress the enter key to continue.") # create a tuple with some items inventory = ("sword", "armor", "shield", "healing potion") # print the tuple print("\nThe tuple inventory is:") print(inventory) # print each element in the tuple print("\nYour items:") for item in inventory: print(item) input("\n\nPress the enter key to exit.")
true
6d19be295873c9c65fcbb19b9adbca57d700cb64
vedk21/data_structure_playground
/Arrays/Rearrangement/Pattern/alternate_positive_negative_numbers_solution.py
1,882
4.125
4
# Rearrange array such that positive and negative elements are alternate to each other, # if positive or negative numbers are more then arrange them all at end # Time Complexity: O(n) # Auxiliary Space Complexity: O(1) # helper functions def swap(arr, a, b): arr[a], arr[b] = arr[b], arr[a] return arr def rightRotate(arr, size, startIndex, endIndex): temp = arr[endIndex] for i in range(endIndex, startIndex, -1): arr[i] = arr[i - 1] arr[startIndex] = temp return arr def arrange(arr, size): # divide array into positive and negative parts i = 0 for j in range(size): if arr[j] < 0: arr = swap(arr, j, i) i += 1 # get index for positive and negative elements positive = i negative = 0 # increase negative index by 2 and positive index by 1 and swap elements while(positive < size and negative < positive and arr[negative] < 0): arr = swap(arr, positive, negative) negative += 2 positive += 1 return arr # Rearrange array such that positive and negative elements are alternate to each other, # if positive or negative numbers are more then arrange them all at end # here we maintain the initial sequence def arrangeInSeq(arr, size): outOfPlaceIndex = -1 for i in range(size): if outOfPlaceIndex >= 0: if (arr[i] < 0 and arr[outOfPlaceIndex] >= 0) or (arr[i] >= 0 and arr[outOfPlaceIndex] < 0): arr = rightRotate(arr, size, outOfPlaceIndex, i) # rearrange outOfPlaceIndex if i - outOfPlaceIndex >= 2: outOfPlaceIndex += 2 else: outOfPlaceIndex = -1 if outOfPlaceIndex == -1: if (arr[i] < 0 and i % 2 == 0) or (arr[i] >= 0 and i % 2 != 0): outOfPlaceIndex = i return arr
true
e149ad4cc8b69c2addbcc4c5070c00885d26726d
KyrillMetalnikov/HelloWorld
/Temperature.py
329
4.21875
4
celsius = 10 fahrenheit = celsius * 9/5 + 32 print("{} degrees celsius is equal to {} degrees fahrenheit!".format(celsius, fahrenheit)) print("Roses are red") print("Violets are blue") print("Sugar is sweet") print("But I have commitment issues") print("So I'd rather just be friends") print("At this point in our relationship")
true
c018cea22879247b24084c56731289a2a0f789f5
abhay-jindal/Coding-Problems
/Minimum Path Sum in Matrix.py
1,409
4.25
4
""" MINIMUM PATH SUM IN MATRIX https://leetcode.com/problems/minimum-path-sum/ https://www.geeksforgeeks.org/min-cost-path-dp-6/ Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. """ def minPathSum(grid, row=0, column=0): row = len(grid) column = len(grid[0]) matrix = [[0 for _ in range(column)] for _ in range(row)] matrix[0][0] = grid[0][0] for i in range(1, row): matrix[i][0] = matrix[i-1][0] + grid[i][0] for i in range(1, column): matrix[0][i] = matrix[0][i-1] + grid[0][i] # For rest of the 2d matrix for i in range(1, row): for j in range(1, column): matrix[i][j] = grid[i][j] + min(matrix[i - 1][j], matrix[i][j - 1]) # In case we can move diagonally as well, consider the previous diagonal element # matrix[i][j] = grid[i][j] + min(matrix[i - 1][j], matrix[i][j - 1], min[i-1][j-1]) return matrix[row-1][column-1] rows = int(input("Number of rows: ")) columns = int(input("Number of columns: ")) grid = [] for _ in range(rows): grid.append(list(map(int,input("\nEnter the elements: ").strip().split()))[:columns]) print(f"Minimum path sum in given matrix: {}")
true
a711681f3168d9f733694126d0487f60f39cdf56
abhay-jindal/Coding-Problems
/Linked List Merge Sort.py
1,275
4.21875
4
""" LINKEDLIST MERGE SORT """ # Class to create an Linked list with an Null head pointer class LinkedList: def __init__(self): self.head = None # sorting of linked list using merge sort in O(nlogn) time complexity def mergeSort(self, head): if head is None or head.next is None: return head middle = self.getMiddleNode(head) nextToMiddle = middle.next middle.next = None left = self.mergeSort(head) right = self.mergeSort(nextToMiddle) sortedList = self.sortedMerge(left, right) return sortedList # helper function for merge sort to compare two elements of partitioned linkedlist. def sortedMerge(self, left, right): sortedList = None if left == None: return right if right == None: return left if left.data <= right.data: sortedList = left sortedList.next = self.sortedMerge(left.next, right) else: sortedList = right sortedList.next = self.sortedMerge(left, right.next) return sortedList # class to create a new node of an linkedlist class Node: def __init__(self,data): self.data = data self.next = None
true
c2c19d072b086c899b227646826b7ef168e24a78
abhay-jindal/Coding-Problems
/Array/Zeroes to Left & Right.py
1,239
4.125
4
""" MOVE ZEROES TO LEFT AND RIGHT IN ARRAY https://leetcode.com/problems/move-zeroes/ Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Time complexity: O(n) """ def zerosToRight(nums, n): start = -1 for i in range(n): if nums[i] == 0: if start < 0: start = i else: continue elif start >= 0: nums[start] = nums[i] nums[i] = 0 start += 1 return nums def zerosToLeft(nums, n): last = -1 for i in range(n-1, -1, -1): if nums[i] == 0: if last < 0: last = i else: continue elif last >= 0: nums[last] = nums[i] nums[i] = 0 last -= 1 return nums if __name__ == "__main__": n = int(input('Number of elements: ')) array = list(map(int,input("\nEnter the elements: ").strip().split()))[:n] print(f"Array after moving all zeroes to left: {zerosToLeft(array, n)}") print(f"Array after moving all zeroes to right: {zerosToRight(array, n)}")
true
952943db49fe23060e99c65a295d35c1aff7c7d5
abhay-jindal/Coding-Problems
/LinkedList/check_palindrome.py
2,523
4.21875
4
""" Palindrome Linked List https://leetcode.com/problems/palindrome-linked-list/ https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/ Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false. """ from main import LinkedList from get_middle_node import get_middle_node from reverse_linked_list import reverse_list def is_palindrome(head): if head is None or head.next is None: return True before_mid = head mid_node = get_middle_node(head) # get middle node of linkedlist from where the next half will be reversed for comparison. next_to_mid = mid_node.next # store next to mid in temp variable # make first half of list independent of second half, both lists will be treated as separate lists. mid_node.next = None after_mid = reverse_list(next_to_mid) # reverse second half list and store the list in variable # here the main comparison happens, as soon as we find unequal data, we return False. while after_mid is not None: if after_mid.data != before_mid.data: return False after_mid = after_mid.next before_mid = before_mid.next # if list is odd, then one node will be left after above comparisons, and we simply return True if before_mid.next is None: return True # if list is even, two nodes will be left to compare, compare before_mid and its next and return accordingly. elif before_mid.data == before_mid.next.data: return True return False # A simple solution is to use a stack of list nodes. def is_palindrome_using_stack(head): if head is None or head.next is None: return True stack, curr = [], head while curr is not None: stack.append(curr.data) curr = curr.next curr = head nodes_to_check = len(stack)//2 # to check first half stack elements with first half of linkedlist while nodes_to_check != 0 and stack and curr is not None: temp = stack.pop() if curr.data != temp: return False curr = curr.next nodes_to_check -= 1 return True if __name__ == "__main__": n = int(input('Number of nodes to be inserted: ')) vals = list(map(int,input("\nEnter the node values in space separated manner: ").strip().split()))[:n] list = LinkedList() list.insert_nodes(vals) print(f"Is list a Palindrome: {is_palindrome_using_stack(list.head)}")
true
9be41506dd4300748e2b37c19e73cd4e62d107f7
abhay-jindal/Coding-Problems
/LinkedList/last_nth_node.py
1,537
4.28125
4
""" Clockwise rotation of Linked List https://leetcode.com/problems/rotate-list/ https://www.geeksforgeeks.org/clockwise-rotation-of-linked-list/ Given a singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places. """ from main import LinkedList # function to return nth node from end of the list def get_nth_from_last(head, n): # corner cases if head is None or head.next is None: return head # get to the nth node of list from head. start = head temp = None for _ in range(n-1): start = start.next # if n is out of range then start will be None, therefore return if start is None: return "Nth index out of range!" # initialize second pointer to again start from head while start pointer which is at nth index reaches the end # of list. second_start = head while start.next is not None: temp = second_start start = start.next second_start = second_start.next return second_start if __name__ == "__main__": n = int(input('Number of nodes to be inserted: ')) vals = list(map(int,input("\nEnter the node values in space separated manner: ").strip().split()))[:n] k = int(input('Nth node position from end: ')) list = LinkedList() list.insert_nodes(vals) print(list) # to print linkedlist representation in 1 -> 2 -> 3 -> None nth_node = get_nth_from_last(list.head, k) print(f"Node from end of linked list: {nth_node}")
true
45eb0065c98e74c6502b973fc234b6a19ffed92a
bakossandor/DataStructures
/Stacks and Queues/single_array_to_implement_3_stacks.py
910
4.28125
4
# describe how would you implement 3 stack in a single array # I would divide the array into 3 spaces and use pointer to mark the end of each stack # [stack1, stack1, stack2, stack2, stack3, stack3] # [None, None, "1", None, "one", "two"] class threeStack: def __init__(self): self.one = 0 self.two = 0 self.three = 0 self.arr = [] def add(self, data, where): if where == 1: self.arr.insert(self.one, data) self.one += 1 elif where == 2: self.arr.insert(self.one + self.two, data) self.two += 1 elif where == 3: self.arr.insert(self.one + self.two + self.three, data) self.three += 1 def printArr(self): print(self.arr) stack = threeStack() stack.add("whatup", 3) stack.add("wher is this", 1) stack.add("twotwo", 2) stack.add("one one", 1) stack.printArr()
true
b86d42a1ed8bd87ddae179fda23d234096459e0c
bakossandor/DataStructures
/LinkedLists/linked_list.py
2,278
4.28125
4
# Implementing a Linked List data structure class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def add(self, val): new_node = Node(val) if self.head is not None: new_node.next = self.head self.head = new_node else: self.head = new_node def remove(self, val): # removing item 2 # [1 -> 2 -> 3] # [1 -> 3] if self.head is None: return False current_node = self.head previous_node = None removed = False while current_node is not None and removed is False: if current_node.data is val: if previous_node is None: # it means we are at the first iteration # and just need to change the head pointer self.head = current_node.next else: # if the element is in the middle of the list # change the next pointer of the previous node previous_node.next = current_node.next removed = True previous_node = current_node current_node = current_node.next return removed def search(self, val): current_node = self.head found = False while current_node is not None and not found: if current_node.data is val: found = True else: current_node = current_node.next return found def print_values(self): current_node = self.head while current_node is not None: print(current_node.data) current_node = current_node.next new_list = LinkedList() for test_val in range(5): new_list.add(test_val) # new_list.print_values() # print(new_list.search(2)) # print(new_list.search("string")) value_to_add_and_remove = "this is the value" new_list.add(value_to_add_and_remove) new_list.print_values() new_list.search(value_to_add_and_remove) print(new_list.remove(value_to_add_and_remove)) print(new_list.search(value_to_add_and_remove)) new_list.remove(2) print("remove 2") new_list.print_values()
true
0578c44f2473824f40d21139c27241366873de41
AnnaLupica/Election-Analysis
/xArchive/Python-practice.py
1,591
4.34375
4
#Creating list counties=["Arapahoe", "Denver", "Jefferson"] print(counties[2]) for county in counties print(county) #Insert new item in list counties.append("El Paso") counties.insert(2,"El Paso") #Remove item from list counties.remove("El Paso") counties.pop(3) print(counties) #Change item in list counties[2]="El Paso" print(counties) #Mod list counties[2]="Jefferson" counties.insert(1,"El Paso") counties.remove("Arapahoe") counties[2]="Denver" counties[1]="Jefferson" counties.append("Arapahoe") print(counties) #Tuples counties_tuple=("Arapahoe", "Denver", "Jefferson") len(counties_tuple) counties_tuple[1] #List of Dictionaries voting_data=[] voting_data.append=({"county":"Arapahoe","registered_voters":422839}) voting_data.append=({"county":"Denver","registered_voters":463353}) voting_data.append=({"county":"Jefferson","registered_voters":432438}) print(voting_data) for county in counties_dict.keys(): print(county) #How many votes did you get? my_votes=int(input("How many votes did you get in the election?")) #Total votes in teh election total_votes=int(input("What is the total votes in the election?")) #Calculate the percentage of votes you've received percentage_votes=(my_votes/total_votes)*100 print("I received"+str(percentage_votes)+"% of the total votes") score = int(input("What is your test score?")) if score >= 90: print('Your grade is an A') elif score >= 80: print('Your grade is a B') elif score >= 70: print('Your grade is a C') elif score >= 60: print('Your grade is a D') else: print('Your grade is an F')
false
97d430a520e681cd8a0db52c1610436583bf9889
raj-rox/Coding-Challenges
/hurdle.py
946
4.125
4
#1st attempt. DONE. bakwaas #https://www.hackerrank.com/challenges/the-hurdle-race/problem #!/bin/python3 import math import os import random import re import sys # # Complete the 'hurdleRace' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER k # 2. INTEGER_ARRAY height # def hurdleRace(k, height): # Write your code here max=height[0] for i in height: if max<i: max=i if max<=k: return 0 else: return (max-k) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) k = int(first_multiple_input[1]) height = list(map(int, input().rstrip().split())) result = hurdleRace(k, height) fptr.write(str(result) + '\n') fptr.close()
true
8d13f16e031bc71d3456e97ec3f98ce81ffe168f
tanbir6666/test-01
/python inside/python list comps 3h 3m.py
1,336
4.15625
4
names=["tanbir","taohid","tayeb","Robin","Amir"] empty_list=[] def loop(loopItem): for x in loopItem: print(x) for person in names: empty_list.append(person) print(empty_list) empty_list.clear() print(empty_list) print([person for person in names]) empty_list.clear() for person in names: print(person," The people That I know") empty_list.append(person + " The people That I know") print(empty_list) loop(empty_list) empty_list.clear() #let's to this in one line ||| always need the 3rd Brackets [] print([person+" Know people" for person in names]) loop([person+" Know people" for person in names]) #Fun time #let's loop threw Dictionary Movie_rateing={"Iron Man":7.5,"Hulk":5.8,"Thor":7.2,"Captain America":8.2} Movie_rateing["The Avengers"]=8.7 popular_movie=[] un_popular_movie=[] for rate in Movie_rateing: if Movie_rateing[rate]>=7.5: popular_movie.append(rate) elif Movie_rateing[rate]<7.5: un_popular_movie.append(rate) else: print("Somthing is wrong") print("popular_movie : ", popular_movie) print("un_popular_movie : ", un_popular_movie) #lets do this in one line. popular_movie.clear() un_popular_movie.clear() print([movie for movie in Movie_rateing if Movie_rateing[movie] >= 7.5])
false
6f134495fa15c220c501a82206a33839d0083079
tanbir6666/test-01
/starting codes/python after 1 hour.py
808
4.21875
4
newString="hello Tanbir"; print(type(newString)); newstring_value= newString[5:] print(newstring_value); print(newstring_value.upper()); print(newstring_value.lower()); print(newstring_value.replace("Tanbir", "Taohid")) print(newstring_value); #replace string whatTosay=newString.replace("hello","how are you"); print(whatTosay) # loop for array or list def loop(listItem): print("Primary stage :",listItem) print("loop through every pice :") itemNumnber=0; for items in listItem: itemNumnber+=1 print(itemNumnber," : ",items); #splits splitSay=whatTosay.split(" ") print(splitSay); loop(splitSay); splitSentence="hi whats up ! how you are doing ? I am coming Buddy. Are you ready ?"; splitWord2 = splitSentence.split("?") print(splitWord2[1]) loop(splitWord2)
true
9c6627692d958ddf64b87aaa495ce7e315dc8e8f
simon-fj-russell/ds_python
/linear_regression.py
2,509
4.1875
4
# Linear Regression model using stats models # First import the modules import pandas as pd import statsmodels.api as sm import seaborn as sns import matplotlib.pyplot as plt sns.set() # User made functions # Use Stats models to train a linear model # Using OLS -> ordinary least squares def train_lr_model(x, y): # X is the feature column(s) of the dataframe (can be in the format df['Column Title']) # y is the target column of the dataframe (can be in the format df['Column Title']) x = sm.add_constant(x) #We add the intercept term model = sm.OLS(y, x).fit() # print out the summary of the model print(model.summary()) return model # Plot observed and predicted values with respect to feature 'x' in log scale. # THERE CAN ONLY BE ONE FEATURE COLUMN (at the moment) def plot_observed_vs_predicted(x, y, pred): # X is the feature column(s) of the dataframe (can be in the format df['Column Title']) # y is the target column of the dataframe (can be in the format df['Column Title']) fig, ax = plt.subplots() plt.plot(x, y, label='Target Column') # Change label to your target column. plt.plot(x, pred, label='Regression') ax.set(xlabel='X Axis', ylabel='Y Axis') ax.set_xscale('log') # If you need to log one of the axis plt.title("Sample Plot") # Title of the graph plt.show() # Read as ether csv or from clipboard data = pd.read_csv('data.csv') data = pd.read_clipboard() # Check out the header to make sure everything is there. print(data.columns.values) # work out the correlation between the feature columns and the target column correlation = data.corr().loc[['Feature Column 1','Feature Column 2','Feature Column 3',...],['Target Column']] print(correlation) # Select the feature with the highest correlation and train the model on it. lr1 = train_lr_model(data['Feature Column 1'],data['Target Column']) # There can be more then one feature column, input x in the format data[['Feature Column 1','Feature Column 2','Feature Column 3',...]] lr2 = train_lr_model(data[['Feature Column 1','Feature Column 2','Feature Column 3',...]],data['Target Column']) # Now you have the model as lr1, use it to predict the Target Column based on a Feature Column pred = lr1.predict(sm.add_constant(data['Feature Column'])) print(pred.head(10)) # Once you have the predicted values you can feed them into the plot function to view the results vs actual data plot_observed_vs_predicted(data['Feature Column'], data['Target Column'], pred)
true
2e8a17d29fd352af98d0cc4b2b53d9d543601f6a
trenton1199/Python-mon-K
/Reminder.py
2,157
4.34375
4
from datetime import date import os def pdf(): pdf = input(f"would you like to turn {file_name} into a pdf file? [y/n] ").lower() if pdf == 'y': pdf_name = input("what would you like the pdf file to be named ") + ".pdf" font_size = int(input("what would you like your font size to be?")) # Python program to convert # text file to pdf file from fpdf import FPDF # save FPDF() class into # a variable pdf pdf = FPDF() # Add a page pdf.add_page() # set style and size of font # that you want in the pdf pdf.set_font("Arial", size=font_size) # open the text file in read mode f = open(file_name, "r") # insert the texts in pdf for x in f: pdf.cell(200, 10, txt=x, ln=1, align='C') # save the pdf with name .pdf pdf.output(pdf_name) question = input("Option A: create a new file or option B: continue with another file [a/b]").lower() if question == 'a': date = str(date.today()) file_name = input("what would you like the file name of this Reminder to be:") + ".txt" body = input("write your reminder here:") with open(file_name, 'w') as f: f.write(f"date: ") f.write(date) f.write(os.linesep) f.write(body) f.write(os.linesep) f.write( '----------------------------------------------------------------------------------------------------------------------------') f.write(os.linesep) pdf() elif question == 'b': file_name = input("what is the previous file name for the To do list? (please do not provide file type):") + ".txt" date = str(date.today()) body = input("write your reminder here:") with open(file_name, 'a') as f: f.write(f"date: ") f.write(date) f.write(os.linesep) f.write("To do:") f.write(body) f.write(os.linesep) f.write( '----------------------------------------------------------------------------------------------------------------------------') f.write(os.linesep) pdf()
true
2dfad5d7fcf6789c93002064f621691677899758
kraftpunk97-zz/Fundamentals-ML-Algos
/k_means.py
2,338
4.1875
4
#! /usr/local/bin/python3 '''Implementing the k-Means Clustering Algorithm from scratch''' import numpy as np import matplotlib.pyplot as plt import pandas as pd def kmeans(dataset, num_clusters=3, max_iter=10): ''' The k-means implemention ''' m, n = dataset.shape cluster_arr = np.zeros(dtype=int, shape=(m,)) # Initialize clusters cluster_centroids = np.array(dataset[np.random.randint(low=0, high=m, size=num_clusters )]) for i in range(max_iter): # To find which cluster a point belongs to, just find the cluster centroid # closest to that point. for i in range(m): cluster_arr[i] = np.argmin(np.linalg.norm(cluster_centroids - dataset[i], axis=1)) # This is where we update the cluster centroids to the mean position of # the datapoints in that cluster for i in range(num_clusters): cluster_family = dataset[np.where(cluster_arr == i)] cluster_centroids[i] = np.mean(cluster_family, axis=0) return cluster_centroids, cluster_arr def nice_plot(dataset, num_clusters, cluster_arr, cluster_centroids): '''A utility function that shows the distribution of data points and the cluster they belong to.''' color_list = ('red', 'blue', 'green', 'black', 'brown', 'turquoise') plt.figure() for i in range(num_clusters): idx = np.where(cluster_arr == i) plt.scatter(dataset[idx, 0], dataset[idx, 1], c=color_list[i], alpha=0.4) plt.scatter(cluster_centroids[:, 0], cluster_centroids[:, 1], c='white') plt.show() data = pd.read_csv('speeding_data.csv', header=0, delimiter='\t') data = data.drop('Driver_ID', axis=1) dataset = np.array(data) print("First, let's see how the points are distributed...") data.plot(x='Distance_Feature', y='Speeding_Feature', kind='scatter', alpha=0.4, c='black') plt.show() print('Running the kmeans algorithm...') num_clusters = 4 num_iterations = 8 cluster_centroids, cluster_arr = kmeans(dataset, num_clusters, num_iterations) print('Alogrithm ran successfully. Plotting results') nice_plot(dataset, num_clusters, cluster_arr, cluster_centroids)
true
ab87e9277d7605bb7353c381f192949b40abcc49
rprustagi/EL-Programming-with-Python
/MT-Python-Programming/MT-Programs/hanoi.py
2,368
4.5
4
#!/usr/bin/env python3 """ turtle-example-suite: tdemo_minimal_hanoi.py A minimal 'Towers of Hanoi' animation: A tower of N discs is transferred from the left to the right peg. The value of N is specified by command line argument An imho quite elegant and concise implementation using a tower class, which is derived from the built-in type list. Discs are turtles with shape "square", but stretched to rectangles by shapesize() --------------------------------------- To exit press STOP button --------------------------------------- """ from turtle import * import sys class Disc(Turtle): def __init__(self, n): Turtle.__init__(self, shape="square", visible=False) self.pu() self.shapesize(1.5, n*1.5, 2) # square-->rectangle self.fillcolor(n/(num_of_disks * 1.0), 1.0, 1-n/(num_of_disks * 1.0)) self.st() class Tower(list): "Hanoi tower, a subclass of built-in type list" def __init__(self, x): "create an empty tower. x is x-position of peg" self.x = x def push(self, d): d.setx(self.x) d.sety(-150+34*len(self)) self.append(d) def pop(self): d = list.pop(self) d.sety(150) return d def hanoi(n, from_, with_, to_): if n > 0: hanoi(n-1, from_, to_, with_) to_.push(from_.pop()) #textinput("Hanoi Tower", "Press any key to continue") hanoi(n-1, with_, from_, to_) def play(): onkey(None,"s") clear() try: hanoi(num_of_disks, t1, t2, t3) write("press q to exit", align="center", font=("Courier", 16, "bold")) except Terminator: pass # turtledemo user pressed STOP def main(): global t1, t2, t3 ht(); penup(); goto(0, -225) # writer turtle t1 = Tower(-250) t2 = Tower(0) t3 = Tower(250) # make tower of num_of_disks discs for i in range(num_of_disks,0,-1): t1.push(Disc(i)) # prepare spartanic user interface ;-) write("press s to start game, q to quit", align="center", font=("Courier", 16, "bold")) onkey(play, "s") onkey(bye,"q") listen() return "EVENTLOOP" if __name__=="__main__": global num_of_disks num_of_disks = 5 if (len(sys.argv) > 1): num_of_disks = int(sys.argv[1]) msg = main() print(msg) mainloop()
true
94fd0458b2282379e6e720d07581fd15467d0581
Anirban2404/HackerRank_Stat
/CLT.py
2,013
4.125
4
#!/bin/python import sys ''' A large elevator can transport a maximum of 9800 pounds. Suppose a load of cargo containing 49 boxes must be transported via the elevator. The box weight of this type of cargo follows a distribution with a mean of 205 pounds and a standard deviation of 15 pounds. Based on this information, what is the probability that 49 all boxes can be safely loaded into the freight elevator and transported? ''' ''' The number of tickets purchased by each student for the University X vs. University Y football game follows a distribution that has a mean of 2.4 and a standard deviation of 2.0. A few hours before the game starts, 100 eager students line up to purchase last-minute tickets. If there are only 250 tickets left, what is the probability that all 100 students will be able to purchase tickets? ''' ''' You have a sample of 100 values from a population with mean 500 and with standard deviation 80. Compute the interval that covers the middle 95% of the distribution of the sample mean; in other words, compute A and B such that P(A < X < B ) = 0.95. Use the value of z = 1.96. Note that z is the z-score. ''' # MAIN # if __name__ == "__main__": #max = int(raw_input().strip()) num_of_elements = int(raw_input().strip()) #mean = int(raw_input().strip()) #std_dev = int(raw_input().strip()) mean = float(raw_input().strip()) std_dev = float(raw_input().strip()) prob = float(raw_input().strip()) Z_score = float(raw_input().strip()) # P ( Xk << 98800 ) = P ( X - n * mean / n^.5 * std_dev) # z_score = (max - num_of_elements * mean) / ((num_of_elements ** 0.5) * std_dev) # print z_score # z_05 = 0.6915 #z_233 = 0.0099 #print z_233 # print z_05 # Z_score = (A - mean) / (std_dev/ (num_of_elements ** 0.5)) A = - Z_score * (std_dev / (num_of_elements ** 0.5)) + mean print A B = Z_score * (std_dev/ (num_of_elements ** 0.5)) + mean print B
true
4aa692633576198ea6580dfd97e2b068d5dbe920
AbhijeetDixit/MyAdventuresWithPython
/OOPython/ClassesExample2.py
1,927
4.34375
4
''' This example shows the use of multiple classes in a single program''' class City: def __init__(self, name): self.name = name self.instituteCount = 0 self.instituteList = [] pass def addInstitute(self, instObj): self.instituteList.append(instObj) self.instituteCount += 1 def displayInstitute(self): print 'instituteCount %d'%self.instituteCount for inst in self.instituteList: inst.displayInfo() pass def displayCity(self): print '________________ City ________________' print 'CityName : %s'%self.name print 'City Institutes' self.displayInstitute() class institute: def __init__(self, name): self.name = name self.numDepts = 0 self.depts = [] def addDepts(self, deptname): self.depts.append(deptname) self.numDepts += 1 def displayInfo(self): print 'name : %s'%self.name print 'dept Count : %d'%self.numDepts i = 0 for dept in self.depts: print '%d. %s'%(i+1, dept) def main(): print 'Creating a new City' cName = raw_input('Enter City Name : ') city1 = City(cName) print 'Displaying new City Information' city1.displayCity() print 'Creating a new institute' iName = raw_input('Enter the name of institute : ') institute1 = institute(iName) print 'Displaying newly created institute' institute1.displayInfo() response = raw_input('Should we add institute to the created city? (y/n) : ') if response == "y" or response == "Y": city1.addInstitute(institute1) print 'The created city now becomes' city1.displayCity() pass print 'We need to add atleast 2 depts in the institute' dept1 = raw_input('Add first dept name : ') institute1.addDepts(dept1) dept2 = raw_input('Add second dept name : ') institute1.addDepts(dept2) if response == "y" or response == "Y": print 'The city now becomes : ' city1.displayCity() else: print 'The new department becomes : ' institute1.displayInfo() if __name__ == '__main__': main()
true
957f18f7ef13a92229a7014300a859319eebae1b
SharukhEqbal/Python
/fibonacci_with_generators.py
483
4.34375
4
# Fibonacci series 1,1,2,3,5,8,... using generators def get_fibonacci(): a = 1 b = 1 for num in range(5): yield a # this will remember the value of a for next iteration a,b = b, a + b [i for i in get_fibonacci()] """ o/p: [1, 1, 2, 3, 5] def get_fibonacci_without_generator(): a = 1 b = 1 result = [] for num in range(5): result.append(a) a,b = b, a+b return result print(get_fibonacci_without_generator()) """
false
8720d528fb634c4a61eeb5b33a3405ee87883ada
Siddhant-Sr/Turtle_race
/main.py
1,006
4.21875
4
from turtle import Turtle, Screen import random race = False screen = Screen() screen.setup(width= 500, height= 400) color = ["red", "yellow", "purple", "pink", "brown", "blue"] y = [-70, -40, -10, 20, 50, 80] bet = screen.textinput(title="make your bet", prompt="Which turtle will win the race? Enter a color") all_turtle = [] for turtle_index in range(0, 6): new_turtle = Turtle(shape="turtle") new_turtle.color(color[turtle_index]) new_turtle.penup() new_turtle.goto(x=-230, y=y[turtle_index]) all_turtle.append(new_turtle) if bet: race = True while race: for turtles in all_turtle: if turtles.xcor()>230: race =False winning_color = turtles.pencolor() if winning_color == bet: print(f"You've won! The {winning_color} turtle is the winner ") else: print(f"You've lost! The {winning_color} turtle is the winner ") turtles.forward(random.randint(0,10)) screen.exitonclick()
true
3c7665bbadb5ae2903b9b5edfda93d3a78ada475
dgupta3102/python_L1
/PythonL1_Q6.py
916
4.25
4
# Write a program to read string and print each character separately. # a) Slice the string using slice operator [:] slice the portion the strings to create a sub strings. # b) Repeat the string 100 times using repeat operator * # c) Read string 2 and concatenate with other string using + operator. Word = input("Please Enter the String : ") sent = Word for i in range(len(Word)): print("The Character at %d Index Position = %c" % (i, Word[i])) # Slice operation --- starts from 2nd index till n-1 index print("Slicing-->",sent[2:5]) # b) Repeat the string 100 times using repeat operator * print("Repeat string 100 times ..",(sent[0:5]*100)) # c) Read string 2 and concatenate with other string using + operator. str1 = input("Enter String 1 ") str2 = input("Enter String 2 ") # concatenation of 2 strings using + operator str3 = str1+" "+str2 print(str3)
true
347ac39407381d1d852124102d38e8e9f746277f
dgupta3102/python_L1
/PythonL1_Q19.py
969
4.21875
4
# Using loop structures print even numbers between 1 to 100. # a) By using For loop, use continue/ break/ pass statement to skip odd numbers. # i) Break the loop if the value is 50 print("part 1a --------------") for j in range(1, 101): if j % 2 != 0: # checks the number is Odd and Pass pass else: print(j) # prints the number if j == 50: # checks if the number is 50 break # it will break the loop and come out # ii) Use continue for the values 10,20,30,40,50 print("Part 2") for i in range(1, 101): # print(i) if i % 2 == 0: # checks the number is even print(i) # prints the number if i == 10: continue elif i == 20: continue elif i == 30: continue elif i == 40: continue elif i == 50: # checks if the number is 50 break # it will break the loop and come out
true
ec2ae4d1db1811fcca703d6a35ddf1732e481e2a
riteshrai11786/python-learning
/InsertionSort.py
1,600
4.40625
4
# My python practice programs # function for sorting the list of integers def insertion_sort(L): # Loop over the list and sort it through insertion algo for index in range(1, len(L)): # define key, which is the current element we are using for sorting key = L[index] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position pivot_idx = index - 1 # Loop over the list and compare while pivot_idx >= 0 and key < L[pivot_idx]: L[pivot_idx + 1] = L[pivot_idx] pivot_idx -= 1 # assign the key to next index L[pivot_idx + 1] = key # Insertion sort with recursion def recursive_insertion_sort(L, n): # Base case if n <= 1: return # Sort n-1 elements recursive_insertion_sort(L, n - 1) '''Insert last element at its correct position in sorted array.''' last = L[n - 1] j = n - 2 # loop over the array and sort while j >= 0 and last < L[j]: L[j + 1] = L[j] j -= 1 # assign the last element to original position L[j + 1] = last # Driver code to test above arr = [12, 11, 13, 5, 6] print(arr) insertion_sort(arr) print("Sorted array:"); for i in range(len(arr)): print(arr[i], end=' ') print() # A utility function to print an array of size n def printArray(arr, n): for i in range(n): print(arr[i], end=' ') # Driver program to test insertion sort arr = [12, 11, 13, 5, 6] n = len(arr) recursive_insertion_sort(arr, n) printArray(arr, n)
true
ad2a9e7d7696c0f62a1f989344f98ebcea07abdd
murilonerdx/exercicios-python
/Exercicio_Lista/exercicio_15.py
507
4.25
4
nome = input("Digite o nome: ") nota1 = float(input("Digite a sua primeira nota: ")) nota2 = float(input("Digite a segunda nota: ")) nota3 = float(input("Digite a terceira nota: ")) nf = float(input("Digite o numero de faltas: ")) notaresult = (nota1+nota2+nota3)/3 faltas = 0,25 * nf if (notaresult >= 7 and faltas >= 60): print("Aprovado") elif (notaresult <= 6 and faltas >= 60): print("Reprovado na media") elif (notaresult >= 7 and faltas <= 60): print("Reprovado em falta")
false
397a6b557c529b95c4084680b596d8781efd8244
NatalieMiles/shopping_list_project
/shopping_list_project.py
1,833
4.40625
4
# target_list = ["socks", "soap", "detergent", "sponges"] # bi_rite_list = ["butter", "cake", "cookies", "bread"] # berkeley_bowl_list = ["apples", "oranges", "bananas", "milk"] # safeway_list = ["oreos", "brownies", "soda"] shopping_list = { "target": ["socks", "soap", "detergent", "sponges"], "bi_rite": ["butter", "cake", "cookies", "bread"], "berkeley": ["apples", "oranges", "bananas", "milk"], "safeway": ["oreos", "brownies", "soda"], } # print shopping_list["target" # user_input = raw_input("What selection?") def menu_choice(user_input): print user_input if user_input == "1": print shopping_list elif user_input == "2": store_selection = raw_input("Which store?").lower() print shopping_list[store_selection] elif user_input == "3": store_input = raw_input("Would you like to add a new shopping list?").lower() if store_input == "yes": store_name = raw_input("What is the name of the store? ").lower() # new_list = %s % store_name shopping_list[store_name] = [] print type(store_name) print shopping_list.keys() menu_choice(raw_input("What selection?")) #Option 1: # print shopping_list # print shopping_list[store_selection] #would you like to add a new shopping_list #user says yes #what store? #user types in store #create new empty list #add empty list into dictionary #would you like to add to a shopping list? #user says yes #which store? #user inputs store #what items would you like to add? #user enters items #call dictionary #call list #add items to list #print list list_input = raw_input("Would you like to add an item to your list?").lower() if list_input == "yes": store_input = raw_input("Which store").lower new_item = shopping_list[store_input]
false
93481419afcb5937eca359b323e038e7e29c6ad9
rzfeeser/20200831python
/monty_python3.py
1,075
4.125
4
#!/usr/bin/python3 round = 0 answer = " " while round < 3: round += 1 # increase the round counter by 1 answer = input('Finish the movie title, "Monty Python\'s The Life of ______": ') # transform answer into something "common" to test answer = answer.lower() # Correct Answer if answer == "brian": print("Correct!") break # you gave an answer... escape the while loop! # Easter Egg elif answer == "shrubbery": print("We are no longer the knights who say Ni! We are now the knights\ who say ekki-ekki-ekki-pitang-zoom-boing!") break # you gave an answer... escape the while loop! # Easter Egg 2 elif answer == "tim": print("Oh great wizard! What do they call you?\nWizard: Some call me... Tim...") break # if counter reaches 3 elif round == 3: # logic to ensure round has not yet reached 3 print("Sorry, the answer was Brian.") else: # if answer was wrong print("Sorry. Try again!") # say goodbye! print("Thanks for playing!")
true
4c5a2f9b26e6d4fa7c3250b3043d1df5865b76c8
g-boy-repo/shoppinglist
/shopping_list_2.py
2,162
4.5
4
# Have a HELP command # Have a SHOW command # clean code up in general #make a list to hold onto our items shopping_list = [] def show_help(): #print out instructions on how to use the app print("What should we pick up at the store?") print(""" Enter 'DONE' to stop addig items. Enter 'HELP' for this help. Enter 'SHOW' to see your current list. """) #We used miltiline comments here #This part will show the list we have already listed def show_list(): #print out the list. print("Here's your list:") for item in shopping_list: print(item) #This function will take new lists. def add_to_list(new_item): #add new items to our list shopping_list.append(new_item) print("Added {}. List now has {} items.".format(new_item, len(shopping_list))) # first {} contains somthing and second {} contains some number. len stands for length of the shopping_list. So len is a function that tells us how many things are in a list or an iterable. #Let's just show the help right here right above the while true. So that way the hlp gets shown before the while loop starts running. show_help() while True: #ask for new items new_item = input("> ") #be able to quit the app if new_item == 'DONE': #What this does is when you type in DONE the program quit using the break keyword. break elif new_item == 'HELP': #Here we need to check to see if they put in help show_help() #Calling out function named show_help() continue # Since we don't want to add help into our list, and we don't wanna break, we don't wanna end the loop. We actually just wanna go to the next step of the loop. We wanna run the loop again so we say continue. elif new_item == 'SHOW': #Here by typing SHOW this show up our list that we have listed down. show_list() #Calling out our show_list function to display the list. continue #And again you wanna go on to the next step of the loop so we say continue again. add_to_list(new_item) #We could do an else here but we dont have to. We called funcion add_to_list(new_item) with its parameter named new_item. show_list() #Calling function named show_list
true
e5dbac6cd3ba92049b640e62c1bf96fb61b6ca03
sankar-vs/Python-and-MySQL
/Data Structures/Tuple/6_Check_element_exists.py
280
4.1875
4
''' @Author: Sankar @Date: 2021-04-11 09:27:25 @Last Modified by: Sankar @Last Modified time: 2021-04-11 09:32:09 @Title : Tuple_Python-6 ''' ''' Write a Python program to check whether an element exists within a tuple. ''' tuple = ("Heyya", False, 3.2, 1) print("Heyya" in tuple)
false
3edf29f645ecb4af1167359eab4c910d47c40805
sankar-vs/Python-and-MySQL
/Data Structures/Basic Program/41_Convert_to_binary.py
519
4.3125
4
''' @Author: Sankar @Date: 2021-04-08 15:20:25 @Last Modified by: Sankar @Last Modified time: 2021-04-08 15:27:09 @Title : Basic_Python-41 ''' ''' Write a Python program to convert an integer to binary keep leading zeros. Sample data : 50 Expected output : 00001100, 0000001100 ''' decimal = 50 print("Convertion to binary from {} is: {:08b}".format(decimal, decimal)) print("Convertion to binary from {} is: {:010b}".format(decimal, decimal)) print("Convertion to binary from {} is: {:012b}".format(decimal, decimal))
true
67bdb85c94a8874623c89d0ac74a9b1464e5c391
sankar-vs/Python-and-MySQL
/Data Structures/List/8_Find_list_of_words.py
739
4.5
4
''' @Author: Sankar @Date: 2021-04-09 12:36:25 @Last Modified by: Sankar @Last Modified time: 2021-04-09 12:42:09 @Title : List_Python-8 ''' ''' Write a Python program to find the list of words that are longer than n from a given list of words. ''' n = 3 list = ['Hi','Sankar','How','are','you',"brotha"] def countWord(n, list): ''' Description: To find the list of words that are longer than n from a given list of words. Parameter: n (int) list (list) Return count (int) ''' count = 0 for i in list: if (len(i)>n): count += 1 return count print("From list {} the words that are greater than {} is: {}".format(list, n, countWord(n, list)))
true
1e16341185e46f060a7a50393d5ec47275f6b009
sankar-vs/Python-and-MySQL
/Data Structures/List/3_Smallest_number.py
440
4.15625
4
''' @Author: Sankar @Date: 2021-04-09 12:07:25 @Last Modified by: Sankar @Last Modified time: 2021-04-09 12:13:09 @Title : List_Python-3 ''' ''' Write a Python program to get the smallest number from a list. ''' list = [1,2,3,4,6,10,0] minimum = list[0] for i in list: if (minimum>i): minimum = i print("Minimum of list {} is: {}".format(list, minimum)) print("Minimum of list using function {} is: {}".format(list, min(list)))
true
08a53c3d25d935e95443f1dfa3d2cefdd10237fb
sankar-vs/Python-and-MySQL
/Data Structures/Array/4_Remove_first_element.py
482
4.1875
4
''' @Author: Sankar @Date: 2021-04-09 07:46:25 @Last Modified by: Sankar @Last Modified time: 2021-04-09 07:51:09 @Title : Array_Python-4 ''' ''' Write a Python program to remove the first occurrence of a specified element from an array. ''' array = [] for i in range(5): element = int(input("Enter Element {} in array: ".format(i))) array.append(element) arrayResult = array print("Remove first occurance of {} in array {} is: {}".format(3, array, arrayResult.remove(3)))
true
2b3f22bb3fcad13848f40e0c938c603acb2f3959
sankar-vs/Python-and-MySQL
/Functional Programs/Distance.py
1,357
4.28125
4
''' @Author: Sankar @Date: 2021-04-01 09:06:25 @Last Modified by: Sankar @Last Modified time: 2021-04-02 12:25:37 @Title : Euclidean Distance ''' import re def num_regex_int(x): ''' Description: Get input from user, check whether the input is matching with the pattern expression, if True then return Parameter: x (str) : Statement to be printed to take the the inputs from user Return: num (int): input from user ''' while True: try: num = input(x) pattern = "^([+-]?[0-9]{,8})$" result = re.match(pattern, num) if (result): return int(num) except: pass print("Only numeric integer") def calculateEuclideanDistance(): ''' Description: Getting the x and y co-ordinates from the user and Calculate the Euclidean Distance by the given formula x**x+y**y and print the distance Parameter: None Return: None ''' try: x = num_regex_int("Enter x co-ordinate: ") y = num_regex_int("Enter y co-ordinate: ") distance = pow(abs(x),abs(x))+pow(abs(y),abs(y)) print("Euclidean distance from the point ({}, {}) to the origin (0, 0) is: {}".format(x, y, distance)) except: pass calculateEuclideanDistance()
true
55f9b7cd0aa5a2b10cd819e5e3e6020728e2c670
Dilshodbek23/Python-lessons
/38_4.py
366
4.4375
4
# Python Standard Libraries # The user was asked to enter a phone number. The entered value was checked against the template. import re regex = "^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$" phone = input("Please enter phone number: ") if re.match(regex, phone): print(f"phone: {phone}") else: print(f"phone number is incorrecr")
true
38c79868e60d20c9a6d5e384b406c3656f565ffb
Haldgerd/Simple_coffee_machine_project
/main.py
2,305
4.5
4
""" An attempt to simulate a simple coffee machine and it's functionality. This version is used as in depth exercise, before writing same program using OOP later within the programming course. The main requirements where: 1. Output a report on resources. 2. Receive user input, referring to type of coffee they want. 3. Check for sufficient resources. 4. Process coin payment. Check if transaction is successful. (refund if payment is not sufficient. ) 5. Return amount of change if needed. """ from functions_module import clear, output_ascii_title, money_function, resource_output_formatter, \ resource_checker_function, resource_modifier_function # MAIN PROGRAM off = False print(output_ascii_title()) while not off: order = input("\nWhat would you like? (espresso/latte/cappuccino): ").lower() if order not in ["latte", "espresso", "cappuccino"]: if order == "off": break elif order == "report": resource_output_formatter() continue else: print("Unknown coffee request.") continue if resource_checker_function(order): print("Please insert coins.") euro_coins = int(input("How many euros: ")) cent_50 = int(input("How many 50 cents: ")) cent_20 = int(input("How many 20 cents: ")) cent_10 = int(input("How many 10 cents: ")) is_enough_money = money_function(order, euro_coins, cent_50, cent_20, cent_10) if not is_enough_money: clear() continue resource_modifier_function(order) print(f"Here is your {order}. Enjoy!") clear() else: continue """ PSEUDO CODE: if off: DONE!! maintenance, break from loop, exit coffee machine. elif report: show report on resources else: 1.check resource quantity (if sufficient or not) when user asks for drink. If there's not enough let user know. 2. if resources are OK., ask for coins -PAYMENT. 3. check if money given is sufficient in amount. ADD profit to machine registry if so, else let user know they didn't give enough money. 4. if all ok, give drink. (behind scenes: take away resources, add money) """ print("\nMaintenance time! Turning off.")
true
2370915fa2514143fc56ea1e055b70805d22d170
samaracanjura/Coding-Portfolio
/Python/Shapes.py
996
4.375
4
#Samara Canjura #shapes.py #Finding the area and perimeter of a square, and finding the circumference and area of a circle. import math # Python Library needed for access to math.pi and math.pow def main(): inNum = getInput("Input some number: ") while inNum != 0: #Loop ends when zero input if inNum > 0: calculate_square(inNum) else: calculate_circle(inNum) inNum = getInput("Input next number: ") print("End of Program") def calculate_square(side): perimeter = side * 4 print("Square with side", side, "has a perimeter", perimeter) print("Square with side", side, "has a area", perimeter) def calculate_circle(radius): radius = math.fabs(radius) pi = math.pi r = radius c = 2*pi*r a = pi*r*r print("Circle w/ radius", radius, "has a circumference", c) print("Circle w/ radius", radius, "has a area", c) def getInput(prompt): number = float(input(prompt)) return number main()
true
7bd0888085542859d08f395731cbfdfc04d1edf7
evaristofm/curso-de-python
/pythonteste/aula08.py
267
4.15625
4
from math import sqrt import emoji num = int(input('Digite um número: ')) raiz = sqrt(num) print('A raiz de {} é igual a {}'.format(num, raiz)) print(emoji.emojize("Olá, Mundo :alien:", use_aliases=True)) print(emoji.emojize('Python is :cry:', use_aliases=True))
false
74c00f287ec85a3a8ac0b3b9fd8f3d0bd6babe70
psmzakaria/Practical-1-2
/Practical2Q1.py
478
4.125
4
# Question 1 # Write codes for the incomplete program below so that it sums up all the digits in the integer variable num (9+3+2) and displays the output as a sum. num = int(input("Enter your Number Here")) print(num) # Getting the first digit number digit1 = int(num/100) print(digit1) # Getting the second digit number digit2 = (int(num/10) % 10) print(digit2) # Getting the third digit number digit3 = (num % 10) print(digit3) sum = digit1 + digit2 + digit3 print(sum)
true
db25359cb2fb8c20efd6093a0392a5c1dd455abc
ZohanHo/ClonePPZ
/all python/lesson 23.py
1,308
4.28125
4
"""""" """Функция zip - В Pyhon функция zip позволяет пройтись одновременно по нескольким итерируемым объектам (спискам и др.):""" a = [10, 20, 30, 40] b = ['a', 'b', 'c', 'd', 'e'] for i, j in zip(a, b): print(i, j) # 10 a # 20 b # 30 c # 40 d """ Здесь выражение zip(a, b) создает объект-итератор, из которого при каждом обороте цикла извлекается кортеж, состоящий из двух элементов. Первый берется из списка a, второй - из b. """ for i in zip(a, b): print(i, type(i)) # (10, 'a') <class 'tuple'> # (20, 'b') <class 'tuple'> # (30, 'c') <class 'tuple'> # (40, 'd') <class 'tuple'> """Если требуется получить не итератор, возвращаемый zip(), а список из элементов, то к объекту zip применима функция list, которая преобразует итератор в список:""" a = [10, 20, 30, 40] c = [1.1, 1.2, 1.3, 1.4] ac = zip(a, c) print(type(ac)) # <class 'zip'> ac = list(ac) print(type(ac)) # <class 'list'> print(ac) # [(10, 1.1), (20, 1.2), (30, 1.3), (40, 1.4)]
false
a071904bc233e29d20c406bbe5d3305c248a3d5b
ZohanHo/ClonePPZ
/all python/lesson 65.py
2,416
4.4375
4
"""""" """Полиморфизм, когда обьект в разных ситуациях ведет себя по разному""" class VectorClass: def __init__(self, x, y): self.x = x self.y = y #def multiplay(self, v2): # В Функцию прийдет обьект класса как аргумент, но мы будем использовать магичесуий метод def __mul__(self, other): # Принимаем какойто озер и используем инициализированые переменныее return VectorClass(self.x * other.x, self.y * other.y) # Возвращаем... v1 = VectorClass(2, 3) v2 = VectorClass(6 ,7) # v3 = v1.multiplay(v2) можно использовать так, но оптимальней использовать магические методы v3 = v1 * v2 print("v3.x = ", v3.x) print("v3.y = ", v3.y) print("---------") class Multiplay(): def __init__(self, x, y): self.x = x self.y = y def __mul__(self, other): # print("self x {}".format(self.x)) # print("self y {}".format(self.y)) return Multiplay(self.x * other.x, self.y * other.y) def __add__(self, other): return Multiplay(self.x + other.x, self.y + other.y) def __repr__(self): # representation - Показует как будет выглядеть обьект на печати, но не печатает, а возвращает значение return "self.x = {} и self.y = {}".format(self.x, self.y) # без него выглядело бы так <__main__.Multiplay object at 0x00A5DCB0> apple = Multiplay(2, 4) orange = Multiplay(3, 6) banana = Multiplay (5, 10) """Захоит 2 аргумента, в зависимости над какими обьктами происходит операция, в етой операции равно self.x = 3, self.y = 6, orange, other.x = 2, other.y = 4, apple""" fructs = orange * apple print(fructs.x) print(fructs.y) # Тут banana будет и self и other fructs2 = banana * banana # захоит 2 аргумента, в зависимости над какими обьктами происходит операция, в етой операции равно 5, 10 print(fructs2.x) print(fructs2.y) fructs3 = orange + apple print(fructs3.x) print(fructs3.y) print(apple)
false
c8a4e387883c143f0d2cf6fde6d74f0ef1e17f78
denisinberg/python_task
/if_else_task(name).py
718
4.125
4
a=int(input('Введите возраст Андрея: ')) b=int(input('Введите возраст Борис: ')) c=int(input('Введите возраст Виктор: ')) if a>b and a>c: print('Андрей старше всех') elif b>a and b>c: print('Борис старше всех') elif b<c>a: print('Виктор старше всех') elif a==b>c: print('Андрей и Борис старше Виктора') elif a==c>b: print('Андрей и Виктор старше Бориса') elif b==c>a: print('Борис и Виктор старше Андрея') else: print('Андрей,Борис и Виктор одного возраста')
false
8da0eff550d0a7ebd436609e472eec25b7a1daa5
JuicyJerry/Python---OOP-Primary_Concepts-
/PythonOOP(SOLID)/03.리스코프_치환_원칙(Liskov_Substitution_Principle)/02.행동_규약을_어기는_자식_클래스.py
1,772
4.125
4
"""자식 클래스가 부모 클래스의 의도와 다르게 메소드를 오버라이딩 하는 경우""" class Rectangle: """직사각형 클래스""" def __init__(self, width, height): """세로와 가로""" self.width = width self.height = height def area(self): """넓이 계산 메소드""" return self.width * self.height @property def width(self): """가로 변수 getter 메소드""" return self._width @width.setter def width(self, value): """가로 변수 setter 메소드""" self._width = value if value > 0 else 1 @property def height(self): """세로 변수 getter 메소드""" return self._height @height.setter def height(self, value): """세로 변수 setter 메소드""" self._height = value if value > 0 else 1 class Square(Rectangle): def __init__(self, side): super().__init__(side, side) @property def width(self): """가로 변수 getter 메소드""" return self._width @width.setter def width(self, value): """가로 변수 setter 메소드""" self._width = value if value > 0 else 1 self._height = value if value > 0 else 1 @property def height(self): """세로 변수 getter 메소드""" return self._height @height.setter def height(self, value): """세로 변수 setter 메소드""" self._width = value if value > 0 else 1 self._height = value if value > 0 else 1 retangle_1 = Rectangle(4, 6) retangle_2 = Square(2) retangle_1.width = 3 retangle_2.width = 7 print(retangle_1.area()) retangle_2.width = 3 retangle_2.height = 7 print(retangle_2.area())
false
5de721579c27704e39cf12b1183a1eebea4d22d4
lion137/Python-Algorithms
/shuffling.py
441
4.1875
4
# algorithm for shuffling given subscriptable data structure (Knuth) import random def swap(alist, i, j): """swaps input lists i, j elements""" alist[i], alist[j] = alist[j], alist[i] def shuffle(data): """randomly shuffles element in the input data""" n = len(data) for token in range(n - 1): swap(data, token, random.randrange(token, n)) alist1 = [1, 3, 5, 6] print(alist1) shuffle(alist1) print(alist1)
true
f882f9dcf344950cc893bf1e2fb49ffb103d168e
chenjyr/AlgorithmProblems
/HackerRank/Search/FindTheMedian.py
1,652
4.3125
4
""" In the Quicksort challenges, you sorted an entire array. Sometimes, you just need specific information about a list of numbers, and doing a full sort would be unnecessary. Can you figure out a way to use your partition code to find the median in an array? Challenge Given a list of numbers, can you find the median? Input Format There will be two lines of input: n - the size of the array ar - n numbers that makes up the array Output Format Output one integer, the median. Constraints 1<= n <= 1000001 -10000 <= x <= 10000 , x ∈ ar There will be an odd number of elements. Sample Input 7 0 1 2 4 6 5 3 Sample Output 3 """ from random import randint def swap(nums, i, j): nums[i], nums[j] = nums[j], nums[i] def partition(nums, index): swap(nums, 0, index) pivot = nums[0] lesser_list = [x for x in nums[1:] if x <= pivot] greater_list = [x for x in nums[1:] if x > pivot] pivot_index = len(lesser_list) return pivot_index, lesser_list + [pivot] + greater_list def median(nums): def helper(nums, index): median_num = -1 rand_index, nums = partition(nums, randint(0, len(nums) - 1)) result = nums[index] if rand_index < index: result = helper(nums[rand_index+1:], index - rand_index - 1) elif rand_index > index: result = helper(nums[:rand_index], index) return result return helper(nums, len(nums) / 2) if __name__ == "__main__": _ = raw_input() nums = map(int, raw_input().split()) if nums and len(nums) > 0: print median(nums)
true
0adf7ed3f2301c043ef269a366a90c3970673b1f
chenjyr/AlgorithmProblems
/HackerRank/Sorting/Quicksort1.py
2,143
4.21875
4
""" The previous challenges covered Insertion Sort, which is a simple and intuitive sorting algorithm. Insertion Sort has a running time of O(N2) which isn’t fast enough for most purposes. Instead, sorting in the real-world is done with faster algorithms like Quicksort, which will be covered in these challenges. The first step of Quicksort is to partition an array into two parts. Challenge Given an array ar and a number p, can you partition the array, so that all elements greater than p are to the right of it and all the numbers smaller than p are to its left? Besides for necessary partitioning, the numbers should otherwise remain in the same order. This means if n1 was before n2 in the original array, it must remain before it in the partitioned array, unless n1 > p > n2. Guideline - In this challenge, you do not need to move around the numbers ‘in-place’. This means you can create 2 lists and combine them at the end. Input Format You will be given an array of integers. The number p is the first element in ar. There are 2 lines of input: n - the number of elements in the array ar the n numbers of ar (including p at the beginning) Output Format Print out the numbers of the partitioned array on one line. Constraints 1<=n<=1000 -1000<=x<= 1000 , x ∈ ar All elements will be distinct Sample Input 5 4 5 3 7 2 Sample Output 3 2 4 5 7 Explanation p = 4. The 5 was moved to the right of the 4, 2 was moved to the left of 4 and the 3 is also moved to the left of 4. The numbers otherwise remained in the same order. Task Complete the method partition which takes in one parameter - an array ar to be partitioned, where the first element in it is the number p. """ def partition(nums): pivot = nums[0] return [x for x in nums[1:] if x <= pivot] + [pivot] + [x for x in nums[1:] if x > pivot] if __name__ == "__main__": _ = raw_input() nums = map(int, raw_input().split()) print " ".join(map(str, partition(nums)))
true
248f5308062ddc2b896413a99dc9d5c3f3c29ac6
chenjyr/AlgorithmProblems
/HackerRank/Sorting/InsertionSort2.py
1,852
4.625
5
""" In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array? Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that in the first step, when you consider an element with just the first element - that is already “sorted” since there’s nothing to its left that is smaller than it. In this challenge, don’t print every time you move an element. Instead, print the array every time an element is “inserted” into the array in (what is currently) its correct place. Since the array composed of just the first element is already “sorted”, begin printing from the second element and on. Input Format There will be two lines of input: s - the size of the array ar - the list of numbers that makes up the array Output Format On each line, output the entire array at every iteration Constraints 1<=s<=1000 -10000<=x<= 10000 , x ∈ ar Sample Input 6 1 4 3 5 6 2 Sample Output 1 4 3 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 2 3 4 5 6 Explanation Insertion Sort checks the ‘4’ first and doesn’t need to move it, so it just prints out the array. Next, the 3 is inserted next to the 4 and the array is printed out. This continues one element at a time until the entire array is sorted. """ def insertion_sort(nums): for i in xrange(1, len(nums)): this_num = nums[i] j = i - 1 while j >= 0 and nums[j] > this_num: nums[j+1] = nums[j] j-= 1 nums[j+1] = this_num print_nums(nums) def print_nums(nums): print " ".join(map(str, nums)) if __name__ == "__main__": _ = raw_input() nums = [int(i) for i in raw_input().strip().split()] insertion_sort(nums)
true
c2098e9dd0710577a8bcac533b34b3bbee7b3a19
NishuOberoi1996/IF_ELSE
/num_alph_chatr.py
206
4.15625
4
num=input("enter anything:-") if num>="a" and num<="z" or num>="A" and num<="Z": print("it is a alphabet") elif num>="0" and num<="9": print("it is number") else: print("Special Character")
true
8c8da9e1a61a6d6d78a2535e2b1bbda1a31b8b17
hhoangnguyen/mit_6.00.1x_python
/test.py
508
4.3125
4
def insertion_sort(items): # sort in increasing order for index_unsorted in range(1, len(items)): next = items[index_unsorted] # item that has to be inserted # in the right place # move all larger items to the right i = index_unsorted while i > 0 and items[i - 1] > next: items[i] = items[i - 1] i = i - 1 # insert the element items[i] = next return items result = insertion_sort([3, 4, 7, -1, 2]) print(result)
true
08b1c52901da46b2e7beb41246effc65ed9b4d3f
hhoangnguyen/mit_6.00.1x_python
/week_1/1_1.py
713
4.15625
4
""" Assume s is a string of lower case characters. Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print: 5 """ string = 'azcbobobegghakl' def is_valid_vowel(char): if char == 'a': return True if char == 'e': return True if char == 'i': return True if char == 'o': return True if char == 'u': return True return False def get_num_vowels(s): num_vowels = 0 for index in range(len(s)): if is_valid_vowel(s[index]): num_vowels += 1 print(num_vowels) get_num_vowels(string)
true
655a5b9cf59b58bde19148bbae7ad6650fe23374
advikchava/python
/learning/ms.py
484
4.21875
4
print("1.Seconds to minutes") print("2.Minutes to seconds") ch=int(input("Choose one option:")) if ch==1: num=int(input("Enter time in seconds:")) minutes=int(num/60) seconds=int(num%60) print("After the Seconds are converted to Minutes, the result is:",minutes,"Minutes", seconds,"Seconds") elif ch==2: num=float(input("Enter time in minutes:")) seconds=int(num*60) print("After the Minutes are converted to Seconds, the result is:", seconds,"Seconds")
true
f5e06e5f3bbea772294cef61d853415f6cf0dc29
CyanGirl/Automation-scripts
/time_zone_conversion/time_zone.py
1,619
4.1875
4
class InvalidHours(Exception): """Invalid""" pass class InvalidMins(Exception): """Invalid""" pass # Taking user input starting_zone = input("Enter starting zone: ") time = input("Enter time: ") end_zone = input("Enter desired time zone: ") lst = time.split(":") hours1 = int(lst[0]) mins1 = int(lst[1][:2]) ampm = lst[1][2:] # Exception handling try: if hours1 >= 12: raise InvalidHours except InvalidHours: print("Invalid Hours") exit() try: if mins1 >= 60: raise InvalidMins except InvalidMins: print("Invalid Minutes") # Time conversion according to zone if starting_zone == "CST": hours1 = hours1 + 6 pass elif starting_zone == "EST": hours1 = hours1 - 10 pass elif starting_zone == "MST": hours1 = hours1 + 7 pass elif starting_zone == "PST": hours1 = hours1 + 8 if hours1 > 12: hours1 = hours1 - 12 if ampm == 'am': ampm = 'pm' elif ampm == 'pm': ampm = 'am' elif hours1 < 0: hours1 = hours1 + 12 if ampm == 'am': ampm = 'pm' elif ampm == 'pm': ampm = 'am' if end_zone == "CST": hours1 = hours1 - 6 elif end_zone == "EST": hours1 = hours1 + 10 elif end_zone == "MST": hours1 = hours1 - 7 elif end_zone == "PST": hours1 = hours1 - 8 if hours1 > 12: hours1 = hours1 - 12 if ampm == 'am': ampm = 'pm' elif ampm == 'pm': ampm = 'am' elif hours1 < 0: hours1 = hours1 + 12 if ampm == 'am': ampm = 'pm' elif ampm == 'pm': ampm = 'am' # Result print('Time: ' + str(hours1) + ":" + str(mins1) + ampm)
false
d7d67479a3d56bb1187acd1e327c2d6a4430c6a5
JasmineOsti/pythonProject1
/Class.py
813
4.21875
4
#WAP to find the number is negative, positive or 0 that is entered y the user. #num=int(input('enter a number')) #if num<0: # print('number is positive') #elif num>0: # print('number is negative') #else: # print('number is zero') #dstring=input("how far did you travel today(in miles)?") #tstring=input("How long did it take you(in hours)?") #dfloat=float(dstring) #tfloat=float(tstring) #s=dfloat/tfloat #print("your speed was "+str(s)+" miles per hour")\ #for i in 'five': # print('hello') # print('hi') # print('namaste') #for i in 1,2,3,4: #for i in range(4): # print('softwarica') # print('dillibazar') #for i in range(1,11): # print(i) for i in range(2,51,2): print(i) if i%2==0: print('the number is even') else: print('the number is odd')
false
156203c9c9a1c80101caf18ba558e1c89f682c42
JasmineOsti/pythonProject1
/Program.py
289
4.3125
4
#Write a program that takes three numbers and prints their sum. Every number is given on a separate line. A = int(input("Enter the first number: ")) B = int(input("Enter the second number: ")) C = int(input("Enter the third number: ")) sum = A+B+C print("the sum of three numbers is", sum)
true
75f90c4b763e1d36e35a2c6e495afa796ca781f1
ZohanHo/untitled
/Задача 27.py
574
4.1875
4
"""Факториалом числа n называется произведение 1 × 2 × ... × n. Обозначение: n!. По данному натуральному n вычислите значение n!. Пользоваться математической библиотекой math в этой задаче запрещено.""" #n = int(input("введите факториал какого числа необходимо вычислить: ")) def fun(n): d = "*".join(str(i) for i in range(1, n + 1 )) return eval(d) print(fun(5))
false
957a0b4055bc67923936088490e9708067ec8e08
Ritakushwaha/Web-Programming
/loops.py
457
4.1875
4
#looping lists for i in [0, 1, 2, 3, 4, 5]: print(i) #looping with range func for i in range(6): print(i) #looping lists of name for i in ["Rita", "Girwar", "Priyanshi", "Pragya", "Vijaya"]: print(i) #loop through each character in name for i in "Rita": print(i) #loop through dictionaries houses = {"Red House" : "Rita", "Blue House" : "Girwar"} #change value to dictionary print(houses) houses["Red House"] = "Priyanshi" print(houses)
false
df5270ff28213fc89bf0ee436b9855c73e026d9d
Sakshi011/Python_Basics
/set.py
1,190
4.21875
4
# set data type # unordered collection of data # INTRO ---------------------------------------------------------------------------------- s = {1,1.1,2.3,3,'string'} print(s) print("\n") # In set all elemets are unique that's why it is used to remove duplicate elements l = [1,2,4,2,3,6,3,7,6,6] s2 = list(set(l)) print(s2) print("\n") # ADD AND REMOVE ELEMENT ----------------------------------------------------------------- s3 = {1,2,3} s3.add(4) s3.add(5) print(s3) s3.remove(4) s3.discard(5) print(s3) print("\n") # FOR LOOP ------------------------------------------------------------------------------ for i in s: print(i) print("\n") # UNION --------------------------------------------------------------------------------- s1 = {1,2,3,4} s2 = {3,4,5,6} union_set = s1 | s2 print(union_set) print("\n") # INTERSECTION -------------------------------------------------------------------------- intersection_set = s1 & s2 print(intersection_set) print("\n") # SET COMPREHENSION --------------------------------------------------------------------- s = {i**2 for i in range(1,11)} print(s) print("\n") names = ['siya','tiya','nia'] first = {i[0] for i in names} print(first)
true
25401f5061ccabbded56366310f5e42e910eddd7
gourdcyberlab/pollen-testbed
/scapy-things/varint.py
1,438
4.375
4
#!/usr/bin/env python import itertools ''' Functions for converting between strings (formatted as varints) and integers. ''' class VarintError(ValueError): '''Invalid varint string.''' def __init__(self, message='', string=None): ValueError.__init__(self, message) self.string = string # Can't add methods to `int` or `str`, so we have these functions instead. def varint_str(x): '''Convert a number to its string varint representation.''' out = [] while x != (x & 0x7F): n, x = x & 0x7F, x >> 7 out += [chr(n | 0x80)] out += [chr(x)] return str.join('', out) def varint_with_remainder(s): '''Convert a string representation of a varint to an integer, with the remainder of the string. Returns (remainder, num).''' try: items = list(itertools.takewhile((lambda c: ord(c) & 0x80), s)) items.append(s[len(items)]) n = reduce((lambda x, (i, c): x+((ord(c) & 0x7F) << (i*7))), enumerate(items), 0) return s[len(items):], n except IndexError: raise VarintError('Not a valid varint', s) def varint_num(s): '''Convert a string representaion of a varint to an integer.''' return varint_with_remainder(s)[1] def varint_list(s): '''Convert a string of varints to integers. Assumes that there is no trailing string after final varint''' while s: s, n = varint_with_remainder(s) yield n
true
2c1699da529112c4820a06bdd0933ae4c6c11032
colinmcnicholl/automate_boring_tasks
/firstWordRegex.py
840
4.25
4
import re """How would you write a regex that matches a sentence where the first word is either Alice, Bob, or Carol; the second word is either eats, pets, or throws; the third word is apples, cats, or baseballs; and the sentence ends with a period? This regex should be case-insensitive.""" firstWordRegex = re.compile(r'^(Alice|Bob|Carol)\s+(eats|pets|throws)\s+(apples|cats|baseballs)\s*.$', re.IGNORECASE) print(firstWordRegex.search('Alice eats apples.')) print(firstWordRegex.search('Bob pets cats.')) print(firstWordRegex.search('Carol throws baseballs.')) print(firstWordRegex.search('Alice throws Apples.')) print(firstWordRegex.search('BOB EATS CATS.')) print(firstWordRegex.search('Robocop eats apples.')) print(firstWordRegex.search('ALICE THROWS FOOTBALLS.')) print(firstWordRegex.search('Carol eats 7 cats.'))
true
91b9cbfeca6f447427a3008795b05eb40c026163
shakhovm/Classes_Lab5
/Classes_Lab5/triangle.py
1,777
4.25
4
from math import sqrt from Classes_Lab5 import line, point class Triangle: """ Triangle """ def __init__(self, top_a, top_b, top_c): """ :param top_a: Point :param top_b: Point :param top_c: Point >>> triangle = Triangle(point.Point(1,1), point.Point(3,1), point.Point(2,3)) >>> triangle.side_ab 2.0 """ self.top_a = top_a self.top_b = top_b self.top_c = top_c self.side_ab = line.Line(self.top_a, self.top_b).line self.side_ac = line.Line(self.top_a, self.top_c).line self.side_bc = line.Line(self.top_b, self.top_c).line def is_triangle(self): """ :return: bool Check if it is a triangle >>> triangle = Triangle(point.Point(1,1), point.Point(3,1), point.Point(2,3)) >>> triangle.is_triangle() True """ return (self.side_ab + self.side_ac > self.side_bc) and \ (self.side_ac + self.side_bc > self.side_ab) and \ (self.side_ab + self.side_bc > self.side_ac) def perimeter(self): """ :return: float Return perimeter of the triangle >>> triangle = Triangle(point.Point(1,1), point.Point(3,1), point.Point(2,3)) >>> triangle.perimeter() 6.47213595499958 """ return self.side_ab + self.side_ac + self.side_bc def area(self): """ :return: float Return area of the triangle >>> triangle = Triangle(point.Point(1,1), point.Point(3,1), point.Point(2,3)) >>> triangle.area() 2.0 """ halfp = self.perimeter()/2 return sqrt(halfp*(halfp - self.side_ab)*(halfp - self.side_ac)*(halfp - self.side_bc))
false
901cfcc418c14cbdc3dc6b67440c0bcd22c42a35
bryano13/holbertonschool-interview
/0x09-utf8_validation/0-validate_utf8.py
1,186
4.15625
4
#!/usr/bin/python3 """ This software defines rules to check if an integer combination is a valid UTF-8 Encoding A valid UTF-8 character can be 1 - 4 bytes long. For a 1-byte character, the first bit is a 0, followed by its unicode. For an n-bytes character, the first n-bits are all ones, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. """ def validUTF8(data): """ args: @data: Integer list with the information about the character Return: True if the integers are UTF 8 encodable False otherwise """ bytes_num = 0 for num in data: mask = 1 << 7 if bytes_num == 0: # If byte is not in chain dont ask for confirmation bytes while mask & num: bytes_num += 1 mask = mask >> 1 if bytes_num == 0: continue elif bytes_num == 1 or bytes_num > 4: return False else: # If byte doesnt start with 10 return false if not (num & 1 << 7 and not (num & 1 << 6)): return False bytes_num -= 1 if bytes_num == 0: return True return False
true
ad34250006ebd1305657f4ba94cd7982895f6ddb
sofiarani02/Assigments
/Assignment-1.2.py
2,825
4.5
4
print("***Python code for List operation***\n") # declaring a list of integers myList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # List slicing operations # printing the complete list print('myList: ',myList) # printing first element print('first element: ',myList[0]) # printing fourth element print('fourth element: ',myList[3]) # printing list elements from 0th index to 4th index print('myList elements from 0 to 4 index:',myList[0: 5]) # printing list -7th or 3rd element from the list print('3rd or -7th element:',myList[-7]) # appending an element to the list myList.append(111) print('myList after append():',myList) # finding index of a specified element print('index of \'80\': ',myList.index(80)) # sorting the elements of iLIst myList.sort() print('after sorting: ', myList); # popping an element print('Popped elements is: ',myList.pop()) print('after pop(): ', myList); # removing specified element myList.remove(80) print('after removing \'80\': ',myList) # inserting an element at specified index # inserting 100 at 2nd index myList.insert(2, 100) print('after insert: ', myList) # counting occurances of a specified element print('number of occurences of \'100\': ', myList.count(100)) # extending elements i.e. inserting a list to the list myList.extend([11, 22, 33]) print('after extending:', myList) #reversing the list myList.reverse() print('after reversing:', myList) #clearing the list myList.clear() print('after clearing:', myList) print("\n*********************************************\n") print("***Python code for String operation***\n") s = "Strings are awesome!" # Length should be 20 print("Length of s = %d" % len(s)) # First occurrence of "a" should be at index 8 print("The first occurrence of the letter a = %d" % s.index("a")) # Number of a's should be 2 print("a occurs %d times" % s.count("a")) # Slicing the string into bits print("The first five characters are '%s'" % s[:5]) # Start to 5 print("The next five characters are '%s'" % s[5:10]) # 5 to 10 print("The thirteenth character is '%s'" % s[12]) # Just number 12 print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing) print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end # Convert everything to uppercase print("String in uppercase: %s" % s.upper()) # Convert everything to lowercase print("String in lowercase: %s" % s.lower()) # Check how a string starts if s.startswith("Str"): print("String starts with 'Str'. Good!") # Check how a string ends if s.endswith("ome!"): print("String ends with 'ome!'. Good!") # Split the string into three separate strings, # each containing only a word print("Split the words of the string: %s" % s.split(" "))
true
56cc4deeb8d82fe0a032ea4b0f84feff308315ab
baroquebloke/project_euler
/python/4.py
541
4.125
4
# A palindromic number reads the same both ways. The largest palindrome made # from the product of two 2-digit numbers is 9009 = 91 x 99. # Find the largest palindrome made from the product of two 3-digit numbers. # result: 906609 # time: 0.433s # # *edit: optimized* def palind_num(): is_pal = 0 for x in range(999, 99, -1): for y in range(x, 99, -1): num = x * y if str(num) == str(num)[::-1]: if is_pal < num: is_pal = num return is_pal print palind_num()
true
054eaa44d1652eb87ed365839643ee4e76d4bbe7
codejoncode/Sorting
/project/iterative_sorting.py
2,418
4.5
4
# Complete the selection_sort() function below in class with your instructor def selection_sort(arr): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for j in range(i, len(arr)): if arr[j] < arr[smallest_index]: smallest_index = j # TO-DO: swap arr[cur_index], arr[smallest_index] = arr[smallest_index], arr[cur_index] return arr # TO-DO: implement the Insertion Sort function below def insertion_sort(arr): i = 1 while i < len(arr): x = arr[i] j = i - 1 while j >= 0 and arr[j] > x: arr[j+1] = arr[j] j = j - 1 # end of nested while arr[j+1] = x i = i + 1 # end of parent while loop return arr # STRETCH: implement the Bubble Sort function below def bubble_sort(arr): """ O(n^2) time complexity should be used with smaller lists can be used with semi sorted lists. arr must be an iterable perferably an array type. Will sort in ascending order. """ for element in arr: for index in range(len(arr) - 1): if arr[index] > arr[index + 1]: arr[index], arr[index+1] = arr[index+1], arr[index] return arr # STRETCH: implement the Count Sort function below def count_sort(arr, maximum=-1): """ algorithm for sorting a collection of objects according to keys that are small integers; that is an integer sorting algorithm It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each value in the output sequence. Time complexity O(n log n) """ if len(arr) == 0: return [] k = max(arr) count = [0 for x in range(k+1)] output = [0 for x in range(len(arr))] for i in range(0, len(arr)): if arr[i] < 0: return "Error, negative numbers not allowed in Count Sort" else: count[arr[i]] = count[arr[i]] + 1 # end of for loop for i in range(2, len(arr)): count[i] = count[i] + count[i-1] # end of for loop i = len(arr) - 1 for i in range(len(arr) - 1, -1, -1): output[count[arr[i]]] = arr[i] # end of for loop return output
true
1ced62858071d7ea1ee50ff2bf50760f9ff7b65c
ElenaMBaudrit/OOP_assignments
/Person.py
1,108
4.25
4
#Todd's March 21st 2018 #example of a class. class Person(object): #Always put "object" inside the parentheses of the class def __init__(self, name, age, location): #double underscores in Python: something that is written somewhere else. "Dunder"= double underscores. #constructor: name of the function/method. There will be the attributes for the specific class. #the "name, age, location" are the parameters that "person" instance will have. "Self" help us create the linkage between the class and the instances. It is similar to "this", from JQuery. self.name = name self.age = age self.location = location def say_hello(self): print "Hello, my name is {}".format(self.name) #Instance: think of it as a variable, defining the class it belongs to. p1 = Person("Javier", 23, "San Jose") print p1.name print p1.age print p1.location #If there are more individuals, it goes like this: p2 = Person ("Rodolfo", 23, "San Jose") p3 = Person("Elena", 21, "San Jose") p4 = Person ("Manzura", 21, "Tempe") p3.say_hello()
true
3690ab99200c1c8f36b2537c14ccd338566e4fa2
glissader/Python
/ДЗ Урок 6/main2.py
1,125
4.25
4
# Реализовать класс Road (дорога). # - определить атрибуты: length (длина), width (ширина); # - значения атрибутов должны передаваться при создании экземпляра класса; # - атрибуты сделать защищёнными; # - определить метод расчёта массы асфальта, необходимого для покрытия всей дороги; # - использовать формулу: длина*ширина*масса асфальта для покрытия одного кв. метра # дороги асфальтом, толщиной в 1 см*число см толщины полотна; # - проверить работу метода. # Например: 20 м*5000 м*25 кг*5 см = 12500 т. class Road: def __init__(self, length: int, width: int): self._length = length self._width = width def mass(self, cm: int): return self._length * self._width * 25 * cm / 1000 road = Road(5000, 20) print(f'{road.mass(5)} т')
false
eceeeb18fb41636815f138b55602cd3956e1ff3b
Jian-Lei/LeetCodeExercise
/example/exercise_9.py
835
4.1875
4
#!/usr/bin/env python # coding=utf-8 """ Auther: jian.lei Email: leijian0907@163.com 给你一个整数 x ,如果 x 是一个回文整数,返回 ture ;否则,返回 false 。 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。 https://leetcode-cn.com/problems/palindrome-number """ def is_palindrome(x): result = False if -1 < x < 2 ** 31 - 1: y = int(str(x)[::-1]) if x == y: result = True return result def is_palindrome_1(x): return str(x) == str(x)[::-1] if __name__ == "__main__": print(is_palindrome(0)) print(is_palindrome(121)) print(is_palindrome(122)) print(is_palindrome_1(0)) print(is_palindrome_1(121)) print(is_palindrome_1(122)) print(is_palindrome_1(-122))
false
d07f8d3ae500f5aefc1e03accc48d230ce4b4edd
adibhatnagar/my-github
/NIE Python/Third Code/Further Lists.py
1,629
4.3125
4
list_1=['Apple','Dell','HP','LG','Samsung','Acer','MSI','Asus','Razer'] #declares list containing names of laptop makers as strings list_2=[1,2,3,3,3,4,5,5,6,7,8,8,8,8,9] #declares list containing integers #Remember list elements have index starting from 0 so for list_1 the element 'Apple' has index 0 #If you store an element of a list using inverted commas then it is stored as a string #For example, list_temporary=['1','2','3'] contains the first three integers as strings #for the following code uncomment each line to see what it does #after observing comment that line re-run code after saving this code #print(list_2.count(8)) #print(list_2.count(3)) #print(list_1.count('Apple')) #print(list_2.index(3)) #print(list_2.index(5)) #print(list_2.index(8)) #print(list_2.pop(0)) #print(list_2.pop(5)) #print(list_2.remove(3)) #print(list_1.reverse()) #print(list_1.sort()) #follow the next 4 lines by uncommenting and recommenting two lines at once #list_1.insert(0,'Lenovo') #print(list_1) #print(list_1.remove('Lenovo')) #print(list_1) #this code prints the list_1 by accessing index through list_2 # to compare values of strings, integers, etc we use comparators #for example '!=' is comparator for 'not-equal-to' # '==' is comporator for 'equal' # '>' and '<' are 'less/greater than' comparators #follow the next six lines one after other or else you will get an error message #for i in range(0, (len(list_2)-1)): # if list_2[i]<list_2[i+1]: # print(list_2[i], list_1[list_2[i]-1]) # if i+1==len(list_2)-1: # if list_2[i] != list_2[i+1]: # print(list_2[i+1], list_1[list_2[i]])
true
e5e227509210a211bbbd4c9c4a7e3fcc9dd23a96
gagande90/Data-Structures-Python
/Comprehensions/comprehension_list.py
562
4.25
4
# list with loop loop_numbers = [] # create an empty list for number in range(1, 101): # use for loop loop_numbers.append(number) # append 100 numbers to list print(loop_numbers) # list comprehension comp_numbers = [ number for number in range(1, 101) ] # create a new list print("-"*25) print(comp_numbers) # list comprehension with added condition comp_numbers_three = [ number for number in range(1, 101) if number % 3 == 0 ] # multiples of three print("&"*25) print(comp_numbers_three)
true
bbd9d9f89619a93c37c79c269f244d899b047394
rebecabramos/Course_Exercises
/Week 6/search_and_replace_per_gone_in_list.py
1,123
4.375
4
# The program create a list containing the integers from (1 to 10) in increasing order, and outputs the list. # Then prompt the user to enter a number between 1 and 10, replace this number by the str object (gone) and output the list. # If the user enters a string that does not represent an integer between 1 and 10, instead output the appropriate message sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(sequence) number_for_verification = input('Enter an integer between 1 and 10 >') for x in sequence: if number_for_verification.isnumeric() == True: if int(number_for_verification) >= sequence[0] and int(number_for_verification) <= sequence[-1]: if x == int(number_for_verification): # knowing that the list in python starts with index zero, # so the third element corresponds to position two of the list sequence[x-1] = 'gone' print(sequence) break else: print(number_for_verification, 'is not between 1 and 10') break else: print(number_for_verification, 'is not a positive integer') break
true
23aed0b18c33addf4ed34a8a25f206b826239b9c
rebecabramos/Course_Exercises
/Week 6/split_str_space-separated_and_convert_upper.py
308
4.46875
4
# The program performs space-separated string conversion in a list # and then cycles through each index of the list # and displays the result in capital and capital letters string = input('Enter some words >') list_string = string.split() print(list_string) for x in list_string: print(x, x.upper())
true
0f8cc167c0447ed209bb00b04ebdb2cb3053b2fb
hm06063/OSP_repo
/py_lab/aver_num.py
282
4.28125
4
#!/usr/bin/python3 if __name__ == '__main__': n = int(input("How many numbers do you wanna input?")) sum = 0 for i in range(0,n): num = int(input("number to input: ")) sum += num mean = sum/n print("the mean of numbers is {}".format(mean))
true
fef5d74c772b75ba6e976e83a848233649484fce
yc-xiao/interview
/design/design_pattern/builder.py
1,452
4.1875
4
""" 建造者模式(Builder Pattern)将一个复杂对象分解成多个相对简单的部分,然后根据不同需要分别创建它们,最后构建成该复杂对象。 汽车 = 发动机 + 底盘 + 车身 产品 = 模块A(模块a1, 模块a2, ...) + 模块B(模块b1, 模块b2, ...) + 模块C(模块c1, 模块c2, ...) 组合使用,Python Logging 使用场景: Logging 组合选择 """ class Engine(): def __str__(self): return f'Engine' class Engine2(Engine): def __str__(self): return f'Engine2' class Car(): def __init__(self, engine, chassis, body): self.engine = engine self.chassis = chassis self.body = body def show(self): return f'{self.engine}, {self.chassis}, {self.body}' class CarBuilder(object): engine = None chassis = None body = None def addEngine(self, engine): self.engine = engine def addChassis(self, chassis): self.chassis = chassis def addBody(self, boy): self.body = boy def build(self): return Car(self.engine, self.chassis, self.body) if __name__ == '__main__': carBuilder = CarBuilder() carBuilder.addEngine(Engine()) carBuilder.addBody('boy1') carBuilder.addChassis('chassis1') car = carBuilder.build() print(car.show()) carBuilder.addEngine(Engine2()) car2 = carBuilder.build() print(car2.show())
false
86b2340e9602b2aa3eab5c4fd4fd3dc1b9b9cf9a
zatserkl/learn
/python/numpy_matrix_solve.py
1,756
4.28125
4
################################################# # See the final solution in the numpy_matrix.py # ################################################# import numpy as np """ Solve equation A*x = b where b is represented by ndarray or matrix NB: use matmul for the multiplication of matrices (or arrays). """ def solve_matrix_matrix(): A = np.mat("1 -2 1;0 2 -8;-4 5 9") print("A:\n", A) # define b as matrix: b should be a column vector b = np.matrix([0, 8, -9]).T print("b is a numpy matrix:\n", b) x = np.linalg.solve(A, b) print("Solution of the equation A*x = b:\n", x, "\ntype(x) =", type(x)) # check the solution # b1 = A.dot(x) # b1 = np.dot(A, x) b1 = np.matmul(A, x) print('b1 = np.matmul(A, x):\n', b1) def solve_matrix_array(): A = np.mat("1 -2 1;0 2 -8;-4 5 9") print("A:\n", A) # define b as ndarray: b should be a row vector b = np.array([0, 8, -9]) # b = np.matrix([0, 8, -9]).T # if b is matrix, it should be column print("b is a numpy array, row vector:\n", b) x = np.linalg.solve(A, b) # if b is column matrix, x will be column matrix print("Solution of the equation A*x = b:\n", x, "\ntype(x) =", type(x)) # check the solution # b1 = A.dot(x) # if b is column matrix, x will be column matrix b1 = np.dot(A, x.T) # if b is array, x will be array: transpose it print('b1 = A.dot(x.T):\n', b1) b1 = np.matmul(A, x.T) # b1 = A.dot(x.T) # if b is array, x will be array: transpose it print('b1 = np.matmul(A, x.T):\n', b1) print("\nSolve equation A*x = b") print("where we use dot-product A.dot(x)") print("\ndefine b as a np.matrix") solve_matrix_matrix() print("\ndefine b as a np.array") solve_matrix_array()
true
cf44c9820ab6c0e5c8ae0c270c5f097cd6c79550
zatserkl/learn
/python/class_set.py
1,286
4.15625
4
class Set: """Implementation of set using list """ def __init__(self, list_init=None): """constructor""" self.list = [] if list_init is not None: for element in list_init: self.list.append(element) """From http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python So, my advice: focus on making __str__ reasonably human-readable, and __repr__ as unambiguous as you possibly can, even if that interferes with the fuzzy unattainable goal of making __repr__'s returned value acceptable as input to __eval__! """ def __repr__(self): """string representation of the Set object It will be printed in IPython if you type object name followed by <CR> """ return str(self.list) def __str__(self): """string representation of the Set object It will be printed in IPython if you type object name followed by <CR> """ return 'list: ' + str(self.list) def contains(self, element): return element in self.list def add(self, element): if element not in self.list: self.list.append(element) def remove(self, element): if element in self.list: self.list.remove(element)
true