blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a585ac1434cfc382a3d1f1f30850b36b4a0c3e35
Millennial-Polymath/alx-higher_level_programming
/0x06-python-classes/5-square.py
1,435
4.375
4
#!/usr/bin/python3 """ Module 5 contains: class square """ class Square: """ Square: defines a square Attributes: size: size of the square. Method: __init__: initialialises size attribute in each of class instances """ def __init__(self, size=0): self.__size = size @property def size(self): """ getter function for private attribute size Return: size """ return self.__size @size.setter def size(self, value): """ Setter function for private attribute size Args: value: the value to be assigned to size Return: Nothing """ if isinstance(value, int): self.__size = value if value < 0: raise ValueError("size must be >= 0") else: raise TypeError("size must be an integer") def area(self): """ public instance method calculates the area of a square args: None Return: current square area """ return self.__size * self.__size def my_print(self): """ Public instance method to print to stdout the square with "#" Args: None Return: None """ if self.__size == 0: print() for i in range(self.__size): print("#" * self.__size, end='') print()
true
944d8d7851bb5f27d6fc1e6d5b4043cacbb4e16a
beyzend/learn-sympy
/chapter3.py
329
4.34375
4
days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"] startDay = 0 whichDay = 0 startDay = int(input("What day is the start of your trip?\n")) totalDays = int(input("How many days is you trip?\n")) whichDay = startDay + totalDays print("The day is: {}".format(days[whichDay % len(days)]))
true
e1730b223bc66de92afdb0f2f857a1b617a43df9
vivekdubeyvkd/python-utilities
/writeToFile.py
462
4.40625
4
# create a new empty file named abc.txt f = open("abc.txt", "x") # Open the file "abc.txt" and append the content to file, "a" will also create "abc.txt" file if this file does not exist f = open("abc.txt", "a") f.write("Now the file has one more line!") # Open the file "abc.txt" and overwrite the content of entire file, "w" will also create "abc.txt" file if this file does not exist f = open("abc.txt", "w") f.write("Woops! I have deleted the content!")
true
191ce4a91dde400ff43493eea3a1b1a4f9ea08c9
HaminKo/MIS3640
/OOP/OOP3/Time1.py
1,646
4.375
4
class Time: """ Represents the time of day. attributes: hour, minute, second """ def __init__(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute self.second = second def print_time(self): print('{:02d}:{:02d}:{:02d}'.format(self.hour, self.minute, self.second)) def time_to_int(self): minutes = self.hour * 60 + self.minute seconds = minutes * 60 +self.second return seconds def increment(self, seconds): result = Time() result.hour, result.minute, result.second = self.hour, self.minute, self.second result.second += seconds if result.second >= 60: result.second -= 60 result.minute += 1 if result.minute >= 60: result.minute -= 60 result.hour += 1 return result def is_after(self, other): return self.time_to_int() > other.time_to_int() def int_to_time(seconds): """Makes a new Time object. seconds: int seconds since midnight. """ minutes, second = divmod(seconds, 60) hour, minute = divmod(minutes, 60) return Time(hour, minute, second) # start = Time(9, 45, 0) start = Time() start.hour = 15 start.minute = 18 start.second = 50 start.print_time() print(start.time_to_int()) end = start.increment(2000) end.print_time() print(end.is_after(start)) # traffic = Time(0, 30, 0) # expected_time = Time(10, 15, 0) # traffic.print_time() # expected_time.print_time() # print(start.is_as_expected(traffic, expected_time)) # default_time = Time() # default_time.print_time()
true
04c359f3e674466994f258820239885690299c21
HaminKo/MIS3640
/session10/binary_search.py
1,143
4.1875
4
import math def binary_search(my_list, x): ''' this function adopts bisection/binary search to find the index of a given number in an ordered list my_list: an ordered list of numbers from smallest to largest x: a number returns the index of x if x is in my_list, None if not. ''' pass index = round(len(my_list)/2) move = round(len(my_list)/4) index_searched = [] while True: print("Printing index: {}".format(index)) if my_list[index] < x: index = index + move elif my_list[index] > x: index = index - move if my_list[index] == x: return index if index in index_searched or index <= 0 or index >= len(my_list) - 1: return "None" index_searched.append(index) move = math.ceil(move/2) test_list = [1, 3, 5, 235425423, 23, 6, 0, -23, 6434] test_list.sort() # [-23, 0, 1, 3, 5, 6, 23, 6434, 235425423] print(binary_search(test_list, -23)) print(binary_search(test_list, 0)) print(binary_search(test_list, 235425423)) print(binary_search(test_list, 30)) # expected output # 0 # 1 # 8 # None
true
fb16eda74a1e4ab4b412c9b206273839e3c8049c
jdogg6ms/project_euler
/p009/p9.py
885
4.1875
4
#!/usr/bin/env python # Project Euler Problem #9 """ A Pythagorean triplet is a set of three natural numbers. For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ from math import sqrt def test_triplet(a,b,c): return (a**2 + b**2 == c**2) def calc_triplet(a,b): return sqrt(a**2 + b**2) if __name__ == "__main__": c = 1 b = 1 done = False for a in xrange(1, 1000): for b in xrange(1, 1000): c = calc_triplet(a,b) if a+b+c == 1000: print a,b,c done = True break elif a+b+c >1000: break if done == True: break print "The triplet whose sum = 1000 is %s, %s, %s, whose product is: %s" %(a,b,c,(a*b*c))
true
0f8bc6d325c0e7af4cae255b3815e10be59148cb
utk09/open-appacademy-io
/1_IntroToProgramming/6_Advanced_Problems/10_prime_factors.py
1,096
4.1875
4
""" Write a method prime_factors that takes in a number and returns an array containing all of the prime factors of the given number. """ def prime_factors(number): final_list = [] prime_list_2 = pick_primes(number) for each_value in prime_list_2: if number % each_value == 0: final_list.append(each_value) return final_list def pick_primes(numbers): prime_list = [] for each_num in range(numbers): x = prime_or_not(each_num) if x != None: prime_list.append(x) return prime_list def prime_or_not(new_num): prime_list = [] last_num = new_num + 1 if new_num == 2: return new_num elif new_num > 2: for each_num in range(2, last_num): if new_num % each_num == 0: prime_list.append(each_num) if len(prime_list) == 1: for each_element in prime_list: return each_element else: return None else: return None print(prime_factors(24)) # => [2, 3] print(prime_factors(60)) # => [2, 3, 5]
true
6ea5413956361c5ce26f70079caefca87f352112
utk09/open-appacademy-io
/1_IntroToProgramming/6_Advanced_Problems/14_sequence.py
1,120
4.46875
4
""" A number's summation is the sum of all positive numbers less than or equal to the number. For example: the summation of 3 is 6 because 1 + 2 + 3 = 6, the summation of 6 is 21 because 1 + 2 + 3 + 4 + 5 + 6 = 21. Write a method summation_sequence that takes in a two numbers: start and length. The method should return an array containing length total elements. The first number of the sequence should be the start number. At any point, to generate the next element of the sequence we take the summation of the previous element. You can assume that length is not zero. """ def summation_sequence(start, length): final_list = [start] val = start i = 0 while i < length - 1: x = total_sum(val) final_list.append(x) val = x i += 1 return final_list def total_sum(num): for i in range(1, num): num = num + i return num print(summation_sequence(3, 4)) # => [3, 6, 21, 231] # => 3, 1+2+3=6, 1+2+3+4+5+6=21, 1+2+3+4+5+6+7+8+9+10+....+19+20+21 = 231 print(summation_sequence(5, 3)) # => [5, 15, 120] # => 5, 1+2+3+4+5=15, 1+2+3+4+5+....13+14+15=120
true
88f52244e93514f9bab7cbfb527c1505f298925b
utk09/open-appacademy-io
/1_IntroToProgramming/2_Arrays/2_yell.py
481
4.28125
4
# Write a method yell(words) that takes in an array of words and returns a new array where every word from the original array has an exclamation point after it. def yell(words): add_exclam = [] for i in range(len(words)): old_word = words[i] new_word = old_word + "!" add_exclam.append(new_word) return add_exclam print(yell(["hello", "world"])) # => ["hello!", "world!"] print(yell(["code", "is", "cool"])) # => ["code!", "is!", "cool!"]
true
ac6ddb7a5ff88871ed728cc8c90c54852658ce30
utk09/open-appacademy-io
/1_IntroToProgramming/2_Arrays/12_sum_elements.py
586
4.15625
4
""" Write a method sum_elements(arr1, arr2) that takes in two arrays. The method should return a new array containing the results of adding together corresponding elements of the original arrays. You can assume the arrays have the same length. """ def sum_elements(arr1, arr2): new_array = [] i = 0 while i < len(arr1): new_array.append(arr1[i]+arr2[i]) i += 1 return new_array print(sum_elements([7, 4, 4], [3, 2, 11])) # => [10, 6, 15] # => ["catdog", "pizzapie", "bootcamp"] print(sum_elements(["cat", "pizza", "boot"], ["dog", "pie", "camp"]))
true
086ed855f74612d9ef8e28b2978ae7ffe5bf62f4
Mzomuhle-git/CapstoneProjects
/FinanceCalculators/finance_calculators.py
2,602
4.25
4
# This program is financial calculator for calculating an investment and home loan repayment amount # r - is the interest rate # P - is the amount that the user deposits / current value of the house # t - is the number of years that the money is being invested for. # A - is the total amount once the interest has been applied. # n - is the number of months over which the bond will be repaid. # i - is the monthly interest rate, calculated by dividing the annual interest rate by 12. # To include extended mathematical functions import math print("Choose either 'investment' or 'bond' from the menu below to proceed: ") print("investment \t - to calculate the amount of interest you'll earn on interest ") print("bond \t \t - to calculate the amount you'll have to pay on a home loan") calculator_type = input(": ") # choosing investment or bond if calculator_type == "investment" or calculator_type == "Investment" or calculator_type == "INVESTMENT": P = float(input("Enter the amount of money to deposit: ")) t = int(input("Enter the number of years: ")) interest_rate = float(input("Enter the percentage interest rate: ")) interest = input("Enter the type of interest [compound or simple] interest: ") r = interest_rate / 100 if interest == "simple" or interest == "SIMPLE" or interest == "Simple": # Formula for calculating simple interest A = P * (1 + r * t) A = round(A, 2) print("The total amount of money the user will earn is: R", A) elif interest == "compound" or interest == "COMPOUND" or interest == "Compound": # Formula for calculating compound A = P * math.pow((1 + r), t) A = round(A, 2) print("The total amount of money the user will earn is: \t R", A) # prints the error massage else: print("Error!!! Please choose the correct word [simple or compound] and try again") elif calculator_type == "bond" or calculator_type == "BOND" or calculator_type == "Bond": P = float(input("Enter the current value of the house: ")) interest_rate = float(input("Enter the annual interest rate: ")) n = int(input("Enter the number of months to repay: ")) r = interest_rate / 100 i = r / 12 # Formula for calculating bond repayment amount repayment = (i * P) / (1 - (1 + i) ** (-n)) repayment = round(repayment, 2) print("After each month the user will need to pay: \t R", repayment) # prints the error massage if the user doesn't enter investment or bond else: print("Error!!! Please enter the correct word [investment or bond] and try again")
true
4cbc8fddcb32ba425cbcbb2ff96f580384c8ddbb
rushabhshah341/Algos
/leetcode38.py
1,397
4.21875
4
'''The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. Example 1: Input: 1 Output: "1" Example 2: Input: 4 Output: "1211" ''' '''Python 2''' import copy class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str 1. 1 2. 11 3. 21 4. 1211 5. 111221 """ str1 = "1" if n == 1: return str1 str2 = "" for x in range(n-1): count = 1 str2 = "" prev = "" for i,c in enumerate(str1): if i == 0: prev = c count = 1 else: if prev == c: count += 1 else: str2 += str(count)+prev prev = c count = 1 str2 += str(count)+prev str1 = copy.deepcopy(str2) return str1
true
ca9c82e87d639e70de2ce6b214706617fb8f6a71
JeterG/Post-Programming-Practice
/CodingBat/Python/String_2/end_other.py
458
4.125
4
#Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string def end_other(a, b): lA=len(a) lB=len(b) if lA>lB: return a.lower()[-lB:]==b.lower() elif lB>lA: return b.lower()[-lA:]==a.lower() return a.lower()==b.lower()
true
f8b9bd890548a5d2b5fd2b60e23f68053b282097
duongtran734/Python_OOP_Practice_Projects
/ReverseString.py
625
4.5625
5
# Class that has method that can reverse a string class ReverseString: # take in a string def __init__(self, str=""): self._str = str # return a reverse string def reverse(self): reverse_str = "" for i in range(len(self._str) - 1, -1, -1): reverse_str += self._str[i] return reverse_str if __name__ == "__main__": #Get string from user str = input("Enter the string you want to reverse: ") #Initialize the object reversed_string = ReverseString(str) #call the method to reverse the string from the class print(reversed_string.reverse())
true
bd12113e4ca9a48b588c74d151d21373cdc9cfa1
pwittchen/learn-python-the-hard-way
/exercises/exercise45.py
875
4.25
4
# Exercise 45: You Make A Game ''' It's a very simple example of a "text-based game", where you can go to one room or another. It uses classes, inheritance and composition. Of course, it can be improved or extended in the future. ''' class Game(object): def __init__(self): self.kitchen = Kitchen() self.living_room = LivingRoom() def start(self): print "starting game..." action = raw_input("choose room: ") if action == "kitchen": self.kitchen.enter() elif action == "living_room": self.living_room.enter() else: print "I don't know that place" class Room(object): def enter(self): pass def leave(self): print "leaving room" class Kitchen(Room): def enter(self): print "entering Kitchen..." class LivingRoom(Room): def enter(self): print "entering Living Room..." game = Game() game.start()
true
4186b70a8f55396abe0bbd533fe61b7e8819f14e
mprior19xx/prior_mike_rps_game
/functions.py
919
4.34375
4
# EXPLORING FUNCTIONS AND WHAT THE DO / HOW THEY WORK # # EVERY DEFINITION NEEDS 2 BLANK LINES BEFORE AND AFTER # def greeting(): # say hello print("hello from your first function!") # this is how you call / invoke a function greeting() def greetings(msg="hello player", num1=0): # creating another function with variable arguments print("Our function says", msg, "and also the number", num1) myVariableNum = 0 # calling default argument for msg greetings() # these show up in place of msg and num # these arguments do nothing outside of the function greetings("This is an argument", 1) greetings("Why are we arguing?", 2) # function with math def math(num2=2, num3=5): # global enlarges scope to use variable global myVariableNum myVariableNum = num2 + num3 return num2 + num3 sum = math() print("the sum of the numbers is:", sum) print("the varial number is also:", sum)
true
53fcbf43171cfb5a3c38e05ee1c1d77d6b89a171
jhmalpern/AdventOfCode
/Puzzles/Day5/Day5Solution.py
2,238
4.1875
4
# Imports import time from re import search # From https://www.geeksforgeeks.org/python-count-display-vowels-string/ # Counts and returns number of vowels in a string ##### Part 1 functions ##### def Check_Vow(string, vowels): final = [each for each in string if each in vowels] return(len(final)) def Check_repeat(string): for each in range(1,len(string)): if(string[each] == string[each-1]): return(True) def Check_bad(string, test_list): res = [each for each in test_list if each in string] if len(res) >=1 : return(True) ##### Part 2 functions ##### def Check_doublet(string): doublet = [] for each in range(len(string)): try: doublet.append(string[each] + string[each + 1]) except: repeats = [doublet[dub] for dub in range(len(doublet)) if doublet[dub] in doublet[dub + 2:len(doublet)]] return(repeats) #return(doublet) def Check_sandwich(string): for each in range(len(string)): try: if string[each] == string[each + 2]: return(True) except: pass ##### Main ##### def main(): with open("PuzzleInput.txt","r") as f: puzzleInput = f.read().splitlines() ##### Part 1 ##### startTime1 = time.time() vowels = "aeiou" bad = ["ab", "cd", "pq", "xy"] niceString = 0 for i in range(len(puzzleInput)): if Check_Vow(puzzleInput[i],vowels) >= 3 and Check_repeat(puzzleInput[i]) and not Check_bad(puzzleInput[i],bad): # If it has more than 2 vowels niceString +=1 endTime1 = time.time() ##### Part 2 ##### startTime2 = time.time() niceString2 = 0 for i in range(len(puzzleInput)): if Check_sandwich(puzzleInput[i]) and len(Check_doublet(puzzleInput[i]))>0: niceString2 += 1 endTime2 = time.time() ##### Calls ##### print("There are %s nice strings in Part1:\t" % (niceString)) print("This solution took %s seconds" % (round(endTime1-startTime1,4))) print("There are %s nice strings in Part2:\t" % (niceString2)) print("This solution took %s seconds" % (round(endTime2-startTime2,4))) if __name__ == "__main__": main()
true
e7f9f4f92b756426ec8dfd9aa75eda62ef6f25f8
ngthnam/Python
/Python Basics/18_MultiDimensional_List.py
761
4.53125
5
x = [2,3,4,6,73,6,87,7] # one dimensional list print(x[4]) # single [] bracket to refer the index x = [2,3,[1,2,3,4],6,73,6,87,7] # two dimensional list print(x[2][1]) # using double [] to refer the index of list x = [[2,3,[8,7,6,5,4,3,2,1]],[1,2,3,4],6,73,6,87,7] # three dimensional list print(x[0][2][2]) # using triple [] to refer the index of the three dimensional list # you can also define a 3-D list in following manner, which is comparatively easy to visualize and understand x = [ [ 2, 3, [8,7,6,5,4,3,2,1] ], [ 1, 2, [5,6,7,8,9,12,34,5,3,2], 4 ], 6, 73, 6, 87, 7 ] print(x[1][2][-1])
true
73c8e86223f7de441517c9206ae526ef5365c664
JonathanFrederick/what-to-watch
/movie_rec.py
2,223
4.28125
4
"""This is a program to recommend movies based on user preference""" from movie_lib import * import sys def get_int(low, high, prompt): """Prompts the player for an integer within a range""" while True: try: integer = int(input(prompt)) if integer < low or integer > high: integer/0 break except: print("Please enter an integer between", low, "and", high) continue return integer def rate_movie(): while True: try: iden = int(input("Please enter the ID of the movie you'd like to rate >>")) except: print("Not a valid movie ID") if iden in all_movies: rate = get_int(0, 5, "Please enter your selected rating for "+all_movies[iden].title+"\nEnter a number 1 through 5 where 5 is more favorable or enter 0 to back out >>") if rate > 0: Rating(0, iden, rate) break else: print("Not a valid movie ID") def search_movies(): string = input("Please enter all or part of a movie title >> ").title() print("ID\tTITLE") for movie in all_movies.values(): if string in movie.title: print(str(movie.ident)+'\t'+movie.title) def main_menu(): while True: choice = get_int(1, 5, """Please select an option: 1 - View movies by highest average rating 2 - Search for a movie 3 - Rate a movie by ID 4 - Get recommendations (must have rated at least 4 movies) 5 - Exit >>>""") if choice == 1: print_movies_by_avg() elif choice == 2: search_movies() elif choice == 3: rate_movie() elif choice == 4: if len(all_users[0].ratings) > 3: num = get_int(1, 20, "Please enter a desired number of recommendations between 1 and 20") for movie in all_users[0].recommendations(num): print(movie.title) else: print("Rate more movies for this feature") else: sys.exit() def main(): load_data() all_users[0] = User(0) main_menu() if __name__ == '__main__': main()
true
eced2979f93a7fe022bab64f1520480b7882bf10
bishnu12345/python-basic
/simpleCalcualtor.py
1,770
4.3125
4
# def displayMenu(): # print('0.Quit') # print('1.Add two numbers') # print('2.Subtract two numbers') # print('3.Multiply two numbers') # print('4.Divide two numbers') def calculate(num1,num2,operator): result = 0 if operator=='+': result = num1 + num2 if operator == '-': result = num1 - num2 if operator == '*': result = num1 * num2 if operator == '/': result = num1 / num2 return result num1=int(input('Enter first number')) num2= int(input('Enter second number')) operator=input('Enter operator') result = calculate(num1,num2,operator) print(result) # displayMenu() # choice = int(input('Your Choice')) # while choice!=0: # if choice==1: # num1 = int(input("Enter first number")) # num2 = int(input("Enter second number")) # sum = num1 + num2 # print('The sum of {} and {} is {}'.format(num1,num2,sum)) # # elif choice==2: # num1 = int(input("Enter first number")) # num2 = int(input("Enter second number")) # subtract = num1 - num2 # print('The difference of {} and {} is {}'.format(num1, num2, subtract)) # # elif choice==3: # num1 = int(input("Enter first number")) # num2 = int(input("Enter second number")) # product = num1*num2 # print('The product of {} and {} is {}'.format(num1, num2, product)) # # elif choice==4: # num1 = int(input("Enter first number")) # num2 = int(input("Enter second number")) # division= num1/num2 # print('{} divided by {} is {}'.format(num1, num2, division)) # # displayMenu() # choice = int(input('Your Choice')) #print('Thank You')
true
789ca9376e8a07fc228c109b4dddaaf796b55173
skishorekanna/PracticePython
/longest_common_string.py
1,093
4.15625
4
""" Implement a function to determine the longest common string between two given strings str1 and str2 """ def check_common_longest(str1, str2): # Make the small string as str1 if not len(str1)< len(str2): str1, str2 = str2, str1 left_index=0 right_index=0 match_list = [] while ( left_index < len(str1)): matches="" if str1[left_index] in str2: temp_right = str2.find(str1[left_index]) temp_left = left_index while(str1[temp_left]==str2[temp_right]): matches+=str1[temp_left] temp_left+=1 temp_right+=1 if temp_left >= len(str1): break match_list.append(matches) left_index+=1 if not match_list: print("No match found") else: result = None for match in match_list: if not result: result = match continue if len(match) > len(result): result = match print("Match found is {}".format(result))
true
8b8471130787bf0c603dd98b79ac77848d72eda4
Andrew-Lindsay42/Week1Day1HW
/precourse_recap.py
277
4.15625
4
user_weather = input("Whats the weather going to do tomorrow? ") weather = user_weather.lower() if weather == "rain": print("You are right! It is Scotland after all.") elif weather == "snow": print("Could well happen.") else: print("It's actually going to rain.")
true
7a03a57714a7e1e7c4be0d714266f119ffbe2667
pankaj-raturi/python-practice
/chapter3.py
1,086
4.34375
4
#!/usr/bin/env python3 separatorLength = 40 lname = 'Raturi' name = 'Pankaj ' + lname # Get length of the string length = len(name) # String Function lower = name.lower() print (lower) # * is repetation operator for string print ( '-' * separatorLength) # Integer Object age = 30 # Convert Integers to string objects # Required to be concatenated with String Objects print(name + ' Age: ' + str(age)) print ( '-' * separatorLength) # --------------------------------------------------------- # Formating String formatted = 'I am {1}\nMy Age is {0} years'. format(age,name) print (formatted) print ( '-' * separatorLength) # ----------------------------------------------------------- # Format Specification (specifying the width of the objects for printing) print('{0:10} | {1:>10}'. format('Fruits', 'Quantity')) print('{0:10} | {1:>10.2f}'. format('Orange', 10)) print ( '-' * separatorLength) # ----------------------------------------------------------- # Accept standard input person = input('Please identify yourself: ') print('Hi {}. How are you?'.format(person))
true
8a3ad8eac1b92fcd869d220e1d41e19c65bf44d3
MegaOktavian/praxis-academy
/novice/01-05/latihan/unpickling-1.py
758
4.1875
4
import pickle class Animal: def __init__(self, number_of_paws, color): self.number_of_paws = number_of_paws self.color = color class Sheep(Animal): def __init__(self, color): Animal.__init__(self, 4, color) # Step 1: Let's create the sheep Mary mary = Sheep("white") # Step 2: Let's pickle Mary my_pickled_mary = pickle.dumps(mary) # Step 3: Now, let's unpickle our sheep Mary creating another instance, another sheep... Dolly! dolly = pickle.loads(my_pickled_mary) # Dolly and Mary are two different objects, in fact if we specify another color for dolly # there are no conseguencies for Mary dolly.color = "black" print (str.format("Dolly is {0} ", dolly.color)) print (str.format("Mary is {0} ", mary.color))
true
ab88ff7a1b5ebad88c6934741a0582603b9313ea
bmschick/DemoProject
/Unit_1.2/1.2.1/Temp_1.2.1.py
1,482
4.15625
4
'''1.2.1 Catch-A-Turtle''' '''Abstracting with Modules & Functions''' # 0.1 How does the college board create a “function”? # 0.2 What is “return” # 1 # Quiz: '''Events''' # # '''Click a Turtle''' # 2 through 14 (Make sure you comment the code!!): # 14 Did you have any bugs throughout this section of code? If so, what were they and how did you fix them? '''Move a Turtle''' # Quiz # How is Random in python different from what the college board uses? # 15 through 25 Copy and Paste the code form section 2-14 and contiune to develop it more here (don't forget to comment out the code above)! # 25 Did you have any bugs throughout this section of code? If so, what were they and how did you fix them? '''Display a Score''' # 26 # 27 # 28 through 41. Copy and Paste the code form section 15-25 and contiune to develop it more here (don't forget to comment out the code above)! # 41 Did you have any bugs throughout this section of code? If so, what were they and how did you fix them? '''Add a Countdown & It’s Your Turn''' # 42 through 50 & the It’s Your Turn Section!Copy and Paste the code form section 28-41 and contiune to develop it more here (don't forget to comment out the code above)! ''' Note: the more you try to do now, the cooler your app will work in 1.2.2, HOWEVER, make sure you know how/what your code does, otherwise 1.2.2 will become that much harder to complete. ''' '''Conclusion''' # 1 # 2
true
77244a8edec8f482e61cfe7cb2da857d989206cb
jesse10930/Similarities
/mario.py
830
4.3125
4
#allows us to use user input from cs50 import get_int #main function for the code def main(): #assigns the user input into the letter n while True: n = get_int("Enter an integer between 1 and 23: ") if n == 0: return elif n >= 1 and n <= 23: break #iterates from 0 up to user input to determine the number of rows for i in range(n): #iterates from 0 to n, determining number of columns. for j in range(n + 1): #prints either a space or a # depending on value of i and j, corresponding #to what row and column is active if n - (i + j) >= 2: print(' ', end='') else: print('#', end='') #moves to next row print() if __name__ == "__main__": main()
true
2c55104e100681e13599c5e033a4750fc3c453d6
gorkemunuvar/Data-Structures
/algorithm_questions/3_find_the_missing_element.py
1,569
4.125
4
# Problem: Consider an array of non-negative integers. A second array is formed by shuffling # the elements of the first array and deleting a random element. Given these two arrays, # find which element is missing in the second array. import collections # O(N) # But this way is not work correctly cause # arrays can have duplicate numbers. def finder1(arr1, arr2): for num in arr1: if num not in arr2: print(f"{num} is missing") return print("No missing element.") # O(N) def finder2(arr1, arr2): # Using defaultdict to avoid missing key errors dict_nums = collections.defaultdict(int) for num in arr2: dict_nums[num] += 1 for num in arr1: if dict_nums[num] == 0: print(f"{num} is missing.") return else: dict_nums[num] -= 1 # O(N) # Using XOR to find missing element. # A XOR A = 0. So when we iterate all the numbers # of arr1 and arr2 we'll find the missing el. def finder3(arr1, arr2): result = 0 for num in arr1 + arr2: result ^= num print(result) # Another solution: Also we could sort arr1 and arr2 and then we # could iterate and compare all the numbers. When a comparing is # false, it is the missing element. But time complexity of sort() # func. is O(nlogn). That's why it's not a good solution. finder3([5, 5, 7, 7], [5, 7, 7]) # 5 is missing finder3([1, 2, 3, 4, 5, 6, 7], [3, 7, 2, 1, 4, 6]) # 5 is missing finder3([9, 8, 7, 6, 5, 4, 3, 2, 1], [9, 8, 7, 5, 4, 3, 2, 1]) # 6 is missing
true
e02442b00cf41f9d3dd1933bee6b63122225e3b6
johnehunt/python-datastructures
/trees/list_based_tree.py
1,441
4.1875
4
# Sample tree constructed using lists test_tree = ['a', # root ['b', # left subtree ['d', [], []], ['e', [], []]], ['c', # right subtree ['f', [], []], []] ] print('tree', test_tree) print('left subtree = ', test_tree[1]) print('root = ', test_tree[0]) print('right subtree = ', test_tree[2]) # Functions to make it easier to work with trees def create_tree(r): return [r, [], []] def insert_left(root, new_branch): t = root.pop(1) if len(t) > 1: root.insert(1, [new_branch, t, []]) else: root.insert(1, [new_branch, [], []]) return root def insert_right(root, new_branch): t = root.pop(2) if len(t) > 1: root.insert(2, [new_branch, [], t]) else: root.insert(2, [new_branch, [], []]) return root def get_root_value(root): return root[0] def set_root_value(root, new_value): root[0] = new_value def get_left_child(root): return root[1] def get_right_child(root): return root[2] # Program to exercise functions defined above list_tree = create_tree(3) insert_left(list_tree, 4) insert_left(list_tree, 5) insert_right(list_tree, 6) insert_right(list_tree, 7) print(list_tree) l = get_left_child(list_tree) print(l) set_root_value(l, 9) print(list_tree) insert_left(l, 11) print(list_tree) print(get_right_child(get_right_child(list_tree)))
true
070be4d1e2e9ebcdbff2f227ec97da5a83c45282
johnehunt/python-datastructures
/abstractdatatypes/queue.py
1,055
4.15625
4
class BasicQueue: """ Queue ADT A queue is an ordered collection of items where the addition of new items happens at one end, called the “rear,” and the removal of existing items occurs at the other end, commonly called the “front.” As an element enters the queue it starts at the rear and makes its way toward the front, waiting until that time when it is the next element to be removed. """ def __init__(self): self.data = [] def is_empty(self): return self.data == [] def enqueue(self, item): self.data.insert(0, item) def dequeue(self): return self.data.pop() def size(self): return len(self.data) def clear(self): self.data = [] def __str__(self): return 'Queue' + str(self.data) # Implement the length protocol def __len__(self): return self.size() # Implement the iterable protocol def __iter__(self): temp = self.data.copy() temp.reverse() return iter(temp)
true
ad133e4c54b80abf48ff3028f7c00db37a622ec5
benwardswards/ProjectEuler
/problem038PanDigitMultiple.py
1,853
4.21875
4
"""Pandigital multiples Problem 38 Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?""" from typing import List def listToNumber(numList: List[int]) -> int: s = "".join([str(i) for i in numList]) return int(s) assert listToNumber([1, 2, 3, 4]) == 1234 def numberToList(number: int) -> List[int]: return [int(digit) for digit in str(number)] assert numberToList(1234) == [1, 2, 3, 4] def concatnumbers(listnumbers: List[int]) -> List[int]: listofdigits = [] for num in listnumbers: for digit in numberToList(num): listofdigits.append(digit) return listofdigits assert concatnumbers([1, 23, 45, 6, 789]) == list(range(1, 10)) def panDigit(start): for max_n in range(2, 11): listofnums: List[int] = [i * start for i in range(1, max_n)] listofdigits: List[int] = concatnumbers(listofnums) # print(listofdigits) if len(listofdigits) > 9: return 0 if len(listofdigits) == 9: if set(listofdigits) == {1, 2, 3, 4, 5, 6, 7, 8, 9}: return listToNumber(listofdigits) return 0 assert panDigit(1) == 123456789 assert panDigit(192) == 192384576 assert panDigit(9) == 918273645 maxes = [panDigit(i) for i in range(1, 10000) if panDigit(i) > 0] print("The Largest pan digit multiple is:", max(maxes))
true
1362ec74ae0c72c10bf26c69151e8d6c8d64105c
hopesfall23/Fizzbuzz
/fizzbuzz.py
530
4.125
4
#William's Fizzbuzz program n = 100 #Hard coded upper line # "fizz" Divisible by 3 # "buzz" #Divisible by 5 #"Fizzbuzz" Divisible by 3 and 5 c = 0 #Current number, Will hold the value in our while loop and be printed for c in range(0,n): #Will run this loop from 0 to 100 then terminate if c <= n: if c%3 == 0 and c%5 == 0 : print("fizzbuzz") elif c%3 == 0: print("fizz") elif c%5 == 0: print("buzz") else: print(c)
true
447850fd37249fc7e61e435c8823d86a73c42512
sprajjwal/CS-2.1-Trees-Sorting
/Code/sorting_iterative.py
2,700
4.25
4
#!python def is_sorted(items): """Return a boolean indicating whether given items are in sorted order. Running time: O(n) because we iterate through the loop once Memory usage: O(1) because we check in place""" # Check that all adjacent items are in order, return early if so if len(items) < 2: return True for index in range(len(items) - 1): if items[index] > items[index + 1]: return False return True def bubble_sort(items): """Sort given items by swapping adjacent items that are out of order, and repeating until all items are in sorted order. Running time: O(n^2) because we iterate over the whole loop once then iterate over n-i items Memory usage: O(1) because it is in place.""" if len(items) < 2: return # Repeat until all items are in sorted order # Swap adjacent items that are out of order for i in range(len(items)): swapped = false for j in range(len(items) - i - 1): if items[j] > items[j+1]: items[j], items[j+1] = items[j+1], items[j] # return items def selection_sort(items): """Sort given items by finding minimum item, swapping it with first unsorted item, and repeating until all items are in sorted order. TODO: Running time: O(n^2) TODO: Memory usage: O(1)""" if len(items) < 2: return # Repeat until all items are in sorted order for i in range(len(items) - 1): min = i for j in range(i, len(items)): # Find minimum item in unsorted items if items[min] > items[j]: min = j # Swap it with first unsorted item items[i], items[min] = items[min], items[i] # return items def insertion_sort(items): """Sort given items by taking first unsorted item, inserting it in sorted order in front of items, and repeating until all items are in order. Running time: O(n^2) Memory usage: O(1)""" # TODO: Repeat until all items are in sorted order for i in range(1, len(items)): # Take first unsorted item selected = items[i] # Insert it in sorted order in front of items move_to = i for j in range(i - 1, -1, -1): if items[j] > selected: items[j + 1] = items[j] move_to = j else: break items[move_to] = selected # return items if __name__ == "__main__": assert is_sorted([(3, 5)]) is True assert is_sorted([(3, 'A')]) is True # Single item assert is_sorted([('A', 3)]) is True # Single item assert is_sorted([('A', 'B')]) is True # Single item
true
cf33043df637dff1470547b466ded6b71d4cd434
nightphoenix13/PythonClassProjects
/FinalExamQuestion31.py
1,412
4.125
4
def main(): month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] highs = [0] * 12 lows = [0] * 12 for temps in range(len(month)): highs[temps] = int(input("Enter the highest temperature for " + month[temps] + ": ")) lows[temps] = int(input("Enter the lowest temperature for " + month[temps] + ": ")) #end for highMonth = findHighest(highs) lowMonth = findLowest(lows) print("The hottest month was ", month[highMonth], " at ", highs[highMonth], " degrees") print("The coldest month was ", month[lowMonth], " at ", lows[lowMonth], " degrees") #main method end #findHighest method start def findHighest(highs): highest = 0 highestIndex = 0 for value in range(len(highs)): if highs[value] > highest: highest = highs[value] highestIndex = value #end if #end for return highestIndex #findHighest method end #findLowest method start def findLowest(lows): lowest = 100 lowestIndex = 0 for value in range(len(lows)): if lows[value] < lowest: lowest = lows[value] lowestIndex = value #end if #end for return lowestIndex #findLowest method end #call to main method main()
true
f6076d80cbf22a0af11337a6a329fe64df60477e
Allaye/Data-Structure-and-Algorithms
/Linked List/reverse_linked_list.py
615
4.3125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: from linked_list import LinkedList L = LinkedList(10) def reverse(L): ''' reverse a linked list nodes, this reverse implementation made use of linked list implemented before ''' lenght = L.length() if(lenght == 0): raise IndexError('The list is an empty list, please append to the list and try reversing again') return nodes, cur = [], L.head while(cur.next !=None): cur = cur.next nodes.append(cur) cur = L.head nodes.reverse() for node in nodes: cur = L.next = node return cur
true
edfba19244397e3c444e910b9650de1a855633b3
Allaye/Data-Structure-and-Algorithms
/Stacks/balancedParen.py
2,399
4.4375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: from Stack import Stack # personal implementation of stack using python list # In[12]: def check_balance(string, opening='('): ''' a function to check if parenthesis used in a statement is balanced this solution used a custom implementation of a stack using python list. the below steps was used: a: check if the length of the string to be checked is even, if yes: c: loop through the string, if the any item there is == to the opening variable: d: push then into the stack, else: e: check if the length is not zero, if it is not pop the stack, else: f: return false: g: if we reach the end of the loop, return True if the size of the stack is zero else return False b: ''' s = Stack() if len(string) % 2 == 0: for w in string: if w == opening: s.push(w) else: if s.size() > 0: s.pop() else: return False return s.size() == 0 else: return False # In[2]: def double_balance(string, openings=['[', '{', '(']): ''' a function to check if the 3 types of parenthesis used in a statement is balanced this solution used a custom implementation of a stack using python list. the below steps was used: a: check if the length of the string to be checked is even, if yes: c: loop through the string, if the item matches openings: d: push then into the stack, else: e: check if the top element in the stack and item matches any tuple in our matches and pop the stack else: f: return false: g: if we reach the end of the loop, return True if the size of the stack is zero else return False b: return False since the parenthesis can only be balance if the have a corresponding closing one ''' s = Stack() matches = [('{', '}'), ('(', ')'), ('[', ']')] if len(string) % 2 == 0: for w in string: if w in openings: s.push(w) else: if (s.peek(), w) in matches: s.pop() else: return False return s.size() == 0 else: <<<<<<< HEAD return False ======= return False >>>>>>> 34dd19a4c05ecb4cd984fb078a578c1934859c39
true
cfcf85b40806e49c8cfaf1a51b78b1aa5c96ca18
bislara/MOS-Simulator
/Initial work/input_type.py
728
4.25
4
name = raw_input("What's your name? ") print("Nice to meet you " + name + "!") age = raw_input("Your age? ") print("So, you are already " + str(age) + " years old, " + name + "!") #The input of the user will be interpreted. If the user e.g. puts in an integer value, the input function returns this integer value. If the user on the other hand inputs a list, the function will return a list. Python takes your name as a variable. So, the error message makes sense! #raw_input does not interpret the input. It always returns the input of the user without changes, i.e. raw. This raw input can be changed into the data type needed for the algorithm. To accomplish this we can use either a casting function or the eval function
true
36906e07dd7a95969fcfbfb24bc566af77d6c290
w0nko/hello_world
/parameters_and_arguments.py
301
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 18 18:20:48 2017 @author: wonko """ def power(base, exponent): # Add your parameters here! result = base ** exponent print ("%d to the power of %d is %d.") % (base, exponent, result) power(37, 4) # Add your arguments here!
true
cc157edc908e4cb99ada1f2f4b880fa939d635cb
alojea/PythonDataStructures
/Tuples.py
1,105
4.5
4
#!/usr/bin/python import isCharacterInsideTuple import convertTupleIntoList import addValueInsideTuple alphabetTuple = ('a', 'b', 'c', 'd', 'e','f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') stringTuple = "" for valueTuple in alphabetTuple: stringTuple = stringTuple + valueTuple print("1.Convert the alphabet tuple to a string and print the string.") print(stringTuple) print() print("2. Output the length of the tuple") print(len(alphabetTuple)) print() print("3. Write a program that ask the user to input a character, and will then tell the user whether the character is in the tuple and give its position if it is.") isCharacterInsideTuple.isCharInsideTuple(alphabetTuple) print() print("4. Write a program that will convert the tuple to a list.") print(type(alphabetTuple)," was converted into ",type(convertTupleIntoList.convertTupleIntoList(alphabetTuple))) print() print("5. Write a program that will ask the user for input, and will then add their input to the tuple.") print(addValueInsideTuple.addValue(alphabetTuple))
true
c50d0f924ae516d9d6bab320cb1bb71cfc35d7a6
nishantvyas/python
/unique_sorted.py
1,603
4.15625
4
""" Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: again and hello makes perfect practice world """ def printListString(listObj): """ This function prints the data in list line by line :param listObj: :return: """ print(" ".join(listObj)) def uniqueWords(stringObj): """ This function takes text string as input and returns the string of unique words :param stringObj: :return: """ returnListObj = [] inputListObj = [x for x in stringObj.split()] ##manually removing duplicate words by creating new list """ for i in range(0,len(inputListObj)): if not inputListObj[i] in returnListObj: returnListObj.append(inputListObj[i]) """ ###using set method on list to remove duplicates returnListObj = list(set(inputListObj)) return returnListObj def sortWords(listObj): """ This function takes list of words as input and returns the sorted list :param listObj: :return: """ listObj.sort() return listObj if __name__ == "__main__": """ """ inputList = [] print("Enter text to be sorted on unique words:") while True: stringObj = input() if stringObj: inputList = sortWords(uniqueWords(stringObj)) else: break printListString(inputList)
true
589f077eb0b0080801f5dc3e7b4da8e3a4d1bf35
applicationsbypaul/Module7
/fun_with_collections/basic_list.py
837
4.46875
4
""" Program: basic_list.py Author: Paul Ford Last date modified: 06/21/2020 Purpose: uses inner functions to be able to get a list of numbers from a user """ def make_list(): """ creates a list and checks for valid data. :return: returns a list of 3 integers """ a_list = [] for index in range(3): while True: try: user_input = int(get_input()) except ValueError: print('User must submit a number.') continue a_list.insert(index, user_input) break return a_list def get_input(): """ Ask the user for a number :return: returns a string of the user input """ user_input = input('Please enter a number') return user_input if __name__ == '__main__': print(make_list())
true
726acce695d62e6d438f2abd93b1685daab8f95a
applicationsbypaul/Module7
/Module8/more_fun_with_collections/dict_membership.py
502
4.15625
4
""" Program: dict_membership.py Author: Paul Ford Last date modified: 06/22/2020 Purpose: using dictionaries for the first time """ def in_dict(dictionary, data): """ accept a set and return a boolean value stating if the element is in the dictionary :param dictionary: The given dictionary to search :param data: The data searching in the dictionary :return: A boolean if the data is in the dictionary """ return data in dictionary if __name__ == '__main__': pass
true
8510a11490351504b7bf1707f5ba14318fae7240
applicationsbypaul/Module7
/Module8/more_fun_with_collections/dictionary_update.py
1,563
4.28125
4
""" Program: dictionary_update.py Author: Paul Ford Last date modified: 06/22/2020 Purpose: using dictionaries to gather store and recall info """ def get_test_scores(): """ Gathers test scores for a user and stores them into a dictionary. :return: scores_dict a dictionary of scores """ scores_dict = dict() num_scores = int(input('Please how many test scores are going to be entered: ')) key_values = 'score' # this value will be the key for the dictionary incrementing by 1 for key in range(num_scores): while True: try: # ask the user for new data since the function data was bad score = int(input('Please enter your test score: ')) scores_dict.update({key_values + str(key + 1): score}) if int(score < 0) or int(score > 100): raise ValueError except ValueError: print('Test score has to be between 1 and 100.') continue else: break return scores_dict def average_scores(dictionary): """ Recall the scores from the dictionary adding them to total calculate the average :param dictionary: a dictionary of scores :return: returns the average score. """ total = 0 # local variable to calculate total key_values = 'score' for score in range(len(dictionary)): total += dictionary[key_values + str(score + 1)] return round(total / len(dictionary), 2) if __name__ == '__main__': pass
true
97d812a9b932e9ae3d7db1726be2089627985347
PikeyG25/Python-class
/forloops.py
658
4.15625
4
##word=input("Enter a word") ##print("\nHere's each letter in your word:") ##for letter in word: ## print(letter) ## print(len(word)) ##message = input("Enter a message: ") ##new_message = "" ##VOWELS = "aeiouy" ## ##for letter in message: ## if letter.lower() not in VOWELS: ## new_message+=letter ## print("A new string has been created",new_message) ##print("\nYour message without vowels is:",new_message) print("Counting: ") for i in range( 10): print(i,end="") print("\n\nCounting by fives: ") for i in range( 0, 50, 5): print(i,end="") print("\n\nCounting backwards:") for i in range( 10, 0, -1): print(i,end="")
true
6700dca221f6a0923ef9b5dbbf1ec56ab69b0671
Reetishchand/Leetcode-Problems
/00328_OddEvenLinkedList_Medium.py
1,368
4.21875
4
'''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 1: Input: 1->2->3->4->5->NULL Output: 1->3->5->2->4->NULL Example 2: Input: 2->1->3->5->6->4->7->NULL Output: 2->3->6->7->1->5->4->NULL Constraints: 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 ... The length of the linked list is between [0, 10^4].''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: even,odd = ListNode(-1), ListNode(-1) e,o=even,odd c=1 while head!=None: if c%2==0: e.next = head head=head.next e=e.next e.next=None else: o.next=head head=head.next o=o.next o.next=None c+=1 o.next=even.next return odd.next
true
56bb70f89a3b2e9fa203c1ee8d4f6f47ec71daf8
Reetishchand/Leetcode-Problems
/00922_SortArrayByParityII_Easy.py
924
4.125
4
'''Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition. Example 1: Input: nums = [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Example 2: Input: nums = [2,3] Output: [2,3] Constraints: 2 <= nums.length <= 2 * 104 nums.length is even. Half of the integers in nums are even. 0 <= nums[i] <= 1000''' class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: odd,even=1,0 while odd<len(A) and even<len(A): if A[odd]%2==0 and A[even]%2!=0: A[odd],A[even]=A[even],A[odd] if A[odd]%2!=0: odd+=2 if A[even]%2==0: even+=2 return A
true
5231912489a4f9b6686e4ffab24f4d4bc13f3a46
Reetishchand/Leetcode-Problems
/00165_CompareVersionNumbers_Medium.py
2,374
4.1875
4
'''Given two version numbers, version1 and version2, compare them. Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers. To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1. Return the following: If version1 < version2, return -1. If version1 > version2, return 1. Otherwise, return 0. Example 1: Input: version1 = "1.01", version2 = "1.001" Output: 0 Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1". Example 2: Input: version1 = "1.0", version2 = "1.0.0" Output: 0 Explanation: version1 does not specify revision 2, which means it is treated as "0". Example 3: Input: version1 = "0.1", version2 = "1.1" Output: -1 Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2. Example 4: Input: version1 = "1.0.1", version2 = "1" Output: 1 Example 5: Input: version1 = "7.5.2.4", version2 = "7.5.3" Output: -1 Constraints: 1 <= version1.length, version2.length <= 500 version1 and version2 only contain digits and '.'. version1 and version2 are valid version numbers. All the given revisions in version1 and version2 can be stored in a 32-bit integer.''' class Solution: def compareVersion(self, v1: str, v2: str) -> int: L,R = v1.split("."), v2.split(".") while len(L)<len(R): L.append("0") while len(L)>len(R): R.append("0") # l1,l2 = len(L),len(R) i,j=0,0 while i<len(L) and j <len(R): if int(L[i])<int(R[j]): return -1 elif int(L[i])>int(R[j]): return 1 i+=1 j+=1 return 0
true
8937e4cc7b216ba837dcbf3a326b2a75fb325cd0
Reetishchand/Leetcode-Problems
/00690_EmployeeImportance_Easy.py
1,800
4.1875
4
'''You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id. For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct. Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all their subordinates. Example 1: Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1 Output: 11 Explanation: Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11. Note: One employee has at most one direct leader and may have several subordinates. The maximum number of employees won't exceed 2000.''' """ # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ class Solution: def getImportance(self, arr: List['Employee'], id: int) -> int: imp={} sub={} for i in range(len(arr)): emp =arr[i].id im = arr[i].importance su = arr[i].subordinates imp[emp]=im sub[emp]=su st=[id] s=0 while st: x=st.pop() s+=imp[x] for i in sub[x]: st.append(i) return s
true
c0a23174b8c9d3021942781c960a21d2ad0699b5
Reetishchand/Leetcode-Problems
/02402_Searcha2DMatrixII_Medium.py
1,388
4.25
4
'''Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example 1: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 Output: true Example 2: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 Output: false Constraints: m == matrix.length n == matrix[i].length 1 <= n, m <= 300 -109 <= matix[i][j] <= 109 All the integers in each row are sorted in ascending order. All the integers in each column are sorted in ascending order. -109 <= target <= 109''' class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if len(matrix)==0 or len(matrix[0])==0: return False row = len(matrix)-1 col=0 while row>=0 and col<len(matrix[0]): print(row,col) if target<matrix[row][col]: row-=1 elif target>matrix[row][col]: col+=1 else: return True return False
true
99202f99cbf5b47e4f294c8e0da826f993ac5d3b
Reetishchand/Leetcode-Problems
/00537_ComplexNumberMultiplication_Medium.py
1,240
4.15625
4
'''Given two strings representing two complex numbers. You need to return a string representing their multiplication. Note i2 = -1 according to the definition. Example 1: Input: "1+1i", "1+1i" Output: "0+2i" Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. Example 2: Input: "1+-1i", "1+-1i" Output: "0+-2i" Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. Note: The input strings will not have extra blank. The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.''' class Solution: def complexNumberMultiply(self, a: str, b: str) -> str: n1=a.split("+") n2=b.split("+") print(n1,n2) ans=[0,0] ans[0]=str((int(n1[0])*int(n2[0]))-(int(n1[1].replace("i",""))*int(n2[1].replace("i","")))) ans[1]=str((int(n1[1].replace("i",""))*int(n2[0])) + (int(n2[1].replace("i","")) * int(n1[0])))+"i" print(int(n1[1].replace("i",""))*int(n2[0])) print(int(n2[1].replace("i","")) * int(n2[0])) return '+'.join(ans)
true
68198c760cdb09b8e882088013830389b0b4d19d
Reetishchand/Leetcode-Problems
/00346_MovingAveragefromDataStream_Easy.py
1,289
4.3125
4
'''Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. Implement the MovingAverage class: MovingAverage(int size) Initializes the object with the size of the window size. double next(int val) Returns the moving average of the last size values of the stream. Example 1: Input ["MovingAverage", "next", "next", "next", "next"] [[3], [1], [10], [3], [5]] Output [null, 1.0, 5.5, 4.66667, 6.0] Explanation MovingAverage movingAverage = new MovingAverage(3); movingAverage.next(1); // return 1.0 = 1 / 1 movingAverage.next(10); // return 5.5 = (1 + 10) / 2 movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3 Constraints: 1 <= size <= 1000 -105 <= val <= 105 At most 104 calls will be made to next.''' from collections import deque class MovingAverage: def __init__(self, size: int): """ Initialize your data structure here. """ self.mov=deque([],maxlen=size) def next(self, val: int) -> float: self.mov.append(val) return sum(self.mov)/len(self.mov) # Your MovingAverage object will be instantiated and called as such: # obj = MovingAverage(size) # param_1 = obj.next(val)
true
68f0b89631b89d1098932cd021cf579348d71004
jaipal24/DataStructures
/Linked List/Detect_Loop_in_LinkedList.py
1,388
4.25
4
# Given a linked list, check if the linked list has loop or not. #node class class Node: def __init__(self, data): self.data = data self.next = None # linked list class class LinkedList: def __init__(self): self.head = None def push(self, data): new_node = Node(data) if self.head is None: self.head = new_node else: new_node.next = self.head self.head = new_node def detect_loop(self): s = set() current = self.head while current: if current in s: return True s.add(current) current = current.next return False def print_list(self): val = [] temp = self.head while temp: val.append(str(temp.data)) temp = temp.next return '->'.join(v for v in val) def __str__(self): return self.print_list() if __name__ == "__main__": L_list = LinkedList() L_list.push(1) L_list.push(3) L_list.push(4) L_list.push(5) L_list.push(2) print("Linked list is:", L_list) # creating a loop in the linked list L_list.head.next.next.next.next = L_list.head if L_list.detect_loop(): print("Loop Detected") else: print("No Loop")
true
87f6078f3f99bd3c33f617e2b7b33143fed70369
BonnieBo/Python
/第二章/2.18.py
412
4.125
4
# 计算时间 import time currentTime = time.time() print(currentTime) totalSeconds = int(currentTime) currentSeconds = totalSeconds % 60 totalMinutes = totalSeconds // 60 currentMinute = totalMinutes % 60 totalHours = totalMinutes // 60 currentHours = totalHours % 24 print("Current time is", currentHours, ":", currentMinute, ":", currentSeconds, "GMT") print(time.asctime(time.localtime(time.time())))
true
7b5b3ff7995758cb199808977015ea635a879309
Farazi-Ahmed/python
/lab-version2-6.py
288
4.125
4
# Question 8 Draw the flowchart of a program that takes a number from user and prints the divisors of that number and then how many divisors there were. a=int(input("Number? ")) c=1 d=0 while c<=a: if a%c==0: d+=1 print(c) c+=1 print("Divisors in total: "+str(d))
true
03074b61771fa4e751fd84c97aac21e3a918fa35
Farazi-Ahmed/python
/problem-solved-9.py
326
4.4375
4
# Question 9 : Draw flowchart of a program to find the largest among three different numbers entered by user. x=int(input("Value of x: ")) y=int(input("Value of y: ")) z=int(input("Value of z: ")) if x>y and x>z: print(x) elif y>z and y>x: print(y) else: print(z) MaxValue = max(x,y,z) print(MaxValue)
true
28f739f2ac311a56f42af138f8c3432a4e0620e9
Farazi-Ahmed/python
/problem-solved-7.py
303
4.375
4
# Question 7: Write a flowchart that reads the values for the three sides x, y, and z of a triangle, and then calculates its area. x=int(input("Value of x: ")) y=int(input("Value of y: ")) z=int(input("Value of z: ")) s = (x + y + z) / 2 area = ((s * (s-x)*(s-y)*(s-z)) ** 0.5) print(area)
true
519d04e843b4966f58d0d2ffc1e4a4596ef1ea09
manand2/python_examples
/comprehension.py
2,044
4.40625
4
# list comprehension nums = [1,2,3,4,5,6,7,8,9,10] # I want 'n' for each 'n' in nums my_list = [] for n in nums: my_list.append(n) print my_list #list comprehension instead of for loop my_list = [n for n in nums] print my_list # more complicated example # I want 'n*n' for each 'n' in nums my_list = [n*n for n in nums] print my_list #another way to do this is using maps and lambda # maps pretty much runs through functions #lambda is a function #using map + lambda my_list = map(lambda n: n*n, nums) # you can convert map and lambda to list comprehension as it is more readable #learn map, lambda and filter #I want 'n' for each 'n in nums if 'n' is even my_list = [] for n in nums: if n%2 == 0: my_list.append(n) print my_list # using list comprehension my_list = [n for n in nums if n%2 == 0] print my_list # Using a filter + lambda my_list = filter(lambda n: n%2 == 0, nums) print my_list # more difficult example # I want a letter and number pair for each letter in 'abcd' and each number in '0123' my_list = [(letter,num) for letter in 'abcd' for num in range(4)]] #dictionary and sets comprehension # Dictionary comprehension names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade'] heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool'] # using for loop for name in names: for hero in heros: my_dict[name] = hero print my_dict # using dictionary comprehension my_dict = {name:hero for name, hero in zip(names, heros)} print my_dict #if name is not equal to Peter my_dict = {name:hero for name, hero in zip(names, heros) if name != 'Peter'} print my_dict # set comprehension - similar to list but have unique values nums = [1,1,2,2,3,3,4,4,5,5,6,7,8,9,9] my_set = {n for n in nums} # generators expression # generators expressions are like list comprehension def gen_func(nums): for n in nums: yield n*n my_gen = gen_func(nums) for in my_gen: print i # let us change for loop code to comprehension my_gen = (n*n for in in nums) for i in my_gen: print i
true
37498e70f1550bd468c29f5b649075ce4254978d
chrishaining/python_stats_with_numpy
/arrays.py
384
4.15625
4
import numpy as np #create an array array = np.array([1, 2, 3, 4, 5, 6]) print(array) #find the items that meet a boolean criterion (expect 4, 5, 6) over_fives = array[array > 3] print(over_fives) #for each item in the array, checks whether that item meets a boolean criterion (expect an array of True/False, in this case [False, False, False, True, True, True]) print(array > 3)
true
c0585d2d162e48dd8553ccfc823c3e363a2b28c0
samson027/HacktoberFest_2021
/Python/Bubble Sort.py
416
4.125
4
def bubblesort(array): for i in range(len(array)): for j in range(len(array) - 1): nextIndex = j + 1 if array[j] > array[nextIndex]: smallernum = array[nextIndex] largernum = array[j] array[nextIndex] = largernum array[j] = smallernum return array # a test case print(bubblesort([9, 8, 7, 4, 5, 6, 12, 10, 3]))
true
148418a17af55f181ecea8ffd5140ba367d7dc2d
youngdukk/python_stack
/python_activities/oop_activities/bike.py
974
4.25
4
class Bike(object): def __init__(self, price, max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print("Bike's Price: ${}".format(self.price)) print("Bike's Maximum Speed: {} mph".format(self.max_speed)) print("Total Miles Ridden: {} miles".format(self.miles)) return self def ride(self): self.miles += 10 print("Riding", self.miles) return self def reverse(self): if self.miles < 6: print("Cannot reverse") else: self.miles -= 5 print("Reversing", self.miles) return self instance1 = Bike(200, 25) instance2 = Bike(100, 10) instance3 = Bike(500, 50) print("Bike 1") instance1.ride().ride().ride().reverse().displayInfo() print("Bike 2") instance2.ride().ride().reverse().reverse().displayInfo() print("Bike 3") instance3.reverse().reverse().reverse().displayInfo()
true
52d35b2a21c30e5f35b1193b123f0b59a795fa17
prefrontal/leetcode
/answers-python/0021-MergeSortedLists.py
1,695
4.21875
4
# LeetCode 21 - Merge Sorted Lists # # Merge two sorted linked lists and return it as a new sorted list. The new list should be # made by splicing together the nodes of the first two lists. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 # Determine where we are going to start regarding the output output = None if l1.val < l2.val: output = l1 l1 = l1.next else: output = l2 l2 = l2.next # Now we can start assembling the rest of the output previous_node = output while l1 or l2: # Handle the cases where we have values in one list but not the other if not l1 and l2: previous_node.next = l2 previous_node = l2 l2 = l2.next continue if l1 and not l2: previous_node.next = l1 previous_node = l1 l1 = l1.next continue # Handle the case where we have values in both lists if l1.val < l2.val or l1.val == l2.val: previous_node.next = l1 previous_node = l1 l1 = l1.next else: previous_node.next = l2 previous_node = l2 l2 = l2.next return output # Tests c = ListNode(4, None) b = ListNode(2, c) a = ListNode(1, b) z = ListNode(4, None) y = ListNode(3, z) x = ListNode(1, y) sortedNode = mergeTwoLists(a, x) # Expected output is 1->1->2->3->4->4 while sortedNode: print(sortedNode.val) sortedNode = sortedNode.next
true
b1ff4822be75f8fffb11b8c2af5c64029a27a874
prefrontal/leetcode
/answers-python/0023-MergeKSortedLists.py
2,349
4.125
4
# LeetCode 23 - Merge k sorted lists # # Given an array of linked-lists lists, each linked list is sorted in ascending order. # Merge all the linked-lists into one sort linked-list and return it. # # Constraints: # k == lists.length # 0 <= k <= 10^4 # 0 <= lists[i].length <= 500 # -10^4 <= lists[i][j] <= 10^4 # lists[i] is sorted in ascending order. # The sum of lists[i].length won't exceed 10^4. from typing import List class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Pulled from answer 21, Merge Sorted Lists def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 # Determine where we are going to start regarding the output output = None if l1.val < l2.val: output = l1 l1 = l1.next else: output = l2 l2 = l2.next # Now we can start assembling the rest of the output previous_node = output while l1 or l2: # Handle the cases where we have values in one list but not the other if not l1 and l2: previous_node.next = l2 previous_node = l2 l2 = l2.next continue if l1 and not l2: previous_node.next = l1 previous_node = l1 l1 = l1.next continue # Handle the case where we have values in both lists if l1.val < l2.val or l1.val == l2.val: previous_node.next = l1 previous_node = l1 l1 = l1.next else: previous_node.next = l2 previous_node = l2 l2 = l2.next return output def mergeKLists(lists: List[ListNode]) -> ListNode: if not lists: return None if len(lists) == 1: return lists[0] output = lists[0] for index, node in enumerate(lists): if index == 0: continue output = mergeTwoLists(output, node) return output # Tests c1 = ListNode(5, None) b1 = ListNode(4, c1) a1 = ListNode(1, b1) c2 = ListNode(4, None) b2 = ListNode(3, c2) a2 = ListNode(1, b2) b3 = ListNode(6, None) a3 = ListNode(2, b3) sortedNode = mergeKLists([a1, a2, a3]) # Expected output is 1,1,2,3,4,4,5,6 while sortedNode: print(sortedNode.val) sortedNode = sortedNode.next
true
9348abc87c6ec5318606464dac6e792960a0bc0f
NNHSComputerScience/cp1ForLoopsStringsTuples
/notes/ch4_for_loops_&_sequences_starter.py
1,795
4.78125
5
# For Loops and Sequences Notes # for_loops_&_sequences_starter.py # SEQUENCE = # For example: range(5) is an ordered list of numbers: 0,1,2,3,4 # ELEMENT = # So far we have used range() to make sequences. # Another type of sequence is a _________, # which is a specific order of letters in a sequence. # For example: # ITEREATE = # FOR LOOP = # So, we can iterate through a string using a for loop just like a range: # CHALLENGE #1: Secret Message - Ask the user for a message and then display # the message with each letter displayed twice. # Ex) message = "great" output = "ggrreeaatt" # Quick Question: What would display? # ANSWER: # The len() function: # Used to count the number of elements in a sequence. # Practice: Save your first name to the variable 'name', and then display # how many letters are in your first name. # Practice 2: Now do the same thing for your first and last name. # Be sure to put your first and last in the SAME string. # What did you learn about the len() function? # ANSWER: # CHALLENGE #2: Ask the user for their last name. # Tell the user the number of letters in their last name. # Then, determine if the user's name includes the letter "A" or not. # If they do, display "Awesome, you have an A!" # CHALLENGE #3: Password # Ask the user for a password. It must be at least 6 characters long, # and it must contain a '!' or a '$' sign. If they give a valid password # display "Valid Password", otherwise display "Invalid Password". # Adv. CHALLENGE: Can you use a while loop to keep asking for the password # until the user enters it in the correct format? input("\nPress enter to exit.")
true
f0499de132924504b7d808d467e88af636eb5d27
KindaExists/daily-programmer
/easy/3/3-easy.py
1,057
4.21875
4
""" [easy] challenge #3 Source / Reddit Post - https://www.reddit.com/r/dailyprogrammer/comments/pkw2m/2112012_challenge_3_easy/ """ # This can most likely be done in less than 2 lines # However still haven't figured a way to stop asking "shift" input def encrypt(string, shift): return ''.join([chr((((ord(char) - 97) + shift) % 26) + 97) if char.isalpha() else char for char in string]) # Actually only the encrypt function is technically needed, as it can both do encrypt(+shift) and decrypt(-shift) # However for the sake of simplicity and formality I just seperated the functionalities def decrypt(string, unshift): return ''.join([chr((((ord(char) - 97) - unshift) % 26) + 97) if char.isalpha() else char for char in string]) if __name__ == '__main__': method = input('(e)ncrypt / (d)ecrypt?: ') text_in = input('String to encrypt: ') shift = int(input('Shift by: ')) if method == 'e': print(f'> output: {encrypt(text_in, shift)}') elif method == 'd': print(f'> output: {decrypt(text_in, shift)}')
true
d84ec922db8eeb84c633c868b5c440b5de7f9445
gaogep/LeetCode
/剑指offer/28.二叉树的镜像.py
1,116
4.125
4
# 请完成一个函数,输入一棵二叉树,改函数输出它的镜像 class treeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right root = treeNode(1) root.left = treeNode(2) root.right = treeNode(3) root.left.left = treeNode(4) root.right.right = treeNode(5) def showMirror(root): if not root: return if not root.left and not root.right: return root.left, root.right = root.right, root.left if root.left: showMirror(root.left) if root.right: showMirror(root.right) return root def showMirrorLoop(root): if not root: return queue = [root] while queue: node = queue.pop(0) if node.left: queue.append(node.left) if node.right: queue.append(node.right) node.left, node.right = node.right, node.left return root showMirrorLoop(root) print(root.value) print(root.left.value, " ", end="") print(root.right.value) print(root.left.left.value, " ", end="") print(root.right.right.value)
true
1e18b7a08b74e804774882603eabc30829622571
pchandraprakash/python_practice
/mit_pyt_ex_1.5_user_input.py
686
4.1875
4
""" In this exercise, we will ask the user for his/her first and last name, and date of birth, and print them out formatted. Output: Enter your first name: Chuck Enter your last name: Norris Enter your date of birth: Month? March Day? 10 Year? 1940 Chuck Norris was born on March 10, 1940. """ def userinput(): fn = input("Please enter your first name: ") ln = input("Please enter your last name: ") print("Please enter your date of birth details") month = input("Month?: ") day = input("Day?: ") year = input("Year?: ") print("----------------") print(fn, ln, 'was born on', month, day + ',', year) exit() userinput()
true
1e10d7f86e975ef682821785ebe59bc5e499d219
J-pcy/Jffery_Leetcode_Python
/Medium/418_SentenceScreenFitting.py
2,233
4.28125
4
""" Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen. Note: A word cannot be split into two lines. The order of words in the sentence must remain unchanged. Two consecutive words in a line must be separated by a single space. Total words in the sentence won't exceed 100. Length of each word is greater than 0 and won't exceed 10. 1 ≤ rows, cols ≤ 20,000. Example 1: Input: rows = 2, cols = 8, sentence = ["hello", "world"] Output: 1 Explanation: hello--- world--- The character '-' signifies an empty space on the screen. Example 2: Input: rows = 3, cols = 6, sentence = ["a", "bcd", "e"] Output: 2 Explanation: a-bcd- e-a--- bcd-e- The character '-' signifies an empty space on the screen. Example 3: Input: rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"] Output: 1 Explanation: I-had apple pie-I had-- The character '-' signifies an empty space on the screen. """ class Solution: def wordsTyping(self, sentence, rows, cols): """ :type sentence: List[str] :type rows: int :type cols: int :rtype: int """ se = ' '.join(sentence) + ' ' length = len(se) res = 0 for i in range(rows): res += cols if se[res % length] == ' ': res += 1 else: while res > 0 and se[(res - 1) % length] != ' ': res -= 1 return res // length """ #Time Limit Exceeded se = ' '.join(sentence) + ' ' length = len(se) n = len(sentence) res, idx = 0, 0 for i in range(rows): restCols = cols while restCols > 0: if restCols >= len(sentence[idx]): restCols -= len(sentence[idx]) if restCols > 0: restCols -= 1 idx += 1 if idx >= n: res += 1 + restCols // length restCols %= length idx = 0 else: break return res """
true
c75df56aed95a3e74e0436c54ea4e22e669c395f
J-pcy/Jffery_Leetcode_Python
/Medium/75_SortColors.py
2,518
4.25
4
""" Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. Example: Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2] Follow up: A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. Could you come up with a one-pass algorithm using only constant space? """ class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ """ red = white = blue = 0 for i in range(len(nums)): if nums[i] == 0: red += 1 if nums[i] == 1: white += 1 if nums[i] == 2: blue += 1 for i in range(red): nums[i] = 0 for i in range(red, red + white): nums[i] = 1 for i in range(red + white, red + white + blue): nums[i] = 2 """ """ cnt = [0] * 3 for i in range(len(nums)): cnt[nums[i]] += 1 index = 0 for i in range(3): for j in range(cnt[i]): nums[index] = i index += 1 """ """ red, blue = 0, len(nums) - 1 index = 0 while index <= blue: if nums[index] == 0: nums[red], nums[index] = nums[index], nums[red] red += 1 elif nums[index] == 2: nums[blue], nums[index] = nums[index], nums[blue] index -= 1 blue -= 1 index += 1 """ red = white = blue = -1 for i in range(len(nums)): if nums[i] == 0: red += 1 white += 1 blue += 1 nums[blue] = 2 nums[white] = 1 nums[red] = 0 elif nums[i] == 1: white += 1 blue += 1 nums[blue] = 2 nums[white] = 1 else: blue += 1 nums[blue] = 2
true
2d8491624e72ef82b1a1b7179dbc13bbbacb8ebb
juan-g-bonilla/Data-Structures-Project
/problem_2.py
1,293
4.125
4
import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ if None in (suffix, path) or "" in (suffix, path): return None sol = [] for fil in os.listdir(path): if os.path.isfile(path + "/" + fil): if fil.endswith(suffix): sol.append(path + "/" + fil) else: sol = sol + find_files(suffix, path + "/" + fil) return sol def test_find_files(): assert(find_files(".c", "./testdir_p_2") == ['./testdir_p_2/subdir1/a.c', './testdir_p_2/subdir3/subsubdir1/b.c', './testdir_p_2/subdir5/a.c', './testdir_p_2/t1.c']) assert(find_files(".gitkeep", "./testdir_p_2") == ['./testdir_p_2/subdir2/.gitkeep', './testdir_p_2/subdir4/.gitkeep']) assert(find_files("", "./testdir_p_2") == None) assert(find_files(".c", "") == None) assert(find_files(None, "") == None) if __name__ == "__main__": test_find_files()
true
31b93a072533214b5f1e592442d6072e1a83c01c
texrer/Python
/CIS007/Lab2/BMICalc.py
658
4.40625
4
#Richard Rogers #Python Programming CIS 007 #Lab 2 #Question 4 #Body mass index (BMI) is a measure of health based on weight. #It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters. #Write a program that prompts the user to enter a weight in pounds and height in inches and displays the BMI. #Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. weight_lbs = eval(input("Enter weight in pounds:")) height_inches = eval(input("Enter height in inches:")) weight_kgs = weight_lbs*0.45359237 height_meters = height_inches*0.0254 print("BMI is:", round(weight_kgs/height_meters**2, 4))
true
ffbff41905680bde74a7d42f06d0aa90f55fca25
yingwei1025/credit-card-checksum-validate
/credit.py
1,333
4.125
4
def main(): card = card_input() check = checksum(card) validate(card, check) def card_input(): while True: card_number = input("Card Number: ") if card_number.isnumeric(): break return card_number def checksum(card_number): even_sum = 0 odd_sum = 0 card_number = reversed([int(digit) for digit in card_number]) for i, digit in enumerate(card_number): if (i + 1) % 2 == 0: odd_digit = digit * 2 if odd_digit > 9: odd_sum += int(odd_digit / 10) + odd_digit % 10 else: odd_sum += odd_digit else: even_sum += digit result = even_sum + odd_sum return result def validate(card_number, checksum): # get the first 2 digit card_prefix = int(card_number[0:2]) # get the length of card length = len(card_number) # check the last digit by % 10 last_digit = checksum % 10 if last_digit == 0: if card_prefix in [34, 37] and length == 15: print("AMEX") elif (card_prefix in range(51, 56)) and length == 16: print("MASTERCARD") elif (int(card_number[0]) == 4) and length in [13, 16]: print("VISA") else: print("INVALID") else: print("INVALID") main()
true
66f0ccab7057084061766ca23e21d790e829922b
irmowan/LeetCode
/Python/Binary-Tree-Maximum-Path-Sum.py
1,307
4.15625
4
# Time: O(n) # Space: O(n) # Given a binary tree, find the maximum path sum. # # For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. # # For example: # Given the below binary tree, # # 1 # / \ # 2 3 # Return 6. # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ return self.maxPathSumRecu(root)[0] def maxPathSumRecu(self, root): if root is None: return float("-inf"), float("-inf") left_inner, left_link = self.maxPathSumRecu(root.left) right_inner, right_link = self.maxPathSumRecu(root.right) link = max(left_link, right_link, 0) + root.val inner = max(left_link + root.val + right_link, link, left_inner, right_inner) return inner, link if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) result = Solution().maxPathSum(root) print result
true
9fe261707283f616194ebe30757a6381d500d534
irmowan/LeetCode
/Python/Palindrome-Number.py
1,065
4.125
4
# Time: O(n) # Space: O(1) # # Determine whether an integer is a palindrome. Do this without extra space. # # click to show spoilers. # # Some hints: # Could negative integers be palindromes? (ie, -1) # # If you are thinking of converting the integer to string, note the restriction of using extra space. # # You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? # # There is a more generic way of solving this problem. class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False temp = x y = 0 while (temp > 0): y = y * 10 + temp % 10 temp = temp / 10 if x == y : return True else: return False if __name__ == "__main__": print(Solution().isPalindrome(-13)) print(Solution().isPalindrome(919)) print(Solution().isPalindrome(120))
true
5f8c9db073643da16d88ef03512b4ca6e97d28ca
LinuxUser255/Python_Penetration_Testing
/Python_Review/dmv.py
308
4.125
4
#!/usr/bin/env python3 #If-else using user defined input: print("""Legal driving age. """) age = int(input("What is your age? ")) if age < 16: print("No.") else: if age in range(16, 67): print("Yes, you are eligible.") if age > 66: print("Yes, but with special requirements.")
true
6361f4914c5a1570c9113a55222c139a9844efb2
mihirbhaskar/save-the-pandas-intpython
/filterNearby.py
973
4.125
4
""" File: filterNearby Description: Function to filter the dataframe with matches within a certain distance Next steps: - This function can be generalised, but for now assuming data is in a DF with lat/long columns named 'latitude' and 'longitude' """ import pandas as pd from geopy.distance import distance def filterNearby(point, data, max_dist = 5): # Combing lat and long columns into one column with tuples data['place_coords'] = data[['LATITUDE', 'LONGITUDE']].apply(tuple, axis=1) ## Alternative code for the above - could be faster? ## data['place_coords'] = list(zip(data.latitude, data.longitude)) # Applying the distance function to each row to create new column with distances data['DISTANCE IN MILES'] = data.apply(lambda x: distance(point, x['place_coords']).miles, axis=1) # Return data frame filtered with rows <= the maximum distance return data[data['DISTANCE IN MILES'] <= max_dist]
true
2096aed0b726883d89aae8c3d886ae5ef3b11518
simplex06/HackerRankSolutions
/Lists.py
1,683
4.3125
4
# HackerRank - "Lists" Solution #Consider a list (list = []). You can perform the following commands: # #insert i e: Insert integer at position . #print: Print the list. #remove e: Delete the first occurrence of integer . #append e: Insert integer at the end of the list. #sort: Sort the list. #pop: Pop the last element from the list. #reverse: Reverse the list. #Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list. # # #Input Format # #The first line contains an integer, , denoting the number of commands. #Each line of the subsequent lines contains one of the commands described above. # #Constraints # #The elements added to the list must be integers. #Output Format # #For each command of type print, print the list on a new line. # #Sample Input 0 # #12 #insert 0 5 #insert 1 10 #insert 0 6 #print #remove 6 #append 9 #append 1 #sort #print #pop #reverse #print #Sample Output 0 # #[6, 5, 10] #[1, 5, 9, 10] #[9, 5, 1] if __name__ == '__main__': L = [] N = int(input()) for i in range(0, N): tokens = input().split() if tokens[0] == 'insert': L.insert(int(tokens[1]), int(tokens[2])) elif tokens[0] == 'print': print(L) elif tokens[0] == 'remove': L.remove(int(tokens[1])) elif tokens[0] == 'append': L.append(int(tokens[1])) elif tokens[0] == 'sort': L.sort() elif tokens[0] == 'pop': L.pop() elif tokens[0] == 'reverse': L.reverse()
true
492689343e28be7cdbb2d807514881925534a010
SynTentional/CS-1.2
/Coursework/Frequency-Counting/Frequency-Counter-Starter-Code/HashTable.py
2,156
4.3125
4
from LinkedList import LinkedList class HashTable: def __init__(self, size): self.size = size self.arr = self.create_arr(size) # 1️⃣ TODO: Complete the create_arr method. # Each element of the hash table (arr) is a linked list. # This method creates an array (list) of a given size and populates each of its elements with a LinkedList object. def create_arr(self, size): #instantiation of array arr = [] #uses the size parameter to append one Linked List function call to each index within range for i in range(size): new_ll = LinkedList() arr.append(new_ll) return arr # 2️⃣ TODO: Create your own hash function. # Hash functions are a function that turns each of these keys into an index value that we can use to decide where in our list each key:value pair should be stored. def hash_func(self, key): return (ord(key[0]) - ord('s')) % self.size # 3️⃣ TODO: Complete the insert method. # Should insert a key value pair into the hash table, where the key is the word and the value is a counter for the number of times the word appeared. When inserting a new word in the hash table, be sure to check if there is a Node with the same key in the table already. def insert(self, key, value): #Find the index where the key value should be placed key_index = self.hash_func(key) # range of index value to tell if key is found within array found = self.arr[key_index].find(key) # if key is within array, take the value associated with it and increment it according to frequency of occurance if found == -1: toople = (key, value) self.arr[key_index].append(toople) # inserting the associated tuple into the Linked List # 4️⃣ TODO: Complete the print_key_values method. # Traverse through the every Linked List in the table and print the key value pairs. # For example: # a: 1 # again: 1 # and: 1 # blooms: 1 # erase: 2 def print_key_values(self): if self.size == None: print("empty") return -1 else: for i in self.arr: i.print_nodes()
true
7f7c20e3c655b59fb28d90a5b7fec803d3b65170
MrSmilez2/z25
/lesson3/4.py
272
4.125
4
items = [] max_element = None while True: number = input('> ') if not number: break number = float(number) items.append(number) if not max_element or number >= max_element: max_element = number print(items) print('MAX', max_element)
true
a2ab21a48d07c3fe753681babeb8cfeea023038c
floryken/Ch.05_Looping
/5.2_Roshambo.py
1,632
4.8125
5
''' ROSHAMBO PROGRAM ---------------- Create a program that randomly prints 1, 2, or 3. Expand the program so it randomly prints rock, paper, or scissors using if statements. Don't select from a list. Add to the program so it first asks the user their choice as well as if they want to quit. (It will be easier if you have them enter 1 for rock, 2 for paper, and 3 for scissors.) Add conditional statements to figure out who wins and keep the records When the user quits print a win/loss record ''' import random print("Welcoome to my ROSHAMBO program") user_win=0 computer=0 ties=0 done=False while done==False: user=int(input("What is your choice?(Type in #)\n 1. Rock\n 2. Paper\n 3. Scissors\n 4. Quit")) if user==1: print("You chose Rock") elif user==2: print("You chose Paper") elif user==3: print("You chose Scissors") elif user==4: done==True else: print("Not an answer") number=random.randrange(1,4) if number==user: print("It's a tie!") ties+=1 elif number==1 and user==2: print("User Won!") user_win+=1 elif number==1 and user==3: print("Computer Won!") computer+=1 elif number==2 and user==1: print("Computer Won!") computer += 1 elif number==2 and user==3: print("User Won!") user_win += 1 elif number==3 and user==2: print("Computer Won!") computer += 1 elif number==3 and user==1: print("User Won!") user_win+=1 print("BYE!") print("Your Win/Loss/Tie record was\n",user_win,"/",computer,"/",ties)
true
f95a79a3a2d6c1718efb817cba7c8cb7072ce57f
goateater/SoloLearn-Notes
/SL-Python/Data Types/Dictionaries.py
2,870
4.71875
5
# Dictionaries # Dictionaries are data structures used to map arbitrary keys to values. # Lists can be thought of as dictionaries with integer keys within a certain range. # Dictionaries can be indexed in the same way as lists, using square brackets containing keys. # Each element in a dictionary is represented by a key:value pair. # Example: ages = {"Dave": 24, "Mary": 42, "John": 58} print(ages["Dave"]) print(ages["Mary"]) print() # Trying to index a key that isn't part of the dictionary returns a KeyError. primary = { "red": [255, 0, 0], "green": [0, 255, 0], "blue": [0, 0, 255], } print("Red is" , type(primary["red"])) print() # print(primary["yellow"]) # As you can see, a dictionary can store any types of data as values. # An empty dictionary is defined as {}. # test = { } # print(test[0]) # Only immutable objects can be used as keys to dictionaries. # Immutable objects are those that can't be changed. # So far, the only mutable objects you've come across are lists and dictionaries. # Trying to use a mutable object as a dictionary key causes a TypeError. # This will work good_dict = { 1: "one two three", } print(good_dict[1]) print() # This will not #bad_dict = { # [1, 2, 3]: "one two three", #} #print(bad_dict[1,2,3]) # Dictionary Functions # Just like lists, dictionary keys can be assigned to different values. # However, unlike lists, a new dictionary key can also be assigned a value, not just ones that already exist. squares = {1: 1, 2: 4, 3: "error", 4: 16,} print(squares) squares[8] = 64 squares[3] = 9 print(squares) print() # Something a little tricky # What you've here is hierarchical nested Key-Value mapping passed on to the print function as an argument. #So, you'd start start out first by solving the inner embedded Dictionary mapping call, primes[4], which maps to the value 7. # And then, this 7 is rather a key to the outer Dictionary call, and thus, primes[7] would map to 17. primes = {1: 2, 2: 3, 4: 7, 7:17} print(primes[primes[4]]) print() # To determine whether a key is in a dictionary, you can use in and not in, just as you can for a list. # Example: nums = { 1: "one", 2: "two", 3: "three", } print(1 in nums) print("three" in nums) print(4 not in nums) print() # A useful dictionary method is get. # It does the same thing as indexing, but if the key is not found in the dictionary it returns another specified value instead ('None', by default). pairs = {1: "apple", "orange": [2, 3, 4], True: False, None: "True", } print(pairs.get("orange")) print(pairs.get(7)) print(pairs.get(True)) print(pairs.get(12345, "not in dictionary")) # returns an alternate value instead of the default None, if they key does not exist. print(pairs.get(None)) print() # What is the result of the code below? fib = {1: 1, 2: 1, 3: 2, 4: 3} print(fib.get(4, 0) + fib.get(7, 5))
true
333d2fae7916937db479ee1778ed237c59e6e57d
goateater/SoloLearn-Notes
/SL-Python/Opening Files/writing_files.py
2,703
4.5625
5
# Writing Files # To write to files you use the write method, which writes a string to the file. # For Example: file = open("newfile.txt", "w") file.write("This has been written to a file") file.close() file = open("newfile.txt", "r") print(file.read()) file.close() print() # When a file is opened in write mode, the file's existing content is deleted. file = open("newfile.txt", "r") print("Reading initial contents") print(file.read()) print("Finished") file.close() print() file = open("newfile.txt", "w") file.write("Some new text") file.close() print() file = open("newfile.txt", "r") print("Reading new contents") print(file.read()) print("Finished") file.close() # Try It Yourself # Result: # >>> # Reading initial contents # some initial text # Finished # Reading new contents # Some new text # Finished # >>> print() # The write method returns the number of bytes written to a file, if successful. msg = "Hello world!" file = open("newfile.txt", "w") print(msg) amount_written = file.write(msg) print(type(amount_written)) print(amount_written) file.close() print() file = open("newfile.txt", "r") print(file.read()) file.close() print() # Working with Files # It is good practice to avoid wasting resources by making sure that files are always closed after they have been used. # One way of doing this is to use try and finally. # This ensures that the file is always closed, even if an error occurs. try: f = open("newfile.txt") print(f.read()) finally: f.close() print() # Finally block won't work properly if FileNotFoundError occurred. So... we can make another try~except block in finally: try: f = open("filename.txt") print(f.read()) except FileNotFoundError: f = open("filename.txt", "w") f.write("The file has now been created") f.close() f = open("filename.txt", "r") print(f.read()) f.close() # print("No such file or directory") finally: try: f.close() except: print("Can't close file") # Or we can force our program to open our py file. Like this: try: f = open("filename.txt") print(f.read()) except FileNotFoundError: print("No such file or directory") f = open(__file__, "r") # open itself finally: f.close() # In other cases when we catch FileNotFoundError f.close() makes error too (and program will stop). # An alternative way of doing this is using "with" statements. # This creates a temporary variable (often called f), which is only accessible in the indented block of the with statement. with open("filename.txt") as f: print(f.read()) # The file is automatically closed at the end of the with statement, even if exceptions occur within it.
true
cb63ddf5d873dc45e0f46f0c048b06cf17864c53
virenparmar/TechPyWeek
/core_python/Function/factorial using recursion.py
499
4.28125
4
# Python program to find the factorial of a number using recursion def recur_factorial(n): """Function to return the factorial of a number using recursion""" if n==1: return n else: return n*recur_factorial(n-1) #take input from the user num=int(input("Enter a number=")) #check is the number is negative if num<0: print("Sorry,factorial does not exist for negative numbers") elif num==0: print("The factorial of 0 is 1") else: print("The factorial of",num,"is",recur_factorial(num))
true
830bf963c902c0382c08fca73c71d2fa2f7d1522
virenparmar/TechPyWeek
/core_python/fibonacci sequence.py
479
4.40625
4
#Python program to display the fibonacci sequence up to n-th term where n is provided #take in input from the user num=int(input("How many term?")) no1=0 no2=1 count=2 # check if the number of terms is valid if num<=0: print("please enter a positive integer") elif num == 1: print("fibonacci sequence") print(no1) else: print("fibonacci sequence") print(no1,",",no2,",") while count<num: nth=no1+no2 print(nth,",") #update values no1=no2 no2=nth count+=1
true
4ae8ad04f48d102055e470f4ca953940a8ca1f25
virenparmar/TechPyWeek
/core_python/Function/anonymous(lambda) function.py
299
4.46875
4
#Python Program to display the power of 2 using anonymous function #take number of terms from user terms=int(input("How many terms?")) #use anonymous function result=list(map(lambda x:2 ** x, range(terms))) #display the result for i in range(terms): print "2 raised to power",i,"is",result[i]
true
01ab8ec47c8154a5d90d5ee4bd207f143a0051b3
virenparmar/TechPyWeek
/core_python/Function/display calandar.py
242
4.40625
4
# Python Program to display calender of given month of the year #import module import calendar #assk of month and year yy=int(input("Enter the year=")) mm=int(input("Enter the month=")) #display the calender print(calendar.month(yy,mm))
true
17af5750832fde25c0a10ec49865f478fae390d9
jonathansantilli/SMSSpamFilter
/spamdetector/file_helper.py
973
4.1875
4
from os import path class FileHelper: def exist_path(self, path_to_check:str) -> bool: """ Verify if a path exist on the machine, returns a True in case it exist, otherwise False :param path_to_check: :return: boolean """ return path.exists(path_to_check) def read_pattern_separated_file(self, file_path:str, pattern:str) -> list: """ Read each of a text file and split them using the provided pattern :param file_path: File path to read :param pattern: The pattern used to split each line :return Array: The array that contain the splitted lines """ pattern_separated_lines = [] if file_path and self.exist_path(file_path): with open(file_path, encoding='UTF-8') as f: lines = f.readlines() pattern_separated_lines = [line.strip().split(pattern) for line in lines] return pattern_separated_lines
true
cf5b64089024a35ddd119fc90ae09cc8e404129e
mani-barathi/Python_MiniProjects
/Beginner_Projects/Number_guessing_game/game.py
926
4.25
4
from random import randint def generateRandomNumber(): no = randint(1,21) return no print('Number Guessing Game!') print("1. Computer will generate a number from 1 to 20") print("2. You have to guess it with in 3 guess") choice = input("Do you want to play?(yes/no): ") if choice.lower() == 'yes': while True: number = generateRandomNumber() chances = 3 found = False while chances>=1: guess = int(input("\nMake a guess: ")) if guess == number: print(f'Yes your guess was correct, it was {guess}') found = True break elif number > guess: print("It's bigger than your guess!") else: print("It's smaller than your guess") chances -=1 if found == False: print(f"\nYour chances got over, the number was {number}") choice = input("\nDo you want to continue playing?(yes/no): ") if choice.lower() == 'no': break print("Thank you...Bye") else: print("Thank you")
true
fc67206793cd483acdbb305f621ab33b8ad63083
rsp-esl/python_examples_learning
/example_set-1/script_ex-1_27.py
1,088
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## # Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB) # Date: 2017-11-17 ############################################################################## from __future__ import print_function # for Python 2.6 or higher ## Data structures, Lists numbers = [0,-1,2,-2,1,-3,3] # create a list of int numbers = sorted( numbers ) # sort the list print (numbers) # show the numbers in the (sorted) list # output: [-3, -2, -1, 0, 1, 2, 3] # create a list of positive numbers from a list positives = [ n for n in numbers if (n > 0) ] print (positives) # output: [1, 2, 3] # create a list of negative numbers from a list negatives = [ n for n in numbers if (n < 0) ] print (negatives) # output: [-3, -2, -1] squares = [ i*i for i in numbers ] print (squares) print (sum(squares)) # output: [9, 4, 1, 0, 1, 4, 9] # output: 28 ##############################################################################
true
ffc5c4eb524cd11e8e452e0e75c50b6ac0933e2b
rsp-esl/python_examples_learning
/example_set-3/script_ex-3_6.py
2,966
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## # Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB) # Date: 2017-11-17 ############################################################################## from __future__ import print_function # for Python 2.6 or higher import threading, time # define the MyThread class as a subclass of threading.Thread class MyThread(threading.Thread): def __init__(self, id, lock): # constructor # call the constructor of its superclass threading.Thread.__init__(self) self.id = id # set thread ID self.lock = lock # set the mutex lock def run(self): # override the run method() of its superclass for i in range(10): # repeat for 10 times with self.lock: # access to the mutex lock print ('[Thread id=%d (%d)]' % (self.id, i)) time.sleep(0.5) # sleep for 0.5 seconds if __name__ == '__main__': # test code lock = threading.Lock() # create a mutex lock threads = [] # create an empty list num_threads = 5 # number of threads to be created for i in range(num_threads): # create a new thread object threads.append( MyThread(i,lock) ); for t in threads: # for each thread in the list # invoke the run() method of this thread t.start() for t in threads: # for each thread in the list # the main thread must wait until this thread exits. t.join() print ('Done...') # Sample output: # # [Thread id=0 (0)] # [Thread id=1 (0)] # [Thread id=2 (0)] # [Thread id=3 (0)] # [Thread id=4 (0)] # [Thread id=1 (1)] # [Thread id=2 (1)] # [Thread id=0 (1)] # [Thread id=3 (1)] # [Thread id=4 (1)] # [Thread id=2 (2)] # [Thread id=3 (2)] # [Thread id=1 (2)] # [Thread id=0 (2)] # [Thread id=4 (2)] # [Thread id=2 (3)] # [Thread id=0 (3)] # [Thread id=3 (3)] # [Thread id=1 (3)] # [Thread id=4 (3)] # [Thread id=2 (4)] # [Thread id=0 (4)] # [Thread id=3 (4)] # [Thread id=1 (4)] # [Thread id=4 (4)] # [Thread id=2 (5)] # [Thread id=0 (5)] # [Thread id=3 (5)] # [Thread id=4 (5)] # [Thread id=1 (5)] # [Thread id=1 (6)] # [Thread id=0 (6)] # [Thread id=3 (6)] # [Thread id=2 (6)] # [Thread id=4 (6)] # [Thread id=4 (7)] # [Thread id=1 (7)] # [Thread id=0 (7)] # [Thread id=3 (7)] # [Thread id=2 (7)] # [Thread id=0 (8)] # [Thread id=1 (8)] # [Thread id=3 (8)] # [Thread id=2 (8)] # [Thread id=4 (8)] # [Thread id=0 (9)] # [Thread id=3 (9)] # [Thread id=1 (9)] # [Thread id=4 (9)] # [Thread id=2 (9)] # Done... ##############################################################################
true
091be1a39775ef12d7eacc6b90c2ab563fddb340
rsp-esl/python_examples_learning
/example_set-1/script_ex-1_34.py
1,238
4.4375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## # Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB) # Date: 2017-11-17 ############################################################################## from __future__ import print_function # for Python 2.6 or higher ## Data structures, Lists, Tuples num_list = [3,4,5] # create a list of integers num_tuple = (0,1,2) # creaet a tuple of integers num_tuple += tuple( num_list ) # convert to tuple and append to a tuple print (num_tuple) # output: (0,1,2,3,4,5) str = "10, 20, 30, 40" tup = tuple( int(i) for i in str.split(',') ) # convert str to tuple print (tup) # output: (10, 20, 30, 40) tup = (10,20,30,40) total = sum( x for x in tup ) # sum all elements of a tuple of integers print ('total = ', total) # output: total= 100 tup = ('a','b','c','d') # create a tuple of strings s = ','.join( x for x in tup) # join all elements of a tuple into a string print (s) # output: a,b,c,d ##############################################################################
true
7f2111375c9fde24f8e238a901f59fd2b338c4b1
theymightbepotatoesafter/School-Work
/CIS 210/p11_quiz_christian_carter.py
2,320
4.3125
4
''' Prior programming experience quiz. CIS 210 Project 1-1 Hello-Quiz Solution Author: Christian Carter Credits: N/A Add docstrings to Python functions that implement quiz 1 pseudocode. (See p11_cricket.py for examples of functions with docstrings.) ''' def q1(onTime, absent): ''' (bool, bool) -> string User inputs boolean values and function returns a tailored message >>>q1(False, False) Better late than never. >>>q1(True, False) Hello! ''' if onTime: return('Hello!') elif absent: return('Is anyone there?') else: return('Better late than never.') def q2(age, salary): ''' (int, int) -> bool User inputs age and salary and function returns bool based on the set values >>> q2(13, 1000) True >>> q2(27, 10000) False >>> q2(27, 10001) False ''' return (age < 18) and (salary < 10000) def q3(): ''' (none) -> int No input and will return a 6 >>> q3() 6 ''' p = 1 q = 2 result = 4 if p < q: if q > 4: result = 5 else: result = 6 return result def q4(balance, deposit): ''' (int/float, int/float) -> (int/float) User inputs balance and deposit and is returned the balance plus ten times the deposit >>> q4(300, 20) 500 >>> q4(300, 20.0) 500.0 ''' count = 0 while count < 10: balance = balance + deposit count += 1 return balance def q5(nums): ''' docstring - (list of numbers) -> int User inputs list of number and is returned the number of numbers in the list that are greater or equal to 0 >>> q5([0, 1, 2, 3, 4, 5]) #examples are given 6 >>> q5([0, -1, 2, -3, 4, -5]) 3 ''' result = 0 i = 0 while i < len(nums): if nums[i] >= 0: result += 1 i += 1 return result def q6(): ''' (none) -> int No user input and won't return anything >>> q6() ''' i = 0 p = 1 while i < 4: i = 1 #This is making the while loop infinite. If this was removed then the returned value would be 16 p = p * 2 i += 1 return p
true
c42d57a4c634bae031e0dc1085cf88e95f1464d3
tartlet/CS303E
/DaysInMonth.py
1,512
4.40625
4
# File: DaysInMonth.py # Student: Jingsi Zhou # UT EID: jz24729 # Course Name: CS303E # Unique Number: 50695 # # Date Created: 09/25/2020 # Date Last Modified: 09/25/2020 # Description of Program: User inputs a month and year in integer form and program # outputs how many days the month has for any given year. Intended for use with the modern # calendar but also accepts obscure numbers for the year. month = eval(input("Enter a month of the year as an integer from 1-12: ")) #display error message if month input is not in the valid range if month > 12 or month < 1: print("Please input an integer from 1-12... ;A;") exit() year = eval(input("Enter a year: ")) if month == 4: days = 30 elif month == 6: days = 30 elif month == 9: days = 30 elif month == 11: days = 30 else: days = 31 if month == 1: month = "January" elif month == 2: month = "February" #looked up how to find if year is leap year if (year % 4 == 0 and year % 100 != 0) or (year % 4 == 0 and year % 100 == 0 and year % 400 == 0): days = 29 else: days = 28 elif month == 3: month = "March" elif month == 4: month = "April" elif month == 5: month = "May" elif month == 6: month = "June" elif month == 7: month = "July" elif month == 8: month = "August" elif month == 9: month = "September" elif month == 10: month = "October" elif month == 11: month = "November" else: month = "December" print(month, year, "has", days, "days")
true
6275743572e4abdd7c0a00d5852bb8b58cb4bd8f
anirudhn18/msba-python
/Lab5/Lab5_Ex1.py
988
4.3125
4
class Point: """ Represents a point in 2D space """ def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __str__(self): return '({},{})'.format(self.x,self.y) class Rectangle: """Represents a rectangle. attributes: width, height, corner.""" # def __init__(self,width=0.0,height=0.0,corner=Point()): def __init__(self,width=20.0,height=10.0,corner=Point()): self.width = width self.height = height self.corner = corner def find_center(self): center = Point() center.x = self.corner.x + self.width/2.0 center.y = self.corner.y + self.height/2.0 return center def __str__(self): return '{:.1f} by {:.1f}, corner is {:s}'.format(self.width,self.height,self.corner) a_box = Rectangle(100.0,200.0) #Start print a_box #Next another_rect = Rectangle() print another_rect #Finally third_rect = Rectangle(30,30,Point(5,5)) print third_rect
true
a72254ff8fee355dd7d06d31f9a3e30457704777
tdhawale/Python_Practise
/Swap.py
1,871
4.59375
5
# One method to swap variable is using another variabl print("--------------------------------------------------------") print("Using the conventional method for swap") a = 5 b = 6 print("The value of a before swap is :", a) print("The value of b before swap is :", b) temp = a a = b b = temp print("The value of a after swap is :", a) print("The value of b after swap is :", b) print("--------------------------------------------------------") print("Swapping without using extra variable") a = 5 # 101 value in binary b = 6 # 110 value in binary print("The value of a before swap is :", a) print("The value of b before swap is :", b) a = a + b # the addition is 11 which will require extra bits 1011 b = a - b a = a - b print("The value of a after swap is :", a) print("The value of b after swap is :", b) print("--------------------------------------------------------") print("Swapping without using extra variable and without wasting extra bits") a = 5 b = 6 print("The value of a before swap is :", a) print("The value of b before swap is :", b) a = a ^ b # we are using XOR here b = a ^ b a = a ^ b print("The value of a after swap is :", a) print("The value of b after swap is :", b) print("--------------------------------------------------------") print("Swapping without using ROT_TWO(Swaps the top most stack items)") a = 5 b = 6 print("The value of a before swap is :", a) print("The value of b before swap is :", b) a, b = b, a # this works only if it written in the same line # the values will be assigned from right to left . i.t right hand side will be solved first # b(top of stack) will be assigned the value of a(top of stack) # a(top of stack) will be assigned the value of b(top of stack) # to get more information on this search for ROT_TWO() in python print("The value of a after swap is :", a) print("The value of b after swap is :", b)
true
2fae6de3cc45cae76936c8253f9951cfad720848
tinadotmoardots/learning
/python/RPSv3.py
1,223
4.375
4
# This is a version of rock, paper, scissors that you can plan against a computer opponent import random player_wins = 0 computer_wins = 0 print("Rock...") print("Paper...") print("Scissors...") while player_wins < 2 and computer_wins < 2: print(f"Player Score: {player_wins} Computer Score: {computer_wins}") player = input("Make your move: ") if player == "quit" or player == "q": break rand_num = random.randint(0,2) if rand_num == 0: computer = "rock" elif rand_num == 1: computer = "paper" else: computer = "scissors" p = "You win!" t = "It's a tie!" c = "Computer wins!" if player == computer: print(t) elif player == "rock": if computer == "scissors": print(p) player_wins += 1 elif computer == "paper": print(c) computer_wins += 1 elif player == "paper": if computer == "rock": print(p) player_wins += 1 elif computer == "scissors": print(c) computer_wins += 1 elif player == "scissors": if computer == "rock": print(c) computer_wins += 1 elif computer == "paper": print(p) player_wins += 1 else: print("Something went wrong") print("Thanks for playing!") print(f"Final score: Player {player_wins} Computer: {computer_wins}")
true
fe065712a5b6500d9b9a8dc88ce1b7910a3990a6
Jacob-Bankston/DigitalCrafts-Assignments
/Week1/Week1-Tuesday-Assignments/add-two-numbers.py
876
4.34375
4
#Defining a function to add two numbers together from user input def add_numbers(input_1, input_2): total = input_1 + input_2 return print(f"Your two numbers added together are: {total}") #Seeking user input for the add_numbers function while 1: try: #Checking for integer input on the first number's input first_number = input("Give me your first number to add: ") first_number = int(first_number) break except ValueError: print("Please enter an integer instead!") while 1: try: #Checking for integer input on the second number's input second_number = input("Give me your second number to add: ") second_number = int(second_number) break except ValueError: print("Please enter an integer instead!") #Calling the function to check the integers add_numbers(first_number, second_number)
true
bff9e6911ee84b2424d298daa4ded0fd29e417f7
acrane1995/projects
/Module 1/absolute beginners.py
2,855
4.15625
4
#my_num = 123 #num_intro = "My number is " + str(my_num) #print(num_intro) #total_cost = 3 + 45 #print(total_cost) #45 was represented as a string and therefore could not be executed #school_num = 123 #print("the street number of Central School is " + str(school_num)) #school_num is an int and needed to be converted to a string to execute #print(type(3.3)) #print(type(3)) #print(3.3 + 3) #executes with no problems and result will always be a float unless converted back to an int #ERRORS #print('my socks do not match") #and neither do your quotation marks #print("my socks do not match") #pront("my socks match now") #but print is misspelled #print("my socks match now") #print"Save the notebook frequently #first parentheses is missing #print("Save the notebook frequently") #student_name = "Alton" #print(STUDENT_NAME) #recalling the variable incorrectly... either capitalize the variable or lower case the recall #print(student_name) #total = 3 #print(total + " students are signed up for tutoring") #total is an int and must be converted to a string #print(str(total) + " students are signed up for tutoring") #ASCII ART #print(" *") #print(" * *") #print(" *****") #print(" * *") #print(" * *") #print() #print("_ _") #rint(" \ /") #print(" \ . . /") #print(" V") #print() #print("eeeeeee") #print("e") #print("eeee") #print("e") #print("eeeeeee") #print() #INPUTS #print("enter a small integer") #small_int = input() #print("Small int: ") #print(small_int) #student_name = input("Enter the student name: ") #print("Hi " + student_name) #type(student_name) #city_name = input("What is the name of your city? ") #print("The city name is " + city_name + "!") #name = input("Name: ") #age = input("Age: ") #email = input("Receive Emails? Yes/No? ") #print("Name = " + name) #print("Age = " + age) #print("Wants email = " + email) #FORMATTED PRINT #name = "Colette" #print("Hello " + name + "!") #print("Hello",name,"how are you?") #print("I will pick you up @", 6,"for the party!") #number_errors = 0 #print("An integer of", 14, "combined with strings causes",number_errors,"TypeErrors in comma formatted print!") #print("I am",24,"years old in the year",2020,".") #st_name = input("Enter street name: ") #st_num = int(input("Enter house number: ")) #print("You live at",st_num,st_name) #min_early = 15 #owner = input("Name for reservation: ") #num_people = input("Number of people attending: ") #training_time = input("Training session start time: ") #print(owner,"your training for",num_people,"people is set to begin @",training_time,"please arrive",min_early,"minutes prior. Thank you!") #"Hello".isalpha() #length = "33" #length.isalnum() #name = "skye homsi" #name_1 = name.title() #name_2 = name_1.swapcase() #print(name_2) #name = "SKYE HOMSI" #print("y" in name.lower())
true
b36975217050a1e3a8af54e7e7a4d1d0e7ae3e1a
divyansh1235/Beta-Algo
/python/tree/PostorderTraversal.py
2,087
4.375
4
#POSTORDER BINARY TREE TRAVERSAL # In this algorithm we print the value of the nodes present in the binary tree in postorder # fashion. # Here we first traverse the left subtree and then traverse the right subtree and finally we # print the root # The sequence is as follows - # Left->Right->Root class node (): #node class def __init__(self,val): #constructor that takes the node value as parameter self.left=None self.right=None self.val=val class Tree(): # Tree class def __init__(self): self.root=None def buildtree(self): #method to take the nodes of the trees as input root=int(input()) if root==-1: return root=node(root) left=self.buildtree() #building the left subtree right=self.buildtree() #building the right subtree root.left=left #Assigning the left and the right subtree to the root root.right=right return root def postorder(self,root): #postorder traversal method if root is None: #in case the root is empty we return from there return self.postorder(root.left) self.postorder(root.right) print(root.val) # Starting with the main code def main(): tree=Tree() #creating the Tree object print("Enter the values of the tree :") tree.root=tree.buildtree() #buiding the tree print("The order of the elements in postorder fashion is given as :") tree.postorder(tree.root) main() """ EXAMPLE TEST CASES 1 1) / \ 2 3 Enter the values ot the tree : 1 2 -1 -1 3 -1 -1 The order of the elements in postorder fashion is given as : 2 3 1 2) 1 / \ 2 3 / \ \ 4 5 6 Enter the values of the tree : 1 2 4 -1 -1 5 -1 -1 3 -1 6 -1 -1 The order of the elements in postorder fashion is given as : 4 5 2 6 3 1 Time Complexity: O(n) Space Complexity: O(1) or O(h) if size of stack of function calls is considered Here, h is the height of the tree """
true
41c9233b4165f4da13629a007e24dfbc248cff9d
jasonluocesc/CS_E3190
/P4/shortest_cycle/solution.py
1,791
4.34375
4
# coding: utf-8 def get_length_of_shortest_cycle(g): """Find the length of the shortest cycle in the graph if a cycle exists. To run doctests: python -m doctest -v solution.py >>> from networkx import Graph >>> get_length_of_shortest_cycle(Graph({1: [2, 3], 2: [], 3: []})) >>> get_length_of_shortest_cycle(Graph({1: [3], 2: [1], 3: [2]})) 3 Parameters ---------- g : Graph Returns ------- length : int or None Length of the shortest cycle, or None if there is no cycle. """ # Write your code here. # Hint! If you'd like to test out these commands without # writing a full-fledged program, you might want to familiarise # yourself with the Python interactive shell or IPython (available # on at least some Aalto IT computers) # Create a simple line graph g: "(1)->(2)->(3)" # (The creation parameter is a dict of {node: list_of_neighbors}, # but this is not something you will be needing in your code.) # >>> from networkx import Graph # >>> g = Graph({1: [2], 2: [3]}) # >>> g.number_of_nodes() # 3 # Example. Iterate over the nodes and mark them as visited # >>> visited = set() # >>> for node in g.nodes_iter(): # There is also g.nodes(), which returns a list # ... # do some work here # ... visited.add(node) # Example. Given a Node v, get all nodes s.t. there is an edge between # v and that node # >>> g.neighbors(1) # [2] # Example. Get the edges of the graph: # >>> e.edges() # as with nodes, there is also g.edges_iter() # [(1, 2), (2, 3)] # For more information, consult the NetworkX documentation: # https://networkx.github.io/documentation/networkx-1.10/tutorial/tutorial.html
true
aca7b1cf5d55a62b67f6156c9b633b7bc811e1ab
hansrajdeshpande18/geeksforgeeksorg-repo
/printreverse.py
206
4.28125
4
#Print first and last name in reverse order with a space between them firstname = (input("Enter your first name:")) lastname = (input("Enter your last name:")) print("Hello " +lastname + " " +firstname)
true
839102579223d22c81a0f54a816f585f7c70262e
skrall3119/prg105
/MyProject/Practice 9.1.py
2,704
4.5625
5
import pickle def add(dic): # adds a new entry to the dictionary name = input('Enter the name you wish to add: ') email = input('Enter the email you wish to associate with this name: ') dic[name] = email print(dictionary) def remove(dic): # removes the entry of the dictionary name = input('Enter the name of the person you want removed from your emails: ') del dic[name] print(dictionary) def change(dic): # allows the user to change the name or email when specified. option = input('Do you want to change the name or the email?: ').lower() if option == 'name': name = input('Enter the name you want to change: ') if name not in dic: name = input("That name is not in the list, please enter a name in the list. or use the 'add' command to add a \ new email address\n") while name not in dic: name = input('Enter the name you want to change: ') new_name = input('Enter the new name: ') dic[new_name] = dic[name] del dic[name] print('\n') print(dic) elif option == 'email': name = input('Enter the name of the persons email you want to change: ') if name not in dic: name = input('That name is not in the list, please enter a name in the list, or use the add command to add \ a new name and email combo.: ') new_email = input('Enter the new email address: ') dic[name] = new_email print('\n') print(dic) def show_dic(dic): # prints the dictionary print(dic) # beginning of main code. opens the file if it exists or creates a new one otherwise. try: dictionary = pickle.load(open('save.p', 'rb')) except EOFError: dictionary = {} print(dictionary) commands = 'List of commands: ' + '\n' + 'add' + '\n' + 'remove' + '\n' 'print' + '\n' + 'quit' + '\n' + 'save' + '\n' print(commands) user = input("Enter a command: ").lower() while user != 'quit': if user == 'add': add(dictionary) user = input('Enter a command: ') elif user == 'remove': remove(dictionary) user = input('Enter a command: ') elif user == 'change': change(dictionary) user = input('Enter a command: ') elif user == 'print': print(dictionary) user = input('Enter a command: ') elif user == 'save': pickle.dump(dictionary, open('save.p', 'wb')) print('Progress saved!') user = input('Enter a command: ') else: print('Invalid command.' + '\n' + commands) user = input('Enter a command:') else: pickle.dump(dictionary, open('save.p', 'wb'))
true