blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7cabf6be4d6c2b465dcdcdfb75e83441fb8c1fd5
PravinSelva5/LeetCode_Grind
/Linked_Lists/RemoveNthNodeFromEndOfList.py
1,247
4.1875
4
''' Given the head of a linked list, remove the nth node from the end of the list and return its head. BECASUE THE GIVEN LIST IS SINGLY-LINKED, THE HARDEST PART OF THIS QUESTION, IS FIGURING OUT WHICH NODE IS THE Nth ONE THAT NEEDS TO BE REMOVED -------- RESULTS -------- Time Complexity: O(N) Space Complexity: O(1) Runtime: 36 ms, faster than 41.26% of Python3 online submissions for Remove Nth Node From End of List. Memory Usage: 14.3 MB, less than 18.59% of Python3 online submissions for Remove Nth Node From End of List. ''' # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: behind_ptr = ListNode(0) answer = behind_ptr ahead_ptr = head behind_ptr.next = head for i in range(1, n+1): ahead_ptr = ahead_ptr.next while ahead_ptr != None: behind_ptr = behind_ptr.next ahead_ptr = ahead_ptr.next behind_ptr.next = behind_ptr.next.next return answer.next
true
9ee562a0c867c164558a362629732cd514632ca5
PravinSelva5/LeetCode_Grind
/Array_101/MergeSortedArray.py
1,051
4.21875
4
''' Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Notes The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. Unfortunately had to reference the solutions for this question ''' class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ #Pointers for nums1 & nums2 p1 = m - 1 p2 = n - 1 #Pointer for nums1 p = m + n - 1 while p1 >= 0 and p2 >= 0: if nums2[p2] > nums1[p1]: nums1[p] = nums2[p2] p2 -= 1 else: nums1[p] = nums1[p1] p1 -= 1 p -= 1 # If there are still nums1[:p2 + 1] = nums2[:p2 + 1]
true
4d8c4cd3b1005c20887c69c87e0b127c1b0189d5
PravinSelva5/LeetCode_Grind
/Linked_Lists/MergeTwoSortedLists.py
1,762
4.25
4
''' Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Runtime: 40 ms, faster than 39.21% of Python3 online submissions for Merge Two Sorted Lists. Memory Usage: 14.3 MB, less than 8.31% of Python3 online submissions for Merge Two Sorted Lists. ----------------------- COMPLEXITY ----------------------- Time Complexity: O(N) Space Complexity: O(1) ''' # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # Utilize the fact that the lists are sorted current = ListNode(0) answer = current # points to the beginning of our list while l1 and l2: if l1.val > l2.val: current.next = l2 l2 = l2.next else: current.next = l1 l1 = l1.next current = current.next # If one list still needs to be added while l1: current.next = l1 l1 = l1.next current = current.next while l2: current.next = l2 l2 = l2.next current = current.next return answer.next s = Solution() l1_1 = ListNode(1) l1_2 = ListNode(2) l1_4 = ListNode(4) l1_1.next = l1_2 l1_2.next = l1_4 l2_1 = ListNode(1) l2_3 = ListNode(3) l2_4 = ListNode(4) l2_1.next =l2_3 l2_3.next = l2_4 answer = s.mergeTwoLists(l1_1, l2_1) while answer is not None: print(answer.val) answer = answer.next
true
480fbd431ed529d6cc8b30ed2e902d271cea3d84
dwkeis/self-learning
/day3_strategy_pattern/fries.py
869
4.15625
4
"""is a test for factory model""" class Fries(): """define fries""" def describe(self): pass class NoSalt(Fries): """define fries without salt""" def __init__(self,flavor): self.__name = flavor def describe(self): print("i am " + self.__name + " fries") class Default(Fries): """ it's the default flavor of fries""" def __init__(self,flavor): self.__name = flavor def describe(self): print("i am " + self.__name + " fries") class Factory: """where to make fries""" def produce_fries(self, flavor): if flavor == 'nosalt': return NoSalt("no salt") if flavor == 'original': return Default("default") if __name__ == '__main__': factory = Factory() factory.produce_fries('nosalt').describe() factory.produce_fries('original').describe()
true
bff349b3cf94bd9cf6fd561259023d81318d9773
R0YLUO/Algorithms-and-Data-Structures
/data_structures/queue.py
1,384
4.1875
4
"""Implementation of a queue using a python list""" from typing import Generic, TypeVar T = TypeVar('T') class Queue(Generic[T]): def __init__(self) -> None: """Instantiates an empty list""" self.length = 0 self.list = [] def __len__(self) -> int: """Length of our queue""" return self.length def is_empty(self) -> bool: return len(self) == 0 def append(self, item: T) -> None: """Add item to rear of queue""" self.list.append(item) self.length += 1 def serve(self) -> T: """Remove item at front of queue and return it""" if not self.is_empty(): self.length -= 1 return self.list.pop(0) else: raise Exception("Queue is empty") def peek(self) -> T: """Look at item at front of queue removing""" if not self.is_empty(): return self.list[0] else: raise Exception("Queue is empty") def __str__(self) -> str: """Prints contents in Queue from front to rear.""" n = len(self) output = "" if n == 0: return output else: output += '[' output += str(self.list[0]) for i in range(1, n): output += ", " + str(self.list[i]) output += ']' return output
true
36131e269728e7573a366ecde5bb68178834c161
pranaymate/100Plus_Python_Exercises
/21.py
1,152
4.25
4
#~ 21. A website requires the users to input username and password to register. Write a program to check the validity of password input by users. #~ Following are the criteria for checking the password: #~ 1. At least 1 letter between [a-z] #~ 2. At least 1 number between [0-9] #~ 1. At least 1 letter between [A-Z] #~ 3. At least 1 character from [$#@] #~ 4. Minimum length of transaction password: 6 #~ 5. Maximum length of transaction password: 12 #~ Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. #~ If the following passwords are given as input to the program: #~ ABd1234@1, aF1#, 2w3E*, 2We3345 #~ Then, the output of the program should be: #~ ABd1234@1 #~ Hints: In case of input data being supplied to the question, it should be assumed to be a console input. import re def main(): passwords = input().split(",") result = [] for password in passwords: if len(password) >= 6 and len(password) <= 12: if re.search("([a-zA-Z0-9])+([@#$])+",password): result.append(password) print(",".join(result)) if __name__=="__main__": main()
true
cb085973dc8a164bcdb82b3beb80310303f0ceee
pranaymate/100Plus_Python_Exercises
/04.py
569
4.40625
4
#~ 04. Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. #~ Suppose the following input is supplied to the program: #~ 34,67,55,33,12,98 #~ Then, the output should be: #~ ['34', '67', '55', '33', '12', '98'] #~ ('34', '67', '55', '33', '12', '98') def Main(): numberSequence = input("Enter the comma-separated sequence: ") numberList = numberSequence.split(',') numberTuple = tuple(numberList) print(numberList) print(numberTuple) if __name__ == '__main__': Main()
true
3a6da2770d72955dd5330363f7a126a033e49d0e
pranaymate/100Plus_Python_Exercises
/12.py
632
4.4375
4
#~ 12. Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. #~ Suppose the following input is supplied to the program: #~ Hello world #~ Practice makes perfect #~ Then, the output should be: #~ HELLO WORLD #~ PRACTICE MAKES PERFECT #~ Hints: In case of input data being supplied to the question, it should be assumed to be a console input. def main(): lines = eval(input("Enter number of lines: ")) seq_lines = [] for i in range(lines): seq_lines.append(input().upper()) for i in seq_lines: print(i) if __name__=='__main__': main()
true
f67dc2f0ab519d287974c0c6ddc403eed51a59fe
Nmeece/MIT_OpenCourseware_Python
/MIT_OCW/MIT_OCW_PSets/PS3_Scrabble/Test_Files/is_word_vaild_wildcard.py
1,979
4.15625
4
''' Safe space to try writing the is_word_valid function. Modified to accomodate for wildcards. '*' is the wildcard character. should a word be entered with a wildcard, the wildcard shall be replaced by a vowel until a word found in the wordlist is created OR no good word is found. Nygel M. 29DEC2020 ''' VOWELS = 'aeiou' word = "h*ney" hand = {'n': 1, 'h': 1, '*': 1, 'y': 1, 'd': 1, 'w': 1, 'e': 2} word_list = ["hello", 'apple', 'honey', 'evil', 'rapture', 'honey'] def is_word_valid(word, hand, word_list): low_word = str.lower(word) hand_copy = hand.copy() vowels_list = list(VOWELS) wild_guess_list = [] wild_guess_counter = 0 while '*' in low_word: while len(vowels_list) >= 1 and ''.join(wild_guess_list) not in word_list: wild_guess_list = [] for n in low_word: if n != str("*"): wild_guess_list.append(n) else: wild_guess_list.append(vowels_list[0]) del vowels_list[0] wild_guess_counter += 1 wild_guess = ''.join(wild_guess_list) if wild_guess in word_list: for letter in low_word: if letter in hand_copy and hand_copy[letter] >= 1: hand_copy[letter] -= 1 if hand_copy[letter] <= 0: del(hand_copy[letter]) else: return print('False') return print('True') else: return print('False') while low_word in word_list: for letter in low_word: if letter in hand_copy and hand_copy[letter] >= 1: hand_copy[letter] -= 1 if hand_copy[letter] <= 0: del (hand_copy[letter]) continue else: return print('False') return print('True') return print('False') is_word_valid(word, hand, word_list)
true
082b03fc887f3cf806c335df90a15c8b4252d491
heikoschmidt1187/DailyCodingChallenges
/day05.py
1,095
4.53125
5
#!/bin/python3 """ cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: def cons(a, b): def pair(f): return f(a, b) return pair Implement car and cdr. """ # cons is a closure that constructs a pair using a given function def cons(a, b): # inner function pair builds the pair based on a given function f # f therefore defines >how< the pair is created def pair(f): return f(a, b) return pair # get the first element of the pair def car(c): # we need a function to forward to the pair function in cons # that is used to return the first value def first(a, b): return a # put the function to the closure and return the result return c(first) # get the second element of the pair - same principle as car def cdr(c): def second(a, b): return b return c(second) if __name__ == '__main__': print(car(cons(3, 4))) print(cdr(cons(3, 4)))
true
c401e5a8cde94a8accd7480f97d201b8a7e01f8c
Mahler7/udemy-python-bootcamp
/errors-and-exceptions/errors-and-exceptions-test.py
965
4.1875
4
###Problem 1 Handle the exception thrown by the code below by using try and except blocks. try: for i in ['a','b','c']: print(i**2) except TypeError: print('The data type is not correct.') ###Problem 2 Handle the exception thrown by the code below by using **try** and **except** blocks. Then use a **finally** block to print 'All Done.' x = 5 y = 0 try: z = x/y except ZeroDivisionError: print('There is a zero division error here') finally: print('All done') ###Problem 3 Write a function that asks for an integer and prints the square of it. Use a while loop with a try,except, else block to account for incorrect inputs. def ask(): while True: try: squared = int(input('Please enter a number to be squared: ')) print(squared ** 2) except: print('You must enter an integer') continue else: print('Integer entered') break ask()
true
5acbcdc262bf5e6a07f4b938dc4cb17599c45df4
Michael37/Programming1-2
/Lesson 9/Exercises/9.3.1.py
683
4.34375
4
# Michael McCullough # Period 4 # 12/7/15 # 9.3.1 # Grade calculator; gets input of grade in numbers and converts info to a letter value grade = float(input("what is a grade in one of your classes? ")) if grade > 0.0 and grade < 0.76: print ("You have an F") elif grade > 0.75 and grade < 1.51: print ("You have a D") elif grade > 1.50 and grade < 2.01: print ("You have a C") elif grade > 2.0 and grade < 2.51: print ("You have a B-") elif grade > 2.50 and grade < 3.01: print ("You have a B") elif grade > 3.0 and grade < 3.51: print ("You have an A-") elif grade > 3.50 or grade <= 4.0: print ("You have a solid A!") else: print ("Grade value not found.")
true
d15526a594a6593a328f8200607616c128eb4296
bozy15/mongodb-test
/test.py
1,245
4.21875
4
def welcome_function(): """ This function is the welcome function, it is called first in the main_program_call function. The function prints a welcome message and instructions to the user. """ print("WELCOME TO LEARNPULSE") print( "Through this program you can submit and search for \n" "staff training information" ) print("\n") print("What would you like to do?") print("Please enter one of the following options to progress:") print('- Enter "input" to add trainee data to the database') print('- Enter "search" to search for trainee data') while True: user_branch_choice = input("Please input your command: ") if user_branch_choice == "input": return user_branch_choice elif user_branch_choice == "search": return user_branch_choice else: print("Sorry, that command was invalid please try again") print("\n") # def program_branch(): def main_program_call(): """ This function is the main function in the program through which all other functions are called. """ branching_variable = welcome_function() print(branching_variable) main_program_call()
true
3e628ae24afa40165546a5ece7ed0078b620a2e3
mattjhann/Powershell
/001 Multiples of 3 and 5.py
342
4.21875
4
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. numbers = [] for i in range(1000): if i % 3 == 0 or i % 5 == 0: numbers.append(i) j = 0 for i in numbers: j += i print(j)
true
e2b2c9b2c24413046ea0a66011ac651c68736a7e
EmilyJRoj/emoji27
/anothernewproj/anothernewproj.py
607
4.1875
4
# starting off print(22 / 7) print(355 / 113) import math print(9801 / (2206 * math.sqrt(2))) def archimedes(numsides, numSides): innerAngleB = 360.0 / numSides halfAngleA = innerAngleB / 2 oneHalfSides = math.sin(math.radians(halfAngleA)) sideS = oneHalfSideS * 2 polygoncircumference = numSides * side5 pi = polygonCircumference / 2 return pi print(archimedes(16)) for sides in range(8, 100, 8): print(sides, archimedes(sides)) # Experiment with the loop above alongside the actual value of pi. How many # sides does it take to make the two close? # 102 sides.
true
4fe99da9a59cc213e6a1f1e2d4cc83064118852e
Sasha1152/Training
/classes/circle_Raymond.py
2,119
4.125
4
# https://www.youtube.com/watch?v=tfaFMfulY1M&feature=youtu.be import math class Circle: """An advanced circle analitic toolkit""" __slots__ = ['diameter'] # flyweight design pattern suppresses the instance dictionary version = '0.1' # class variable def __init__(self, radius): self.radius = radius # instance variable @property # convert dotted access to method calls def radius(self): """Radius of a circle""" return self.diameter / 2 @radius.setter def radius(self, radius): self.diameter = radius * 2 def area(self): """Perform quadrature on a shape of uniform radius""" return math.pi * self.radius ** 2 def perimeter(self): return 2.0 * math.pi * self.radius @classmethod # alternative constructor def from_bbd(cls, bbd): """Construct a circle form a bounding box diagonal""" radius = bbd / 2.0 / math.sqrt(2.0) return cls(radius) # or Circle(radius) @staticmethod # attach functions to classes def angle_to_grade(angle): """Convert angle in degree to a percentage grade""" return math.tan(math.radians(angle)) * 100 cuts = [0.1, 0.5, 0.8] circles = [Circle(r) for r in cuts] for c in circles: print( f'A circlet with a radius of {c.radius}\n' f'has a perimeter {c.perimeter()}\n' f'and a cold area of {c.area()}' ) c.radius *= 1.1 # attribute was changed! print(f'and a warm area of {c.area()}\n') с = Circle.from_bbd(25.1) print( f'A circlet with a bbd of 25.1\n' # f'has a radius {c.radius()}\n' # TypeError: 'float' object is not callable f'and an area of {c.area()}\n' ) class Tire(Circle): """Tires are circles with a corected perimeter""" def perimeter(self): """Circumference corrected for rubber""" return Circle.perimeter(self) * 1.25 t = Tire(22) print( f'A tire of radius {t.radius}\n' f'has an inner area of {t.area()}\n' f'and an odometer corrected perimeter of {t.perimeter()}' )
true
a5a57b64d94b05d9d17fb70835b7957caa2eff62
cihangirkoral/python-rewiew
/homework_02.py
1,834
4.71875
5
# ################ HOMEWORK 02 ###################### # 4-1. Pizzas: Think of at least three kinds of your favorite pizza Store these # pizza names in a list, and then use a for loop to print the name of each pizza # • Modify your for loop to print a sentence using the name of the pizza # instead of printing just the name of the pizza For each pizza you should # have one line of output containing a simple statement like I like pepperoni # pizza # • Add a line at the end of your program, outside the for loop, that states # how much you like pizza The output should consist of three or more lines # about the kinds of pizza you like and then an additional sentence, such as # I really love pizza! # 4-2. Animals: Think of at least three different animals that have a common characteristic Store the names of these animals in a list, and then use a for loop to # print out the name of each animal # • Modify your program to print a statement about each animal, such as # A dog would make a great pet. # • Add a line at the end of your program stating what these animals have in # common You could print a sentence such as Any of these animals would # make a great pet! ############################ P İ Z Z A ########################### pizza_list = ["margarita" , "pepperoni" , "cheddar"] for pizza in pizza_list: print (pizza + " is great" + ". I love it soooo much.") print ("me and my best friend Köksal, we love pizza so much, the best pizza is margarita\n") ############################ A N İ M A L S ####################### animal_list = ["dog" , "cat" , "hamster"] for animal in animal_list: print ("A " + animal + " is very cute") print ("These animals would make great pets!!!")
true
efe029dfb58aa46842ed74b76c21914d988a802e
SyedAltamash/AltamashProgramming
/Fibonacci_Sequence.py
393
4.15625
4
#from math import e #result = input('How many decimal places do you want to print for e: ') #print('{:.{}f}'.format(e, result)) def fibonacci_sequence(number): list = [] a =1 b = 1 for i in range(number): list.append(a) a,b = b,a+b print(list) result = int(input('Hey enter a number for the Fibonacci Sequence: ')) fibonacci_sequence(result)
true
539949c601098bf6ee18857023a80eb440d06426
6reg/data_visualization
/visualize.py
1,899
4.1875
4
""" Image Visualization Project. This program creates visualizations of data sets that change over time. For example, 'child-mortality.txt' is loaded in and the output is a vsualization of the change in child mortality around the world from 1960 until 2017. Red means high and green means low. """ from simpleimage import SimpleImage DATA_SET = 'data-illiteracy.txt' GREEN = 127 BLUE = 127 MAX_RED_VALUE = 255 CANVAS_WIDTH = 1100 CANVAS_HEIGHT = 200 def main(): canvas = SimpleImage.blank(CANVAS_WIDTH, CANVAS_HEIGHT) red_values = get_red_values() canvas = make_image(red_values, canvas) canvas.show() def get_red_values(): red_values = [] with open(DATA_SET) as file: for i in range(2): next(file) for line in file: line = line.strip() red_values.append(round(float(line) * MAX_RED_VALUE)) return red_values def get_pixel_color(red_value, pixel): pixel.red = red_value pixel.green = GREEN pixel.blue = BLUE return pixel def make_image(red_values, canvas): # Get width each stripe should be stripe_width = CANVAS_WIDTH // len(red_values) # 100 // 11 = 100 # Create blank canvas as wide as length of data set new_canvas = SimpleImage.blank(stripe_width * len(red_values), CANVAS_HEIGHT) # For each stripe on canvas.. for each_stripe in range(len(red_values)): for x in range(stripe_width): for y in range(CANVAS_HEIGHT): # Get starting point of each "each_stripe" start_x = stripe_width * each_stripe + x pixel = canvas.get_pixel(start_x, y) # Update pixel with red value from data set pixel = get_pixel_color(red_values[each_stripe], pixel) new_canvas.set_pixel(start_x, y, pixel) return new_canvas if __name__ == '__main__': main()
true
b98da74f144dc5cb6a3f6e691f9a0f2e41a8cb03
frisomeijer/ProjectEuler100
/Problem_020/Solution_020.py
660
4.15625
4
''' Problem 20: n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! ''' import time start_time = time.time() def factorial_digit_sum(n): factorial=1 fact_sum=0 for number in range(1,n+1): factorial*=number for digit in str(factorial): fact_sum+=int(digit) return fact_sum print(factorial_digit_sum(100)) # calculation time: 0.0030336380004882812 seconds print("calculation time: %s seconds" % (time.time() - start_time))
true
cf39769061e619e9a3edf87688327e97f96ccf26
prasanna1695/python-code
/1-2.py
474
4.34375
4
#Write code to reverse a C-Style String. #(C-String means that abcd is represented as five characters # including the null character.) def reverseCStyleString(s): reversed_string = "" for char in s: reversed_string = char + reversed_string return reversed_string print "Test1: hello" print reverseCStyleString("hello") == "olleh" print "Test2: ob" print reverseCStyleString("ob") == "bo" print "Test3: ''" print reverseCStyleString('') == '' ## To do later, utf-8?
true
487b0fedc3b0d970786718cf9034254afbf0d8b4
prasanna1695/python-code
/4-1.py
2,695
4.40625
4
#Implement a function to check if a tree is balanced. For the purposes of this question, #a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one class Tree(object): def __init__(self): self.left = None self.right = None self.data = None #not necessarily a binary tree so I'll implement it as binary and comment how to extend it def isTreeBalenced(tree): if abs(maxDistance(tree) - minDistance(tree)) < 2: return True else: return False def maxDistance(tree): #keep adding and "tree.direcrection == None" for non-binary case if tree == None or tree.left == None and tree.right == None: return 0 #seems messy to have to do this type of checking if the tree is more than binary. elif cases grow exponentially... :( elif tree.left == None and tree.right != None: return 1 + maxDistance(tree.right) elif tree.right == None and tree.left != None: return 1 + maxDistance(tree.left) else: #keep adding and ", maxDistance(tree.direction)" for non-binary case return 1 + max(maxDistance(tree.left), maxDistance(tree.right)) def minDistance(tree): #keep adding and "tree.direcrection == None" for non-binary case if tree == None or tree.left == None and tree.right == None: return 0 #seems messy to have to do this type of checking if the tree is more than binary. elif cases grow exponentially... :( elif tree.left == None and tree.right != None: return 1 + minDistance(tree.right) elif tree.right == None and tree.left != None: return 1 + minDistance(tree.left) else: #keep adding and ", minDistance(tree.direction)" for non-binary case return 1 + min(minDistance(tree.left), minDistance(tree.right)) root = Tree() root.data = "root" print "Test 0: empty tree" print isTreeBalenced(root) == True root.left = Tree() root.left.data = "left" root.left.left = Tree() root.left.left.data = "left left" root.left.right = Tree() root.left.right.data = "left right" root.right = Tree() root.right.data = "right" root.right.left = Tree() root.right.left.data = "right left" root.right.right = Tree() root.right.right.data = "right right" print "Test 1: full binary tree of depth 2" print isTreeBalenced(root) == True root.left.left.left = Tree() root.left.left.left.data = "left, left, left" print "Test 2: add a leaf on the left" print isTreeBalenced(root) == True root.left.left.left.left = Tree() root.left.left.left.left.data = "left, left, left, left" print "Test 3: add a leaf too many on the left" print isTreeBalenced(root) == False root.left.left.left.left = None root.right.left = None print "Test 4: trim too long left & also clip right>left" print isTreeBalenced(root) == True
true
f98cea48e5ef2da1ddd158c9cab3e2102f4a2fa0
johnsonl7597/CTI-110
/P2HW2_ListSets_JohnsonLilee.py
1,190
4.34375
4
#This program will demonstrate the students understanding of lists and sets. #CTI-110, P2HW2 - List and Sets #Lilee Johnson #05 Oct 2021 #----------------------------------------------------------------------------- #pesudocode #prompt user for 6 indivual numbers #store the numbers in a list called List6 #display lowNum, highNum, total, average #set(List6) #display List6, set #----------------------------------------------------------------------------- num1 = int(input("Enter number 1 of 6 > ")) num2 = int(input("Enter number 2 of 6 > ")) num3 = int(input("Enter number 3 of 6 > ")) num4 = int(input("Enter number 4 of 6 > ")) num5 = int(input("Enter number 5 of 6 > ")) num6 = int(input("Enter number 6 of 6 > ")) list6 = [num1, num2, num3, num4, num5, num6] print("\nList6 list:\n", list6) lowNum = min(list6) highNum = max(list6) total = num1 + num2 + num3 + num4 + num5 + num6 average = total / 6 listSix = {num1, num2, num3, num4, num5, num6} print("smallest number in List6: ", lowNum) print("LARGEST number in List6: ", highNum) print("Sum of numbers in List6: ", total) print("The average in List6: ", average) print("\nListSix set:\n", listSix)
true
124651b1e5621e7b54ff62ce933226a778393798
hnhillol/PythonExercise
/HwAssignment7.py
1,903
4.125
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 02:34:40 2019 @author: hnhillol Homework Assignment #7: Dictionaries and Sets Details: Return to your first homework assignments, when you described your favorite song. Refactor that code so all the variables are held as dictionary keys and value. Then refactor your print statements so that it's a single loop that passes through each item in the dictionary and prints out it's key and then it's value. Extra Credit: Create a function that allows someone to guess the value of any key in the dictionary, and find out if they were right or wrong. This function should accept two parameters: Key and Value. If the key exists in the dictionary and that value is the correct value, then the function should return true. In all other cases, it should return false. """ MyFavSong={"Song Name":"Here comes the Sun","Band Name":"The Beatles", "Artist":"George Harrison","Album" : "Abbey Road", "Publisher":"Harrisongs","Released Date":"26" ,"Release Months":"September","Release Year":"1969", "Recorded Period":"7th July-19th August","Genre":"Folk pop , Pop Rock","Length":"3.06","Lable":"Apple", "Writter":"George Harrison","Producer":"George Martin"} print("Here is the song Data") print("*********************") for key in MyFavSong : print(key,":",MyFavSong[key]) print ("\n") print("Cross Checking the input data") print("*****************************") def FindSongInfo(key,value): if key in MyFavSong: if MyFavSong[key]==value: print("You are Correct !!") return True else: print("Attribute Data is incorrect !!") return False else: print("Attribute Doesn't Exist") return False key=input("Please enter the Attribute to check: ") value=input("Guess the Data of the Attribute: ") print(FindSongInfo(key,value))
true
7f3cf610dffccafa759a59ce287ffc73ee2a9639
SyriiAdvent/Intro-Python-I
/src/13_file_io.py
967
4.28125
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # Note: pay close attention to your current directory when trying to open "foo.txt" with open('foo.txt', mode="r") as f: print(f.read()) # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain with open('bar.txt', 'a') as f: f.write("I am line 1 \n") f.write("I am line 2 \n") f.write("I am line 3 \n") # Using python to create python script files! with open('bar.py', 'a') as f: f.write("for ltr in 'Tuna ate the goldfish!':") f.write(f"\n \t print(ltr)")
true
48d2d40bb733d33b57da20111b607832579a9aee
cs-fullstack-2019-fall/python-loops-cw-rjrobins16
/classwork.py
1,507
4.5625
5
# ### Exercise 1: # Print -20 to and including 50. Use any loop you want. # for x in range(-20,51,1): print(x) # ### Exercise 2: # Create a loop that prints even numbers from 0 to and including 20. # Hint: You can find multiples of 2 with (whatever_number % 2 == 0) for x in range(0,21,2): if x % 2 == 0: print(x) # ### Exercise 3: # Prompt the user for 3 numbers. Then print the 3 numbers along with their average after the 3rd number is entered. # Refer to example below replacing ```NUMBER1```, ```NUMBER2```, ```NUMBER3```, and ```THEAVERAGE``` with the actual values. # # Ex.Output # ``` # The average of NUMBER1, NUMBER2, and NUMBER3 is THEAVERAGE num1 = int(input("Enter a number.")) num2 = int(input("Enter a second number.")) num3 = int(input("Enter a third number.")) average = (num1 + num2 + num3) / 3 print(average) # ### Exercise 4: # Use any loop to print all numbers between 0 and 100 that are divisible by 4. # #for x in range(0,100,1): #print (100 % 4 == 0) for x in range(0,100,1): if x % 4 == 0: print (x) # ### Challenge: # Password Checker - Ask the user to enter a password. Ask them to confirm the password. # If it's not equal, keep asking until it's correct or they enter 'Q' to quit. userpassword=input("Enter a password.") userpassword2=input("Re-enter a password.") while userpassword != userpassword2 and userpassword2 != 'q': print ("Passwords do not match. Please re-enter your password:") userpassword2=input() ###
true
3325662f01c1766dc3c42943e6a1e12c56c354ef
jarvis-1805/Simple-Python-Projects
/theGuessingGame.py
900
4.15625
4
import random print("\t\t\tThe Guessing Game!") print("WARNING!!! Once you enter the game you have to guess the right number!!!\n") c = input("Still want to enter the game!!! ('y' or 'n'): ") print() while c == 'y': true_value = random.randint(1, 100) while True: chosed_value = int(input("Choose a number between 1 and 100: ")) if (chosed_value == true_value): print("\nYou guessed it right!!! Good job!!!") break elif (chosed_value > 100 or chosed_value < 0): print("\nYou did not choose the number within range!!!") elif (chosed_value < true_value): print("\nYour number is low...Try again!!!") elif (chosed_value > true_value): print("\nYour number is high...Try again!!!") c = input("\nDo you want to play again? ('y' or 'n'): ")
true
f1f869c390877cfc42bcd25dbec63137b46e3533
kaizer1v/ds-algo
/datastructures/matrix.py
1,797
4.125
4
class Matrix: ''' [[1, 2], [2, 1]] is a matrix ''' def __init__(self, arr): self.matrix = arr self.height = self.calc_height() self.width = self.calc_width() def calc_height(self): return len(self.matrix) def calc_width(self): if self._is_valid(): return len(self.matrix[0]) else: raise Exception('Size of all rows must be same') def _is_valid(self): ''' checks if size of each row of the matrix is the same ''' f = len(self.matrix[0]) for a in self.matrix: if len(a) != f: return False return True def get_dimension(self): return (self.width, self.height) def _is_square(self): ''' compute if height & widht of matrix is the same ''' return self.width == self.height def __repr__(self): print( '\n'.join([ ' '.join(list(map(lambda x: str(x), a))) for a in self.matrix ]) ) def __add__(self, m): ''' adds current matrix with `m` | 1 2 | | 2 1 | | . . | | 2 1 | + | 1 2 | = | . . | ''' # if not self.get_dimension(m): # return False pass def __sub__(self, m): ''' substracts current matrix with `m` ''' pass def __mul__(self, m): ''' multiplies current matrix with `m` ''' pass def eq_size(self, m): ''' checks if current matrix and given matrix are of same dimensions ''' return self.get_dimension() == m.get_dimension() def __eq__(self, m): ''' checks if current matrix == `m` ''' pass
true
5dd783701c899fae07a094a2e2fce4094e370942
kaizer1v/ds-algo
/datastructures/priority_queue.py
1,388
4.40625
4
''' Priority Queue Prioritiy queue operates just like a queue, but when `pop`-ing out the first element that was added, it instead takes out the highest (max) element from the queue. Thus, the items in the priority queue should be comparable. When you add a new item into the queue, it will automatically remove the min value so that the size of the queue remains fixed. WHY? One could always use a normal queue, sort it (desc) and then pop the first one (max). NO - this isn't efficient because, doing that the memory required will be `N` (size of the items in the queue) and the sorting time will take `n log(n)` time, but using a Priority Queue will do that in `n log(m)` and the space required will be `m` only where m < n IMPLEMENTATION The implementation can be done using a linked list or a binary tree. Either way, the data structure (DS) will always be sorted as soon as you insert an item in the DS. ''' class PriorityQueueUsingLinkedList: pass class PriorityQueueUsingBinaryTree: def __init__(self): pass def swim(self): ''' Moves the item up in order of the tree ''' pass def sink(self): ''' Moves the item down in order of the tree ''' pass def xchange(self, a, b): ''' Exchanges a with b ''' a, b = b, a return self
true
803aa2044f18114b72acaa66d0412cdcb61a3d48
Arsenault-CMSC201-Fall2019/Spring_2020_code_samples
/February_17_coding.py
985
4.28125
4
# Examples of code using while loops # from Monday, Feb. 17 age = 0; while (age < 18): age = input("enter your age in years: ") print ("If you’re 18 or older you should vote") print ("that's the end of our story") # compute 10! Using a while loop product = 1 factor = 1 while factor <= 10: product *= factor #or product = product * factor factor += 1 print("our answer is ", product) num = 1 while num % 2 == 0: print(num) num += 2 age = int(input("please enter your age in years: ")) while (age < 0) or (age > 100): print("Age must be between 0 and 100 inclusive ") age = int(input("please enter your age in years: ") grade = "" name = "" while name != "Hrabowski": # get the user's grade grade = input("What is your grade? ") print("You passed!") cookiesLeft = 50 while cookiesLeft > 0: # eat a cookie cookiesLeft = cookiesLeft + 1 #print all the positive odd numbers #less than 100 num = 1 while num != 100: print(num) num = num + 2
true
e7f171ee421609f0c28813cb89cb8869ca9510fe
Arsenault-CMSC201-Fall2019/Spring_2020_code_samples
/February_5_code.py
408
4.1875
4
###################### # # This is one way to write a block # of comments # ######################## """ This is another way to write a block of comments """ ''' This will work too ''' verb = input("please enter a verb") new_verb = verb + "ing" print(new_verb) principal = 10000 rate = 0.03/12 n_payments = 72 cost = (principal * rate * (1 + rate)**n_payments)/((1 + rate)**n_payments -1) print(cost)
true
864d5005fbc7a132a7ee970d006bbf40503496e6
Arsenault-CMSC201-Fall2019/Spring_2020_code_samples
/February_19_coding.py
1,230
4.125
4
#coding for Wednesday, February 19 # Printing new lines, or not print("this produces two lines", "\n", "of output") print("this produces one line", end="") print("of output") # printing out an integer print("{:d} is the answer to the question".format(42)) #printing the same value as a float print("{:f} is the answer to the question".format(42)) #limiting the number of decimal places print("{:6.2f} is the answer to the question".format(42)) if roll == 7 or roll == 11: print ("you win") elif roll == 2 or roll == 3 or roll == 12: print("you lose") else: print("roll again") CRAPS_WINNING_VALUES = [7,11] CRAPS_LOSING_VALUES = [2,3,12] if roll in CRAPS_WINNING_VALUES: print("you win") elif roll in [2,3,12]: print ("you lose") else: print("roll again") str = 'Hey diddle diddle the cat and the fiddle”' str_list = str.split() #this will split on whitespace, and the whitespace will be deleted str_list = str.split("e") #what does this do? What happened to the “e” ? int_str = "3 1 4 5 6 7 8 9 10" int_list = int_str.split() actual_int_list = [] for num in int_list: actual_int_list.append(int(num)) print("now is the time", end="this is where we stop") print("and now we start again")
true
b987f123317a7f8e3feaf6dac464732e13fec601
Spideyboi21/jash_python_pdxcode
/python learning/test.py
350
4.125
4
if -4 < -6: print("True") else: print('False') if "part" in "party!!!1": print("True") else: print("False") age = input('how old are you?') if int(age)< 28 and int(age) >=0: print("this is valid") else: print("not valid") name = input('What is my name? ') if name == "Jash": print("that is correct congratulations")
true
82b473b6d4b8ce07c42b92870b91fee3fb5c8da5
soonebabu/firstPY
/first.py
318
4.21875
4
def checkPrime(num): if num==1 or num==2 or prime(num): return False else: return True def prime(num): for i in range(3,num-1): if (num%i)==0: return True value = input('enter the value') print(value) if checkPrime(value): print('prime') else: print('not')
true
aa5377b9f0a11e32cde4fa8c7ac47ca3bbb9f659
BigBoiTom/Hangman-Game
/Hangman_Game.py
2,686
4.15625
4
import random, time def play_again(): answer = input('Would you like to play again? yes/no: ').lower() if answer == 'y' or answer == 'yes': play_game() elif answer == 'n' or answer == 'no': print("Thanks for Playing!") time.sleep(2) exit() else: pass def get_word(): words = ['pear', 'apple', 'banana', 'grape', 'pineapple', 'orange', 'apricot', 'grapefruit', 'eggplant', 'cabbage', 'broccoli', 'lavender', 'spinach', 'cauliflower', 'lettuce', 'onions', 'pepper', 'carrot', 'tomato', 'strawberry', 'mango', 'pumpkin', 'celery', 'cucumber', 'garlic', 'avocado', 'kiwi', 'blueberry', 'raspberry', 'mandarin'] return random.choice(words) name = input("Please enter your name: ") print("Hello", name, "let's Begin!") time.sleep(1) print("Try to guess the word chosen by the computer!") time.sleep(1) print("You can only guess 1 letter at a time") print("Press Enter after typing a letter") time.sleep(2) print("Let's Start!!") time.sleep(1) def play_game (): alphabet = 'abcdefghijklmnopqrstuvwxyz' word = get_word() letters_guessed = [] tries = 10 guessed = False print('The word contains ', len(word), ' letters.') print(len(word) * '*') while guessed == False and tries > 0: print("You have " + str(tries) + ' tries left') guess = input("Please enter one letter. ").lower() if len(guess) == 1: if guess not in alphabet: print("You have not entered a letter!") elif guess in letters_guessed: print("You already guessed this letter, try another!") elif guess not in word: print("That letter is not part of the word!") letters_guessed.append(guess) tries -=1 elif guess in word: print("Good Job, You guessed a letter!") letters_guessed.append(guess) else: print("How did you even get this message? Go away!") if len(guess) != 1: print("Please only put in 1 letter!") status = '' if guessed == False: for letter in word: if letter in letters_guessed: status += letter else: status += '*' print(status) if status == word: print("Great Job ", name, " You guessed the word") guessed == True play_again() elif tries == 0: print("You are out of tries, better luck next time!") print("The word was: ", word) play_again() play_game()
true
1e9b87bca4f32738e79e1dec5654589374328125
juancoan/python
/Basic/WtihASDemo.py
989
4.125
4
""" WITH / AS keywords """ # print("Normal WRITE start") # File2 = open("File_IO.txt", "w") # File2.write("Trying to write to the file2.") # File2.close() #If I do not write the close() statement, nothing will happen. ALWAYS write it # # print("Normal READ start") # File3 = open("File_IO.txt", "r") # for line in File3: # print(line) print("WITH AS WRITE start") #no need to use CLOSE statement with open("WtihASDemo.txt", 'w') as VariableName: #start using 'with' keybord, variable object at the end 'as Variable name' print("Writting to file...") VariableName.write("Writting with WITH_AS function.") # same write function print('#*'*20) print("WITH AS READ start") #no need to use CLOSE statement with open("WtihASDemo.txt", 'r') as VariableName2: for lines in VariableName2: print(lines) print('#*'*20) print("Using .READ() function") #no need to use CLOSE statement with open("WtihASDemo.txt", 'r') as VariableName2: print(VariableName2.read())
true
3a136144b49f4e564b98cd44b97e77cf73866e93
juancoan/python
/Basic/File2Read.py
795
4.1875
4
my_file2 = open("File2Read.txt", 'r') #use the 'r' mode to read print(str(my_file2.read())) #prints the read method, all the content of the file my_file2.close() print('#*'*20) print("LINE BY LINE EXAMPLE......... Will print the first line only, unless I call that print method twice") my_file_BY_LINE = open("File2Read.txt", 'r') #use the 'r' mode to read print(str(my_file_BY_LINE.readline())) #prints the read method, all the content of the file my_file_BY_LINE.close() print('#*'*20) print("LINE BY LINE EXAMPLE with FOR LOOP.........") my_file_withFOR = open("File2Read.txt", 'r') #use the 'r' mode to read for line in my_file_withFOR: Mayuscula = line.upper() #guardo el cambio en una variable y le aplico el metodo print(Mayuscula)#imprimo la variable my_file_withFOR.close()
true
80a1b64a82ff503d1d41333e893f449881ee87c6
CircleZ3791117/CodingPractice
/source_code/717_1BitAnd2BitCharacters.py
1,646
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'circlezhou' ''' Description: We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. Example 1: Input: bits = [1, 0, 0] Output: True Explanation: The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. Example 2: Input: bits = [1, 1, 1, 0] Output: False Explanation: The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character. Note: 1 <= len(bits) <= 1000. bits[i] is always 0 or 1. ''' class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ if len(bits) < 2: return True nums_of_1 = 0 current_index = -2 while(abs(current_index) <= len(bits)): if bits[current_index] == 0 and nums_of_1 % 2 == 0: return True if bits[current_index] == 0 and nums_of_1 % 2 == 1: return False if bits[current_index] == 1: nums_of_1 += 1 current_index -= 1 if nums_of_1 % 2 == 0: return True else: return False ## Super cool, the above method beats 100.00% of python3 submissions. # A more elegant expression using Greedy class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ parity = bits.pop() while bits and bits.pop(): parity ^= 1 return parity == 0
true
ad79baa9bd795e7e28ba7df8db472be9725d86de
amitauti/HelloWorldPython
/ex02.py
1,019
4.25
4
# http://www.practicepython.org/exercise/2014/02/05/02-odd-or-even.html # Ask the user for a number. Depending on whether the number is even or # odd, print out an appropriate message to the user. import sys def main(): askuser () def askuser(): #part one str = input("Enter a number: ") num = int(float(str)) newnum = num % 2 if newnum == 0: print ("It is even number") else: print ("It is odd number") #part two num = num % 4 if num == 0: print (" and divisible by 4 as well!") #part three str1 = input("Give me a number as numerator ") str2 = input("Give me a number as denomitor ") num_one = int(float(str1)) num_two = int(float(str2)) # this is comment this if num_two == 0: print("We can not devide by zero") sys.exit() else: if num_one % num_two == 0: print("It is a even number") else: print ("It is a odd number") if __name__ == '__main__': main()
true
2f7f8cb23eb74c9046769b6200a49147384375cd
nasirmajid29/Anthology-of-Algorithms
/Algorithms/sorting/mergeSort/mergeSort.py
972
4.28125
4
def mergeSort(array): if len(array) > 1: middle = len(array) // 2 # Finding the middle of the array left = array[:middle] # Split array into 2 right = array[middle:] mergeSort(left) # sorting the first half mergeSort(right) # sorting the second half # Copy data to temp arrays L[] and R[] merge(array, left, right) def merge(array, left, right): i = j = k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: array[k] = left[i] i += 1 else: array[k] = right[j] j += 1 k += 1 # Checking if any element are left from either array while i < len(left): array[k] = left[i] i += 1 k += 1 while j < len(right): array[k] = right[j] j += 1 k += 1 if __name__ == "__main__": alist = [54,26,93,17,77,31,44,55,20] mergeSort(alist) print(alist)
true
2929f49be61557f3233c7c68291711c9426c4638
huchen086/web-caesar
/caesar.py
1,154
4.1875
4
def alphabet_position(letter): """receives a letter (that is, a string with only one alphabetic character)""" """and returns the 0-based numerical position of that letter""" """within the alphabet.""" letter = letter.upper() position = ord(letter) - 65 return position def rotate_character(char, rot): """receives a character char (that is, a string of length 1),""" """and an integer rot. Your function should return a new string of length 1,""" """ the result of rotating char by rot number of places to the right.""" newchar = "" if char.isalpha(): position = alphabet_position(char) if position + rot <= 25: newposition = position + rot else: newposition = (position + rot) % 26 newchar = chr(newposition+65) if char.islower(): newchar = newchar.lower() else: newchar = newchar.upper() else: newchar = char return newchar def encrypt(text, rot): rot = rot newtext = "" for char in text: newchar = rotate_character(char, rot) newtext += newchar return newtext
true
9afee39db5f15d957c60df0a1c50213b73d888aa
ciccolini/Python
/Function.py
2,459
4.46875
4
#to create a function #by using def keyword def my_function(): print("Hello from a function") #to call a function my_function() #to add as many parameters as possible def my_function(fsurname): print(fsurname + " " + "Name") my_function("Anthony") my_function("Romain") my_function("MP") #improvement def my_function(fsurname, fname): print(fsurname + " " + fname) my_function("Anthony","Da Mota") my_function("Romain", "Alexandre") my_function("MP", "Ciccolini") #to set up a default parameter value def my_country(country = "France"): print("I am from " + country) my_country("UK") my_country("Spain") my_country() my_country("Singapore") #to let the function return a value def my_result(x): return 5 * x print(my_result(3)) print(my_result(4)) print(my_result(5)) #to create a recursion of a function #It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result #example 1 def tri_recursion(k): if k > 0 : result = k + tri_recursion(k - 1) print(result) else: result = 0 return result print("\nRecursion example result") tri_recursion(6) #example 2; find all final values from each node world = { "Africa": { "Waganda": 7000 }, "Europe": { "France": { "PACA": { "Nice": 1520 } } }, "America": { "United States": { "New York": 142 } } } def display_population(node): for key in node.keys(): next_value = node[key] if type(next_value) is dict: display_population(next_value) else: print(f"\n{next_value}") display_population(world) #example 3; sum from world def sum_population(node): result = 0 for key in node.keys(): next_value = node[key] if type(next_value) is dict: result += sum_population(next_value) else: return next_value return result print(sum_population(world)) #LAMBDA FUNCTION; small anonymous function with any number of arguments, but can only have one expression x = lambda a : a + 10 print(f"\n{x(5)}") x = lambda a, b : a * b print(x(4, 5)) x = lambda a, b, c : a + b + c print(x(1, 2, 3)) #to combine a function and a lambda function def my_func(n): return lambda a : a * n mydoubler = my_func(2) mytripler = my_func(3) print(mydoubler(6)) print(mytripler(6)) exit()
true
e09d88413f22afee9604ef82652ba6a367214362
idan0610/intro2cs-ex3
/decomposition.py
897
4.25
4
###################################################################### # FILE: decomposition.py # WRITER: Idan Refaeli, idan0610, 305681132 # EXERCISE: intro2cs ex3 2014-2015 # DESCRIPTION: # Find the number of goblets Gimli drank of each day ####################################################################### num_Of_Goblets = int(input("Insert composed number:")) num_Of_Days = 1 DECIMAL_BASE = 10 if num_Of_Goblets == 0: #Gimli has not drank nothing print("The number of goblets Gimli drank on day", num_Of_Days, "was",\ num_Of_Goblets) while num_Of_Goblets != 0: #Check whats the last digit and prints with the current day last_Digit = num_Of_Goblets % 10 print("The number of goblets Gimli drank on day", num_Of_Days, "was",\ last_Digit) #Change for next day and divide (integer) the number by 10 num_Of_Days += 1 num_Of_Goblets //= DECIMAL_BASE
true
625086292e7df6169fd0029150706ea71f67c7bc
Nermeen3/Python-Practice
/Merge Sort Recursion.py
1,444
4.40625
4
### Merge sort: works by dividing the array into halves and each half into another half ### until we're left with n arrays each holds one element from the original array ### then we go back up by comparing arrays and sorrting them as we go up ### time complexity is O(nlogn) ### Auxillary space is O(n) from random import randint def RandomGenerator(size): return [randint(0, 50) for x in range(size)] def Merge(array1, array2): #print(array1, array2) newArray = [] index1, index2 = 0, 0 for i in range(len(array1)+len(array2)): if index1 == len(array1): newArray.extend(array2[index2:]) break elif index2 == len(array2): newArray.extend(array1[index1:]) break elif array1[index1] < array2[index2]: newArray.append(array1[index1]) index1+= 1 else: newArray.append(array2[index2]) index2+= 1 #print(len(array1)+len(array2), len(newArray)) #print('merged array: ', newArray) return newArray def MergeSort(array): # Base Case when we reach last step of dividing the original array's elements if len(array) <= 1: return array # next is recusiveley divide the array into halves LArray, RArray = MergeSort(array[:int(len(array)/2)]), MergeSort(array[int(len(array)/2):]) #print(LArray, RArray) return Merge(LArray, RArray) print(MergeSort(RandomGenerator(14)))
true
39351a74c9a0e7e20d2fd64e10982fdd2cd0611b
ospupegam/for-test
/Processing_DNA_in_file .py
570
4.28125
4
''' Processing DNA in a file The file input.txt contains a number of DNA sequences, one per line. Each sequence starts with the same 14 base pair fragment – a sequencing adapter that should have been removed. Write a program that will trim this adapter and write the cleaned sequences to a new file print the length of each sequence to the screen. ''' my_file=open(r"input.txt") f=my_file.read() lines=f.split("\n") seq_line=[] lenght_line=[] for line in lines: seq_line.append(line[15:]) lenght_line.append(len(line[15:])) print(seq_line) print(lenght_line)
true
566e05e99024a9a86095738523f5ad0522c41da1
DanglaGT/code_snippets
/pandas/operations_on_columns.py
303
4.15625
4
import pandas as pd # using a dictionary to create a pandas dataframe # the keys are the column names and the values are the data df = pd.DataFrame({ 'x': [1, 3, 5], 'y': [2, 4, 6]}) print(df) # adding column x and column y in newly created # column z df['z'] = df['x'] + df['y'] print(df)
true
c6dd52dc9c6f3ff0711c27cfe6acc4f4eaedffdd
jmccutchan/python_snippets
/generator.py
1,386
4.1875
4
#This example uses generator functions and yields a generator instead of returning a list #use 'yield' instead of 'return' - yield a generator instead of returning a list, this consumes less memory def index_words(text): if text: yield 0 for index, letter in enumerate(text): if letter == ' ': yield index + 1 ipsum = "is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." it = index_words(ipsum) print(it) #returns a generator (iterator) object print(next(it)) #returns each consecutive iterable def index_file(handle): offset = 0 for line in handle: if line: yield offset for letter in line: offset += 1 if letter == ' ': yield offset address = """ Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all are created equal.""" with open('/tmp/address.txt', 'w') as f: f.write(address) with open('/tmp/address.txt') as f: it = index_file(f) print(next(it)) #returns the next index print(next(it)) #returns the next index print(list(it)) #returns everything in a list
true
5b4d8c87bdac439f9129969434726c5f1d988172
jeffalstott/powerlaw
/testing/walkobj.py
2,106
4.21875
4
"""walkobj - object walker module Functions for walking the tree of an object Usage: Recursively print values of slots in a class instance obj: walk(obj, print) Recursively print values of all slots in a list of classes: walk([obj1, obj2, ...], print) Convert an object into a typed tree typedtree(obj) A typed tree is a (recursive) list of the items in an object, prefixed by the type of the object """ from collections.abc import Iterable BASE_TYPES = [str, int, float, bool, type(None)] def atom(obj): """Return true if object is a known atomic type. obj : Object to identify Known atomic types are strings, ints, floats, bools & type(None). """ return type(obj) in BASE_TYPES def walk(obj, fun): """Recursively walk object tree, applying a function to each leaf. obj : Object to walk fun : function to apply A leaf is an atom (str, int, float, bool or None), or something that is not a dictionary, a class instance or an iterable object. """ if atom(obj): fun(obj) elif isinstance(obj, dict): for keyobj in obj.items(): walk(keyobj, fun) elif isinstance(obj, Iterable): for item in obj: walk(item, fun) elif '__dict__' in dir(obj): walk(obj.__dict__, fun) else: fun(obj) def typedtree(obj): """Convert object to a typed nested list. obj : Object to walk Returns the object if it's an atom or unrecognized. If it's a class, return the list [type(obj)] + nested list of the object's slots (i.e., typedtree(obj.__dict__). If it's iterable, return the list [type(obj)] + nested list of items in list. Otherwise, it's unrecognized and just returned as if it's an atom. """ if atom(obj): return obj if isinstance(obj, dict): return (dict, [typedtree(obj) for obj in obj.items()]) if isinstance(obj, Iterable): return (type(obj), [typedtree(obj) for obj in obj]) if '__dict__' in dir(obj): return (type(obj), typedtree(obj.__dict__)) return obj
true
dea24af2de89866d3a77fce75b268f6be6306b8d
AntGrimm/180bytwo_home_assignment
/app.py
1,881
4.21875
4
# Functions are commented out at the bottom, remove comment to run each function import itertools # Removing a character in a loop and checking word against dictionary def check_super_word(check_str, dictionary): for i in range(0, len(check_str)): # Removing each character in loop new_str = ''.join([check_str[j] for j in range(len(check_str)) if j != i]) if new_str in dictionary: # Checking if each iteration of word is in the dictionary return True # print(check_str + " is a super word") else: continue # Combining integers and interlacing strings def combine_integers(a, b): c = ''.join(map(''.join, itertools.zip_longest(str(a), str(b), fillvalue=""))) return int(c) # Python program for implementation of MergeSort def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 # Finding the mid of the array left = arr[:mid] # Dividing the array elements right = arr[mid:] # into 2 halves merge_sort(left) # Sorting the first half merge_sort(right) # Sorting the second half i = j = k = 0 # Copy data to temp arrays left[] and right[] while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 print("count") k += 1 # Checking if any element was left while i < len(left): arr[k] = left[i] i += 1 k += 1 while j < len(right): arr[k] = right[j] j += 1 k += 1 return arr # Remove below comment to run function print(check_super_word("print", ["pint", "pit", "hat"])) # print(combine_integers(123, 456)) # print(merge_sort([1, 2, 6, 5, 4, 7, 8]))
true
41d2b009044c0725c83d588cc15700d4775a48a6
KKEIO1000/Sorting-Algorithms
/Bubble Sort (Optimized Ω(n)).py
707
4.3125
4
import random def bubble_sort(lst): """Function to sort a list via optimized bubble sort, O(n^2), Ω(n) if the list is already sorted""" #Sets a flag so if no swap happened, the loop exits sort = True #Main body of the iterative loop while sort: sort = False for i in range(len(lst)-1): if lst[i] > lst[i+1]: lst[i], lst[i+1] = lst[i+1], lst[i] sort = True return lst #Test the algorithm using a randomly generated list of 10 numbers lst = list(random.randint(0,1000) for i in range(10)) print("Original: ", lst) print("Python's sort function: ", sorted(lst)) print("Bubble sort: ", bubble_sort(lst))
true
a55e7da40409b9160df98169b4bf7ac36eb7735b
sajay/learnbycoding
/learnpy/capital_city_loop.py
1,449
4.5625
5
#Review your state capitals along with dictionaries and while loops! #First, finish filling out the following dictionary with the remaining states and their #associated capitals in a file called capitals.py. Or you can grab the finished file directly from the exercises folder in the course repository #on Github. #capitals_dict = { #'Alabama': 'Montgomery', #'Alaska': 'Juneau', #'Arizona': 'Phoenix', #'Arkansas': 'Little Rock', #'California': 'Sacramento', #'Colorado': 'Denver', #'Connecticut': 'Hartford', #'Delaware': 'Dover', #'Florida': 'Tallahassee', #'Georgia': 'Atlanta', #} #Next, write a script that imports the capitals_dict variable along with the 'random' #package: #from capitals import capitals_dict #import random #This script should use a while loop to iterate through the dictionary and grab a random #state and capital, assigning each to a variable. The user is then asked what the capital of #the randomly picked state is. The loop continues forever, asking the user what the #capital is, unless the user either answers correctly or types "exit".#If the user answers correctly, "Correct" is displayed after the loop ends. #However, if the user exits without guessing correctly, the answer is displayed along with "Goodbye." #NOTE: Make sure the user is not punished for case sensitivity. In other words, a guess of "Denver" is the same as "denver". The same rings true #for exiting - "EXIT" and "Exit" are the same as "exit".
true
3fe028c17fbe2be2504d6caee35ada09f9c008d2
sajay/learnbycoding
/dailycodeproblems/car-cdr.py
944
4.34375
4
#This problem was asked by Jane Street. #cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. #For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. # Given this implementation of cons: # def cons(a, b): # def pair(f): # return f(a, b) # return pair # Implement car and cdr. #This is a really cool example of using closures to store data. # We must look at the signature type of cons to retrieve its first and last elements. # cons takes in a and b, and returns a new anonymous function, which itself takes in f, # and calls f with a and b. # So the input to car and cdr is that anonymous function, which is pair. # To get a and b back, we must feed it yet another function, one that takes in two parameters # and returns the first (if car) or last (if cdr) one. def car(pair): return pair(lambda a, b: a) def cdr(pair): return pair(lambda a, b: b)
true
1030840b3ca5e98c70aa8d878c41a3bffed72114
niqaabi01/Intro_python
/Week2/Perimter2.py
577
4.1875
4
width1 = float(input("enter width one : ")) height1 =float(input("enter height one : ")) width2 = float(input("enter width two : ")) height2 = float(input("enter height two :")) cost_mp =float(input(" enter price per meter :")) height = 2 * float(height1) width = float(width1) + (width2) def multiply(width): result = 2 for index in range(1): result = result * width return result total = height + multiply(width) result = total * cost_mp print("The total amount fencing per meter : " + str(total)) print(" The total cost of fencing R" + str(result))
true
2551c03e063d0cd16da6e3e0ee2881f5279faaae
ewang14/hello-world
/pizza.py
2,399
4.1875
4
# pizzaQuiz2 # tell the user what's going on print ("What Type of Pizza Are You?") print (" ") print ("Take our quiz to find out what type of pizza you are!") print (" ") # player information on the player player = { "name": "unknown", "superpower": "unknown", "faveColor" : "unknown", "drink" : "unknown" } # name = raw_input("What is your name? ") player ["name"] = name # the chosen superpower will be the players superpower # pepperoniType = super strength/invisitibility and red/yellow # cheeseType = super strength/invisibility and blue/orange # anchovyType = flying/telekinesis and water/tea # marinaraType = flying/telekinesis and wine/coffee print (" ") # spacing superpower = raw_input("Hi, " + player["name"] + "! Choose one superpower: super strength, invisibility, flying, telekinesis: ") player ["superpower"] = superpower # if the player chooses super strength or invisibility we will give them a color prompt. Red/yellow is Pepperoni. Blue/orange is Cheese. if (player["superpower"] == "super strength") or (player["superpower"] == "invisibility"): print (" ") faveColor = raw_input("Woaaaaah, interesting choice. Now that you have " + superpower + "," "which of the following colors speaks to you the most: red, blue, yellow, orange: ") player ["faveColor"] = faveColor if (player["faveColor"] == "red") or (player["faveColor"] == "yellow"): print(" ") print("Everyone loves you, except ve getarians. " + name + ", you are a Pepperoni Pizza!") elif (player["faveColor"] == "blue") or (player["faveColor"] == "orange"): print(" ") print("Some might say you're a little vanilla, but tell those haters, you are timeless - you're a Cheese Pizza!") # if the player chooses flying or telekinesis we will give them a drink prompt else: drink = raw_input("Cool! Now that you have " + superpower + "choose one type of drink: water, wine, coffee, tea. ") player ["drink"] = drink # water or tea is anchovy. wine or coffee is marinara. if (drink == "water") or (drink == "tea"): print(" ") print("Not many understand you, but when they do, they LOVE you. You are an Anchovy Pizza!!") else: print(" ") print(name + ", no need to be cheesy here. You are who you are, you're a Marinara Pizza!!") # if (player["superpower"] == pepperoniType[0]) and (player["faveColor"] == pepperoniType[1]): # print "You are Pepperoni Pizza"
true
735db79beeb3cb7c513e97a79f5aa846b15d46d2
rspurlock/SP_Online_PY210
/students/rspurlock/lesson4/dict_lab.py
2,290
4.5625
5
#!/usr/bin/env python3 def printDictionary(dictionary): """ Function to display a dictionary in a nice readable fashion Positional Parameters :param dictionary: Dictionary to print key/value pairs for """ # Loop thru all the dictionary items (key/value pairs) printing them for key, value in dictionary.items(): print(f'{key} = {value}') # Print a blank line for readability print() # Dictionaries 1 print('Dictionaries 1') dictionary = {'name' : 'Chris', 'city' : 'Seattle', 'cake' : 'Chocolate'} printDictionary(dictionary) del dictionary['cake'] printDictionary(dictionary) dictionary['fruit'] = 'Mango' printDictionary(dictionary) print('Keys') for key in dictionary.keys(): print(f'{key}') print() print('Values') for value in dictionary.values(): print(f'{value}') print() # Dictionaries 2 print('Dictionaries 2') # Create and print the original dictionary dictionary = {'name' : 'Chris', 'city' : 'Seattle', 'cake' : 'Chocolate'} printDictionary(dictionary) # Copy original dictionary and update values to number of letter t's newDictionary = dictionary.copy() for key, value in newDictionary.items(): newDictionary[key] = value.lower().count('t') # Print the updated dictionary printDictionary(newDictionary) # Sets 1 print('Sets 1') # Create the 'empty' sets to build s2 = set() s3 = set() s4 = set() # Loop through the number 0 - 20 building the sets for n in range(0, 21): if ((n % 2) == 0): s2.add(n) if ((n % 3) == 0): s3.add(n) if ((n % 4) == 0): s4.add(n) # Print all of the created sets print('s2 = ' + str(s2)) print('s3 = ' + str(s3)) print('s4 = ' + str(s4)) print() # Check for subsets print('Is s3 a subset of s2? ' + str(s3.issubset(s2))) print('Is s4 a subset of s2? ' + str(s4.issubset(s2))) print() # Sets 2 print('Sets 2') # Create the python and marathon sets pythonSet = set('Python') marathonSet = frozenset('marathon') # Display these two sets print('Python set - ' + str(pythonSet)) print('marathon set - ' + str(marathonSet)) print() # Display the union and intersection of these sets print("Python union marathon is " + str(pythonSet.union(marathonSet))) print("Python intersect marathon is " + str(pythonSet.intersection(marathonSet))) print()
true
50c346bdbdbd12de77a6f3c92e0928e027440cf9
emurph1/ENGR-102-Labs
/CFUs/CFU3.py
1,304
4.125
4
# By submitting this assignment, I agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # Emily Murphy # ENGR 102-552 # CFU 3 # 10/03/2018 homework = int(input('Enter homework grade: ')) # user inputs homework grade exam = int(input('Enter exam grade: ')) # user inputs exam score outside = input('Enter Yes if you did an outside project and No if you didn\'t: ') # user inputs outside project numGrade = 0 # starting numGrade numGrade += exam * 0.6 # adding homework score to overall with the weight of exam (60%) numGrade += homework * 0.4 # adding homework score to overall with the weight of homework (40%) # conditional to add 5 extra points with outside project if outside == 'Yes': numGrade += 5 # Conditionals that find letter grade and print the letter grade if numGrade >= 90 and outside == 'Yes': print('You get an A') elif numGrade >= 90 and outside == 'No': print('You would\'ve gotten an A, but did not do the outside project. You get a B.') elif 80 <= numGrade < 90: print('You get an B') elif 70 <= numGrade < 80: print('You get an C') elif 60 <= numGrade < 70: print('You get an D') else: print('You get an F')
true
bc2cebe6671e920cb68096f6222ff5a24846a32e
greenfox-zerda-lasers/hvaradi
/week-04/day-4/trial.py
380
4.25
4
# def factorial(number): # product=1 # for i in range(number): # product=product * (i+1) # return product # # print(factorial(3)) def factorial(number): if number <= 1: return 1 else: return number * factorial(number-1) print(factorial(3)) # product = 1 # for i in range (number): # product = product * (i+1) # # print(product)
true
76459e26f6290338ca907294bc7d5daf660e2491
greenfox-zerda-lasers/hvaradi
/week-05/day-1/helga_work.py
834
4.1875
4
#Write a function, that takes two strings and returns a boolean value based on #if the two strings are Anagramms or not. from collections import Counter word1="hu la" word2="hoop" def anagramm(word1, word2): letters1=[] letters2=[] for i in range(len(word1)): letters1.append(word1.lower()[i]) letters1.sort() for i in range(len(word2)): letters2.append(word2.lower()[i]) letters2.sort() if " " in letters1: letters1.remove(" ") if " " in letters2: letters2.remove(" ") if letters1 == letters2: return True else: return False anagramm(word1, word2) def count_letters(string): result = list(string.lower()) if " " in result: result.remove(" ") result = Counter(result) return result print(count_letters("babbala"))
true
19e59384dc5e93fe24c6be1d883c441b6de1a7e7
greenfox-zerda-lasers/hvaradi
/week-03/day-3/circle_area_circumference.py
618
4.3125
4
# Create a `Circle` class that takes it's radius as cinstructor parameter # It should have a `get_circumference` method that returns it's circumference # It should have a `get_area` method that returns it's area class Circle(): radius = 0 def __init__(self, radius, pi): self.radius = radius self.pi = 3.14 def get_circumference(self): return self.radius * 2 * self.pi def get_area(self): return self.pi * self.radius ** 2 HelgaCircle = Circle(100, 3.14) print("The circumference of the circle:",(HelgaCircle.get_circumference())) print("The area of the circle:",(HelgaCircle.get_area()))
true
b881fe869bdf97f6da563415c2b3a7bd7da23434
Amar-Ag/PythonAssignment
/Functions3.py
1,623
4.8125
5
""" 11) Python program to create a lambda function that adds 15 to a given number passed in as an argument, also create a lambda function that multiplies argument x with argument y and print the result. """ fifteen = lambda num: num + 15 multiplyTwo = lambda num1, num2: num1 * num2 print(fifteen(15)) print(multiplyTwo(15, 15)) """ 12) Python program to create a function that takes one argument, and that argument will be multiplied with an unknown given number. """ def unknownMultiply(num): return lambda random: random * num result = unknownMultiply(2) print("Calling the function with random number:", result(12)) """ 13) Python program to sort a list of tuples using Lambda. """ tupleList = [(0, 'c'), (1, 'a'), (2, "b")] print("Tuple before sorting:", tupleList) tupleList.sort(key=lambda x: x[1]) print("Tuple after sorting:", tupleList) """ 14) Python program to sort a list of dictionaries using Lambda """ sampleDict = [{'number': '0', 'spelling': 'zero'}, {'number': '2', 'spelling': 'two'}, {'number': '1', 'spelling': 'one'}] print("Existing list:", sampleDict) sampleDict.sort(key=lambda x: x['spelling']) print("After sorting:", sampleDict) """ 15) Python program to filter a list of integers using Lambda """ sampleList = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] print("Original List:", sampleList) positiveList = list(filter(lambda x: x > 0, sampleList)) negativeList = list(filter(lambda x: x < 0, sampleList)) neutralList = list(filter(lambda x: x == 0, sampleList)) print("Positive List", positiveList) print("Negative List", negativeList) print("Neutral List", neutralList)
true
c1c57774c47113e39d38d942341708aff20135af
TomMarquez/Evolutionary-Programming
/Final_Project/Main.py
1,391
4.125
4
from Population import Population from Window import Window import tkinter as tk from tkinter import * import random import time import random import matplotlib.pyplot as plt def main(): pop_size = 100 iteration = 10000 max_fit = 0 top_fit = 0 average_fit = 0 pop = Population(pop_size, 10, 10) pop.init_pop() road = 1 iterations = [] top_fits = [] max_fits = [] for i in range(iteration): iterations.append(i) obstacle = -1 while(not pop.done()): if random.randint(0, 10) == 0: obstacle = random.randint(0, 9) road_move = random.randint(0,2) -1 pop.make_move(road, obstacle, road_move) #road = road + road_move pop.rank_fitness() fit_sum = 0 top_fit = pop.fit[0][1] if max_fit < top_fit: max_fit = top_fit for j in range(pop_size): fit_sum += pop.fit[j][1] average_fit = fit_sum / pop_size top_fits.append(top_fit) max_fits.append(max_fit) pop.breed(pop_size, 95, 2) print("Iteration: " + str(i)) print("Max Fitness: " + str(max_fit)) print("Top Fitness: " + str(top_fit)) print("Average Fitness: " + str(average_fit)) plt.plot(top_fits, label= 'Top Fit') plt.plot(max_fits, label = 'Max Fit') plt.title("Fitness vs Time(Population: 100)") plt.ylabel('Fitness') plt.xlabel('Iterations') plt.legend(); plt.show() if __name__=='__main__': main()
true
f15086d8e41223760acc5830fe0051e5b6edaa75
chay360/learning-python
/ex3.py
519
4.3125
4
#.............Numbers and Math..........# print("I will count my chickens:") print("Hens", 25 + 30/6) print("Roosters",100 -25 * 3 % 4) print("Now i will count eggs:") print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print("Is it true that 2 + 3 < 5 - 7?") print(2 + 3 < 5 - 7) print("What is 3 + 2?", 3 + 2) print("What is 5 - 7?", 5 - 7) print("Oh that's why it's FALSE.") print("How about some more.") print("Is it greater ", 5 > -2) print("Is it greater or equal?", 5 >= -2) print("Is it less or equal?", 5 <= -2)
true
dbf2ad366c7b4cdb31587c9f352a24b1f9e41252
MLGNateDog/untitledPycharmProject
/Comparison Operators.py
222
4.34375
4
# Here are the different types of Comparison Operators # > Greater than # >= Greater than or equal to # < Less than # <= Less than or equal to # == equal to # != not equal to # Example of use x = 3 != 2 print(x)
true
cb1d0c79331de9a64c5973e7db253ac42f783265
omogbolahan94/Budget-App
/main.py
2,024
4.3125
4
class Budget: """ Create a Budget class that can instantiate objects based on different budget categories(class instances) like food, clothing, and entertainment. These objects should allow for: 1. Depositing funds to each of the categories 2. Withdrawing funds from each category 3. Computing category balances 4. Transferring balance amounts between categories """ def __init__(self): self.amount = 200 def deposit(self, deposit_amount): """ Deposit money to budget :param deposit_amount: :return: None """ self.amount += deposit_amount def withdraw(self, withdraw_amount): """ Withdraw money from budget :param withdraw_amount: :return: None """ self.amount -= withdraw_amount def balance(self): """ To check budget balance :return: None """ return f"${self.amount}" def transfer(self, category_budget, amount): """ Transfer money from this this category to the category_budget class composition is a way of instantiating instant method parameter with another class object :param: category_budget, amount: :return: None """ self.amount -= amount category_budget.amount += amount print("\n") print("==" * 5, "Food Budget", "==" * 5) food = Budget() food.deposit(100) food.withdraw(50) print(f"Food balance after depositing $100 and Withdrawing $50 is: {food.balance()}") print("\n") print("==" * 5, "Clothing Budget", "==" * 5) clothing = Budget() food.transfer(clothing, 100) print(f"Clothing balance after receiving $100 from food budget balance: {clothing.balance()}") print(f"Food budget balance after transferring $100 to clothing budget balance: {food.balance()}") print("\n") print("==" * 5, "Entertainment Budget", "==" * 5) entertainment = Budget() print(f"Entertainment budget balance is untouched and it is: {entertainment.balance()}")
true
2440ddb0f0e2bc3873f11d0fe7bee65d50b55365
zhianwang/Python
/Regression/A02Module_G33419803.py
2,852
4.125
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 24 16:53:56 2016 @author: Zhian Wang GWID: G33419803 This program is define 3 function to to compute the regression coefficients for the data in an input csv file and plot the regression. """ import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model import argparse as ap from mpl_toolkits.mplot3d import * # Part1 Read data def fileInput(filename): """ Input = name of csv text file with comma separated numbers Output = nunmpy array """ myData = np.loadtxt(filename, delimiter = ',', dtype = float) return(myData) # Part 2 Compute the regression coefficients def regress(myData): """ Input = numpy array with three columns Column 1 is the dependent variable Column 2 and 3 are the independent variables Returns = a colum vector with the b coefficients and """ # In order to do multiple regression we need to add a column of 1s for x Data = np.array([np.concatenate((xi,[1])) for xi in myData]) x = Data[:,1:4] y = myData[:,0] # Create linear regression object linreg = linear_model.LinearRegression() # Train the model using the training sets linreg.fit(x,y) # We can view the regression coefficients B = np.concatenate(([linreg.intercept_], linreg.coef_), axis=0) b = B[0:3].reshape(3,1) from sklearn.metrics import r2_score pred = linreg.predict(x) r2 = r2_score(y,pred) return(b,r2) # Part 3 Plot the regression def myPlot(myData,b): """ Input = numpy array with three columns Column 1 is the dependent variable Column 2 and 3 are the independent variables and a cloumn vector with the b coefficients Reurns = Nothing Output = 3D plot of the actual data and the surface plot of the linear model """ import matplotlib.pyplot as plt import numpy as np from matplotlib import cm fig = plt.figure() ax = fig.gca(projection='3d') # to work in 3d plt.hold(True) x_max = max(myData[:,1]) y_max = max(myData[:,2]) b0 = float(b[0]) b1 = float(b[1]) b2 = float(b[2]) x_surf=np.linspace(0, x_max, 100) # generate a mesh y_surf=np.linspace(0, y_max, 100) x_surf, y_surf = np.meshgrid(x_surf, y_surf) z_surf = b0 + b1*x_surf +b2*y_surf # ex. function, which depends on x and y ax.plot_surface(x_surf, y_surf, z_surf, cmap=cm.hot, alpha=0.2); # plot a 3d surface plot x=myData[:,1] y=myData[:,2] z=myData[:,0] ax.scatter(x, y, z); # plot a 3d scatter plot ax.set_xlabel('x1') ax.set_ylabel('y2') ax.set_zlabel('y') plt.show()
true
0ff2439b7a7ced2ab34e6f91b0eb9fbe8f2122ce
Aqua5lad/CDs-Sample-Python-Code
/ListForRange.py
1,315
4.53125
5
# Colm Doherty 2018-02-21 # These are chunks of code I've written to test the List, For & Range functions # they are tested & proven to work! # here are some Lists, showing indexing & len(gth) (ie. number of items) Beatles = ['John', 'Paul', 'George', 'Ringo'] print ("the third Beatle was", Beatles[-2]) print ("the number of Beatles was:", len(Beatles)) homes = [55,13,19,58,7,21,86,190,2,49,219,55] print ("the numbers of homes I've lived in are:", homes) print ("the number of the third home I lived at was", homes[2]) for j in homes: print ("my home numbers, in sequence:", j) for i in range(2,219,11): print (i) for k in range(len(Beatles)): print (k, Beatles[k]) for s in Beatles: print (s) for s in homes: print (s) # script will go through the list and give the index position, then value, of each list in sequence l = 0 while l < len(homes): print (l, homes[l]) l = l + 1 # script will go through the list and, for the word it's currently at, will give the length of that word for m in Beatles: print(m,len(m)) # unlike using "while" - it cannot show the index position of each word, because as it loops through, the value of 'm' keeps changing # but there is a way to do it: for m in range(len(Beatles)): print(m, Beatles[m], len(Beatles[m]))
true
852c089e789383369c2b5f7a58efeacd1142aab6
mwenz27/python_onsite_2019
/week_01/05_lists/Exercise_01.py
568
4.15625
4
''' Take in 10 numbers from the user. Place the numbers in a list. Using the loop of your choice, calculate the sum of all of the numbers in the list as well as the average. Print the results. ''' num = []# create a list of numbers count = 0 try: print('Input numbers 10 times \n') for i in range(10): count += 1 x = int(input(f'Enter a number for number {count}: ')) num.append(x) except ValueError: print('there is no number in one input, please just enter just numbers') print('\nThe sum of numbers you entered is', sum(num))
true
437962b8b376a8148dd7848d5aeebc836f08a188
mwenz27/python_onsite_2019
/week_03/02_exception_handling/04_validate.py
562
4.59375
5
''' Create a script that asks a user to input an integer, checks for the validity of the input type, and displays a message depending on whether the input was an integer or not. The script should keep prompting the user until they enter an integer. ''' flag = True while flag: try: user_input = input('Enter a Number : ') user_input = float(user_input) except ValueError as err: print(err) print('Your still in the loop') else: print('congrats this is a number!, your out of the loop') flag = False
true
d2ba4e9f40f018006ef974c6a2a1624120ff5aff
mwenz27/python_onsite_2019
/week_01/04_strings/01_str_methods.py
938
4.40625
4
''' There are many string methods available to perform all sorts of tasks. Experiment with some of them to make sure you understand how they work. strip and replace are particularly useful. Python documentation uses a syntax that might be confusing. For example, in find(sub[, start[, end]]), the brackets indicate optional arguments. So sub is required, but start is optional, and if you include start, then end is optional. For this exercise, demonstrate the following string methods below: - strip - replace - find ''' sentence = ' This is a string to test bbb bb ' print((sentence.strip())) print((sentence.rstrip())) print(sentence.lstrip()) print(sentence.replace('s', 'SS')) print(len(sentence)) print('\tFind', sentence.find('b')) # find fines the first position on the argument to be seen print(sentence[27]) print('\tFind R', sentence.rfind('b')) # finds the first position on the right hand side print(sentence[32])
true
5b9ca8cd066392ae59f20e6e311ccefb363bebc0
mwenz27/python_onsite_2019
/week_01/04_strings/05_mixcase.py
840
4.40625
4
''' Write a script that takes a user inputted string and prints it out in the following three formats. - All letters capitalized. - All letters lower case. - All vowels lower case and all consonants upper case. ''' sentence = "If real is what you can feel, smell, taste and see, then real is simply electrical signals interpreted by your brain." vowels = ['a', 'e', 'i', 'o', 'u'] print(sentence.upper()) print(sentence.lower()) reconstructed_list = [] for letter in sentence.lower(): #print(letter, end='') if letter in vowels: # membership operator #print('passed through here') x = letter.lower() reconstructed_list.append(x) else: x = letter.upper() reconstructed_list.append(x) print('\n') #print(reconstructed_list) for i in reconstructed_list: print(i, end='')
true
2e6f49c33c863d56f3270f10ffb4d2467b8074cd
standrewscollege2018/2021-year-11-classwork-RyanBanks1827
/List playground.py
569
4.28125
4
# For lists we use square brackets # Items must be split by comma # Items = ["Item1", "Item2"] # print(Items[0]) # To add something to the end of a list, use append() # Items.append("Dr Evil") # To add something directly into a list, use the Items.insert() or list.insert() # Items.insert(1, "Dr good") # Lists are mutable, they can be written to and deleted from # You can override a value of an item in the list, like this! # Items[1]= "Not any doctor here!" # print(Items) List = [["Tobias", 15]] Listoprint=List Listoprint.append(["Gavith", 15]) print(List)
true
838fdf5d8d24feaa89d08ef78f434be1247e5756
spohlson/Linked-Lists
/circular_linked.py
1,557
4.21875
4
""" Implement a circular linked list """ class Node(object): def __init__(self, data = None, next = None): self.data = data self.next = next def __str__(self): # Node data in string form return str(self.data) class CircleLinkedList(object): def __init__(self): self.head = None self.tail = None self.length = 0 def addNode(self, data): # Add node to end of linked list to point to the head node to create/connect circle node = Node(data) node.data = data node.next = self.head if self.head == None: self.head = node if self.tail != None: self.tail.next = node self.tail = node self.length += 1 def __str__(self): # String representation of circular linked list list_length = self.length node = self.head node_list = [str(node.data)] i = 1 # head node has already been added to the list while i < list_length: node = node.next node_list.append(str(node.data)) i += 1 return "->" + "->".join(node_list) + "->" ## Function to determine if a linked list has a loop ## def circularLink(linked_list): fast = linked_list.head slow = linked_list.head while fast != slow and fast != None: fast = fast.next.next slow = slow.next if fast == slow: return True else: return False """ Create the Circular Linked List """ def main(): circle_ll = CircleLinkedList() # Create empty circular linked list for x in range(1, 101): # Populate with 100 nodes circle_ll.addNode(x) print circle_ll # Display list as string if __name__ == '__main__': main()
true
56fcf653effc79c4b8371d94f5102088b7253dcb
ParkerCS/ch-tkinter-sdemirjian
/tkinter_8ball.py
2,493
4.59375
5
# MAGIC 8-BALL (25pts) # Create a tkinter app which acts as a "Magic 8-ball" fortune teller # The user asks a yes/no question that they want an answer to. # Then the user clicks a button, and your program displays # the "magic" random answer to their question. # Your program will have the following properties: # - Use an App class to create the tkinter app # - Add a proper title (appears in the window tab) # - Add a Label widget at the top to give the user instructions/intro. # - Add an Entry widget so the user can enter their question. # - Add a Button widget which will trigger the answer. # - Add a Label widget to display the answer (set to a initial value of "Your Fortune Here" or "--" or similar) # - Get your random answer message from a list of at least 10 possible strings. (e.g. ["Yes", "No", "Most Likely", "Definitely", etc...]) # - Add THREE or more other style modifications to make your app unique (font family, font size, color, padding, image, borders, justification, whatever you can find in tkinter library etc.) Make a comment at the top or bottom of your code to tell me your 3 things you did. (Just to help me out in checking your assignment) from tkinter import * from tkinter import font import random class App(): def __init__(self, master): #variables self.response = StringVar() self.list = ["Sure, why not", "Who cares?", "There can be no question.", "Definitely not", "Probably", "Try again later", "Only on Tuesdays", "Yes", "No", "It is certain", "That's the dumbest question I've ever been asked don't even think about asking that again or I swear to God I'll find where you live and make sure it never happens again."] #Labels self.intro_label = Label(master, text="Ask the 8-Ball a question!", bg="gold").grid(row=1, column=1, columnspan=4, sticky="e" + "w") self.response_label = Label(master, textvariable=self.response).grid(row=4, column=1, columnspan=4, sticky="e" + "w") #Entry: self.entry = Entry(master, text="Enter your question here.").grid(row=2, column=1, columnspan=4, sticky="e" + "w") #Buttons self.receive_fortune = Button(master, text="Receive Fortune", relief="raised", bg="blue", fg="yellow", command=lambda:self.response.set(self.list[random.randrange(len(self.list))])).grid(row=3, column=1, columnspan=4, sticky="e" + "w") if __name__ == "__main__": root = Tk() root.title("Magic 8-Ball") my_app = App(root) root.mainloop()
true
e39e0dcff94b1416043dd5124c81bf8186e95809
otisscott/1114-Stuff
/Lab 6/sqrprinter.py
269
4.125
4
inp = int(input("Enter a positive integer: ")) for rows in range(inp): row = "" for columns in range(inp): if columns < rows: row += "#" elif rows < columns: row += "$" else: row += "%" print(row)
true
ad608cd56dd0019920087c779e26f69e97d9882a
otisscott/1114-Stuff
/Lab 2/simplecalculator.py
490
4.25
4
firstInt = int(input("Please enter the first integer:")) secondInt = int((input("Please enter the second integer:"))) simpSum = str(firstInt + secondInt) simpDif = str(firstInt - secondInt) simpProd = str(firstInt * secondInt) simpQuot = str(firstInt // secondInt) simpRem = str(firstInt % secondInt) print("This sum is: " + simpSum + ", their difference is: " + simpDif + ", their product is: " + simpProd + ", their quotient is: " + simpQuot + ", their remainder is " + simpRem)
true
6f0cb2d42343987c32067f038502547114b46511
aleckramarczyk/project-euler
/smallestmultiple.py
839
4.125
4
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # #What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? def main(): found = False num = 2520 #any number that is divisible by 1 through 20 will be a multiple of 2520, which is given to us in the problem #therefore, by checking only multiples of 2520 we save a massive amount of computing power compared to bruteforcing every number while found == False: print("Testing: " + str(num),end="\r") test = [num%n for n in range(11, 21)] if sum(test) == 0: print("\nThe smallest number that is divisible by 1-20 is: " + str(num)) found = True else: num = num + 2520 if __name__ == "__main__": main()
true
ee9d9d9256c74a84275211c616b8e4f1bf3b22b9
jeremy-wischusen/codingbat
/python/logicone/caught_speeding_test.py
819
4.1875
4
""" You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. """ """ Solution """ def caught_speeding(speed, is_birthday): if is_birthday: u = 85 l = 65 else: u = 80 l = 60 if speed <= l: return 0 if speed > u: return 2 return 1 """ Tests """ def test_exercise(): assert caught_speeding(60, False) == 0 assert caught_speeding(65, False) == 1 assert caught_speeding(65, True) == 0 """ """
true
af1ef8b6837deec2de38278564e515bb854d92d8
sandeep-skb/Data-Structures
/Python/Trees/diameter.py
1,465
4.25
4
class Node: def __init__(self, val): self.data = val self.left = None self.right = None def height(node): if node == None: return 0 return (max(height(node.left), height(node.right))+1) def diameter(node): ''' The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes. The diagram below shows two trees each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes). https://www.geeksforgeeks.org/diameter-of-a-binary-tree/ ''' if node == None: return 0 lheight = height(node.left) rheight = height(node.right) ldiameter = diameter(node.left) rdiameter = diameter(node.right) #diameter will be the max of the following: #1. diameter through the root Node #2. diameter of the left subtree #3. diamter of the right subtree return(max((lheight+rheight+1), max(ldiameter, rdiameter))) def main(): t1 = Node(1) t1.left = Node(2) t1.right = Node(3) t1.left.left = Node(4) t1.left.right = Node(5) t1.right.left = Node(6) t1.right.right = Node(7) t1.right.right.right = Node(9) ''' 1 / \ 2 3 / \ / \ 4 5 6 7 \ 9 ''' print("Printing the diameter of tree: ") print(diameter(t1)) if __name__ == "__main__": main()
true
04b293e819b642b0755f35e10fd270879f0b5a32
sandeep-skb/Data-Structures
/Python/Linked-list/Singly-Linked-List/exchange_by_2.py
879
4.1875
4
def traverse(node): if node != None: print(node.data) traverse(node.next) def exchange(node): prev = Node(0) prev.next = node head = prev while((node != None) and (node.next != None)): prev.next = node.next temp = node.next.next node.next.next = node node.next = temp prev = node node = temp return head class Node: def __init__(self, data): self.data = data self.next = None def main(): e1 = Node(1) e2 = Node(2) e1.next = e2 e3 = Node(3) e2.next = e3 e4 = Node(4) e3.next = e4 e5 = Node(5) e4.next = e5 print("Original order of the linked list:") traverse(e1) print() node = exchange(e1) print("After reversing the order of the linked list:") traverse(node.next) if __name__ == "__main__": main()
true
dac456345780fe6ced123598995a6e2285a89ef2
zabcdefghijklmnopqrstuvwxy/AI-Study
/1.numpy/topic59/topic59.py
1,558
4.4375
4
#argsort(a, axis=-1, kind='quicksort', order=None) # Returns the indices that would sort an array. # # Perform an indirect sort along the given axis using the algorithm specified # by the `kind` keyword. It returns an array of indices of the same shape as # `a` that index data along the given axis in sorted order. # Parameters # ---------- # a : array_like # Array to sort. # axis : int or None, optional # Axis along which to sort. The default is -1 (the last axis). If None, # the flattened array is used. # kind : {'quicksort', 'mergesort', 'heapsort'}, optional # Sorting algorithm. # order : str or list of str, optional # When `a` is an array with fields defined, this argument specifies # which fields to compare first, second, etc. A single field can # be specified as a string, and not all fields need be specified, # but unspecified fields will still be used, in the order in which # they come up in the dtype, to break ties. # Returns # ------- # index_array : ndarray, int # Array of indices that sort `a` along the specified axis. # If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`. #argsort()函数返回的是数组值从小到大的索引值。 #排序后会产生一个新的数组,不改变原有的数组。 import numpy as np arr=np.random.randint(0,100,size=(5,5)) print(f"random arr is \n{arr}") Z=arr[arr[:,1].argsort()] #Z=np.argsort(arr,axis=1) print(f"sort arr is \n{Z}")
true
0add5d9bcab734baa48b5bfc76db3e12b8be0617
pratikv06/Python-Practice
/Object Oriented/2_class.py
850
4.1875
4
class Dog(): def __init__(self, name, age): ''' Its like constructor - called when object is created (once)''' # self - represent object of that instance self.name = name self.age = age def get_name(self): ''' Display dog name''' print("Name: " + self.name) def get_age(self): print("Age: " + str(self.age)) def set_name(self, name): self.name = name def set_age(self, age): self.age = age def bark(self): '''user method''' print(self.name + " is barking...") print(">> Creating object") d = Dog('Tom', 5) print(type(d)) print(type(d.bark)) print(">> accessing attribute") print(d.name) #bad practice # create method to access variable d.get_name() d.get_age() d.set_age(10) d.get_age()
true
9a707d82601e9d9624b52f04884606cfe8d81e53
noevazz/learning_python
/035_list_comprehension.py
681
4.46875
4
#A list comprehension is actually a list, but created on-the-fly during program execution, # and is not described statically. # sintax = [ value for value in expression1 if expression2] # it will generate a list with the values if the optional expression is True my_list = [number for number in range(1, 11)] # this will create a list with al the numbers generated print(my_list) even_numbers = [number for number in range(1, 11) if number%2==0] # this will create a list with al the numbers generated print(even_numbers) print("\n complicationg the things") print("creating lists in list using comprehension lists") a = [[i*2 for i in range(5, 11)] for a in range(3)] print(a)
true
e09e60bf03324e754a246d9ef71870103a86ee3a
noevazz/learning_python
/082__init__method.py
811
4.3125
4
# classes have an implicit method (that you can customize) to initialize your class with some values or etc. # the __init__ method is called constructor # __init__ cannot return a value!!!!!!!! as it is designed to return a newly created object and nothing else; class MyNiceClass(): # whenever you see "self" it is used to refer to the object. This is useful (and sometimes required) # so each object can have its own varaible def __init__(self, argument1): # self is required in the constructor. # argumentXs are optionals in the __init__ definition but required on instancing if you define a __init__ with arguments print("Hi :D") # code inside __init__() will be executed once you instance the class for each obkect obj = MyNiceClass("here you go, here is your now required argument")
true
1ac5d30ca8eb886ca9e3c293d490ca97d314024d
noevazz/learning_python
/072_ord_chr.py
708
4.59375
5
print("------ ord ------") # if you want to know a specific character's ASCII/UNICODE code point value, # you can use a function named ord() (as in ordinal). print(ord("A")) # 65 print(ord("a")) # 97 print(ord(" ")) # 32 (a-A) print(ord("ę")) # The function needs a >strong>one-character string as its argument # breaching this requirement causes a TypeError exception, # and returns a number representing the argument's code point. #print(ord("sadasdasd")) # TypeError: ord() expected a character, but string of length 9 found print("------ chr ------") # If you know the code point (number) and want to get the corresponding character, # you can use a function named chr(). print(chr(97)) print(chr(945))
true
1e78bed77a7b9c6d2c986581073098305e0fb66b
noevazz/learning_python
/010_basic_operations.py
676
4.59375
5
# +, -, *, /, //, %, ** print("BINARY operators require 2 parts, e.g. 3+2:") print("addition", 23+20) print("addition", 23+20.) # if at least one number is float the result will be a float print("subtraction", 1.-23) print("multiplication", 2*9) print("division", 5/2) print("floor division", 5//2) # floor division (IT DOES NOOOT MEAN AN INTEGER DIVISION, see below) print("floor division", 5.//2) print("floor division", 5//2.) print("mod", 10%4) #it return the remainder of the division print("exponentiation", 2**4) # it means 2*2*2*2 print("\nUnary operators require only one part:") print(-2) print(+3) # well this is not really useful, numbers are positive by default
true
f45f0ea56e2ab05a60c1b897cf1dc2076a13fd09
noevazz/learning_python
/027_negative_indeces.py
477
4.375
4
# Negative indexes are legal my_list = [4, 7, 10, 6] print("List=", my_list) # An element with an index equal to -1 is the last one in the list print("[-1] index=", my_list[-1]) # The element with an index equal to -2 is the one before last in the list print("[-2] index=", my_list[-2]) # We can also use the "del" insttruction to delete an element print("List before deleting the [-2] index=", my_list) del my_list[-2] print("List after deleting the [-2] index=", my_list)
true
0d5eaf303605eeec6370c7a1b1caf06ef909a248
noevazz/learning_python
/105_polymorphism_and_virtual_methods.py
434
4.375
4
""" The situation in which the subclass is able to modify its superclass behavior (just like in the example) is called polymorphism. """ class One: def doit(self): print("doit from One") def doanything(self): self.doit() class Two(One): def doit(self): # overrides the partent's: doit() is now a "virtual" method print("doit from Two") one = One() two = Two() one.doanything() two.doanything()
true
6116132b63fe41387440472cd5846af34a8ab792
noevazz/learning_python
/045_recursion.py
468
4.375
4
# recursion is when you invoke a function inside the same function: def factorialFun(n): # Factorial of N number is equal to N*(N-1)*(N-2) ... *(1) if n < 0: return None if n < 2: return 1 return n * factorialFun(n - 1) print(factorialFun(3)) # Yes, there is a little risk indeed. If you forget to consider the conditions which # can stop the chain of recursive invocations, the program may enter an infinite loop. You have to be careful.
true
6a022528eb1b7cd8400e72293bc12805dcd6aaef
noevazz/learning_python
/021_while_loop.py
1,988
4.25
4
# loops allow us to execute code several times while a boolean expression is True or while we do not break the loop explicit # while loop: money = 0 fanta = 43 while money < fanta: #save 11 dollar each day to buy a fanta money += 11 print("I have", money, "dollars") # there is also inifinite loops: money_in_bank = 12 while True: deposit = float(input("enter deposit: ")) money_in_bank += deposit if money_in_bank > 100: print("you already have more thatn 100 dollars") break # break the loop right now print("\nlet's go to the next exercise\n") # loops can have an else estatement, it will execute its code at the end of the loop, # but if the loop is broke (using break) the else code is not executed control_loop = True while control_loop: option = input("you are in a loop, insert your option \n[break: exit using break, normal: exit normally]: ") if option == "break": print("Ok let's break the loop") break # the else is not going to be executed elif option == "normal": print("Ok let's stop the loop normally") control_loop = False # ends the loop normally, the else will be executed else: print("continuing...") else: print("Hi from the else statement") print("\nLet's go to the next exercise:\n") print(":D") # Note: rember you can use the pass structure if you don't have a specific code to put inside a if/elif/else and also a while: #while True: #pass <-- but this will cause the program to be stuck doing nothing # FINALLY: the continue structure # The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. number = 10 while number >= 0: if number%2 == 0: number -= 1 continue print("I have a lot of code to execute but only if", number, "is an odd number, an yes it is") number -= 1 else: print("end of the loop")
true
58311959e0e85debd79c0aecdd11058d3ac97566
noevazz/learning_python
/037_you_first_function.py
903
4.4375
4
# in order to use our own function we first need to define them: def my_first_function(): print("Hello world, this is my first function") # Now we can call (INVOCATION) our function: my_first_function() # remember the "pass" keyword that we saw when we were learning about loops, it can be used if you don't know what to execute: def other(): pass # of course if you call this function it will not do anything: other() # but you can do it to start laying out your program # Now you can call you function at any time: my_first_function() my_first_function() my_first_function() # NOTE tha you defined the function to not receive any argument, # Passing an argument will cause an error because python knows that the functions is not expecting arguments my_first_function(23, 43, "hello") # this will cause an error # TypeError: my_first_function() takes 0 positional arguments but 3 were given
true
2124475661e15275a16886dbb68fc430120db14b
shwetati199/Python-Beginner
/8_for_loop.py
1,158
4.59375
5
#For loop- it is used mostly to loop over a sequence #It works more like iterator method namelist=["Shweta","Riya", "Priya", "Supriya"] print("Namelist: ") for name in namelist: print(name) #For loop don't require indexing variable to get set. #For loop over String print("For loop for string") for i in "Shweta": print(i) #Break Statemnets- this is used to break the innermost loop whenever the given condition is true evennums=[2, 4, 6, 8, 9, 10, 12, 13, 15, 16] #Ex- we want to only print even numbers from this list and if odd numbers encounter more than two time we have to Print that # "2 Odds found" and need to break the loop #Here we will use continue and break to do the given task. oddcount=0 for i in evennums: if i%2!=0: oddcount+=1 if(oddcount==2): print("2 Odds found") break continue print(i) #Nested for loops: we can have loop inside loop and this is called as nested for loop # For example- if we want to print pattern we can use nested loop for i in range(5): for j in range(i+1): print("*", end=" ") print()
true
d2bfb582e28f444727b40bdc7869b9d585450325
Squidjigg/pythonProjects
/wordCount.py
318
4.125
4
userInput = input(f"What is on your mind today? ") # split each word into a list wordList = userInput.split() #print(wordList) # this is here for debugging only # count the number of items in the list wordCount = len(wordList) print(f"That's great! You told me what is on your mind in {wordCount} words!")
true
4f81440511b981bb636bf62c7d24afc3aed9172b
tjkabambe/pythonBeginnerTutorial
/Quiz.py
2,027
4.5
4
# Quiz time # Question 1: Assigning variables # create 2 variables x and y where any number you want # find sum of x and y, x divided by y, x minus y, x multiplied by y x = 4 y = 3 print(x + y) print(x - y) print(x * y) print(x / y) # Question 2: Lists # Create a list of all even numbers from 0 to 100 # Print first 10 elements and find the length of this list # Append a value of your choice to the end of the list (It can be any type!) mylist = list(range(0, 101, 2)) # Create the list print(mylist[0:10]) # Print the first 10 elements print(len(mylist)) # Print length of list mylist.append(102) # Add element to list print(mylist) # Question 3 # Assign a variable to any integer you want # using an if statement, find whether this integer is divisible by 5 # Get python to print whether it is or isn't x = 19 if x % 5 == True: print("x is divisible by 5") else: print("x is NOT divisible by 5") # Question 4 # Using a for loop, get python to print the numbers 0 to 5 for i in range(6): print(i) # Question 5 # Draw a pentagon in turtle import turtle for i in range(5): turtle.forward(150) turtle.left(72) turtle.done() # Question 6 # Create a function that tests whether three number (a,b,c) are a pythagorean triple # ie if a^2 + b^2 = c^2 def pythagorean(a, b, c): if a ** 2 + b ** 2 == c ** 2: return print("These 3 numbers are pythagorean triple.") else: return print("These 3 numbers are not a pythagorean triple.") print(pythagorean(3, 4, 5)) # this is true print(pythagorean(1, 4, 9)) # this is false # Question 7 # Spot the error n = 5 while n < 10: n = n + 1 print(n) # Question 8 # Create 2 lists (of size 5) and plot these lists against each other using matplotlib import matplotlib.pyplot as plt list2 = [1, 3, 5, 8, 11, 16, 22] list3 = [2, 4, 6, 8, 10, 12, 14] plt.plot(list2, list3, c="blue", linewidth=2, Label="lines", linestyle="dashed") plt.xlabel("list2") plt.ylabel("list3") plt.title("Question 8 solution") plt.legend plt.show()
true
3d595b15d88d0e05bad1b86a5d21c9875aceced0
gehoon/fun
/birthday.py
1,138
4.25
4
#!~/bin/python ## Simulation of the birthday paradox (https://en.wikipedia.org/wiki/Birthday_problem) import random ## Each Birthdays class comprises n number of birthdays class Birthdays: def __init__(self, n=23): # initialization self.birthday = [] for x in range(n): self.birthday.append(int(random.random()*365)) def shared(self): # this function returns whether or not there's redundant birthdays seen = [] for value in self.birthday: if value not in seen: seen.append(value) else: return True return False ## main script ## Generate 10000 groups with n number of birthdays, and count how many have redundant birthdays in them. total = 10000 shared = 0 for x in range(total): birthdays = Birthdays() if birthdays.shared(): shared = shared +1 print shared, "groups out of", total, "have members sharing the same birthday." ''' ## Another algorithm for birthday paradox person = 23 odd = 1.0 for x in range(2,person+1): odd = odd * (366 - x)/365 print x, "person:", (1-odd)*100, "%" '''
true
65fd056b3c9cdc37c72a927d314a1c83a21f3ebc
Py-Contributors/AlgorithmsAndDataStructure
/Python/Algorithms/Sieve Algorithms/sieveOfEratosthenes.py
867
4.34375
4
# Sieve of Eratosthenes # It is an efficient algorithm used to find all the prime numbers smaller than # or equal to a number(n) # We will create a list and add all the elements and then remove those elements # which are not prime def sieveOfEratosthenes(n): # Creating an empty list primeList = [] for i in range(2, n + 1): # Adding all the elements primeList.append(i) i = 2 while i * i <= n: if i in primeList: # Here we will remove all the elements that are multiples of i less # than n + 1 and greater than i for j in range(i * 2, n + 1, i): if j in primeList: primeList.remove(j) i = i + 1 print(primeList) n = int(input("Enter the number upto which \ you want to print the prime numbers :")) sieveOfEratosthenes(n)
true
23a893a893954dc4fea0aaaea5e0f927635b193e
Py-Contributors/AlgorithmsAndDataStructure
/Python/Algorithms/DivideAndConquer/MergeSort.py
1,462
4.46875
4
from typing import List def merge(left: List[int], right: List[int]) -> List[int]: """Merges two sorted lists into a single sorted list. Args: left (list): The left half of the list to be merged. right (list): The right half of the list to be merged. Returns: list: The sorted list resulting from merging the left and right halves. """ if len(left) == 0: return right if len(right) == 0: return left result = [] index_left = index_right = 0 while len(result) < len(left) + len(right): if left[index_left] <= right[index_right]: result.append(left[index_left]) index_left += 1 else: result.append(right[index_right]) index_right += 1 if index_right == len(right): result += left[index_left:] break if index_left == len(left): result += right[index_right:] break return result def merge_sort(unsorted_list: List[int]) -> List[int]: """Sorts a list of integers using the merge sort algorithm. Args: unsorted_list (list): The unsorted list to be sorted. Returns: list: The sorted list. """ if len(unsorted_list) < 2: return unsorted_list midpoint = len(unsorted_list) // 2 return merge(left=merge_sort(unsorted_list[:midpoint]), right=merge_sort(unsorted_list[midpoint:]))
true
2185d883e7209cd249717e152153d6dfbed0cfbc
jmsrch8/codeDump
/HumphriesCHW10.py
1,266
4.125
4
#! /bin/python3 #name: HumphriesCHW10 #programmer: Cullen Humphries #date: friday, august 5, 2016 #abstract This program will add records to a file and display records using a module #===========================================================# import time from assign10_module import * # define main def main(): #print menu print(''' MENU 1. Add records to file 2. Display Records in file 3. search records in file 4. change records in file 5. remove recods in file 0. quit''') #reading user choice flag = 1 while flag == 1: try: choice = input('\nEnter number of menu choice: ') except: print('error') exit() if choice == '0': exit() elif choice == '1': addrec() exit() elif choice == '2': print('displaying the first 10 entrys in the file:') disrec() exit() elif choice == '3': input('searching for record... ...press enter to continue...') flag = 2 elif choice == '4': input('changing record... ...press enter to continue...') flag = 2 elif choice == '5': input('removing record... ...press enter to continue...') flag = 2 else: print('\nplease choose 1, 2, 3, 4, 5, or 0') exit() #creating simple exit function def exit(): input('\nPress \'ENTER\' to exit... ') raise SystemExit main()
true
dbdd36983477cda4f79005891bc432a7ddc542fa
UnderGrounder96/mastering-python
/03. Implemented Data Structures/1.Stack.py
316
4.1875
4
##### 13. STACKS # Last In First OUT stack = [] stack.append(1) stack.append(2) stack.append(3) print(stack) last = stack.pop() print(last) print(stack) print(stack[-1]) # getting the item on top of the stack # checking if the stack is empty if not stack: # that means we have an empty stack # do something
true
823f785ada0a4688d09c16e06e7eed11c3c5b8ac
UnderGrounder96/mastering-python
/10. OOP/05.ClassVsInstanceMethods.py
539
4.1875
4
# 5. CLASS VS INSTANCE METHODS class Point: def __init__(self, x, y): # this is an instance method self.x = x self.y = y # 1. defining a Class Method @classmethod # this is called a decorator and it's a way to extend the behavior of a method def zero(cls): return cls(0, 0) def draw(self): # this is an instance method print(f"Point ({self.x}, {self.y})") # 2. calling the Class Method point = Point.zero() # this is a class method. It's equivant to -> point = Point(0, 0) point.draw()
true
30882ebeb9098c8a1dfd0e587dbc8b23d3c4b00b
UnderGrounder96/mastering-python
/07. Functions/2.args.py
513
4.5
4
# *args (arguments) # *args behaves like a tuple of parameters that are coming in. # *args allows us to take random numbers of arguments. # * means a collection of arguments # EXAMPLE 1 def myfunc(*args): return sum(args) myfunc(40,60,100) # EXAMPLE 2 def myfunc(*args): for item in args: print(item) myfunc(40,60,70,100) # EXAMPLE 3 def multiply(*numbers): # * means a collection of arguments total = 1 for number in numbers: total *= number return total print(multiply(2, 3, 4, 5))
true