blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d99af8d7a19d0e1545818127008ba451c76e0669
zainab404/zsfirstrepo
/packing_with_dictionaries.py
390
4.375
4
#packing is when you can pass multiple arguments. #here, we used **kwargs to signify the use of multiple arguments. #the for loop will iterate over the arguments given and print each one def print_student(**kwargs): for key,value in kwargs.items(): print("{} {}".format(key,value)) print_student(name = "Zainab", job = "Programmer", major = "ISOM", boyfriend = "Guillermo")
true
6aa6d30c03cb59c7a67036aeb778971356e70959
wherby/hackerrank
/Temp/Scala/add.py
406
4.1875
4
def addInt(input): if "a" in input and "b" in input: a = input["a"] b = input["b"] try: int(a) try: int(b) return a+b except: print b + " is not int" except: print a + " is not int" else: print "a or b not in input parameters" print addInt({"a":1,"b":2})
true
2d47bef22ea73a37b69df451cd60b9df4834603a
Andrewzh112/Data-Structures-and-Algorithms-Practice
/Two Pointers II.py
1,257
4.15625
4
# Valid Palindrome class Solution: """ @param s: A string @return: Whether the string is a valid palindrome """ def isPalindrome(self, s): start, end = 0, len(s) - 1 while start < end: while start < end and not s[start].isalnum(): start += 1 while start < end and not s[end].isalnum(): end -= 1 if start < end and s[start].lower() != s[end].lower(): return False start += 1 end -= 1 return True # Valid PalindromeII class Solution2: """ @param s: a string @return bool: whether you can make s a palindrome by deleting at most one character """ def validPalindrome(self, s): # Write your code here start, end = 0, len(s) - 1 while start < end: if s[start] != s[end]: return self.isSubPalindrome(start+1, end, s) or self.isSubPalindrome(start, end-1, s) start += 1 end -= 1 return True def isSubPalindrome(self, start, end, s): while start < end: if s[start] != s[end]: return False start += 1 end -= 1 return True
true
958cb78be722ee0cf1de35a0587da701bc078646
WayneGoodwin95/Algorithms
/selection_sort.py
710
4.125
4
""" SELECTION SORT loop through list keeping track of smallest unchecked index (min_index) if another index is smaller swap the value to min_index once looped through, change the minimum index to the next array element repeat """ def selectionSort(my_arr): min_index = 0 for min_index in range(len(my_arr)): min_value = my_arr[min_index] for j in range(min_index, len(my_arr)): if my_arr[j] < my_arr[min_index]: min_value = my_arr[j] my_arr[j] = my_arr[min_index] my_arr[min_index] = min_value return my_arr my_arr = [22, 11, 99, 88, 9, 7, 42] print('output [7, 9, 11, 22, 42, 88, 99]') print(selectionSort(my_arr))
true
97bc3c6267200c16610d7e6725c022b0f47730a2
andre-lobo/Complete-Python-Bootcamp
/011-if_elif_else.py
446
4.1875
4
#if, elif and else examples if True: print("It was True") print() x = False if x: print("x was True") else: print("x was False") print() loc = "Bank" if loc == "Auto Shop": print("Welcome to the Auto Shop") elif loc == "Bank": print("Welcome to the Bank") elif loc == "Mall": print("Welcome to the Mall") else: print("Where are you?") print() person = "Sam" if person == "Sam": print("Hi Sam!") else: print("What's your name?")
true
7a8de130d4c4ee9fccf98ce22e0fb60dd647b0da
Sabrina-Sumona/Python-learning
/oop_1.py
1,344
4.125
4
class StoryBook: # CLASS VARIABLE no_of_books = 0 discount = 0.5 def __init__(self, name, price, author_name, author_born, no_of_pages): # setting the instance variables here self.name = name self.price = price self.author_name = author_name self.author_born = author_born self.publishing_year = 2020 self.no_of_pages = no_of_pages StoryBook.no_of_books += 1 # regular method 1 def get_book_info(self): print(f'The book name: {self.name}, price: {self.price}, pages: {self.no_of_pages}') # regular method 2 def get_author_info(self): print(f'The author name: {self.author_name}, born: {self.author_born}') # applying discount to an instance def apply_discount(self): self.price = int(self.price - self.price * StoryBook.discount) # creating an instance/object of the StoryBook class book_1 = StoryBook('Hamlet', 350, 'Shakespeare', 1564, 500) book_2 = StoryBook('the_kite_runner', 200, 'khaled hosseini', 1965, 200) # book_1.get_book_info() # StoryBook.get_book_info(book_1) # # book_1.get_author_info() # print(book_1.publishing_year) # print(book_2.price) # print(book_1.no_of_books) # print(book_2.no_of_books) # print(StoryBook.no_of_books) print(book_2.price) book_2.apply_discount() print(book_2.price)
true
273b56a48a8bcb4eccfd6020852347a27407649c
Napster56/Sandbox
/function_scpoe_demo.py
666
4.21875
4
def main(): """Demo function for scope of an immutable object.""" x = 3 # int is immutable print("in main, id is {}".format(id(x))) function(x) print("in func, id is {}".format(id(x))) def function(y: int): print("in func, id is {}".format(id(y))) y += 1 # assignment creates a new object print("in func, id is {}".format(id(y))) main() # reference equality # returns: in main, id is 1396426896 } # in func, id is 1396426896 } sharing the same object # after assignment y += 1: # in main, id is 1396426896 # in func, id is 1396426896 # in func, id is 1396426928 # assignment creates a new object
true
87f0528ad87ca333109df2a21864358aff4f4a8e
Napster56/Sandbox
/reverse_text_recursively.py
284
4.28125
4
""" Function to reverse a string recursively. """ def reverse(text): if len(text) < 2: # base case return text else: # recursive step = reverse(rest of text) + first char of text return reverse(text[1:]) + text[0] print(reverse("photon"))
true
165bd77cb033c6535f0ebf67d16986a24f83dd7f
Napster56/Sandbox
/CreditCard_class.py
2,471
4.15625
4
""" Create a class for a consumer credit card """ class CreditCard: def __init__(self, customer, bank, account, limit): """Make a new credit card instance The initial balance is zero. """ self.customer = customer self.bank = bank self.account = account self.limit = limit self.balance = 0 def get_customer(self): """Return the name of the customer""" return self.customer def get_bank(self): """Return the bank's name""" return self.bank def get_account(self): """Return the card id number""" return self.account def get_limit(self): """Return credit limit""" return self.limit def get_balance(self): """Return the current balance""" return self.balance def debit_card(self, price): """Charge price to the card, if sufficient credit limit Return True if charge was processed; False if charge denied """ if price + self.balance > self.limit: return False else: self.balance += price return True def make_payment(self, amount): """Process customer payment to reduce balance""" self.balance -= amount def __str__(self): return "Customer = {}, Bank = {}, Account = {}, Balance = {}, Limit = {}".format(self.customer, self.bank, self.account, self.account, self.limit) Joe = CreditCard("Jeff", "ANZ", "555 555", 2500) print(Joe) if __name__ == '__main__': wallet = [] wallet.append(CreditCard("John Doe", "CBA", "5391 0375 9387 5309", 1000)) wallet.append(CreditCard("John Doe", "NAB", "3485 0399 3395 1954", 3500)) wallet.append(CreditCard("John Doe", "Westpac", "2248 1362 0477 3900", 5500)) for i in range(1, 55): wallet[0].debit_card(i) wallet[1].debit_card(2 * i) wallet[2].debit_card(3 * i) for i in range(3): print(("Customer =", wallet[i].get_customer())) print(("Bank =", wallet[i].get_bank())) print(("Account =", wallet[i].get_account())) print(("Balance =", wallet[i].get_balance())) print(("Limit =", wallet[i].get_limit())) while wallet[i].get_balance() > 500: wallet[i].make_payment(500) print(("New balance =", wallet[i].get_balance())) print()
true
689b0af2411c98e7bd92590ceb0b24d8ac68b254
Napster56/Sandbox
/user_name.py
547
4.3125
4
""" Ask user for their name Tell them how many vowels are in their name Tell them how many capitals are in their name """ count_vowels = 0 name = "Bobby McAardvark" # name = input("Name: ") for letter in name: if letter.lower() in 'aeiou': count_vowels += 1 print("Out of {} letters, {} has {} vowels".format(len(name), name, count_vowels)) # str function retuns a list of letters print(str([letter for letter in name if letter.isupper()])) # join is a string method & returns print("".join([letter for letter in name if letter.isupper()]))
true
5f522189d56fe7cd74fcdd8153ada80032a89cee
Napster56/Sandbox
/Classes demo/circle_class.py
498
4.46875
4
""" Program to create a Circle class which inherits from the Shape class. The subclass Circle extends the superclass Shape; Circle 'is-a' Shape. """ from shape import Shape class Circle(Shape): def __init__(self, x=0, y=0, radius=1): super().__init__(x, y) # used to access the instance of the Shape class self.radius = radius # redefines the __init__ with a new instance variable def area(self): from math import pi return self.radius ** 2 * pi
true
f4ca8f55ec31d63d82b33b20a76085bcb6a258ea
Napster56/Sandbox
/file_methods.py
813
4.15625
4
""" # readline method temp = open("temp.txt", "r") # open file for reading first_line = temp.readline() # reads exactly one line print(first_line) for line in temp: # read remaining lines print(line) temp.readline() # read file, return empty string print(temp) temp.close() # read method temp = open("temp.txt", "r") # open file for reading print(temp.read(1)) # reads exactly one char print(temp.read(2)) # reads next 2 chars print(temp.read()) # read remaining file temp.close() """ # readlines method temp = open("temp.txt", "r") # open file for reading file_contents = temp.readlines() # read all file lines into a list print(file_contents) string = "to be or not to be" temp.write(string) print(temp) temp.close()
true
4a50ac2346aee77dfd6080be2541d3c810b04cea
alexisdavalos/DailyBytes
/BinaryTreeVisibleValues/binaryTreeVisibleValues.py
921
4.21875
4
# Given a binary tree return all the values you’d be able to see if you were standing on the left side of it with values ordered from top to bottom. # This is the class of the input binary tree. Do not Edit! class Tree: def __init__(self, value): self.val = value self.left = None self.right = None def visibleValues(root): # Your Code Here return # Ex: Given the following tree… # # --> 4 # / \ # --> 2 7 # return [4, 2] tree = Tree(4) tree.left = Tree(2) tree.right == Tree(7) # Ex: Given the following tree… # # --> 7 # / \ # --> 4 9 # / \ / \ # --> 1 4 8 9 # \ # --> 9 # return [7, 4, 1, 9] tree = Tree(7) tree.left = Tree(4) tree.right = Tree(9) tree.left.left = Tree(1) tree.left.right = Tree(4) tree.right.left = Tree(8) tree.right.right = Tree(9) tree.right.right.right = Tree(9)
true
6681a57d55dbe2ea18d6f6d5c65776935455dde9
alexisdavalos/DailyBytes
/MakePalindrome/makePalindrome.py
524
4.1875
4
# Write a function that takes in a string with any set of characters # Determine if that string can become a palindrome # Returns a Boolean after processing the input string def makePalindrome(string): # Your Code Here return # Test Cases Setup print(makePalindrome("aabb")) # => true (abba) print(makePalindrome("asdf")) # asdf => false print(makePalindrome("asdfasdf")) # asdfasdf => true (asdffdsa) print(makePalindrome("aaabb")) # aaabb => true (baaab) print(makePalindrome("racecar")) # racecar => true
true
dc4b771cc52cb1a5d19e2a5e07858472fcb9254d
razorblack/python_programming
/PythonPractice/PrimeOrComposite.py
307
4.28125
4
userInput = int(input("Enter a number to check for prime \n")) count = 0 # To count no. of factors of user input number for i in range(2, userInput): if userInput % i == 0: count += 1 if count > 0: print(f"{userInput} is composite number") else: print(f"{userInput} is a prime number")
true
e5e647601be99ae9e20aa7c3f0f37f4867a18802
razorblack/python_programming
/PythonLab/Program6.1.py
673
4.125
4
# Method to perform Linear Search def linear_search(list_of_number, no_to_search): size = len(list_of_number) for i in range(0, size): if list_of_number[i] == no_to_search: print(f"Search Successful: Element found at index {i}") return print("Search Unsuccessful: Element Not Found") return size_of_list = int(input("Enter the size of the list \n")) entered_list = [] for i in range(0, size_of_list): entered_list.append(int(input("Enter a element in list \n"))) print("Entered list is:") print(entered_list) search_number = int(input("Enter a number to search in list \n")) linear_search(entered_list, search_number)
true
b8f6125de3b647d2b8c3c6a8fee82d258c6b8731
minaeid90/pycourse
/advanced/example0.py
2,923
4.53125
5
#-*- coding: utf-8 -*- u''' DESCRIPTORS EXAMPLE 0: How attributes look up works ''' # Let's define a class with 'class' and 'instance' attributes class MyClass(object): class_attr = "Value of class attrib" def __init__(self): self.instance_attr = "Value of instance of {0} attrib".format(self.__class__.__name__) def a_method(self): print "A method was called on", self # Let's instantiate it and access the attributes inst = MyClass() print inst.class_attr print inst.instance_attr # Let's access attributes in a different way print inst.__getattribute__("class_attr") # http://docs.python.org/2/reference/datamodel.html#more-attribute-access-for-new-style-classes print getattr(inst, "instance_attr") print getattr(inst, "unknown_attr", "This attribute was not found!!") # http://docs.python.org/2/library/functions.html#getattr # Let's check the instance and class __dict__ print inst.__dict__ print MyClass.__dict__ #=========================================================================== # _ __dict__ is the object dictionary. All (new style) Python objects have it # - So there is instance and class __dict__ # - Class attributes are stored in class __dict__ #=========================================================================== # Let's change the attributes values new_inst = MyClass() inst.class_attr = 12345 inst.instance_attr = 67890 new_inst.instance_attr = "BBBB" # Let's check what was changed print inst.__dict__ print MyClass.__dict__ print new_inst.__dict__ #=========================================================================== # - Instance __dict__ overrides the classes __dict__ (or is looked up in first place) # - Changed attributes value is stored in the instance __dict__ #=========================================================================== # Let's see how inheritance works class MyClassInh(MyClass): pass inst_inh = MyClassInh() print inst_inh.class_attr print inst_inh.instance_attr # Note that now it prints a different message # Let's check their __dict__ print inst_inh.__dict__ print MyClassInh.__dict__ #=========================================================================== # - Each superclass holds its own __dict__ # - They are looked up in order #=========================================================================== # Let's try to list all __dict__ elements for an instance lst = MyClass.__dict__.keys() lst.extend(MyClassInh.__dict__.keys()) lst.extend(inst_inh.__dict__.keys()) print sorted(list(set(lst))) # Trick: http://docs.python.org/2/library/functions.html#dir print dir(inst_inh) # Let's manually add a new instance attribute inst_inh.__dict__['new_instance_attr'] = "New value of instance of MyClassInh attrib" print inst_inh.new_instance_attr print inst_inh.__dict__ # Let's try to go a bit further try: MyClassInh.__dict__['new_class_attr'] = 9 except TypeError, e: print e
true
e4598a7212964d5dc6440bb57d16342e46b1fd95
usfrank02/pythonProjects
/project3.py
288
4.34375
4
#! python import sys name = input("Enter your name:") print (name) #Request user to input the year he was born year_of_born = int(input("What's the year you were born?")) #Calculate the age of the user age = 2020 - year_of_born print("You will be {} years old this year!".format(age))
true
2e046c0d4fc1e243a8ae9e85b56d10f9195e473b
Regato/exersise12
/Romanov_Yehor_Exercise14.py
582
4.15625
4
# Entering input and making from string all UPPER case: input_string = input('[!] INPUT: Please enter your value (only string type): ') upper_string = input_string.upper() # Function that count letters in string: def letter_counter(x): return upper_string.count(x) # For cycle that check every letter for duplicates by the previous function: for i in upper_string: if (letter_counter(i) > 1): output_value = True break else: output_value = False # Printing output (the result of program): print('[/] OUTPUT: Your result is: ', output_value)
true
38582bca142960e852de0445e04d76afb018a1fb
Jattwood90/DataStructures-Algorithms
/1. Arrays/4.continuous_sum.py
435
4.25
4
# find the largest continuous sum in an array. If all numbers are positive, then simply return the sum. def largest_sum(arr): if len(arr) == 0: return 0 max_sum = current = arr[0] # sets two variables as the first element of the list for num in arr[1:]: current = max(current+num, num) max_sum = max(max_sum, current) return max_sum print(largest_sum([1,3,-1,5,6,-10])) # 14
true
088a600b0d851da9345a6ef2e336bdf32c9dddb8
rhaydengh/IS211_Assignment1
/assignment1_part2.py
614
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """Assignment 1, Part 2""" class Book: """Class for books""" def __init__(self, author, title): """this function returns a book by author and title based on variables""" self.author = author self.title = title def display(self): """This function provides instructions on printing format and displays 2 books""" print(self.title, 'written by', self.author) Book1 = Book('John Steinbeck', 'Of Mice and Men') Book2 = Book('Harper Lee', 'To Kill a Mockingbird') print(Book1.display(),Book2.display())
true
6e29c29f32d27aa1e76cc0a3ead78b2b3cca6515
sachlinux/python
/exercise/strings/s3.py
369
4.15625
4
#embedding value in string value = "500" message = "i hav %s rupees" print(message % value) #we can do without variable also print(message % 1000) #more example var1 = "sachin" var2 = "dentist" message1 = "%s: is in love with %s" message2 = "%s is so %s" print(message1 % (var1,var2)) print(message2 % ('she','pretty')) #multiplying string print(5 * var1)
true
658ec398f352a09390fd9534cb448e2a91bffc9c
debakshmi-hub/Hacktoberfest2021-2
/checkPrime.py
756
4.21875
4
# //your code here # Program to check if a number is prime or not num = int(input("Enter a Number ")) flag = False if num > 1: for i in range(2, num): if (num % i) == 0: flag = True break if flag: print(num, "is not a prime number") else: print(num, "is a prime number") # Program to check if a number is prime or not num = 407 # To take input from the user #num = int(input("Enter a number: ")) if num > 1: # check for factors for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") else: print(num,"is not a prime number")
true
fb54c0d63382752c3c9a3feb327321a2c77492cc
gautamk/ProjectEuler
/problem1.py
528
4.25
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. MAX = 1000 def mul_of(multiple_of, max=MAX): multiplier = 1 multiple = multiple_of * multiplier while multiple < MAX: yield multiple multiple = multiple_of * multiplier multiplier += 1 multiples_of_3_or_5 = set(mul_of(3)).union(mul_of(5)) print multiples_of_3_or_5 print sum(multiples_of_3_or_5)
true
250aaa13de0944d78fc6f7a6083c5413ea1961e5
KhallilB/Tweet-Generator
/Code/practice_code/sampling.py
1,731
4.125
4
import random import sys import histograms def random_word(histogram): '''Generates a random word without using weights''' random_word = '' random_index = random.randrange(len(histogram)) random_word += histogram[random_index][0] return random_word def weighted_random_word(histogram): '''Generates random words based on how often they appear''' random_word = '' weights = 0 for items in histogram: weights += items[1] random_weight = random.randrange(weights) index = 0 while random_weight >= 0: random_word = histogram[index][0] random_weight -= histogram[index][1] index += 1 return random_word def test_probability(histogram): ''' Tests the probability of word ocurrances in the histogram that gets passed through ''' words = '' for i in range(10000): words += ' ' + weighted_random_word(histogram=histogram) test_histogram = histograms.histogram_counts(words) sample_amount = 25 index = len(test_histogram) - 1 while sample_amount > 0 and index >= 0: for entry in test_histogram[index][1]: if sample_amount > 0: printline = entry + ' = ' printline += str(test_histogram[index][0]) print(printline) sample_amount -= 1 index -= 1 if __name__ == '__main__': path = sys.argv[1] with open(path, 'r') as file: source_text = file.read() source_histogram = histograms.histogram_tuples(source=source_text) word = weighted_random_word(histogram=source_histogram) print(word) print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^') test_probability(source_histogram)
true
79ec249c78604d85bf5612da0d597d41c39214e3
qcl643062/leetcode
/110-Balanced-Binary-Tree.py
1,730
4.15625
4
#coding=utf-8 """ Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. """ class TreeNode(object): def __init__(self, x, left = None, right = None): self.val = x self.left = left self.right = right class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ #统计节点深度 def numofnode(root): if root == None: return 0 def priorder(root): if not root: return 0 return 1 + max(priorder(root.left), priorder(root.right)) return priorder(root) #判断一个节点是否符合 def nodetrue(root): if not root: return True numofleft = numofnode(root.left) numofright = numofnode(root.right) if abs(numofright - numofleft) <= 1: return True else: return False #对每个节点进行判断 result = nodetrue(root) if result == False: return False boo1 = True boo2 = True if root: if root.left: boo1 = self.isBalanced(root.left) if boo1 == False: return False if root.right: boo2 = self.isBalanced(root.right) if boo2 == False: return False return True s = Solution() print s.isBalanced(TreeNode(0, TreeNode(1, TreeNode(2))))
true
a2f10d28828b2fe43054860554e2915bbe1a3e13
EngrDevDom/Everyday-Coding-in-Python
/Distance.py
379
4.25
4
# File : Distance.py # Desc : This program accepts two points and determines the distance between them. import math def main(): x1, y1 = eval(input("Enter first coordinate.(x1, y1): ")) x2, y2 = eval(input("Enter second coordinate.(x2, y2): ")) distance = math.sqrt((x2-x1)**2 + (y2-y1)**2) print("The distance between two points is:", distance) main()
true
38af1cc91d8307cf8d0adfb77e19b558ad5b6bb5
EngrDevDom/Everyday-Coding-in-Python
/SciPy/polynomials.py
830
4.25
4
from numpy import poly1d # We'll use some functions from numpy remember!! # Creating a simple polynomial object using coefficients somePolynomial = poly1d([1,2,3]) # Printing the result # Notice how easy it is to read the polynomial this way print(somePolynomial) # Let's perform some manipulations print("\nSquaring the polynomial: \n") print(somePolynomial*somePolynomial) # How about integration, we just have to call a function # We just have to pass a constant say 3 print("\nIntegrating the polynomial: \n") print(somePolynomial.integ(k=3)) # We can also find derivatives in similar way print("\nFinding derivative of the polynomial: \n") print(somePolynomial.deriv()) # We can also solve the polynomial for some value, # let's try to solve it for 2 print("\nSolving the polynomial for 2: \n") print(somePolynomial(2))
true
d43dcc1e99425696cdaeff16dc969344a3205a95
EngrDevDom/Everyday-Coding-in-Python
/Identify_triangle.py
496
4.4375
4
# This program identifies what type of triangle it is # based on the measure of it's angle angle = int(input("Give an angle in degrees: ")) type = "" if angle > 0 and angle < 90: type = "ACUTE" elif angle == 90: type = "RIGHT" elif angle > 90 and angle < 180: type = "OBTUSE" elif angle == 180: type = "STRAIGHT" elif angle > 180 and angle < 360: type = "REFLEX" elif angle == 360: type = "COMPLETE" else: type = "UNIDENTIFIED" print("The triangle is a/an: ", type)
true
96ff1baf71e2a5f8e24a0985a95a4cf52e2d14b4
EngrDevDom/Everyday-Coding-in-Python
/Ladder.py
447
4.46875
4
# File : Ladder.py # Desc : This program determine the length of the ladder required to # reach a given height leaned. import math def main(): angle = float(input("Enter the value of angle in degrees: ")) radians = math.radians(angle) # Convert degrees to radians height = float(input("Enter the value of height: ")) length = height/math.sin(angle) print("The length of the ladder is", length) main()
true
0cea260a3dcf1852cbd66920e3aa23e94e7d26b7
EngrDevDom/Everyday-Coding-in-Python
/quadratic_5.py
702
4.1875
4
# File : quadratic_5.py # Desc : A program that computes the real roots of a quadratic equation. Version 5.0 # Note: This program catches the exception if the equation has no real roots. import math def main(): print("This program finds the real solutions to a quadratic\n") try: a = float(input("Enter coefficient a: ")) b = float(input("Enter coefficient b: ")) c = float(input("Enter coefficient c: ")) discRoot = math.sqrt(b**2 - 4*a*c) root1 = (-b + discRoot) / (2*a) root2 = (-b - discRoot) / (2*a) print("\nThe solutions are:", root1, root2) except ValueError: print("\nNo real roots.") main()
true
de25351bfb982437ac08ebd4d1c7ba94ffd86490
EngrDevDom/Everyday-Coding-in-Python
/quizzes_2.py
549
4.1875
4
# File : quizzes_2.py # Desc : A program that accepts a quiz score as an input and uses a decision # structure to calculate the corresponding grade. def main(): grade = int(input("Enter your grade: ")) scale = '' if grade <= 100 or grade >= 90: scale = 'A' elif grade <= 89 or grade > 80: scale = 'B' elif grade <= 79 or grade > 70: scale = 'C' elif grade <= 69 or grade > 60: scale = 'D' elif grade <= 60: scale = 'F' print("Your scale is", scale, "\nDone!") main()
true
f05e35fdc63cfcb45bb19620d0478dfc7b91ab8c
EngrDevDom/Everyday-Coding-in-Python
/Eq_of_Motion.py
261
4.28125
4
# Program for computing the height of a ball in vertical motion v0 = 5 # Initial velocity (m/s) g = 9.81 # Acceleration of gravity (m/s^2) t = 0.6 # Time (s) y = v0*t - 0.5*g*t**2 # Vertical position print("Height of the ball: ", y, " m")
true
0db588fb91a034b200427bc709206e201947fc9f
EngrDevDom/Everyday-Coding-in-Python
/Algorithms/Sorting Algorithms/Tim_sort.py
2,652
4.28125
4
# Tim_sort Algorithm from random import randint from timeit import repeat def timsort(array): min_run = 32 n = len(array) # Start by slicing and sorting small portions of the # input array. The size of these slices is defined by # your `min_run` size. for i in range(0, n, min_run): insertion_sort(array, i, min((i + min_run - 1), n - 1)) # Now you can start merging the sorted slices. # Start from `min_run`, doubling the size on # each iteration until you surpass the length of # the array. size = min_run while size < n: # Determine the arrays that will # be merged together for start in range(0, n, size * 2): # Compute the `midpoint` (where the first array ends # and the second starts) and the `endpoint` (where # the second array ends) midpoint = start + size - 1 end = min((start + size * 2 - 1), (n-1)) # Merge the two subarrays. # The `left` array should go from `start` to # `midpoint + 1`, while the `right` array should # go from `midpoint + 1` to `end + 1`. merged_array = merge( left=array[start:midpoint + 1], right=array[midpoint + 1:end + 1]) # Finally, put the merged array back into # your array array[start:start + len(merged_array)] = merged_array # Each iteration should double the size of your arrays size *= 2 return array # This is the timing algorithm def run_sorting_algorithm(algorithm, array): # Set up the context and prepare the call to the specified # algorithm using the supplied array. Only import the # algorithm function if it's not the built-in `sorted()`. setup_code = f"from __main__ import {algorithm}" \ if algorithm != "sorted" else "" stmt = f"{algorithm}({array})" # Execute the code ten different times and return the time # in seconds that each execution took times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10) # Finally, display the name of the algorithm and the # minimum time it took to run print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}") ARRAY_LENGTH = 0 if __name__ == "__main__": # Generate an array of `ARRAY_LENGTH` items consisting # of random integer values between 0 and 999 array = [randint(0, 1000) for i in range(ARRAY_LENGTH)] # Call the function using the name of the sorting algorithm # and the array we just created run_sorting_algorithm(algorithm="timsort", array=array)
true
88f6afcf9589102e21cd694e2ce4f9104d61b08e
EngrDevDom/Everyday-Coding-in-Python
/Resistor_Color_Coding.py
508
4.21875
4
''' Resistor Color Coding - This program calculates the value of a resistor based on the colors entered by the user. ''' # Initialize the values black = 0 brown = 1 red = 2 orange = 3 yellow = 4 green = 5 blue = 6 violet = 7 grey = 8 white = 9 gold = 0 silver = 0 bands = input('Enter the color bands: ') code = bands.split(" ") print('1st Band\t', '2nd Band\t', 'Multiplier\t', 'Tolerance\t', 'Reliability') print(code[0], '\t\t', code[1], '\t\t', code[2], '\t\t', code[3], '\t\t', code[4])
true
7d5ad562c1fd4fd490af54eeca2429e41b04e95c
sreedhr92/Computer-Science-Laboratory
/Design And Analysis of Algorithms/power_iterative.py
251
4.28125
4
def power_iterative(x,n): result =1 for i in range(0,n): result = x*result return result x = int(input("Enter the base:")) y = int(input("Enter the exponent:")) print("The value of",x,"to the power of",y,"=",power_iterative(x,y))
true
15544b46b10a29d6f235de86dbf6a1af00bae4bd
UzairIshfaq1234/python_programming_PF_OOP_GUI
/07_color_mixer.py
891
4.46875
4
colour1 = input("Enter the first primary colour: ") colour2 = input("Enter the second primary colour: ") mixed_colour = "" if (colour1 == "red" or colour1 == "blue" or colour1 == "yellow") and (colour2 == "red" or colour2 == "blue" or colour2 == "yellow"): if (colour1 == "red" and colour2 == "blue") or (colour2 == "red" and colour1 == "blue"): mixed_colour = "purple" elif (colour1 == "red" and colour2 == "yellow") or (colour2 == "red" and colour1 == "yellow"): mixed_colour = "orange" elif (colour1 == "blue" and colour2 == "yellow") or (colour2 == "blue" and colour1 == "yellow"): mixed_colour = "green" else: print("-----------") print("Invalid mixing of colours!") if mixed_colour: print("-----------") print("Your mixed color is:", mixed_colour) else: print("Your colour is not a primary colour!")
true
f8d641ea4352a27b00c1d30c84545fd5e5c7744c
nirakarmohanty/Python
/controlflow/IfExample.py
248
4.375
4
print('If Example , We will do multiple if else condition') value =int(input('Enter one integer value: ')) print('You entered the value as : ',value) if value>0: print('value is an integer') else: print('Please enter one integer number')
true
9a107acee38a1fc5a4632d6ed1c20b5b81408161
nirakarmohanty/Python
/datatype/ListExample.py
513
4.46875
4
#Define simple List and print them nameList=['Stela','Dia','Kiara','Anna'] print(nameList) #List indexing print(nameList[1],nameList[2],nameList[3]) print(nameList[-1],nameList[-2]) #length of List print(len(nameList)) #Add a new list to the original list nameList= nameList + ['Budapest','Croatia','Prague'] print(nameList) print("Length of the List =", len(nameList)) # Slicing of list print("print upto 3",nameList[:3]) #Assign values to list nameList[3]='XXXX' print("Assign at 3rd position ",nameList)
true
b9ec0f8c814393ce080abe964c5c59f417dfc897
dspwithaheart/blinkDetector
/modules/read_csv.py
2,833
4.1875
4
''' csv module for reading csv file to the 2D list Default mode is 'rb' Default delimiter is ',' and the quotechar '|' # # # arguments: csv_file - read csv file name coma - if True replaces all the comas with dots (in all cells) header - specify how many lines (from the begining) are removed to_float - if set all transpose - if True transposes the data transposition - switch columns with rows e.g. list = [1, 2, 3 4, 5, 6 7, 8, 9] list.T: [1, 4, 7 2, 5, 8 3, 6, 8] # # # example use: import read_csv some_list = read_csv.read(example.csv) other_list = read_csv.read(example.csv, header=5) ''' import csv import numpy as np def read( csv_file, comas=True, delimiter=',', header=None, mode='rb', to_float=True, transpose=True, quotechar='|' ): data = [] print('init') if len(delimiter) > 1: data = advanced( csv_file, comas=comas, data=data, delimiter=delimiter, mode=mode) else: data = basic( csv_file=csv_file, comas=comas, data=data, delimiter=delimiter, mode=mode, quotechar=quotechar ) if header is not None: data = data[header:] if transpose or to_float: data = np.array(data) if transpose: data = data.T if to_float: data = data.astype(np.float) data = data.tolist() return data def basic( csv_file, data, comas=False, delimiter=',', mode='rb', quotechar='|' ): with open(csv_file, mode) as csv_file: csv_reader = csv.reader( csv_file, delimiter=delimiter, quotechar=quotechar ) for row_list in csv_reader: if comas: # change comas to dots row_list = [i.replace(',', '.') for i in row_list] data.append(row_list) return data def advanced( csv_file, data, delimiter=', ', comas=True, mode='rb' ): with open(csv_file, mode) as f: for line in f: # remove new line character line = line.rstrip('\n') # split to cells accordingly to the double delimiter line = line.split(delimiter) if comas: # change comas to dots line = [i.replace(',', '.') for i in line] data.append(line) return data
true
1c43a8a8cccb45600465dc2389894102763ad40b
a-bl/counting
/task_1.py
243
4.15625
4
# What is FOR loop? sum = 0 while True: n = int(input('Enter N:')) if n > 0: for num in range(1, n + 1): sum += num print(sum) break else: print('Enter positive integer!')
true
53490c2c6e9feba29d73cb1024895eda79298a2e
rollbackzero/projects
/ex30.py
458
4.1875
4
people = 40 cars = 30 trucks = 45 if cars > people: print("We should take cars") elif cars < people: print("We should not take cars") else: print("We can't decide") if trucks > cars: print("Thats too many trucks") elif trucks < cars: print("Maybe we could take the trucks") else: print("We still cant decide") if people > trucks: print("Alright, lets just take the trucks") else: print("Fine, lets stay home then")
true
009d63fffab9020cf7c8ebc4b9deec98b0f656a9
UVvirus/frequency-analysis
/frequency analysis.py
1,099
4.4375
4
from collections import Counter non_letters=["1","2","3","4","5","6","7","8","9","0",":",";"," ","/n",".",","] key_phrase_1=input("Enter the phrase:").lower() #Removing non letters from phrase for non_letters in non_letters: key_phrase_1=key_phrase_1.replace(non_letters,'') total_occurences=len(key_phrase_1) #Counter object """""A Counter is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. """ letter_count=Counter(key_phrase_1) print("frequency analysisfrom the phrase:") for key,value in sorted(letter_count.items()): percentage=100 * value/total_occurences percentage=round(percentage,2) print("\t \t"+key+"\t\t"+str(value)+"\t\t"+str(percentage)) ordered_letter_count=letter_count.most_common() key_phrase_1_ordered_letters=[] for pair in ordered_letter_count: key_phrase_1_ordered_letters.append(pair[0]) print("letters from high occurence to lower occurence:") for letter in key_phrase_1_ordered_letters: print(letter, end='')
true
5445d08db0f152cba9a08f2f6d176a071d61c080
habbyt/python_collections
/challenge_1.py
292
4.15625
4
#Challenge #1 #function takes a single string parameter and #return a list of all the indexes in the string that have capital letters. def capital_indexes(word): word="HeLlO" x=[] for i in range(len(word)): if word[i].isupper()==True: x.append(i) return x
true
cd2ae708b13c6359cbbcefa0b957fa58d304f722
okazkayasi/03_CodeWars
/14_write_in_expanded_form.py
682
4.375
4
# Write Number in Expanded Form # # You will be given a number and you will need to return it as a string in Expanded Form. For example: # # expanded_form(12) # Should return '10 + 2' # expanded_form(42) # Should return '40 + 2' # expanded_form(70304) # Should return '70000 + 300 + 4' # # NOTE: All numbers will be whole numbers greater than 0. # # If you liked this kata, check out part 2!! def expanded_form(num): aList = [] digs = len(str(num)) div = 10 ** (digs-1) for i in range(digs): x = (num / div) * div div /= 10 num -= x if x > 0: aList.append(str(x)) return " + ".join(aList) print expanded_form(70304)
true
4f7cbb96396df971f262b7faecee06a8be3a23a9
okazkayasi/03_CodeWars
/24_car_park_escape_5kyu.py
2,297
4.15625
4
# Your task is to escape from the carpark using only the staircases provided to reach the exit. You may not jump over the edge of the levels (youre not Superman) and the exit is always on the far right of the ground floor. # 1. You are passed the carpark data as an argument into the function. # 2. Free carparking spaces are represented by a 0 # 3. Staircases are represented by a 1 # 4. Your parking place (start position) is represented by a 2 # 5. The exit is always the far right element of the ground floor. # 6. You must use the staircases to go down a level. # 7. You will never start on a staircase. # 8. The start level may be any level of the car park. # Returns # Return an array of the quickest route out of the carpark # R1 = Move Right one parking space. # L1 = Move Left one parking space. # D1 = Move Down one level. # Example # Initialise # # carpark = [[1, 0, 0, 0, 2], # [0, 0, 0, 0, 0]] # # Working Out # # You start in the most far right position on level 1 # You have to move Left 4 places to reach the staircase => "L4" # You then go down one flight of stairs => "D1" # To escape you have to move Right 4 places => "R4" # # Result # # result = ["L4", "D1", "R4"] # # Good luck and enjoy! def escape(carpark): # in case we didnt park the car on top for k in range(len(carpark)): if 2 in carpark[k]: carpark = carpark[k:] pos = [0, carpark[0].index(2)] ret = [] for i in range(len(carpark)-1): # check where the stair is stair = carpark[i].index(1) # go to the stair and go down if stair < pos[1]: ret.append("L" + str(pos[1]-stair)) ret.append("D1") elif stair > pos[1]: ret.append("R" + str(stair-pos[1])) ret.append("D1") # if two stair is same column else: num = int(ret.pop()[1])+1 ret.append("D" + str(num)) pos = [pos[0]+1, stair] # go to the rightmost place stair = len(carpark[0])-1 if stair > pos[1]: ret.append("R" + str(stair-pos[1])) return ret carpark = [[1, 0, 0, 0, 2], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [1, 0, 0, 0, 0], [0, 0, 0, 0, 0]] print escape(carpark)
true
8b79cb22ebf59ff6dd2b8f1efbe840c8d519beb3
okazkayasi/03_CodeWars
/06_title_case.py
1,651
4.375
4
# A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised. # # Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed. # # ###Arguments (Haskell) # # First argument: space-delimited list of minor words that must always be lowercase except for the first word in the string. # Second argument: the original string to be converted. # # ###Arguments (Other languages) # # First argument (required): the original string to be converted. # Second argument (optional): space-delimited list of minor words that must always be lowercase except for the first word in the string. The JavaScript/CoffeeScript tests will pass undefined when this argument is unused. def title_case(title, minor_words = 'uk'): if title == '': return '' title = title.lower() exception = minor_words.lower().split() listed = title.split() titled = listed[0].capitalize() del listed[0] for word in listed: if word not in exception: titled += " " + word.capitalize() else: titled += " " + word return titled print title_case('a clash of KINGS', 'a an the of')
true
1df122ea8c6cbe2473ffa0be8626f86c38d65760
abby2407/Data_Structures-and-Algorithms
/PYTHON/Graph/Graph_Finding_Mother_Vertex.py
1,339
4.15625
4
''' A mother vertex in a graph G = (V,E) is a vertex v such that all other vertices in G can be reached by a path from v.''' from collections import defaultdict class Graph: def __init__(self, vertices): self.vertices = vertices self.graph = defaultdict(list) def addEdge(self, src, dest): self.graph[src].append(dest) def DFS(self, node, visited): visited[node] = True for n in self.graph[node]: if visited[n] == False: self.DFS(n, visited) # ------------------ Method to find a Mother Vertex in a Graph ------------------- def findMother(self): visited = [False] * self.vertices v = 0 for i in range(self.vertices): if visited[i] == False: self.DFS(i, visited) v = i visited = [False] * self.vertices self.DFS(v, visited) if any(i == False for i in visited): return -1 else: return v # ------------------ Testing the Program ----------------- g = Graph(7) g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 3) g.addEdge(4, 1) g.addEdge(6, 4) g.addEdge(5, 6) g.addEdge(5, 2) g.addEdge(6, 0) print("Mother vertex is: {} ".format(g.findMother()))
true
04245a627a81d206fd76d72a9808524609498db9
S-Tim/Codewars
/python/sudoku_solver.py
1,926
4.1875
4
""" Write a function that will solve a 9x9 Sudoku puzzle. The function will take one argument consisting of the 2D puzzle array, with the value 0 representing an unknown square. The Sudokus tested against your function will be "easy" (i.e. determinable; there will be no need to assume and test possibilities on unknowns) and can be solved with a brute-force approach. """ import itertools def sudoku(puzzle): """return the solved puzzle as a 2d array of 9 x 9""" for i in range(len(puzzle)): for j in range(len(puzzle)): # Find next not filled out square if puzzle[i][j] == 0: # Test all the numbers for num in range(1, 10): copy_puzzle = [row[:] for row in puzzle] copy_puzzle[i][j] = num if check_sudoku(copy_puzzle): # If this number works in this square so far # then keep working with it and fill in next solution = sudoku(copy_puzzle) if solution is not None: # only get here when all fields are filled in return solution # No number worked so backtrack return None return puzzle # Credit to StackOverflow for the checking. def sudoku_ok(line): return (len(line) == 9 and sum(line) == sum(set(line))) def check_sudoku(grid): bad_rows = [row for row in grid if not sudoku_ok(row)] grid = list(zip(*grid)) bad_cols = [col for col in grid if not sudoku_ok(col)] squares = [] for i in range(0, 9, 3): for j in range(0, 9, 3): square = list(itertools.chain(*[row[j:j+3] for row in grid[i:i+3]])) squares.append(square) bad_squares = [square for square in squares if not sudoku_ok(square)] return not (bad_rows or bad_cols or bad_squares)
true
58ddbfe8f4eca1b019b54c2dcac4c73c94f145e9
clarkmp/CSCI215_Assignment_1
/portfolio/csci220/Assignment03/assignment03.py
2,218
4.15625
4
from math import * def checkIfPrime(): userNumber = eval(input("Give me a number: ")) if userNumber > 1: #this makes sure the number is greater than 1 which is not a prime number while userNumber > 1: #this only loops if the number is greater than 1 if userNumber % 2 == 0: #this will determine if the number is a prime number or not by seeing if it is a multiple of 2 print('Your number is not a prime number!') break else: print('Your number is a prime number!') break else: print('Your number is prime!') checkIfPrime() def checkIfEven(): userValue = eval(input('Give me a value: ')) while userValue > -1: #this runs the loop only if the number is not a negative number if userValue % 2 == 0: #if the remainder is 0 then the number is even because it is divisible by 2 print('The number is even') else: #if the remainder is not 0, then it is odd because it is not divisible by 2 print('The number is odd') userValue = eval(input('Give me a value: ')) #since this line is still in the loop it will ask the user for a value again and restarts the loop #checkIfEven() def messageEncrypter(list): for el in (list): #takes a list and goes through each letter in the list if ord(el) > ord('Z'): newCharacter = ord(el) - 25 print(chr(newCharacter), end='') elif ord(el) < ord('Z'): newCharacter = ord(el) + 25 print(chr(newCharacter), end='') firstList = 'M[h[@e^ddo#Yec[#bWj[b_[i$M[b_l[_dj^[Yeic_YXeedZeYai$M[[c[h][Z\hecc_YheX[iWdZckYa$7f[iWh[ekhYeki_di$Ekhj^ek]^jiWdZ\[[b_d]iWh[dej\kbbokdZ[hekhemdYedjheb$J^[h[cWoX[ckY^icWhj[hWdZl[hoZ_\\[h[djX[_d]i[bi[m^[h[$7dZedjefe\Wbbj^_i"m[h[cWa_d]Wc[iie\ekhfbWd[jWdZX[Yec_d]WZWd][hjeekhi[bl[i$' #secondList = '=djgjbdnonjao`io\gf\]jpooc`"`^jgjbt"ja\ijmb\idnh5oc`o\gg`noj\fdioc`ajm`nodnoc`o\gg`noijoepno]`^\pn`dobm`ramjhoc`c\m_d`no\^jmi6dodnoc`o\gg`no\gnj]`^\pn`ijjoc`mom``n]gj^f`_donnpigdbco'oc`njdg\mjpi_dor\n_``k\i_md^c'ijm\]]do^c`r`_ocmjpbcdon]\mf\n\n\kgdib'\i_ijgph]`me\^f^podo_jri]`ajm`doh\opm`_)' #messageEncrypter(firstList)
true
0678f44e86e93fdef14ff4f35e8b6e5b7fe3ad31
gkc23456/BIS-397-497-CHANDRATILLEKEGANA
/Assignment 2/Assignment 2 - Excercise 3.16.py
477
4.15625
4
# Exercise 3.16 largest = int(input('Enter number: ')) number = int(input('Enter number: ')) if number > largest: next_largest = largest largest = number else: next_largest = number for counter in range(2, 10): number = int(input('Enter number: ')) if number > largest: next_largest = largest largest = number elif number > next_largest: next_largest = number print(f'Largest is {largest}\nSecond largest is {next_largest}')
true
d368e0f0e8acbbf8dbecb6a5e6a9a64f8f3efdd7
fmojica30/learning_python
/Palindrome.py
2,851
4.21875
4
# File: Palindrome.py # Description: # Student Name: Fernando Martinez Mojica # Student UT EID: fmm566 # Course Name: CS 313E # Unique Number: 50725 # Date Created: 2/20/19 # Date Last Modified: 2/20/19 def is_palindrome(s): #define if a string is a palindrome for i in range(len(s)//2): if s[i] != s[-i-1]: return False return True def make_palindrome(s): #function for making a palindrome out of a word newWord = '' #initial counter for the new word to see where to do the #palindrome if len(s) == 1: #single letter palindrome case return s elif len(s) == 2: #2 letter palindrome case easy solve if s[0] == s[1]: return s else: #append the last letter to the front newWord += s[1] newWord += s newPalindrome = newWord return newPalindrome else: #all other length cases if is_palindrome(s) == True: #if the word is already a palindrome return s else: for i in range(len(s)): newWord += s[i] #determine if the set of letters we are looking at is a palindrome if (is_palindrome(newWord)) and (len(newWord) > 3): if i == len(s): #the whole word is a palindrome return newPalindrome else: #creating a palindrome shortest appender = '' #define letters to append at the front adders = s[i+1:] #all of the letters required to append adders = list(adders) order = list(reversed(adders)) #putting them in order for j in order: newLetter = j appender += newLetter newPalindrome = appender + s return newPalindrome elif newWord == s: #case where the word does not include a #palindrome adder = '' for i in range(-1,(-len(s) - 1),-1): adder += s[i] #adding letters to the front from the back #of the word until we get a palindrome newPalindrome = adder + newWord if is_palindrome(newPalindrome): return newPalindrome else: continue else: continue def main(): inf = open('palindrome.txt','r') line = inf.readline() line = line.strip() while line != '': print(make_palindrome(line)) line = inf.readline() line = line.strip() main()
true
1807e2597e8d8c7ac920d57a3dd53ed7d5e14033
manjusha18119/manju18119python
/python/swap.py
207
4.3125
4
#2.Write a program to swap two variables. a=input("Enter the value of a :") #a=int(a) b=input("Enter the value of b :") #b=int(b) temp=a a=b b=temp print("swap value of a=",a) print("swap value of b=",b)
true
3e0c9760a73a7629837f54f67d86ac97157cfa32
PriceLab/STP
/chapter4/aishah/challenges.py
575
4.25
4
#1 ------write function that takes number as input and returns it squared def func1(x): return x ** 2 print(func1(2)) #2---- write a program with 2 functions-- first one takes an int #and returns the int by 2. second one returns an integer * 4. #call the first function, save the number, then pass to the second one def divideBy2(x): return x/2 y = divideBy2(6) def multiplyBy4(u): return u *4 print(multiplyBy4(divideBy2(6))) #3----a function that can convert a string to a float def convert(g): return toFloat(g) c = convert("3.3") print(c)
true
6f2f3648576cdf8da47ca0dc88ee1a8d9ea4d80d
Kotuzo/Python_crash_course
/Follow_Up/OOP.py
1,284
4.34375
4
import math # This is examplary class class Point: # This is constructor # Every method from class, needs to have self, as a first argument # (it tells Python that this method belongs to the class) def __init__(self, x, y): self.x = x # attributes self.y = y # typical method def distance_from_origin(self): return math.hypot(self.x, self.y) # override of == def __eq__(self, other): return self.x == other.x and self.y == other.y # override of str(X) def __str__(self): return "Pxy = ({0.x}, {0.y})".format(self) # override of + def __add__(self, other): return self.x + other.x, self.y + other.y # Now Point is a base class, so Circle inherits from Point class Circle(Point): def __init__(self, radius, x=0, y=0): super().__init__(x, y) self.radius = radius def area(self): return math.pi * (self.radius ** 2) if __name__ == '__main__': P1 = Point(3, 4) P2 = Point(8, 10) print("Distance from (0,0): %f" % P1.distance_from_origin()) print("Is P1 equal to P2? %s" % (P1 == P2)) print(str(P1)) print("P1 + P2 (as vectors) = " + str((P1 + P2))) C1 = Circle(2) print("Area of circle with r=2 is %f" % C1.area())
true
66ec4ee68f6db85940fd3bd9e22f91179507e5c2
sushidools/PythonCrashCourse
/PythonCrashCourse/Ch.4/try it yourself ch4.py
1,434
4.28125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Aug 5 15:55:17 2018 @author: aleksandradooley """ spc = "\n" pizzas = ['Hawaiin', 'BBQ chickcen', 'pepperoni'] friend_pizzas = pizzas[:] for pizza in pizzas: print "I like " + pizza + " pizza." print "I really love pizza!" pizzas.append('cheese') print "My favorite pizzas are:" print pizzas print spc print "My friend's favorite pizzas are:" print friend_pizzas print spc for pizza in friend_pizzas: print "I love " + pizza + " pizza." print spc # 4-2 animals = ['cat', 'dog', 'rabbit'] for animal in animals: print "A " + animal + " would make a great pet." print "Any of these animals would make a great pet!" #Try it yourself pg 64 numbers = range(1,21) print numbers # use a for loop this time for value in range(1,21): print value #look at how it printed the values. the for loop gives a new number on each new line #the other one will print a list instead #for value in range(1,100000000): # print value #you have to be careful doing whats above only because it takes time numbers = range(1,100000001) print min(numbers) print max(numbers) print sum(numbers) print spc odd_numbers = range(1,20,2) print odd_numbers print spc numbers = range(3,31) for number in numbers: print number * 3 print spc numbers = range(1,11) for number in numbers: print number ** 3 print spc cubes = [value**3 for value in range(1,11)] print cubes
true
dea18ed1dcc6504cf5d31352a5f76485418e18d6
catalanjrj/Learning-Python
/exercises/ex19.py
1,560
4.21875
4
# create a function named chees_and_crackers with two arguments. def cheese_and_crackers(cheese_count, boxes_of_crackers): # print the amount of cheeses. print(f"You have {cheese_count} cheeses!") # print the number of boxes of crackers. print(f"You have {boxes_of_crackers} boxes of crackers!") # print "Man that's enough for a party!". print("Man that's enough for a party!") # print "Get a blanket." and add a new line. print("Get a blanket. \n") # give the function values for the two arguments. print("We can just give the function numbers directly:") cheese_and_crackers(20,30) # give amount_of_cheese and amount_of_crackers values print("OR, we can use variable from our script:") amount_of_cheese = 10 amount_of_crackers = 50 # give cheese_and_crackers the value of amount_of_cheese and amount_of_crackers. cheese_and_crackers(amount_of_cheese, amount_of_crackers) # Do some math inside cheese_and_crackers. print("We can even do math inside too:") cheese_and_crackers(10 + 20, 5 + 6) # Do math with both variables and numbers. print("And we can combine the two, variables and math:") cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) def sandwiches(with_cheese, without_cheese): # print("We also have sandwiches") print(f"We have {with_cheese} sandwiches with cheese") print(f"We have {without_cheese} sandwiches without cheese") print("How many sandwiches do we have?");sandwiches(30,40) print("How many sandwiches do we have?");sandwiches(input("With cheese?"), input("No cheese?"))
true
5bbf167d0de558186b79ad5aade880d6119973fb
catalanjrj/Learning-Python
/exercises/ex4.py
1,232
4.15625
4
# Assign a value of 100 to cars cars = 100 # Assign a value of 4 to space_in_a_car space_in_a_car = 4 # Assign a value of 30 to drivers drivers = 30 # Assign a value of 90 to passengers passengers = 90 # Assign the result of cars minus drivers to cars_not_driven cars_not_driven = cars - drivers # Assign the value of drivers to cars_driven cars_driven = drivers # Assign the result of cars_driven multiplied by space_in_a_car to carpool_capactiy carpool_capacity = cars_driven * space_in_a_car # Assign the result of passengers divided by cars_driven to average_passengers_per_car average_passengers_per_car = passengers / cars_driven # Number of available cars print("There are", cars, "cars available.") # Number of available drivers print("There are only", drivers, "drivers available.") # The number of empty cars that there will be today print("There will be", cars_not_driven, "empty cars today.") # The number of people that we can transport today print("We can transport", carpool_capacity, "people today.") # The number of passengers to carpool today print("We have", passengers, "to carpool today.") # The number of passengers per car print("We need to put about", average_passengers_per_car, "in each car.")
true
3d33eb6cadd1028c81b2190b91fb3cdde5763a7c
sewald00/Pick-Three-Generator
/pick_three.py
951
4.28125
4
"""Random pick three number generator Seth Ewald Feb. 16 2018""" import tkinter as tk from tkinter import ttk from random import randint #Define the main program function to run def main(): #Define function to change label text on button click def onClick(): a = randint(0, 9) b = randint(0, 9) c = randint(0, 9) d=(a,b,c) label.config(text=d) #Create app window root = tk.Tk() root.minsize(width=300, height=75) root.maxsize(width=300, height=75) root.title("Pick Three Generator") #Create button to generate a random pick three button = tk.Button(root, text='Generate Numbers', width=25, command=onClick) button.pack() #Create a label to display the random pick three label = tk.Label(root, text='') label.pack() root.mainloop() if __name__ =='__main__': main()
true
7d3279e79e140c6feffd735171703b00a5310377
katcosgrove/data-structures-and-algorithms
/challenges/binary-search/binary_search.py
321
4.21875
4
def BinarySearch(arr, val): """ Arguments: A list and value to search for Output: The index of the matched value, or -1 if no match """ if len(arr) == 0: return -1 counter = 0 for item in arr: counter += 1 if item == val: return counter - 1 return -1
true
3cbb921b6d67b3811de9e9e117d3013dd03bb5bc
renefueger/cryptex
/path_util.py
980
4.4375
4
def simplify_path(path: str, from_separator='/', to_separator='/') -> str: """Returns the result of removing leading/trailing whitespace and consecutive separators from each segment of the given path.""" path_parts = path.split(from_separator) stripped_parts = map(lambda x: x.strip(), path_parts) valid_parts = filter(lambda x: x, stripped_parts) return to_separator + to_separator.join(valid_parts) def encode_path(path: str) -> str: """Converts a standard *nix/URL-style path to one which uses the '+' character for path separators. Before making this replacement, the path is simplified, using simplify_path(). For example, given the path /foo/bar/, this function will return +foo+bar. """ return simplify_path(path, to_separator='+') def decode_path(path: str) -> str: """Performs the reverse of encode_path(), namely, replacing '+' with '/' in the given path.""" return simplify_path(path, from_separator='+')
true
da73cd924c0b1e5b33b8a47a882815fb8c232b3a
nramiscal/spiral
/spiral.py
1,598
4.25
4
''' Given a N by M matrix of numbers, print out the matrix in a clockwise spiral. For example, given the following matrix: [[1, 2, 3, 4, 5], <-- matrix[0] [6, 7, 8, 9, 10], <-- matrix[1] [11, 12, 13, 14, 15], <-- matrix[2] [16, 17, 18, 19, 20]] <-- matrix[3] You should print out the following: 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12 ''' def spiral(m): Xmin = 0 minY = 0 Xmax = len(m)-1 maxY = len(m[0])-1 size = len(m) * len(m[0]) # print(size) count = 0 while size > 0: for i in range(minY, maxY+1, 1): size -= 1 # print(m[Xmin][i], size) print(m[Xmin][i]) if size == 0: return for i in range(Xmin+1, Xmax+1, 1): size -= 1 # print(m[i][maxY], size) print(m[i][maxY]) if size == 0: return for i in range(maxY-1, minY-1, -1): size -= 1 # print(m[Xmax][i], size) print(m[Xmax][i]) if size == 0: return for i in range(Xmax-1, Xmin, -1): size -= 1 # print(m[i][minY], size) print(m[i][minY]) if size == 0: return Xmin += 1 minY += 1 Xmax -= 1 maxY -=1 matrix = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35], [36, 37, 38, 39, 40] ] spiral(matrix)
true
adf804c78c165f98bff660077784aeca3bbc1932
BryantCR/FunctionsBasicII
/index.py
2,717
4.3125
4
#1 Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element). # Example: countdown(5) should return [5,4,3,2,1,0] def countDown(num): result = [] for i in range(num, -1, -1): result.append(i) print(result) countDown(5) #2 Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second. # Example: print_and_return([1,2]) should print 1 and return 2 def printAndReturn(myList): # for i in range(0, len(myList), 1): print(myList[0]) # break return myList[1] print(printAndReturn([1, 2])) print(printAndReturn([5, 8])) #3 First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length. # Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5) def first_plus_length(arr): for i in range(0, len(arr), 1): sum = 0 sum = arr[0] + len(arr) return sum print(first_plus_length([1, 2, 3, 4, 5])) #4 Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False # Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4] # Example: values_greater_than_second([3]) should return False def values_greater_than_second(arr): greaterValues = [] if len(arr) < 2: return False else: for i in range (0 ,len(arr), 1): if arr[i] > arr[1]: greaterValues.append(arr[i]) print(len(greaterValues)) return greaterValues print(values_greater_than_second([5, 2, 3, 2, 1, 4])) #5 This Length, That Value - Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value. # Example: length_and_value(4,7) should return [7,7,7,7] # Example: length_and_value(6,2) should return [2,2,2,2,2,2] def length_and_value(a,b): newlist = [] for i in range (0 ,a, 1): newlist.append(b) print(newlist) length_and_value(4,7) length_and_value(6,2) # newlist.append(arr[1]) # return newlist # def length_and_value(arr): # newlist = [] # for i in range (0 , arr[0], 1): # newlist.append(arr[1]) # return newlist # print(length_and_value([7,2])) # print(length_and_value([4,3]))
true
1ef6cc0dd575247f5b227eca08802a0f623744f1
dhilankp/GameDesign2021
/Python2021/VarAndStrings.py
902
4.15625
4
#Dhilan Patel # We are learning how to work with Srtings # While loop # Different type of var num1=19 num2=3.5 num3=0x2342FABADCDACFACEEDFA #How to know what type of data is a variable print(type(num1)) print(type(num2)) print(type(num3)) phrase='Hello there!' print(type(phrase)) #String functions num=len(phrase) print(num) print(phrase[3:7]) #print from 3 to 6 print(phrase[6:]) #from index to the end print(phrase *2) #Print it twice #concadenation --> joining strings phrase = phrase + " "+ "Goodbye" print(phrase[2:num-2]) while "there" in phrase: print("there" in phrase) phrase="changed" print(phrase) # make 3 string variables print them individualy #"print s1+s2" #print st2+st3 #print st1+st2 +st3 string= "Good Morning!" string2="Good Afternoon!" string3="Have a good day!" print(string +" " + string2 ) print(string2 +" "+ string3) print(string +" " + string2 +" " +string3)
true
c866c92036fbd6d45abb7efc3beca71b065abda9
DNA-16/LetsUpgrade-Python
/Day3Assign.py
679
4.21875
4
#Assignment1:Sum of N numbers using while sum=0 N=eval(input("Enter the number ")) flag=0 n=0 while n!=N+1: if(type(N)==float): flag=1 break sum=sum+n n+=1 if(flag==1): print(N,"is not a natural number") else: print("Sum of first",N,"natural number is ",sum) #Assignment2:To check whether the number is prime or not num=int(input("Enter the number ")) flag1=0 for each in range(2,int((num+1)/2)): if(num%each==0): flag1=1 break if(num==1): print("1 is neither prime nor composite.") elif(flag1==1): print(num,"is not a prime number.") else: print(num,"is a prime number.")
true
594cd76e835384d665f0a8390f82265616e34359
stackpearson/cs-project-time-and-space-complexity
/csSortedTwosum.py
667
4.1875
4
# Given a sorted array (in ascending order) of integers and a target, write a function that finds the two integers that add up to the target. # Examples: # csSortedTwoSum([3,8,12,16], 11) -> [0,1] # csSortedTwoSum([3,4,5], 8) -> [0,2] # csSortedTwoSum([0,1], 1) -> [0,1] # Notes: # Each input will have exactly one solution. # You may not use the same element twice. def csSortedTwoSum(numbers, target): for i in range(len(numbers)): for j in range (i + 1, len(numbers)): if numbers[i] + numbers[j] == target: return [i, j] return "no valid solution found" print(csSortedTwoSum([3,7,12,16], 11)) ## should bwe [0, 1]
true
263e35c47464a3fee4967b212ac0b7ba6a2c286e
maheshbabuvanamala/Python
/LinkedList.py
839
4.15625
4
class Node: """ Node in Linked List """ def __init__(self,value): self.data=value self.next=None def set_data(self,data): self.data=data def get_data(self): return self.data def set_next(self,next): self.next=next def get_next(self): return self.next def hasNext(self): return self.next!=None class LinkedList: def __init__(self, head=None): self.head = head def insert(self, data): new_node = Node(data) new_node.set_next(self.head) self.head = new_node """ Traversing Element """ def traverse(self): current=self.head while current is not None: print(current.get_data()) current=current.get_next() a=LinkedList() a.insert(10) a.insert(11) a.insert(12) a.traverse()
true
12f482950563599c33857c3264b4ce5c56e6a64d
xwinxu/foobar
/p1/cake.py
2,679
4.1875
4
""" The cake is not a lie! ====================== Commander Lambda has had an incredibly successful week: she completed the first test run of her LAMBCHOP doomsday device, she captured six key members of the Bunny Rebellion, and she beat her personal high score in Tetris. To celebrate, she's ordered cake for everyone - even the lowliest of minions! But competition among minions is fierce, and if you don't cut exactly equal slices of cake for everyone, you'll get in big trouble. The cake is round, and decorated with M&Ms in a circle around the edge. But while the rest of the cake is uniform, the M&Ms are not: there are multiple colors, and every minion must get exactly the same sequence of M&Ms. Commander Lambda hates waste and will not tolerate any leftovers, so you also want to make sure you can serve the entire cake. To help you best cut the cake, you have turned the sequence of colors of the M&Ms on the cake into a string: each possible letter (between a and z) corresponds to a unique color, and the sequence of M&Ms is given clockwise (the decorations form a circle around the outer edge of the cake). Write a function called solution(s) that, given a non-empty string less than 200 characters in length describing the sequence of M&Ms, returns the maximum number of equal parts that can be cut from the cake without leaving any leftovers. Languages ========= To provide a Python solution, edit solution.py To provide a Java solution, edit solution.java Test cases ========== Inputs: (string) s = "abccbaabccba" Output: (int) 2 Inputs: (string) s = "abcabcabcabc" Output: (int) 4 """ def is_valid(pattern: str, s: str, parts: int) -> bool: """ Essentially to do this more efficiently: pattern = s[0:i] * parts if pattern == s: return parts """ for i in range(1, parts): start = i * len(pattern) if pattern != s[start:start + len(pattern)]: return False return True def solution(s: str) -> int: n = len(s) # technically don't need to think of this, because it wouldn't make sense # to have an empty string for this question, what would you even do? if n == 0: return 0 for i in range(1, n // 2 + 1): # check every substring divisible by n if n % i == 0: parts = n // i pattern = s[0:i] # check that the substring is a repetition for the entire string if is_valid(pattern, s, parts): return parts # print("hit") # eg can't divide, return the whole cake, so hence why we can just loop thru half of the string return 1 if __name__ == '__main__': s1 = "abcabcabcabc" s2 = 'abccbaabccba' print("s1: ", solution(s1)) print("s2: ", solution(s2))
true
f30a9c52b7223972fcacf450c8815820989f22a7
AdamJDuggan/starter-files
/frontEndandPython/lists.py
847
4.59375
5
the_count = [1, 2, 3, 4, 5] fruits = ["apples", "oranges", "pears", "apricots"] change = [1, "pennies", 2, "dimes", 3, "quarters"] #this kind of for loop goes through a list for number in the_count: print("This is count {}".format(number)) #same as above for adam in fruits: print("A fruit of type {}".format(adam)) #we can also go through mixed lists to: #we have to use {} because we dont yet know what i is for i in change: print("I got {}". format(i)) #we can also build lists. First start with an empty one: elements = [] #then do a range function to do 0 to 5 counts for i in range(0, 6): print("Adding {} to the list".format(i)) #append is a function that lists Understand elements.append(i) #we can now print them out to: for i in elements: print("Element was: {}".format(i))
true
a8e5e788a73225147820189ea73a638e1547345e
sherrymou/CS110_Python
/Mou_Keni_A52_Assignment4/1. gradeChecker.py
1,188
4.125
4
''' Keni Mou Kmou1@binghamton.edu Assignment 4, Exercise 1 Lab Section 52 CA Kyle Mille ''' ''' Analysis Get grade from mark Output to monitor: grade(str) Input from keyboard: mark(float) Tasks allocated to Functions: gradeChecker Check the mark, determine the mark belongs to which grade ''' # Constants A_LINE = 90 B_LINE = 80 C_LINE = 70 D_LINE = 60 # Check the mark, determine the mark belongs to which grade # param mark(float) # param grade(str) # return the grade of the mark def gradeChecker(mark): if mark >= A_LINE: grade = "A" elif mark >= B_LINE: grade = "B" elif mark >= C_LINE: grade = "C" elif mark >= D_LINE: grade = "D" else: grade = "F" return grade # let user input a mark and check the grade. def main(): print("This program is to check your grade from your mark.\n"\ "The rule is: A(>=90), B(>=80), C(>=70), D(>=60),F(<60)") # Take in user input and convert markStr = input ("Please enter your mark") mark = float(markStr) # Compute grade = gradeChecker(mark) # Display print("Your mark is ", mark, ",and your grade is ",grade) main()
true
c438c3f44c1a2e9b7e12d3a8289e058361f99228
sherrymou/CS110_Python
/Mou_Keni_A52_Lab9/#1-2.py
1,729
4.21875
4
''' Keni Mou Kmou1@binghamton.edu Lab9, Excerise 1-2 Lab Section 52 CA Kyle Mille ''' ''' Analyze To compute the max rain fall, min rain fall, and average rain fall use the readline() method Output to the monitor: maxrain(float) minrain(float) average(float) Input from keyboard: filename(str) Tasks: getMax to get the max rainfall getMin to get the min rainfall getAverage to get the average rainfall ''' #Constants READ="r" #get the max rainfall #param rainValue(float) #param maxrain(float) #return maxrain(float) def getMax(rainValue,maxrain): if rainValue > maxrain: maxrain = rainValue return maxrain #get the min rainfall #param rainValue(float) #param minrain(flaot) #return minrain(float) def getMin(rainValue,minrain): if rainValue < minrain: minrain = rainValue return minrain #get the average rainfall #param theSum(float) #param theCounter(int) #return average(flaot) def getAverage(theSum,theCounter): return theSum/theCounter #Get the file, compute the needed values with the readline method def main(): filename=input("Please enter file name containing rainfall data: ") rainfall=open(filename,READ) #initialization maxrain=0 minrain=1000000000 theSum=0 theCounter=0 #read lines and compute line=rainfall.readline() while line: values=line.split() rainValue=float(values[1]) maxrain=getMax(rainValue, maxrain) minrain=getMin(rainValue, minrain) theSum+=rainValue theCounter+=1 #start another line line=rainfall.readline() average=getAverage(theSum, theCounter) #display print("Max rain fall is %.2f"%(maxrain), "Min rain fall is %.2f"%(minrain),'\n'\ "The average is %.2f"%(average)) main()
true
cc2d9b75be11f392906fab1f1e840f0865773c87
vicasindia/programming
/Python/even_odd.py
376
4.5
4
# Program to check whether the given number is Even or Odd. # Any integer number that can be exactly divided by 2 is called as an even number. # Using bit-manipulation (if a number is odd than it's bitwise AND(&) with 1 is equal to 1) def even_or_odd(n): if n & 1: print(n, "is Odd number") else: print(n, "is Even number") even_or_odd(int(input("Enter a number ")))
true
419411b48b60121fec7809cb902b8f5ad027a6d2
PDXDevCampJuly/john_broxton
/python/maths/find_prime.py
813
4.1875
4
# # This program inputs a number prints out the primes of that number in a text file # ################################################################################### import math maximum = eval(input("Please enter a number. >>> ")) primes = [] if maximum > 1: for candidate in range(2, maximum + 1): is_prime = True for factor in range(2, candidate): if candidate % factor == 0: is_prime = False break if is_prime: primes.append(candidate) newFile = "\n".join(map(str, primes)) with open('primes.txt', 'w') as f: f.write(newFile) def factors(n): fact=[1,n] check=2 rootn=math.sqrt(n) while check<rootn: if n%check==0: fact.append(check) fact.append(n/check) check+=1 if rootn==check: fact.append(check) fact.sort() return fact print(fact) factors(100)
true
e80520fea7160878811113027d0483d028041d82
PDXDevCampJuly/john_broxton
/python/sorting/insertion_sort.py
1,441
4.25
4
def list_swap(our_list, low, high): insIst[low], insIst[high] = insIst[high], insIst[low] return insIst pass def insertion_sort(insIst): numbers = len(insIst) for each in range(numbers - 1): start = each minimum = insIst[each] for index in range(1, len(insIst)): candidate = insIst[index] comparison_index = index - 1 while index >= 0: if candidate < insIst[comparison_index]: list_swap(insIst, comparison_index, comparison_index + 1) comparison_index =- 1 else: break return insIst pass #This type of sort goes through the list and compares the two values that are next to each other. n and n+1. #If n+1 is smaller than n, then it swaps the values. Then it moves on to the next position. #create an index of this list #iterate through the list while comparing each value in the list to the one before it #run the listSwap algorithm on each pair of values from the current to the first def insertSort(myList): for index in range(1, len(myList)): currentvalue = myList[index] position = index while position>0 and myList[position-1]>currentvalue: myList[position]=myList[position-1] position = position-1 myList[position]=currentvalue myList = [54,26,93,17,77,31,44,55,20] insertSort(myList) print(myList)
true
31ea7b76addea2e6c4f11acd957550a69c864ef1
DKNY1201/cracking-the-coding-interview
/LinkedList/2_3_DeleteMiddleNode.py
1,263
4.125
4
""" Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node. EXAMPLE Input: the node c from the linked list a -> b -> c -> d -> e -> f Result: nothing is returned, but the new linked list looks like a -> b -> d -> e -> f """ import unittest from LinkedList import LinkedList def delete_middle_node(ll, middle_node): if not ll or not ll.head or not middle_node: return next = middle_node.next middle_node.val = next.val middle_node.next = next.next next.next = None class Test(unittest.TestCase): def test_delete_middle_node(self): ll = LinkedList() vals = [7, 3, 4, 5, 6, 7, 10, 100, 4, 7] ll.add_nodes_to_tail(vals) expect = [7, 3, 4, 6, 7, 10, 100, 4, 7] delete_middle_node(ll, ll.get_k_th_node(3)) self.assertEqual(expect, ll.to_list(), "Should remove provided middle node") ll = LinkedList() vals = [7, 3, 4] ll.add_nodes_to_tail(vals) expect = [7, 4] delete_middle_node(ll, ll.get_k_th_node(1)) self.assertEqual(expect, ll.to_list(), "Should remove provided middle node")
true
bb3f4cde389b50ffa4157e4310c764f66d7f9cb0
KUSH2107/FIrst_day_task
/17.py
237
4.125
4
# Please write a program to shuffle and print the list [3,6,7,8] import random a1_list = [1, 4, 5, 6, 3] print ("The original list is : " + str(a1_list)) random.shuffle(a1_list) print ("The shuffled list is : " + str(a1_list))
true
bd4fb7517823537a46ff3d5b28ff2f5fe36efc32
ethanschafer/ethanschafer.github.io
/Python/PythonBasicsPart1/labs/mathRunner.py
957
4.125
4
from mathTricks import * inst1 = "Math Trick 1\n\ 1. Pick a number less than 10\n\ 2. Double the number\n\ 3. Add 6 to the answer\n\ 4. Divide the answer by 2\n\ 5. Subtract your original number from the answer\n" print (inst1) # Get input for the first math trick num = input("Enter a number less than 10: ") num = int(num) # Call the trick1 method and print the result print ("Your answer is", str(trick1(num)), "\n\n") inst2 = "Math Trick 2\n\ 1. Pick any number\n\ 2. Multiply the number by 3\n\ 3. Add 45 to the answer\n\ 4. Multiple the answer by 2\n\ 5. Divide the answer by 6\n\ 6. Subtract your original number from the answer\n" print (inst2) num = input("Enter a number less than 10: ") num = int(num) print ("Your answer is", str(trick2(num)), "\n\n") # Get input for the second math trick # Call the trick2 method and print the result
true
8e80b1006bc765ff53493073f34731554ff52c27
yuliaua1/algorithms
/RandomList_01.py
382
4.3125
4
# This is a simple program to generate a random list of integers as stated below import random def genList(s): randomList = [] for i in range(s): randomList.append(random.randint(1, 50)) return randomList print(genList(30)) #This is creating the list using list comprehensions #randomList = [ random.randint(1, 50) for i in range(20) ] #print(randomList)
true
37aaf1fd82c0ded9d0578e8a971eb146463ba95f
testlikeachamp/codecademy
/codecademy/day_at_the_supermarket.py
1,874
4.125
4
# from collections import Counter prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } # Write your code below! def compute_bill(food): stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } assert isinstance(food, (list, tuple, set)), "{} error enter type".format(food) total = 0 for item in food: if item not in stock: print(str(item) + " not in price") elif stock[item] > 0: total += prices[item] stock[item] -= 1 else: print(str(item) + " out of stock") print("total: " + str(total)) return total # 4 Lists + Functions def fizz_count(x): """The function counts str 'fizz' in the input list""" assert isinstance(x, list), "{} error enter type".format(x) count = 0 for item in x: if item == 'fizz': count += 1 return count # 11 Making a Purchase def compute_bill_11(food): """Calculate the sum of prices for fruit's list""" assert isinstance(food, (list, tuple, set)), "{} error enter type".format(food) total = 0 for item in food: try: total += prices[item] except KeyError as e: print("The item {} is not in price-list".format(e)) return total # 13 Let's check out def compute_bill_13(food): """Finalize A day at the supermarket""" stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } assert isinstance(food, (list, tuple, set)), "{} error enter type".format(food) total = 0 for item in food: try: if stock[item] > 0: total += prices[item] stock[item] -= 1 except KeyError as e: print("The item {} is not in price-list".format(e)) return total
true
20849ee4f75e876464e380437d45a5b0f8835f4d
shedaniel/python_3
/Lesson4.2.py
235
4.5
4
#Range #It is used for loops #it will run the loop form %start% to %stop% which each time added it by %plus% #range(start, stop) for x in range(1 , 6): print(x) #range(start, stop, plus) for x in range(100, 107, 3): print(x)
true
18c656d4e69e8c6ee881c0c9a4bd9af8908196c9
GlenboLake/DailyProgrammer
/C204E_remembering_your_lines.py
2,868
4.21875
4
''' I didn't always want to be a computer programmer, you know. I used to have dreams, dreams of standing on the world stage, being one of the great actors of my generation! Alas, my acting career was brief, lasting exactly as long as one high-school production of Macbeth. I played old King Duncan, who gets brutally murdered by Macbeth in the beginning of Act II. It was just as well, really, because I had a terribly hard time remembering all those lines! For instance: I would remember that Act IV started with the three witches brewing up some sort of horrible potion, filled will all sorts nasty stuff, but except for "Eye of newt", I couldn't for the life of me remember what was in it! Today, with our modern computers and internet, such a question is easy to settle: you simply open up the full text of the play and press Ctrl-F (or Cmd-F, if you're on a Mac) and search for "Eye of newt". And, indeed, here's the passage: Fillet of a fenny snake, In the caldron boil and bake; Eye of newt, and toe of frog, Wool of bat, and tongue of dog, Adder's fork, and blind-worm's sting, Lizard's leg, and howlet's wing,- For a charm of powerful trouble, Like a hell-broth boil and bubble. Sounds delicious! In today's challenge, we will automate this process. You will be given the full text of Shakespeare's Macbeth, and then a phrase that's used somewhere in it. You will then output the full passage of dialog where the phrase appears. ''' import re def get_line_number(lines, phrase): for row in range(len(lines)): if lines[row].find(phrase) >= 0: return row def get_passage(lines, phrase): start = get_line_number(lines, phrase) end = start + 1 while lines[start - 1].startswith(' '): start -= 1 while lines[end].startswith(' '): end += 1 passage = '\n'.join(lines[start:end]) speaker = "Spoken by {}:".format(lines[start - 1].strip(' .')) sceneline = start while not lines[sceneline].startswith("SCENE"): sceneline -= 1 scene = lines[sceneline][0:lines[sceneline].index('.')] actline = sceneline while not lines[actline].startswith("ACT"): actline -= 1 act = lines[actline].rstrip('.') chars = set() row = sceneline + 1 while not (lines[row].startswith("ACT") or lines[row].startswith("SCENE")): match = re.match('^ (\w[^.]+)', lines[row]) if match: chars.add(match.group(1)) row += 1 characters = "Characters in scene: " + ', '.join(chars) return '\n'.join([act, scene, characters, speaker, passage]) macbeth = [row.strip('\n') for row in open('input/macbeth.txt', 'r').readlines()] # print get_passage(macbeth, 'break this enterprise') # print get_passage(macbeth, 'Yet who would have thought') print(get_passage(macbeth, 'rugged Russian bear'))
true
26d5df3fd92ed228fb3b46e32b1372a0eb5e9664
UIHackyHour/AutomateTheBoringSweigart
/07-pattern-matching-with-regular-expressions/dateDetection.py
2,902
4.46875
4
#! python3 # Write a regular expression that can detect dates in the DD/MM/YYYY format. ## Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range ## from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero. # The regular expression doesn’t have to detect correct days for each month or for leap years; ## it will accept nonexistent dates like 31/02/2020 or 31/04/2021. # Then store these strings into variables named month, day, and year, ## and write additional code that can detect if it is a valid date. # April(4), June(6), September(9), and November(11) have 30 days, February has 28 days, ## and the rest of the months have 31 days. February has 29 days in leap years. # Leap years are every year evenly divisible by 4, except for years evenly divisible by 100, ## unless the year is also evenly divisible by 400. import pyperclip, re text = str(pyperclip.paste()) # Save whatever is on computer clipboard to text variable dateRegex = re.compile(r'(\d+)/(\d+)/(\d+)') # Object for "number / number / number" ## with each number in its own group allDates = dateRegex.findall(text) # This will find all date formats as a list of tuples [(day/month/year)] validDates = [] # Valid dates will fill this list for aTuple in allDates: dateValid = True # Instantiate to reference later shortMonths = [2, 4, 6, 9, 11] # Months: Feb, Mar, June, Sep, Nov day, month, year = aTuple[0], aTuple[1], aTuple[2] # Creates an independant variable with all groups of tuple if int(month) >12 or int(month) <1: # Is month a valid number? dateValid = False if int(day) >31 or int(day) <1: # Is day a valid number? dateValid = False if int(day) == 31 and int(month) in shortMonths: # Is day addionally valid in the context of Month? dateValid = False if int(day) >29 and int(month) == 2: # Is day valid in the context of February? dateValid = False if int(day) == 29 and int(month) == 2: # Is it a leap year (year divisible by 4 but not 100 unless also 400)? if int(year) % 4 == 0: if int(year) % 400 == 0: pass elif int(year) % 100 == 0: dateValid = False else: pass else: dateValid = False if dateValid == True: # If no checks find False validDates.append([day, month, year]) datesString = "" # This string will be built a new string from the contents of validDates for aList in validDates: for item in aList: datesString += item if item != aList[-1]: # Add a slah or a space in respective place datesString += "/" else: datesString += " " pyperclip.copy("Valid dates: " + datesString) # Past new string
true
24e238601bfe282712b8fbea574a98114ecf9b99
omarBnZaky/python-data-structures
/check_palanced_parenthece.py
1,231
4.3125
4
""" Use a stack to check whether or not a string has balanced usage of parnthesis. """ from stack import Stack def is_match(p1,p2): print("math func:" + str((p1,p2))) if p1 == '(' and p2 == ')': print("match") return True elif p1 == '{' and p2 == '}': print("match") return True elif p1 == '[' and p2 == ']': print("match") return True else: print("never") return False def is_paren_balanced(paren_string): s = Stack() is_balanced = True index = 0 # print(len(paren_string)) while index < len(paren_string) and is_balanced: print(index) paren = paren_string[index] if paren in '([{': s.push(paren) else: if s.is_empty(): is_balanced=False else: top = s.pop() if not is_match(top,paren): is_balanced = False index+=1 print("items :" +str(s.get_stack())) # return is_balanced if s.is_empty() and is_balanced: return True else: return False print(is_paren_balanced('[()]]')) # elif s.is_empty() or not is_match(s.stack_top_element(),paren):
true
dacd4f6e242c40d72e9f5a664828d26c576d457d
Katt44/dragon_realm_game
/dragon_realm_game.py
1,195
4.1875
4
import random import time # having the user pick between to caves, that randomly are friendly or dangerous # printing text out slowly for suspense in checking the cave # asking user if they want to play again def display_intro(): print ('''Standing at the mouth of a cave you take one long inhale and you exhale as you pass through the threshold. The cave up ahead forks but both paths are damp, seeming to breathing, and onimnious. ''') def choose_a_cave(): cave = "" # i need help here while cave != '1' and cave != '2': # what does this mean cave = raw_input(("Do you go left or right?(1,2)")) # return cave def check_cave(chosen_cave): print (" The once narrow cave expands sharply..") time.sleep(2) print ("In the pitch black, you feel a rush of hot foul smelling air hit you.. ") time.sleep(2) friendly_cave = random.randint(1,2) if chosen_cave == str(friendly_cave): print(" dragon likes you ") else: print ("dragon eats you") #def play_again(): play_again = "yes" while play_again == "yes" or play_again == "y": display_intro() cave_number = choose_a_cave() check_cave(cave_number) play_again =raw_input("Do you want to play again?(yes or no)")
true
9cea2b8c8abb1262791201e1d03b12e2684673ea
gsandoval49/stp
/ch5_lists_append_index_popmethod.py
712
4.25
4
fruit = ["Apple", "Pear", "Orange"] fruit.append("Banana") fruit.append("Tangerine") #the append will always store the new at the end of the list print(fruit) #lists are not limited to storing strings # they can store any data type random = [] random.append(True) random.append(100) random.append(1.0) random.append("hello") print(random) # i can use an index to retrieve it's place in a list print(fruit[1]) ### if you try to access an index that doesn't exist, python raises this exception # print(fruit[8]) # you can change an item in a list by assigning it sindex to a new object fruit[2] = 'kiwi' print(fruit) # you can remove the last item from a list using pop method fruit.pop() print(fruit)
true
cf8f18ec1b0e9ae0ee1bfce22be037b352681437
afialydia/Intro-Python-I
/src/13_file_io.py
982
4.1875
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" # YOUR CODE HERE def fooTest(): with open("./src/foo.txt") as fooOpen: openfoo = fooOpen.read() print(openfoo) fooTest() # 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 # YOUR CODE HERE bars = ["Test me", "Twice" ,"Thrice"] def barTest(): with open("bar.txt","w") as f: for bar in bars: f.write(bar) f.write("\n") barTest()
true
c48dcb189abf82abb6bee0cac9b92777b6ab1380
zuwannn/Python
/Tree based DSA/TreeTraversal.py
1,029
4.21875
4
# tree traversal - in-order, pre-order and post-order class Node: def __init__(self, item): self.left = None self.right = None self.value = item # left -> root -> right def inorder(root): if root: # traverse left inorder(root.left) # traverse root print(str(root.value), end=" ") # traverse right inorder(root.right) # root -> left -> right def preorder(root): if root: print(str(root.value), end=" ") preorder(root.left) preorder(root.right) # left -> right -> root def postorder(root): if root: postorder(root.left) postorder(root.right) print(str(root.value), end=" ") if __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print("inorder traversal") inorder(root) print("\npreorder traversal") preorder(root) print("\npostorder traversal") postorder(root)
true
e367ed81791d2dfc42e60202b1c12e8d75d47de8
zuwannn/Python
/Tree based DSA/binary_tree.py
1,362
4.21875
4
#Binary Tree """ Tree represents the nodes connected by edges(Left Node & Right Node). It is a non-linear data structure. -One node is marked as Root node. -Every node other than the root is associated with one parent node. -Each node can have an arbiatry number of chid node. We designate one node as root node and then add more nodes as child nodes. """ # this function present inorder traversal class Node: #create Root def __init__(self, data): self.left = None self.right = None self.data = data #insert node def insert(self, data): #compare the new value with the parent if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data #print tree def PrintTree(self): if self.left: self.left.PrintTree() print(self.data,end=" ") if self.right: self.right.PrintTree() # use insert method to add nodes root = Node(10) root.insert(6) root.insert(14) root.insert(3) root.PrintTree()
true
eac9eea7860abcb3474cfa2c4599b31c3e2a0af1
ayushiagarwal99/leetcode-lintcode
/leetcode/breadth_first_search/199.binary_tree_right_side_view/199.BinaryTreeRightSideView_yhwhu.py
1,597
4.125
4
# Source : https://leetcode.com/problems/binary-tree-right-side-view/ # Author : yhwhu # Date : 2020-07-30 ##################################################################################################### # # Given a binary tree, imagine yourself standing on the right side of it, return the values of the # nodes you can see ordered from top to bottom. # # Example: # # Input: [1,2,3,null,5,null,4] # Output: [1, 3, 4] # Explanation: # # 1 <--- # / \ # 2 3 <--- # \ \ # 5 4 <--- ##################################################################################################### class Solution: def rightSideView_bfs(self, root: TreeNode) -> List[int]: res = [] if not root: return res queue = deque() queue.append(root) while queue: is_first = True for _ in range(len(queue)): node = queue.popleft() if is_first: res.append(node.val) is_first = False if node.right: queue.append(node.right) if node.left: queue.append(node.left) return res def rightSideView_dfs(self, root: TreeNode) -> List[int]: res = [] self._dfs(res, 0, root) return res def _dfs(self, res, step, node): if not node: return if len(res) == step: res.append(node.val) self._dfs(res, step + 1, node.right) self._dfs(res, step + 1, node.left)
true
3e75a6666d33bc5965ff3df6d54f7eef487a9900
sammienjihia/dataStractures
/Trees/inOrderTraversal.py
2,293
4.15625
4
class Node: def __init__(self, val): self.val = val self.rightchild = None self.leftchild = None def insert(self, node): # compare the data val of the nodes if self.val == node.val: return False if self.val > node.val: # make the new node the left child of this if self.leftchild: # check if the left child has a left child self.leftchild.insert(node) else: self.leftchild = node else: if self.rightchild: self.rightchild.insert(node) else: self.rightchild = node return True class Tree: def __init__(self): self.root = None def insert(self, data): if self.root: # Check whether the tree has a root node return self.root.insert(Node(data)) else: # if it doesn't make it the root node self.root = Node(data) return True # create a BST bst = Tree() items = [5,3,6,1,4,7,8,9,2,0] for item in items: print(bst.insert(item)) ############################################## # # # INODER TRAVERSAL # ############################################## ml = [] def inOrderTraversal(root_node): if root_node == None: return inOrderTraversal(root_node.leftchild) ml.append(root_node.val) inOrderTraversal(root_node.rightchild) return ml print(inOrderTraversal(bst.root)) def inOrderTraversalIterative(root_node): my_stack = [] # add to stack all the left children of the tree. my_stack.append(root_node) # first step is to add the root's left child/children while root_node or len(my_stack): root_node = root_node.leftchild if root_node != None else root_node if root_node == None and len(my_stack): # pop the stack, print it and make the right child of the current root node to be the root_node node = my_stack.pop() print(node.val) root_node = node.rightchild if root_node: my_stack.append(root_node) elif root_node != None: my_stack.append(root_node) inOrderTraversalIterative(bst.root)
true
20ce3fc899aa6766a27dfe73c6dd0c14aa3d4099
Julien-Verdun/Project-Euler
/problems/problem9.py
711
4.3125
4
# Problem 9 : Special Pythagorean triplet def is_pythagorean_triplet(a,b,c): """ This function takes 3 integers a, b and c and returns whether or not those three numbers are a pythagorean triplet (i-e sum of square of a and b equel square of c). """ return a**2 + b**2 == c**2 def product_pythagorean_triplet(N): """ This function returns 3 numbers, if they exist, such that, all 3 numbers are lesser than N, their sum equals 1000, and they are pythagorean numbers. """ for a in range(0,N): for b in range(a+1,N): for c in range(b+1,N): if a+b+c == 1000 and is_pythagorean_triplet(a,b,c): return a*b*c return "N too small" print(product_pythagorean_triplet(500)) # Resultat 31875000
true
ccee97b325a717c7031159ee1c4a7569ff0675d6
digant0705/Algorithm
/LeetCode/Python/274 H-Index.py
1,647
4.125
4
# -*- coding: utf-8 -*- ''' H-Index ======= Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. Note: If there are several possible values for h, the maximum one is taken as the h-index. ''' class Solution(object): '''算法思路: 将数组按照从大到小的顺序排序,然后从前往后遍历直到 index > 当前的 citation 值 Time: O(n*log(n)) ''' def hIndex(self, citations): for i, num in enumerate(sorted(citations), 1): if num < i: return i - 1 return len(citations) class Solution(object): '''算法思路: 由于 h-index <= 数组的长度, 因此可以利用 couting sort Time: O(n) ''' def hIndex(self, citations): n = len(citations) count = [0] * (n + 1) for num in citations: count[min(n, num)] += 1 r = 0 for i in xrange(n, 0, -1): r += count[i] if r >= i: return i return 0 s = Solution() print s.hIndex([3, 0, 6, 1, 5])
true
e8163d4faddd7f6abeacdea9c6ebbb86a57dd195
digant0705/Algorithm
/LeetCode/Python/328 Odd Even Linked List.py
1,532
4.28125
4
# -*- coding: utf-8 -*- ''' Odd Even Linked List ==================== Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. Example: Given 1->2->3->4->5->NULL, return 1->3->5->2->4->NULL. Note: - The relative order inside both the even and odd groups should remain as it was in the input. - The first node is considered odd, the second node even and so on ... ''' class Solution(object): '''算法思路: 用两个指针分别把奇偶串起来,然后连接起来即可 ''' def oddEvenList(self, head): oddHead = oddTail = ListNode(None) evenHead = evenTail = ListNode(None) cnt = 1 while head: if cnt & 1: oddTail.next = oddTail = head else: evenTail.next = evenTail = head head = head.next cnt += 1 evenTail.next, oddTail.next = None, evenHead.next return oddHead.next class ListNode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): return str(self.val) a = ListNode(1) b = ListNode(2) c = ListNode(3) d = ListNode(4) e = ListNode(5) a.next = b b.next = c c.next = d d.next = e s = Solution() head = s.oddEvenList(a) while head: print head, head = head.next
true
f43f14fe47b99787333551c200df24d211f2f466
digant0705/Algorithm
/LeetCode/Python/156 Binary Tree Upside Down.py
823
4.25
4
# -*- coding: utf-8 -*- ''' Binary Tree Upside Down ======================= Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root. For example: Given a binary tree {1,2,3,4,5}, 1 / \ 2 3 / \ 4 5 return the root of the binary tree [4,5,2,#,#,3,1]. 4 / \ 5 2 / \ 3 1 ''' class Solution(object): def upsideDownBinaryTree(self, root): if not root or not root.left: return root newRoot = self.upsideDownBinaryTree(root.left) root.left.left, root.left.right = root.right, root root.left = root.right = None return newRoot
true
bb74d28eb5e2fae422a278a02c920d856bd11b5d
digant0705/Algorithm
/LeetCode/Python/059 Spiral Matrix II.py
1,968
4.28125
4
# -*- coding: utf-8 -*- ''' Spiral Matrix II ================ Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] ''' class Solution(object): '''算法思路: 一圈一圈的生成 ''' def generateMatrix(self, n): start, row, col, matrix = 1, 0, 0, [[0] * n for _ in xrange(n)] while n > 0: i = j = 0 for index, iterator in enumerate([ xrange(n), xrange(1, n), xrange(n - 2, -1, -1), xrange(n - 2, 0, -1)]): for x in iterator: if index & 1: i = x else: j = x matrix[row + i][col + j] = start start += 1 row += 1 col += 1 n -= 2 return matrix class Solution(object): """算法思路: 同上,只不过是另外一种写法 """ def generate(self, x, y, w, start, board): i, j = 0, 0 for j in xrange(w): board[x + i][y + j] = start start += 1 for i in xrange(1, w): board[x + i][y + j] = start start += 1 if w > 1: for j in xrange(w - 2, -1, -1): board[x + i][y + j] = start start += 1 for i in xrange(w - 2, 0, -1): board[x + i][y + j] = start start += 1 return start def generateMatrix(self, n): board = [[0] * n for _ in xrange(n)] x, y, start = 0, 0, 1 while n > 0: start = self.generate(x, y, n, start, board) x += 1 y += 1 n -= 2 return board s = Solution() print s.generateMatrix(3)
true
422aa7064b6f08b428a782685507ecd3d6b8b98a
digant0705/Algorithm
/LeetCode/Python/117 Populating Next Right Pointers in Each Node II.py
1,611
4.28125
4
# -*- coding: utf-8 -*- ''' Populating Next Right Pointers in Each Node II ============================================== Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tree could be any binary tree? Would your previous solution still work? Note: - You may only use constant extra space. For example, Given the following binary tree, 1 / \ 2 3 / \ \ 4 5 7 After calling your function, the tree should look like: 1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL ''' class Solution(object): '''算法思路: 同 166 第一种解法,但依旧用了 queue ''' def connect(self, root): if not root: return queue = [root] while queue: pre = None for i in xrange(len(queue)): peek = queue.pop(0) peek.next, pre = pre, peek [queue.append(c) for c in (peek.right, peek.left) if c] class Solution(object): '''算法思路: 先访问 当前节点,再访问 右孩子,最后访问 左孩子,依次连接 ''' def connect(self, root): if not (root and (root.left or root.right)): return if root.left and root.right: root.left.next = root.right next = root.next while next and not (next.left or next.right): next = next.next if next: (root.right or root.left).next = next.left or next.right map(self.connect, (root.right, root.left))
true
49948daded2dd54ec0580b90f49602a9f109b623
digant0705/Algorithm
/LeetCode/Python/114 Flatten Binary Tree to Linked List.py
903
4.28125
4
# -*- coding: utf-8 -*- ''' Flatten Binary Tree to Linked List ================================== Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 ''' class Solution(object): '''算法思路: 先序遍历,然后把遍历结果构成 Linked List ''' def flatten(self, root): stack, r = [], [] while stack or root: if root: r.append(root) stack.append(root) root = root.left else: root = stack.pop().right tail = None for i in xrange(len(r) - 1, -1, -1): r[i].left, r[i].right, tail = None, tail, r[i]
true
f70831de914e8e30bc7d5b585d604621b153d989
digant0705/Algorithm
/LeetCode/Python/044 Wildcard Matching.py
2,354
4.1875
4
# -*- coding: utf-8 -*- ''' Wildcard Matching ================= Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "*") → true isMatch("aa", "a*") → true isMatch("ab", "?*") → true isMatch("aab", "c*a*b") → false ''' def cache(f): def method(obj, s, p, i, j): key = '{}:{}'.format(i, j) if key not in obj.cache: obj.cache[key] = f(obj, s, p, i, j) return obj.cache[key] return method class Solution(object): '''算法思路: DFS + cache ''' def __init__(self): self.cache = {} @cache def dfs(self, s, p, i, j): m, n = map(len, (s, p)) if i == m and j == n: return True if i < m and j == n: return False if i == m and j < n: return p[j] == '*' and self.dfs(s, p, i, j + 1) if p[j] == '?' or s[i] == p[j]: return self.dfs(s, p, i + 1, j + 1) if p[j] == '*': return (self.dfs(s, p, i, j + 1) or self.dfs(s, p, i + 1, j + 1) or self.dfs(s, p, i + 1, j)) return False def isMatch(self, s, p): if len(p) - p.count('*') > len(s): return False return self.dfs(s, p, 0, 0) class Solution(object): '''算法思路: 动态规划,同第 10 题差不多 ''' def isMatch(self, s, p): m, n = map(len, (s, p)) if n - p.count('*') > m: return False dp = [[False] * (n + 1) for _ in range(m + 1)] dp[0][0] = True for j in range(n): dp[0][j + 1] = p[j] == '*' and dp[0][j] for i in range(m): for j in range(n): if s[i] == p[j] or p[j] == '?': dp[i + 1][j + 1] = dp[i][j] elif p[j] == '*': dp[i + 1][j + 1] = dp[i + 1][j] or dp[i][j] or dp[i][j + 1] return dp[-1][-1] s = Solution() print s.isMatch("", "*")
true
676462bbeb65b4c86a49a3e15fda440170e117cb
digant0705/Algorithm
/LeetCode/Python/281 Zigzag Iterator.py
1,770
4.25
4
# -*- coding: utf-8 -*- ''' Zigzag Iterator =============== Given two 1d vectors, implement an iterator to return their elements alternately. For example, given two 1d vectors: v1 = [1, 2] v2 = [3, 4, 5, 6] By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]. Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases? Clarification for the follow up question - Update (2015-09-18): The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example, given the following input: [1,2,3] [4,5,6,7] [8,9] It should return [1,4,8,2,5,9,3,6,7]. ''' class ZigzagIterator(object): '''算法思路: 记录遍历指针即可,对于 k 个,只需把 self.arrays 改成对应的 arrays 即可 ''' def __init__(self, v1, v2): self.arrays = [v1, v2] self.lenArrays = len(self.arrays) self.arrayLengths = map(len, self.arrays) self.pointers = [0] * self.lenArrays self.total = sum(self.arrayLengths) self.count = 0 self.cursor = 0 def incrCursor(self): self.cursor = (self.cursor + 1) % self.lenArrays def next(self): while self.pointers[self.cursor] >= self.arrayLengths[self.cursor]: self.incrCursor() val = self.arrays[self.cursor][self.pointers[self.cursor]] self.pointers[self.cursor] += 1 self.incrCursor() self.count += 1 return val def hasNext(self): return self.count < self.total i = ZigzagIterator([1, 2, 3], [4, 5, 6, 7]) while i.hasNext(): print i.next()
true
b1d4c792fa5bed9318d6b06ef5040f8033da7b92
digant0705/Algorithm
/LeetCode/Python/371 Sum of Two Integers.py
663
4.21875
4
# -*- coding: utf-8 -*- """ Sum of Two Integers =================== Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. """ class Solution(object): def add(self, a, b): for _ in xrange(32): a, b = a ^ b, (a & b) << 1 return a def getSum(self, a, b): s = self.add(a, b) & 0xFFFFFFFF # if sum is negative, we should translate two's complement to # the true form if s & 0x80000000: return -self.add(~(s & 0x7FFFFFFF) & 0x7FFFFFFF, 1) return s s = Solution() print s.getSum(-9, 10)
true