blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
deb7b21d9a08444b3681c1fce4ce1f82e38a6192
kelpasa/Code_Wars_Python
/6 кю/Selective Array Reversing.py
893
4.46875
4
''' Given an array, return the reversed version of the array (a different kind of reverse though), you reverse portions of the array, you'll be given a length argument which represents the length of each portion you are to reverse. E.g selReverse([1,2,3,4,5,6], 2) //=> [2,1, 4,3, 6,5] if after reversing some portions of the array and the length of the remaining portion in the array is not up to the length argument, just reverse them. selReverse([2,4,6,8,10,12,14,16], 3) //=> [6,4,2, 12,10,8, 16,14] selReverse(array, length) array - array to reverse length - length of each portion to reverse Note : if the length argument exceeds the array length, reverse all of them, if the length argument is zero do not reverse at all. ''' def sel_reverse(arr,n): if n == 0: return arr else: return sum([i[::-1] for i in [arr[i:i+n] for i in range(0, len(arr), n)]],[])
true
2b6315a9c117156389761fb6d25ec1d375ed9d1b
kelpasa/Code_Wars_Python
/5 кю/Human Readable Time.py
690
4.15625
4
''' Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS) HH = hours, padded to 2 digits, range: 00 - 99 MM = minutes, padded to 2 digits, range: 00 - 59 SS = seconds, padded to 2 digits, range: 00 - 59 The maximum time never exceeds 359999 (99:59:59) You can find some examples in the test fixtures. ''' def make_readable(seconds): H = seconds // 3600 M = (seconds-H*3600) // 60 S = ((seconds-H*3600)+(seconds-M*60))-seconds if len(str(H)) == 1: H = '0'+str(H) if len(str(M)) == 1: M = '0'+str(M) if len(str(S)) == 1: S = '0'+str(S) return f"{H}:{M}:{S}"
true
f67afbb5da9f57dd033101e6b219a495e466b392
kelpasa/Code_Wars_Python
/6 кю/Duplicate Arguments.py
584
4.25
4
''' Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function. The array values passed in will only be strings or numbers. The only valid return values are true and false. Examples: solution(1, 2, 3) --> false solution(1, 2, 3, 2) --> true solution('1', '2', '3', '2') --> true ''' def solution(*args): arr = [] for i in args: if i not in arr: arr.append(i) if tuple(arr) == args: return False else: return True
true
421b1232a36a6718cce0560efee1260a906f84fb
miguel-nascimento/coding-challenges-stuffs
/project-euler/004 - Largest palindrome product.py
375
4.1875
4
# Find the largest palindrome made from the product of two 3-digit numbers. # A palindromic number reads the same both ways def three_digits_palindome(): answer = max(i * j for i in range(100, 1000) for j in range(100, 1000) if str(i * j) == str(i * j)[:: -1]) return str(answer) print(three_digits_palindome())
true
50e6dc86d6a2dcec1df9cac643815c3e9c3a7f06
ArnoBali/python-onsite
/week_01/03_basics_variables/08_trip_cost.py
402
4.46875
4
''' Receive the following arguments from the user: - miles to drive - MPG of the car - Price per gallon of fuel Display the cost of the trip in the console. ''' miles = int(input("please input miles to drive:" )) mpg = int(input("please input MPG of the car:" )) p_gallon = int(input("please input Price per gallon of fuel:" )) cost_trip = (miles / mpg) * p_gallon print(cost_trip) _
true
1bdcfa5db635cbba8f5f54f3d651187ee1865810
ArnoBali/python-onsite
/week_02/07_conditionals_loops/Exercise_05.py
532
4.375
4
''' Take two numbers from the user, an upper and lower bound. Using a loop, calculate the sum of numbers from the lower bound to the upper bound. Also, calculate the average of numbers. Print the results to the console. For example, if a user enters 1 and 100, the output should be: The sum is: 5050 The average is: 50.5 ''' input1 = 1 + int(input("Upper bound: ")) input2 = int(input("Lower bound: ")) sum = 0 for i in range(input2, input1): sum += i print(sum) average = sum / (input1 - input2) print(average)
true
d2dd93a12035f03644a19898b5e8356a16320a02
ArnoBali/python-onsite
/week_02/07_conditionals_loops/Exercise_01.py
382
4.5625
5
''' Write a program that gets a number between 1 and 1,000,000,000 from the user and determines whether it is odd or even using an if statement. Print the result. NOTE: We will be using the input() function. This is demonstrated below. ''' input_ = int(input("Please input a number between 1 - 1,000,000,000: ")) if input_ % 2 == 0: print("Even") else: print("Uneven")
true
c3eafe4b5b245cf0ad6e77460780af570a92560c
chandrakant100/Assignments_Python
/Practical/assignment4/factorial.py
246
4.28125
4
# To find factorial of a number using recursion def rec_fact(num): if num <= 1: return 1 return num * rec_fact(num - 1) num = int(input("Enter a number: ")) print("Factorial of {0} is {1}".format(num, rec_fact(num)))
true
349d17c98133a3970fe6f20f369a802ab59d8c3b
govindarajanv/python
/programming-practice-solutions/exercises-set-1/exercise-01-solution.py
968
4.21875
4
#1 printing "Hello World" print ("Hello World") #Displaying Python's list of keywords import keyword print ("List of key words are ..") print (keyword.kwlist) #2 Single and multi line comments # This is the single line comment ''' This is multiline comment, can be used for a paragraph ''' #3 Multi line statements sum = 1+\ 2+\ 3\ print ("sum = ",sum) #4 mutiple assignments a,b,c = 1, 2.0, "govindarajanv" print ("a = ",a) print ("b = ",b) print ("c = ",c) print ("Multiple statements in a line") #5 multiple statements in a line a = 3; b=4; c = 5 print ("a = ",a) print ("b = ",b) print ("c = ",c) #print 1,2,3,4 with sep as '|' and end character as '&' default is \n print (1,2,3,4) print (1,2,3,4,sep='|',end='&') print ("") print ("a",1,"b",2,sep='+',end='=') #Read input from the user and greet him print ("Now let us greet and meet") name = input ("I am Python. May I know your name?") print ("Hi", name,"!. Glad to meet you!!!")
true
4f5ad33e6485de134980f5523cb21c41b51bfb99
govindarajanv/python
/gui-applications/if-else.py
338
4.15625
4
# number = 23 # input() is used to get input from the user guess = int(input('Enter an integer : ')) if guess == number: print('Congratulations, you guessed it.') # New block starts here elif guess < number: print('No, it is a little higher than that') # Another block else: print('No, it is a little lower than that')
true
6658ab77e9521efd122e1348c1860401d6b7abda
govindarajanv/python
/regex/regex-special-sequences.py
1,679
4.34375
4
import re pattern = r"(.+) \1" print ("pattern is",pattern) match = re.match(pattern, "word word") if match: print ("Match 1") match = re.match(pattern, "?! ?!") if match: print ("Match 2") match = re.match(pattern, "abc cde") if match: print ("Match 3") match = re.match(pattern, "abc ab") if match: print ("Match 4") match = re.match(pattern, "abc abcd") if match: print ("Match 5") # \d, \s, and \w match digits, whitespace, and word characters respectively. # In ASCII mode they are equivalent to [0-9], [ \t\n\r\f\v], and [a-zA-Z0-9_]. # Versions of these special sequences with upper case letters - \D, \S, and \W - mean the opposite to the lower-case versions. # For instance, \D matches anything that isn't a digit #(\D+\d) matches one or more non-digits followed by a digit. pattern = r"(\D+\d)" print ("pattern is",pattern) match = re.match(pattern, "Hi 999!") if match: print("Match 1") match = re.match(pattern, "1, 23, 456!") if match: print("Match 2") match = re.match(pattern, " ! $?") if match: print("Match 3") # The sequences \A and \Z match the beginning and end of a string, respectively. # The sequence \b matches the empty string between \w and \W characters, or \w characters and the beginning or end of the string. Informally, it represents the boundary between words. # The sequence \B matches the empty string anywhere else. pattern = r"\b(cat)\b" print ("pattern is",pattern) match = re.search(pattern, "The cat sat!") if match: print ("Match 1") match = re.search(pattern, "We s>cat<tered?") if match: print ("Match 2") match = re.search(pattern, "We scattered.") if match: print ("Match 3")
true
170ffd1a881e4043e7e9be7d70841c5652443d9d
govindarajanv/python
/regex/regex.py
1,061
4.125
4
import re # Methods like match, search, finall and sub pattern = r"spam" print ("\nFinding \'spam\' in \'eggspamsausagespam\'\n") print ("Usage of match - exact match as it looks at the beginning of the string") if re.match(pattern, "eggspamsausagespam"): print("Match") else: print("No match") print ("\nUsage of search - search a given substring in a string and returns the resuult in boolean") if re.search(pattern, "eggspamsausagespam"): print("Match") else: print("No match") print ("\nUsage of findall - returns list of substrings matching the pattern") print(re.findall(pattern, "eggspamsausagespam")) print ("\nFinding \'pam\' in \'eggspamsausages\'\n") pattern1 = r"pam" match = re.search(pattern1, "eggspamsausages") if match: # returns string matched print(match.group()) print(match.start()) print(match.end()) # positions as tuples print(match.span()) str = "My name is David. Hi David." print ("old string:",str) pattern = r"David" newstr = re.sub(pattern, "John", str) print ("new string:",newstr)
true
8638bd18648d6ed7aceaffd6c842e42a0cad680b
govindarajanv/python
/functional-programming/loops/fibonacci.py
539
4.1875
4
""" 0,1,1,2,3,5,8,13...n """ def factorial(n): first_value = 0 second_value = 1 for i in range(1,n,1): if i == 1: print ("{} ".format(first_value)) elif i==2: print ("{} ".format(second_value)) else: sum = first_value + second_value print ("{} ".format(sum)) first_value = second_value second_value = sum n=int(input("Enter the number of terms:")) if n <= 0: print ("Enter any number greater than zero") else: factorial(n)
true
04db43932905662ea741f34a135cd9097941e469
govindarajanv/python
/regex/regex-character-classes.py
1,794
4.6875
5
import re #Character classes provide a way to match only one of a specific set of characters. #A character class is created by putting the characters it matches inside square brackets pattern = r"[aeiou]" if re.search(pattern, "grey"): print("Match 1") if re.search(pattern, "qwertyuiop"): print("Match 2") if re.search(pattern, "rhythm myths"): print("Match 3") pattern = r"[abc][def]" if re.search(pattern, "ad"): print("Match found for ad") if re.search(pattern, "ae"): print("Match found for ae") if re.search(pattern, "ea"): print("Match found for ea") #Character classes can also match ranges of characters. """ The class [a-z] matches any lowercase alphabetic character. The class [G-P] matches any uppercase character from G to P. The class [0-9] matches any digit. Multiple ranges can be included in one class. For example, [A-Za-z] matches a letter of any case """ pattern = r"[A-Z][A-Z][0-9]" if re.search(pattern, "LS8"): print("Match 1") if re.search(pattern, "E3"): print("Match 2") if re.search(pattern, "1ab"): print("Match 3") """ Place a ^ at the start of a character class to invert it. This causes it to match any character other than the ones included. Other metacharacters such as $ and ., have no meaning within character classes. The metacharacter ^ has no meaning unless it is the first character in a class """ print ("\n\n") pattern = r"[^A-Z]" if re.search(pattern, "this is all quiet"): print("Match 1") if re.search(pattern, "AbCdEfG123"): print("Match 2") if re.search(pattern, "THISISALLSHOUTING"): print("Match 3") if re.search(pattern, "this is all quiet"): print("Match 1") if re.search(pattern, "AbCdEfG123"): print("Match 2") if re.search(pattern, "THISISALLSHOUTING"): print("Match 3")
true
10e85d68d0c5c121457de9a464b8cc8a22bf62db
Achraf19-okh/python-problems
/ex7.py
469
4.15625
4
print("please typpe correct informations") user_height = float(input("please enter your height in meters")) user_weight = float(input("please enter your weight in kg")) BMI = user_weight/(user_height*user_height) print("your body mass index is" , round(BMI,2)) if(BMI <= 18.5): print("you are under weight") elif(BMI > 18.5 and BMI <= 24.9): print("you are normal weight") elif(BMI > 24.9 and BMI <= 29.9): print("overweight") else: print("Obesity")
true
e5e26adc9ce9c5c85bd2b8afdb2bc556746f8d20
azhar-azad/Python-Practice
/07. list_comprehension.py
770
4.125
4
# Author: Azad # Date: 4/2/18 # Desc: Let’s say I give you a list saved in a variable: # a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. # Write one line of Python that takes this list a and makes a new list # that has only the even elements of this list in it. # ----------------------------------------------------------------------------------- a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] even_list = [i for i in a if i % 2 == 0] print(even_list) print("\n") print("Using a random list: ") import random rand_list = [] list_length = random.randint(5, 15) while len(rand_list) < list_length: rand_list.append(random.randint(1, 75)) even_list = [i for i in rand_list if i % 2 == 0] print(rand_list) print(even_list)
true
bcd76925689d3e401ce55f7efe88aa323b02c0d0
azhar-azad/Python-Practice
/10. list_overlap_comprehensions.py
995
4.3125
4
# Author: Azad # Date: 4/5/18 # Desc: Take two lists, say for example these two: # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] # and write a program that returns a list that # contains only the elements that are common between the lists(without duplicates). # Make sure your program works on two lists of different sizes. # Write this program using at least one list comprehension. # # Extra: # Randomly generate two lists to test this #_______________________________________________________________________________________________________ a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] common_list = [] # using list comprehensions common_list_dup = [i for i in a if i in b] # contains duplicates values for i in common_list_dup: if i not in common_list: common_list.append(i) print(common_list)
true
900685d187fce72a3edb34daef753d90395b2a8b
ARBUCHELI/100-DAYS-OF-CODE-THE-COMPLETE-PYTHON-PRO-BOOTCAMP-FOR-2021
/Guess the Number/guess_the_number.py
1,951
4.4375
4
#Number Guessing Game Objectives: # Include an ASCII art logo. # Allow the player to submit a guess for a number between 1 and 100. # Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer. # If they got the answer correct, show the actual answer to the player. # Track the number of turns remaining. # If they run out of turns, provide feedback to the player. # Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode). from art import logo import random print(logo) print("Welcome to the Number Guessing Name!") print("I'm thinking of a number between 1 and 100.") computer_number = random.randint(1, 100) print(f"Pssst, the correct answer is {computer_number}") level = input("Choose a difficulty. Type 'easy' or 'hard': ") attempts = 0 end_game = False if level == "easy": print("You have 10 attempts remaining to guess the number.") attempts = 10 elif level == "hard": print("You have 5 attempts remaining to guess the number.") attempts = 5 def guessing(): global attempts guess = int(input("Make a guess: ")) if not guess == computer_number: attempts -= 1 if guess < computer_number and attempts == 0: print("Too low.") print("You've run out of guesses, you lose.") elif guess > computer_number and attempts == 0: print("Too high.") print("You've run out of guesses, you lose.") elif guess > computer_number: print("Too high.") print("Guess again.") print(f"You have {attempts} attempts remaining to guess the number.") elif guess < computer_number: print("Too low.") print("Guess again.") print(f"You have {attempts} attempts remaining to guess the number.") elif guess == computer_number: print(f"You got it! The answer was {guess}.") global end_game end_game = True while attempts > 0: if end_game == False: guessing()
true
4e51ccfe4bbdf4401dd6c2741d3f2d8ca63ef3c2
tzyl/ctci-python
/chapter9/9.2.py
1,672
4.125
4
def number_of_paths(X, Y): """Returns the number of paths to move from (0, 0) to (X, Y) in an X by Y grid if can only move right or down.""" if X == 0 or Y == 0: return 1 return number_of_paths(X - 1, Y) + number_of_paths(X, Y - 1) def number_of_paths2(X, Y): """Solution using mathematical analysis that the number of paths is (X + Y - 2) choose (min(X, Y) - 1).""" if X == 0 or Y == 0: return 1 numerator = X + Y denominator = 1 for i in xrange(1, min(X, Y)): numerator *= X + Y - i denominator *= 1 + i return numerator / denominator def memoize(fn): cache = {} def wrapper(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = fn(*args, **kwargs) return cache[key] return wrapper @memoize def find_a_path(X, Y, blocked): """Finds a path from (0, 0) to (X, Y) with blocked positions.""" if (X, Y) in blocked: return None if X == 0 and Y == 0: return [(X, Y)] if X != 0: right_path = find_a_path(X - 1, Y, blocked) if right_path is not None: right_path.append((X, Y)) return right_path if Y != 0: down_path = find_a_path(X, Y - 1, blocked) if down_path is not None: down_path.append((X, Y)) return down_path return None if __name__ == '__main__': for i in xrange(1, 10): for j in xrange(1, 10): print number_of_paths(i, j), number_of_paths2(i, j) print find_a_path(100, 100, [(9, 10), (0, 1), (1, 2)])[::-1]
true
9f8201a7a55fd59dc02cdd24fbd64ee8cd10ebfc
tzyl/ctci-python
/chapter5/5.5.py
736
4.28125
4
def to_convert(A, B): """Clears the least significant bit rather than continuously shifting.""" different = 0 C = A ^ B while C: different += 1 C = C & C - 1 return different def to_convert2(A, B): """Using XOR.""" different = 0 C = A ^ B while C: if C & 1: different += 1 C >>= 1 return different def to_convert3(A, B): """Returns the number of bits required to convert integer A into integer B. """ different = 0 while A or B: if A & 1 != B & 1: different += 1 A >>= 1 B >>= 1 return different if __name__ == '__main__': print to_convert(31, 14)
true
2e925cbed4eaeb10f9f822f1b7600823bf8f0603
carlosmertens/Python-Introduction
/default_argument.py
2,221
4.59375
5
""" DEFAULT ARGUMENTS """ print("\n==================== Example 1 ====================\n") def box(width, height, symbol="*"): """print a box made up of asterisks, or some other character. symbol="*" is a default in case there is not input width: width of box in characters, must be at least 2 height: height of box in lines, must be at least 2 symbol: a single character string used to draw the box edges """ # print top edge of box print(symbol * width) # print sides of box for _ in range(height - 2): print(symbol + " " * (width - 2) + symbol) # print bottom edge of box print(symbol * width) # Call function box(10, 10) box(10, 10, "$") print("\n==================== Example 2 ====================\n") def print_list(l, numbered=False, bullet_character="-"): """Prints a list on multiple lines, with numbers or bullets Arguments: l: The list to print numbered: set to True to print a numbered list bullet_character: The symbol placed before each list element. This is ignored if numbered is True. """ for index, element in enumerate(l): if numbered: print("{}: {}".format(index + 1, element)) else: print("{} {}".format(bullet_character, element)) print_list(["cats", "in", "space"]) print_list(["cats", "in", "space"], True) print("\n==================== Example 3 ====================\n") """ Default arguments are a helpful feature, but there is one situation where they can be surprisingly unhelpful. Using a mutable type (like a list or dictionary) as a default argument and then modifying that argument can lead to strange results. It's usually best to avoid using mutable default arguments: to see why, try the following code locally. Consider this function which adds items to a todo list. Users can provide their own todo list, or add items to a default list: """ def todo_list(new_task, base_list=['wake up']): """Docstring is expected.""" base_list.append(new_task) return base_list print(todo_list("check the mail")) print(todo_list("begin orbital transfer")) print("\n==================== Example 4 ====================\n")
true
62ce698cea9b770dd6f641a27aec07034898d2e8
usmanwardag/Python-Tutorial
/strings.py
1,619
4.28125
4
import sys ''' Demonstrates string functions ''' def stringMethods(): s = 'Hello, how are you doing?' print s.strip() #Removes whitespaces print s.lower() print s.upper() #Changes case print s.isalpha() print s.isdigit() print s.isspace() #If all characters belong to a class print s.startswith('H') print s.endswith('ng?') print s.find('are') #Locates the index where the char/string starts print s.replace('?', '!?') print s.split('o') #Splits on specified character examples = ['Usman','Mahmood','Khan'] print ' '.join(examples) #Joins list with a given character/string #Search for more by typing "Python String methods" print '---------------------------------------------------------------------' ''' Demonstrates procedures to find sub-strings ''' def stringSlicing(): s = 'I am doing great! How about you?' print s[4:] #all characters from 4 onwards print s[-1] #last character print s[:-3] #all characters until the third last print s[-5:] #all characters starting from fifth last print '---------------------------------------------------------------------' ''' Displays the string in unicode format ''' def unicodeString(): examples = ['Usman','Mahmood','Khan'] s = ('\n').join(examples) t = unicode(s,'utf-8') print t #String in unicode format print '---------------------------------------------------------------------' ''' Main function to run test modules. Run any one of above listed function to test with commands. ''' def main(): stringMethods() stringSlicing() unicodeString() if __name__ == '__main__': main()
true
16d8dd34584e0b7bddc27bd9bddddbea2be24baf
fibeep/calculator
/hwk1.py
1,058
4.21875
4
#This code will find out how much money you make and evaluate whether you #are using your finances apropriately salary = int(input("How much money do you make? ")) spending = int (input("How much do you spend per month? ")) saving = salary - spending #This line will tell you if you are saving enough money to eventually reach "financial freedom" if spending >= salary * 0.9: print("You are spending too much money") else: print("Good job, you are on the path to financial freedom") print("You are currently saving " + str(saving) + " dollars per month") #This code will help you calculate wether you are making enough money to save X ammount in 10 years future = int(input("How much money do you want to have in your savings account in 10 years? (Please include only a number) ")) if future / 10 <= salary: print("You need to save",future/10,"dollars every year from now on.") else: print("You need to find a new job that pays " + str(future/10) + " dollars because with your current salary it is impossible to save this much money.")
true
7d090650fc7fc908e6a8914310b12878ce38dd80
SpencerBeloin/Python-files
/factorial.py
228
4.21875
4
#factorial.py #computes a factorial using reassignment of a variable def main(): n= eval(input("Please enter a whole number: ")) fact = 1 for factor in range(n,1,-1): fact = fact*factor print fact main()
true
0e4b133eba2337b2e30e389d1fe95606bf439233
annettemathew/rockpaperscissors
/rock_paper_scissors.py
2,038
4.1875
4
#Question 2 # Write a class called Rock_paper_scissors that implements the logic of # the game Rock-paper-scissors. For this game the user plays against the computer # for a certain number of rounds. Your class should have fields for how many rounds # there will be, the current round number, and the number of wins each player has. # There should be methods for getting the computer’s choice, finding the winner of a round, # and checking to see if someone has won the (entire) game. You may want more methods. from random import randint exit_flag = False class Rock_paper_scissors: def __init__(self, choice): self.choice = choice self.list = ['r', 'p', 's'] def generate_comp_response(self): rand_int = randint(0, 2) print("Computer generated: ", self.list[rand_int]) return self.list[rand_int] def check_win(self, choice, c_choice): if(choice == c_choice): print("Draw") return if(choice == 'r'): if(c_choice == 'p'): print('Computer won') else: #computer picked scissors print('User won') elif(choice == 'p'): if(c_choice == 'r'): print('User won') else: #computer picked scissors print('Computer won') else: #user picked scissors if(c_choice == 'r'): print('Computer won') else: #Computer picked paper print('User won') print("Hi! Welcome to Rock Paper Scissors!") while(exit_flag == False): user_choice = input("Please enter r, p, s, or x(to exit): ") user_choice = user_choice.lower() if(user_choice == 'x'): exit(0) elif(user_choice != 'r' and user_choice != 'p' and user_choice != 's'): print("Error: incorrect input") exit(-1) Rps = Rock_paper_scissors(user_choice) comp_choice = Rps.generate_comp_response() Rps.check_win(user_choice, comp_choice)
true
50888ff04c2d2ad05058c3ff77a6a94a2cd93fcf
atulmkamble/100DaysOfCode
/Day 19 - Turtle Race/turtle_race.py
1,896
4.46875
4
""" This program implements a Turtle Race. Place your bet on a turtle and tune on to see who wins. """ # Import required modules from turtle import Turtle, Screen from random import randint from turtle_race_art import logo def main(): """ Creates turtles and puts them up for the race :return: nothing """ # Greet the user with logo print(logo) # Initialize the required variables colors = ['purple', 'blue', 'green', 'yellow', 'orange', 'red'] all_turtles = [] is_game_on = True # Setup the screen screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title='Make your bet', prompt='Which turtle will win the race? Enter a color (purple, blue, green, yellow, ' 'orange, red): ').casefold() # Set the y axis position of turtles y = -100 for t in range(len(colors)): new_turtle = Turtle(shape='turtle') new_turtle.color(colors[t]) new_turtle.penup() new_turtle.goto(x=-230, y=y) all_turtles.append(new_turtle) y += 40 # If the user has entered the bet, start the race if user_bet: while is_game_on: for turt in all_turtles: # If the turtle is at finish line if turt.xcor() >= 220: is_game_on = False winner = turt.pencolor() if user_bet == winner: print(f'You won! The {winner} turtle is the winner.') else: print(f'You lost! The {winner} turtle is the winner.') break else: turt.forward(randint(1, 10)) screen.exitonclick() else: print('You have not placed your bet!') if __name__ == '__main__': main()
true
d70fb4d40081bda2356d7f9909c5873a7ab3a126
atulmkamble/100DaysOfCode
/Day 21 - Snake Game (Part 2)/main.py
1,529
4.125
4
""" This program implements the complete snake game """ from turtle import Screen from time import sleep from snake import Snake from food import Food from scoreboard import Scoreboard def main(): # Setup the screen screen = Screen() screen.setup(width=600, height=600) screen.bgcolor('black') screen.title('Snake Game') screen.tracer(0) # Create snake, food & score object and bind keys for snake movement snake = Snake() food = Food() scoreboard = Scoreboard() screen.listen() screen.onkeypress(snake.up, 'Up') screen.onkeypress(snake.down, 'Down') screen.onkeypress(snake.left, 'Left') screen.onkeypress(snake.right, 'Right') # Start the game is_game_on = True while is_game_on: scoreboard.display_score() screen.update() sleep(0.1) snake.move() # Detect collision with the food if snake.head.distance(food) < 15: food.refresh() snake.extend() scoreboard.update_score() # Detect collision with wall if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: scoreboard.game_over() is_game_on = False # Detect collision with tail for square in snake.snake_list[1:]: if snake.head.distance(square) < 10: is_game_on = False scoreboard.game_over() screen.exitonclick() if __name__ == '__main__': main()
true
cec29c33017cd1b9398ea08710e6ff219a43933c
atulmkamble/100DaysOfCode
/Day 10 - Calculator/calculator.py
1,736
4.21875
4
""" This program implements the classic calculator functionality (Addition, Subtraction, Multiplication & Division) """ from calculator_art import logo def add(n1, n2): return n1 + n2 def subtract(n1, n2): return n1 - n2 def multiply(n1, n2): return n1 * n2 def divide(n1, n2): return n1 / n2 def calculator(): """ This function get the numbers from user and operate on them recursively :return: returns nothing """ # Greet the user print(logo) print('Note: You can close the program/window to exit') operations = { '+': add, '-': subtract, '*': multiply, '/': divide, } # Get the first number num1 = float(input('What\'s the first number?: ')) # Print the operations for key in operations: print(key) # Initialize a variable to start a new calculation go_again = True while go_again: # Get the operation and second number operation_symbol = input('Pick an operation: ') num2 = float(input('What\'s the next number?: ')) # Call the respective function as per the input operation answer = operations[operation_symbol](num1, num2) # Print the output print(f'{num1} {operation_symbol} {num2} = {answer}') # Get a response to start a new calculation or continue with the current answer response = input( f'Type "y" to continue calculating with {answer} or type "n" start a new calculation: ').casefold() if response == 'n': go_again = False # Use recursion calculator() elif response == 'y': num1 = answer # Execute the calculator function calculator()
true
02089de9852f240b5ff07e1ca47e8e41e19537c2
atulmkamble/100DaysOfCode
/Day 4 - Rock Paper Scissors/rock_paper_scissors.py
2,029
4.3125
4
""" This program is a game of rock, paper and scissors. You and the program compete in this game to emerge as a winner. The program is not aware of your choice and it's a fair game. Please follow the directions in the program. """ from random import randint from time import perf_counter from time import process_time # Time Tracking Start tic1 = perf_counter() tic2 = process_time() rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' # Define a list with ASCII images of rock, paper, and scissors game_options = [rock, paper, scissors] # Display a welcome message and get the player choice print('Welcome to Rock Paper Scissors!\nLet us see if you can beat the program and emerge as a winner. Let\'s Go!!!\n') player_choice = int(input('What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors\n')) # Handle invalid inputs and compare the choices to determine the winner if 0 <= player_choice <= 2: print(game_options[player_choice]) program_choice = randint(0, 2) print('Computer chose:') print(game_options[program_choice]) if player_choice == program_choice: print('Result: It\'s a Draw!') # Considered only player win scenarios elif (player_choice == 0 and program_choice == 2) or (player_choice == 2 and program_choice == 1) or ( player_choice == 1 and program_choice == 0): print('Result: You Won!') else: print('Result: You Lose!') else: print('Invalid choice! You Lose!') # Time Tracking End toc1 = perf_counter() toc2 = process_time() # Print execution time print('\nExecution Time Details:') print(f'Total execution time including wait/sleep time: {round(toc1 - tic1, 2)}s') print(f'Total execution time excluding wait/sleep time: {round(toc2 - tic2, 2)}s')
true
f97594ad3514fa073068bc4f54194ab13abeaec3
duochen/Python-Kids
/Lecture06_Functions/Homework/rock-paper-scissors-game.py
891
4.15625
4
print("Welcome to the Rock Paper Scissors Game!") player_1 = "Duo" player_2 = "Mario" def compare(item_1, item_2): if item_1 == item_2: return("It's a tie!") elif item_1 == 'rock': if item_2 == 'scissors': return("Rock wins!") else: return("Paper wins!") elif item_1 == 'scissors': if item_2 == 'paper': return("Scissors win!") else: return("Rock wins!") elif item_1 == 'paper': if item_2 == 'rock': return("Paper wins!") else: return("Scissors win!") else: return("Uh, that's not valid! You have not entered rock, paper or scissors.") player_1_choice = input("%s, rock, paper, or scissors?" % player_1) player_2_choice = input("%s, rock, paper, or scissors?" % player_2) print(compare(player_1_choice, player_2_choice))
true
c2abe9e5d0fce7f2cfbb6657e98349b4cfcbd591
JohannesHamann/freeCodeCamp
/Python for everybody/time_calculator/time_calculator.py
2,997
4.4375
4
def add_time(start, duration, day= None): """ Write a function named add_time that takes in two required parameters and one optional parameter: - a start time in the 12-hour clock format (ending in AM or PM) - a duration time that indicates the number of hours and minutes - (optional) a starting day of the week, case insensitive The function should add the duration time to the start time and return the result. """ # setting up lookup tables AM_PM_dic = {"AM":0 , "PM":1} AM_PM_keys_list = list(AM_PM_dic.keys()) days_dic = {"monday":0 , "tuesday":1 , "wednesday":2 , "thursday":3 , "friday":4 , "saturday":5 , "sunday":6} days_dic_key_list = list(days_dic.keys()) # extracting information from arguments eingabe = start.split() zeit = eingabe[0].split(":") hours_start = int(zeit[0]) minutes_start = int(zeit[1]) AM_PM_start = AM_PM_dic[eingabe[1]] if day != None: day_start = days_dic[day.lower()] # extracing information from "duration" zeit_add = duration.split(":") hours_add = int(zeit_add[0]) minutes_add = int(zeit_add[1]) # implementing calculation formula minutes_after_addition = divmod(minutes_start + minutes_add, 60) hours_after_addition = divmod(hours_start + hours_add + minutes_after_addition[0] , 12) hours_result = hours_after_addition[1] if hours_after_addition[1] == 0: # so that there is 12:04 AM and not 00:04 AM hours_result = 12 full_12_cicles = hours_after_addition[0] minutes_result = str(minutes_after_addition[1]).zfill(2) #zfill(2) displays 12:04 instead of 12:4 AM_PM_result = AM_PM_keys_list[(AM_PM_start+full_12_cicles)%2] full_days_later = (full_12_cicles + AM_PM_start)//2 """generating output""" # a day-argument is given if day != None: if full_days_later == 0: new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result + ", " + day if full_days_later == 1: day_result = days_dic_key_list[(day_start + full_days_later)%7].capitalize() new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result + ", " + day_result + " (next day)" if full_days_later > 1: day_result = days_dic_key_list[(day_start + full_days_later)%7].capitalize() new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result + ", " + day_result + " (" + str(full_days_later) +" days later" +")" # no day-argument given if day == None: if full_days_later == 0: new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result if full_days_later == 1: new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result + " (next day)" if full_days_later > 1: new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result + " (" + str(full_days_later) +" days later" +")" return new_time
true
e4fc4b53e49fb44be9d4f1a0879948264fbf635d
prasannarajaram/python_programs
/palindrome.py
340
4.6875
5
# Get an input string and verify if it is a palindrome or not # To make this a little more challenging: # - Take a text input file and search for palindrome words # - Print if any word is found. text = raw_input("Enter the string: ") reverse = text[::-1] if (text == reverse): print ("Palindrome") else: print ("Not Palindrome")
true
9fbf936bdf5c6f4798aa4ce97146394de3dadc40
evanmiracle/python
/ex5.py
1,230
4.15625
4
my_name = 'Evan Miracle' my_age = 40 #comment my_height = 72 #inches my_weight = 160 # lbs my_eyes = 'brown' my_teeth = 'white' my_hair = 'brown' # this works in python 3.51 print("Test %s" % my_name) # the code below only works in 3.6 or later print(f'Lets talk about {my_name}.') print(f"He's {my_height} inches tall.") print(f"He's {my_weight} pounds heavy.") print("Actually that's not too heavy.") print(f"He's got {my_eyes} eyes and {my_hair} hair.") print(f"His teeth are usually {my_teeth} depending on coffee.") total = my_age + my_height + my_weight print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.") # code for earlier versions of python print('Lets talk about %s' % my_name) print("He's %s inches tall." % my_height) print("He's %s pounds heavy." % my_weight) print("Actually that's not too heavy.") # multples seem only to work when explicit print("He's got" , my_eyes, "eyes and",my_hair, "hair.") # This should work too print("He's got %s eyes and %s hair." %(my_eyes, my_hair) ) print("His teeth are usually %s depending on coffee." % my_teeth) total = my_age + my_height + my_weight print("If I add", my_age, my_height, my_weight, "I get", total)
true
5204daaef67721495cd2bf137d21ff70c374b393
adeshshukla/python_tutorial
/loop_for.py
719
4.15625
4
print() print('--------- Nested for loops---------') for i in range(1,6): for j in range(1,i+1): print(j, end=' ') # to print on the same line with space. Default it prints on next line. #print('\t') print() print('\n') # to print two lines. print('-------- For loop In a tuple with break ----------------') # for i in (1,2,3,4,5,6,7,8): # this is also good tuple = (1,2,3,4,5,6,7,8) for i in tuple: if i==5: print(' 5 found in the list... Now breaking out...!!!!') break print('\n') print('---------- For loop In a list with continue --------------') #list=['Adesh',28,1094.67,'IRIS','Angular',2,142] for i in ['Adesh',28,1094.67,'IRIS','Angular',2,142]: if i=='IRIS': continue print(i) print('\n')
true
ca0e358ea678b2c375709e2efb286194b58cc697
Annie677/me
/week3/exercise3.py
2,483
4.40625
4
"""Week 3, Exercise 3. Steps on the way to making your own guessing game. """ import random def not_number_rejector(message): while True: try: your_input = int(input(message)) print("Thank you, {} is a number.".format(your_input)) return your_input except: print ("that is not a number. Please try again.") def advancedGuessingGame(): """Play a guessing game with a user. The exercise here is to rewrite the exampleGuessingGame() function from exercise 3, but to allow for: * a lower bound to be entered, e.g. guess numbers between 10 and 20 * ask for a better input if the user gives a non integer value anywhere. I.e. throw away inputs like "ten" or "8!" but instead of crashing ask for another value. * chastise them if they pick a number outside the bounds. * see if you can find the other failure modes. There are three that I can think of. (They are tested for.) NOTE: whilst you CAN write this from scratch, and it'd be good for you to be able to eventually, it'd be better to take the code from exercise 2 and merge it with code from excercise 1. Remember to think modular. Try to keep your functions small and single purpose if you can! """ print("Welcome to the guessing game!") print("Please guess a number between _ and _?") lower_bound = not_number_rejector("Enter a lower bound: ") upper_bound = not_number_rejector("Enter an upper bound: ") while lower_bound >= upper_bound: lower_bound = not_number_rejector("Enter a lower bound: ") upper_bound = not_number_rejector("Enter an upper bound: ") print("Great, a number between {lower} and {upper}.".format(lower=lower_bound, upper=upper_bound)) guess_number = not_number_rejector("Guess a number: ") actualNumber = random.randint(lower_bound, upper_bound) while True: print("Your number is {},".format(guess_number)) if guess_number == actualNumber: print("It was {}".format(actualNumber)) return "You got it!" elif guess_number < actualNumber: print("Too small. Please try again.") guess_number = not_number_rejector("Guess a number: ") if guess_number > actualNumber: print("Too big.Please try again.") guess_number = not_number_rejector("Guess a number: ") if __name__ == "__main__": print(advancedGuessingGame())
true
10054b21be49bc24ea3b3772c97c116bf425533b
L51332/Project-Euler
/2 - Even Fibonacci numbers.py
854
4.125
4
''' Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ''' def even_fibonacci_sum_below(cutoff_number): fib_list = [1,1] sum = 0 next_term = 2 while next_term < cutoff_number: if next_term % 2 == 0 and next_term < cutoff_number: sum += next_term fib_list.append(next_term) next_term = fib_list[-1] + fib_list[-2] #print("fiblist: " + str(fib_list)) print("sum: " + str(sum)) even_fibonacci_sum_below(4000000) # Note: the fib_list variable could be modified to only keep track of the last two terms of the sequence to minimize space complexity
true
ed2527878b79f75db82f16c90f223922834bd933
Joyojyoti/intro__to_python
/using_class.py
618
4.21875
4
#Defining a class of name 'Student' class Student: #defining the properties that the class will contain def __init__(self, name, roll): self.name = name self.roll = roll #defining the methods or functions of the class. def get_details(self): print("The Roll number of {} is {}.".format(self.name, self.roll)) #Creating the instance of class Student stdnt1 = Student('Alexa',1234) stdnt2 = Student('Joy',1235) #Here Calling the functions of the class stdnt2.get_details() stdnt1.get_details() """The output will be like: The Roll number of Joy is 1235. The Roll number of Alexa is 1234. """
true
0df7f56ad62d036dee1dc972a5d35984cfebcbec
snpushpi/P_solving
/preorder.py
1,020
4.1875
4
''' Return the root node of a binary search tree that matches the given preorder traversal. (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def generate_tree(preorder_list): if len(preorder_list)==0: return None node = TreeNode(preorder_list[0]) for i in range(1, len(preorder_list)): if preorder_list[i]>preorder_list[0]: node.left = generate_tree(preorder_list[:i]) node.right = generate_tree(preorder_list[i:]) return node node.left = generate_tree(preorder_list[1:]) node.right = generate_tree([]) return node
true
c4cd3e7b687b65968f2863e2e19fb4fa303d4612
snpushpi/P_solving
/1007.py
1,356
4.125
4
''' In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i-th domino, so that A[i] and B[i] swap values. Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same. If it cannot be done, return -1. Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by A and B: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. ''' def domino(A,B): if len(A)!=len(B): return -1 marker_set = {A[0], B[0]} for i in range(1,len(A)): track_set = marker_set.copy() for elt in track_set: if elt not in {A[i], B[i]}: marker_set.remove(elt) if len(marker_set)==0: return -1 if len(marker_set)==1: elt = marker_set.pop() return min(len(A)-A.count(elt),len(B)-B.count(elt)) if len(marker_set)==2: elt1= marker_set.pop() elt2 = marker_set.pop() return min(len(A)-A.count(elt1), len(A)-A.count(elt2), len(B)-B.count(elt1), len(B)-B.count(elt2)) print(domino([2,1,2,4,2,2],[5,2,6,2,3,2]))
true
602dd4b4552f050d3e799cc9bc76fc3816f40358
snpushpi/P_solving
/next_permut.py
1,499
4.1875
4
''' Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1 ''' def next_permutation(num_list): l = len(num_list) inc_index = 0 strictly_decreasing = True strictly_increasing = True for i in range(1,l-1): if num_list[i-1]<=num_list[i] and num_list[i]>=num_list[i+1]: inc_index=i for i in range(l-1): if num_list[i]<num_list[i+1]: strictly_decreasing = False if num_list[i]>num_list[i+1]: strictly_increasing = False print(strictly_decreasing, strictly_increasing) if not strictly_decreasing and not strictly_increasing: swap = num_list[inc_index] num_list[inc_index]=num_list[inc_index-1] num_list[inc_index-1]=swap elif strictly_decreasing: for i in range(int(l/2)): swap = num_list[i] num_list[i]=num_list[l-1-i] num_list[l-1-i]=swap else: print('hi') swap = num_list[l-1] num_list[l-1]=num_list[l-2] num_list[l-2]=swap return num_list print(next_permutation([1,2,3]))
true
82d7b5ebca2d850aea48cc1a4719ef53f7bd09de
snpushpi/P_solving
/1041.py
1,536
4.25
4
''' On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle. Example 1: Input: "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin. Example 2: Input: "GG" Output: false Explanation: The robot moves north indefinetely. Example 3: Input: "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ... Note: 1 <= instructions.length <= 100 instructions[i] is in {'G', 'L', 'R'} ''' def boundedRobot(instructions): directions = [[0,1],[1,0],[0,-1],[-1,0]] direct = 0 start_point = [0,0] new_instructions = '' for i in range(4): new_instructions+=instructions for instruction in new_instructions: if instruction=='L': direct = (direct+3)%4 elif instruction=='R': direct = (direct+1)%4 else: start_point[0]+=directions[direct][0] start_point[1]+=directions[direct][1] if start_point==[0,0]: return True else: return False print(boundedRobot("GL"))
true
9b6d023f110699aee047ab231e17a18989abd40d
snpushpi/P_solving
/search.py
906
4.15625
4
''' Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). You are given a target value to search. If found in the array return true, otherwise return false. Example 1: Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true Example 2: Input: nums = [2,5,6,0,0,1,2], target = 3 Output: false ''' def search(nums, target): left, right = 0, len(nums)-1 mid = int((left+right)/2) wwhile left<=right: if nums[mid]==target: return mid elif nums[left]<nums[mid]: if nums[left]<target<nums[mid]: right=mid-1 else: left=mid+1 elif nums[mid]<nums[left]: if nums[mid]<target<=nums[right]: left = mid+1 else: right=mid-1 else: left+=1
true
101f7b9e37b22819c534e66c6319e363a4cfa99f
Ahmodiyy/Learn-python
/pythonpractice.py
1,142
4.21875
4
# list comprehension number_list = [1, 2, 3, 5, 6, 7, 8, 9, 10] oddNumber_list = [odd for odd in number_list if odd % 2 == 1] print(oddNumber_list) number_list = [1, 2, 3, 5, 6, 7, 8, 9, 10] oddNumber_list = [odd if odd % 2 == 1 else None for odd in number_list] print(oddNumber_list) # generator as use to get Iterator object 'stream of data' def generate_to_any_number(x=10): i = 0 while i < x: yield i i += 1 print("generate to any number: ", generate_to_any_number()) for g in generate_to_any_number(): print("generator object: ", g) # handling error try: tenth = int(input("enter num")) except ValueError: print("enter an integer") # reading from a file txt_file = None try: txt_file = open('C:/New folder/txtfile.txt', 'r') numbers_in_txtfile = txt_file.read() print("numbers in txtfile: ", numbers_in_txtfile) except: print("unable to open file") finally: txt_file.close() # using python with as to autoclose object with open('C:/New folder/txtfile.txt', 'r') as txt_file2: numbers_in_txtfile2 = txt_file2.read() print("numbers_in_txtfile2: ", numbers_in_txtfile2)
true
2c3370cfb32e84cc709f9fbeaa99e961aa0a8ce0
Asresha42/Bootcamp_day25
/day25.py
2,902
4.28125
4
# Write a program to Python find the values which is not divisible 3 but is should be a multiple of 7. Make sure to use only higher order function. def division(m): return True if m % 3!= 0 and m%7==0 else False print(division(23)) print(division(35)) # Write a program in Python to multiple the element of list by itself using a traditional function and pass the function to map to complete the operation. def b(c): return c * c a=[89,90,5,7,333,45,6,11,22,456] print(list(map(b,a))) # Write a program to Python find out the character in a string which is uppercase using list comprehension. a="AsrESha KaR" b=[c for c in a if c.isupper()] print(b) # Write a program to construct a dictionary from the two lists containing the names of students and their corresponding subjects. The dictionary should maps the students with their respective subjects. Let’s see how to do this using for loops and dictionary comprehension. HINT-Use Zip function also # ● Student = [&#39;Smit&#39;, &#39;Jaya&#39;, &#39;Rayyan&#39;] # ● capital = [&#39;CSE&#39;, &#39;Networking&#39;, &#39;Operating System&#39;] students = ["Smit", "Jaya", "Rayyan"] capital = ["CSE","Networking", "Operating System"] print ("Students : " + str(students)) print ("Capital : " + str(capital)) a = dict(zip(students, capital)) print ("Information : " + str(a)) # Learn More about Yield, next and Generators # Write a program in Python using generators to reverse the string. Input String = “Consultadd Training” def a(b): for i in range (len(b) - 1, -1, -1): yield b[i] for i in a('Consultadd Training'): print(i ,end="") # Write any example on decorators. def make_bold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def make_italic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped def make_underline(fn): def wrapped(): return "<u>" + fn() + "</u>" return wrapped @make_bold @make_italic @make_underline def hello(): return "hello world" print(hello()) # Write a program to handle an error if the user entered the number more than four digits it should return “Please length is too short/long !!! Please provide only four digits while True: a = input("Enter the numbers: ") if len(a)==4: print(a) break else: print("Please length is too short/long !!! Please provide only four digits") # Create a login page backend to ask user to enter the UserEmail and password. Make sure to ask Re-Type Password and if the password is incorrect give chance to enter it again but it should not be more than 3 times. i = 0 while (i<3): a = str(input("Enter Email Id: ")) b = str(input("Enter password: ")) if a=="asha5@gmail.com" and b =="asha": print("Welcome!") break else: print("Retry wrong values") i+=1
true
d0f1e4c5434d246faf1d73097a00a8b87af298b4
anjmehta8/learning_python
/Lecture 1.py
1,113
4.375
4
print(4+3+5) #this is a comment """ hello this is a multiline comment """ #values #data types #date type of x is value. #Eg. 4 is integer. The 4 is value, integer is data type """ #integer 4 7 9 15 100 35 0 -3 #float 3.0 4.6 33.9 17.80 43.2 """ print(6/3) print(6//3) print(7/2) print(7//2) #// rounds downward #/ exact number print(9/2) print(9//2) print(5**3) #** is exponent print(9 % 3) print(11 % 3) print(10 % 3) print(14 % 3) #modulo % is the remainder, how much would be left over #comparison operators, boolean operators T or F #True #False print(4 < 7) print(4 > 7) print(True) print(4 == 7) #if two things are identical print(4 != 7) #not equal print(4 >= 7) #greater than or equal to #and print(4 < 7 and 6 < 7) print(4 < 7 and 9 < 7) print(11 < 7 and 9 < 7) print(11 < 7 and 6 < 7) print(True and False) print(True and True) print(False and False) #or, inclusive print(4 < 7 or 6 < 7) print(4 < 7 or 9 < 7) print(11 < 7 or 9 < 7) print(11 < 7 or 6 < 7) print(True or False) print(True or True) print(False or False) #not print(not(4 < 7)) print(not(9 < 7))
true
278942c8419ff38e9fe29adfb040ab2607afa0f7
geekmj/fml
/python-programming/panda/accessing_elements_pandas_dataframes.py
2,626
4.21875
4
import pandas as pd items2 = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes':15,'pants': 5 } ] store_items = pd.DataFrame(items2, index = ['Store 1', 'Store 2']) print(store_items) ## We can access rows, columns, or individual elements of the DataFrame # by using the row and column labels. print() print('How many bikes are in each store:\n', store_items[['bikes']]) print() print('How many bikes and pants are in each store:\n', store_items[['bikes','pants']]) ## Check [[]], while [] worked for one index but not for 2 print() print('How items are in in Store 1:\n', store_items.loc[['Store 1']]) print() ## Notice for accessing row u have to use loc print('How many bikes are in Store 2:\n', store_items['bikes']['Store 2']) ## Notice Column first than row ## For modification we can use dataframe[column][row] ## Adding a column named shirts, provide info shirts in stock at each store store_items['shirts'] = [15,2] print(store_items) ## It is possible to add a column having values which are outcome # of arithmatic operation between other column # New Suits column with values addition of number of shirts and pants store_items['suits'] = store_items['shirts'] + store_items['pants'] print(store_items) ## To add rows to our DataFrame we first have to create a new Dataframe # and than append # New dictionary new_items = [{'bikes': 20, 'pants': 30, 'watches': 35, 'glasses': 4}] # New dataframe new_store = pd.DataFrame(new_items, index = ['Store 3']) print(new_store) # Use append and add it to existing dataframe store_items = store_items.append(new_store) print(store_items) # Notice Alphabetical order in which they appended # we add a new column using data from particular rows in the watches column store_items['new watches'] = store_items['watches'][1:] print(store_items) # Insert a new column with label shoes right before the # column with numerical index 4 store_items.insert(4, 'shoes', [8,5,0]) print(store_items) ## .pop() delete column and .drop() to delete row store_items1 = store_items.pop('new watches') print(store_items1) # Remove the store 2 and store 1 rows store_items2 = store_items.drop(['Store 2', 'Store 1'], axis = 0) print(store_items2) # Change row and column label store_items = store_items.rename(columns = {'bikes': 'hats'}) print(store_items) store_items = store_items.rename(index = {'Store 3': 'Last Store'}) print(store_items) # We change the row index to be the data in the pants column store_items = store_items.set_index('pants') # we display the modified DataFrame print(store_items)
true
900ff84b08de1fb33a0262702f2e79dd11125470
geekmj/fml
/python-programming/panda/accessing_deleting_elements_series.py
2,231
4.75
5
import pandas as pd # Creating a Panda Series that stores a grocerry list groceries = pd.Series(data = [30, 6, 'Yes', 'No'], index = ['eggs', 'apples', 'milk', 'bread']) print(groceries) # We access elements in Groceries using index labels: # We use a single index label print('How many eggs do we need to buy:', groceries['eggs']) print() # we can access multiple index labels print('Do we need milk and bread:\n', groceries[['milk', 'bread']]) print() # we use loc to access multiple index labels print('How many eggs and apples do we need to buy:\n', groceries.loc[['eggs', 'apples']]) print() # We access elements in Groceries using numerical indices: # we use multiple numerical indices print('How many eggs and apples do we need to buy:\n', groceries[[0, 1]]) print() # We use a negative numerical index print('Do we need bread:\n', groceries[[-1]]) print() # We use a single numerical index print('How many eggs do we need to buy:', groceries[0]) print() # we use iloc to access multiple numerical indices print('Do we need milk and bread:\n', groceries.iloc[[2, 3]]) # We display the original grocery list print('Original Grocery List:\n', groceries) ## Changing values # We change the number of eggs to 2 groceries['eggs'] = 2 # We display the changed grocery list print() print('Modified Grocery List:\n', groceries) ## Deleting items # We display the original grocery list print('Original Grocery List:\n', groceries) # We remove apples from our grocery list. The drop function removes elements out of place print() print('We remove apples (out of place):\n', groceries.drop('apples')) # When we remove elements out of place the original Series remains intact. To see this # we display our grocery list again print() print('Grocery List after removing apples out of place:\n', groceries) # We display the original grocery list print('Original Grocery List:\n', groceries) # We remove apples from our grocery list in place by setting the inplace keyword to True groceries.drop('apples', inplace = True) # When we remove elements in place the original Series its modified. To see this # we display our grocery list again print() print('Grocery List after removing apples in place:\n', groceries)
true
dc0168556ef464beab6eb6371d24d7a726a08df0
ads2100/pythonProject
/72.mysql3.py
1,748
4.15625
4
# 71 . Python MySql p2 """ # The ORDER BY statement to sort the result in ascending or descending order. # The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC keyword # Delete: delete records from an existing table by using the "DELETE FROM" statement # Important!: Notice the statement: mydb.commit() It is required to make the changes otherwise no changes are made to the table # Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record(s) that should be deleted. If you omit the WHERE clause, all records will be deleted! # delete an existing table by using the "DROP TABLE" statement. # If the table you want to delete is already deleted, or for any other reason does not exist, you can use the IF EXISTS keyword to avoid getting an error. """ import mysql.connector con = mysql.connector.connect( host = "localhost", user = "root", password= "omarroot000", database= "pythondb" ) mycursor = con.cursor() q = "SELECT * FROM categories ORDER BY name DESC" mycursor.execute(q) result = mycursor.fetchall() for x in result: print(x) q = "DELETE FROM categories WHERE name = 'Javascript'" mycursor.execute(q) con.commit() print(mycursor.rowcount,"record(s) deleted") mycursor.execute("SELECT * FROM categories ORDER BY name DESC") result = mycursor.fetchall() for x in result: print(x) #mycursor.execute("CREATE TABLE categories_tt(name VARCHAR(255), description VARCHAR(255))") mycursor.execute("SHOW TABLES") print("Tables:") for tbl in mycursor: print(tbl) mycursor.execute("DROP TABLE categories_tt") mycursor.execute("SHOW TABLES") print("Tables:") for tbl in mycursor: print(tbl)
true
e3476d68e724f57e66131177f595e38d0ec492fe
ads2100/pythonProject
/15.list.py
658
4.34375
4
# 15. List In python 3 """ # List Methods len() the length of items append() add item to the list insert() add item in specific position remove() remove specified item pop() remove specified index, remove last item if index is not specified clear() remove all items """ print("Lesson 15: List Method") list = ["apple", "banana", "cherry"] list.append("orange") list.append("blueberry") print(list) list.insert(0, "kiwi") print(list) list.remove("banana") print(list) list.pop() print(list) list.pop(3) print(len(list)) print(list) mylist = list.copy(); list.pop(2) print(mylist) print(list) list2 = [1,2] list.clear() print(list)
true
61a30c2c64aa88706a32b898c7fca786775c8ae1
ads2100/pythonProject
/59.regularexpression3.py
994
4.4375
4
# 59. Regular Expressions In Python p3 """ # The sub() function replaces the matches with the text of your choice: # You can control the number of replacements by specifying the count parameter. sub('','',string,no) # Match Object: A Match Object is as object containing information about the search and the result. The Match object has properties and methods used to retrieve information about the search, and the result. Ex: <re.Match object; span=(2, 4), match='is'> span() returns a tuple containing the start-, and end positions of the match. string returns the string passed into the function group() returns the part of the string where there was a match """ import re as myRegEx str = "This Is His Issue" match = myRegEx.sub('\s', '_', str, 2) if (match): print('\nmatch') print(myRegEx.search('is',str)) print(myRegEx.search(r"\bH+",str).span()) print(myRegEx.search(r"\bH",str).string) print(myRegEx.search(r"\bH\w+",str).group())
true
4c36b5214ebd5c63b66233c33a2c3bc59701e770
ads2100/pythonProject
/16.tuple.py
655
4.1875
4
# 16. Tuple in Python """ # A tuple is a collection which is ordered and unchangeable. # In Python tuples are written with round brackets (). # if the tuple has just one item... ("item",) # acces item in tuple with referring [index] # You cannot change its values. Tuples are unchangeable. # You cannot add items to it. # You cannot remove items in a tuple, but you can delete the tuple completely using del(). # You can loop through the tuple items by using a for loop. """ mixtuple = (1, "yellow", 0.1, "green") print(mixtuple[1:3]) for item in mixtuple: print(item) del mixtuple print(mixtuple) # An error because it's no longer exist
true
4054eb15aa4e1c1a406a7766e5874288d321232b
tianyunzqs/LeetCodePractise
/leetcode_61_80/69_mySqrt.py
956
4.15625
4
# -*- coding: utf-8 -*- # @Time : 2019/7/3 9:44 # @Author : tianyunzqs # @Description : """ 69. Sqrt(x) Easy Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. Example 1: Input: 4 Output: 2 Example 2: Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. """ def mySqrt(x: int) -> int: def fun(x, d_min, d_max): if d_max == d_min or (d_max - d_min == 1 and d_min * d_min <= x < d_max * d_max): return d_min mid = (d_min + d_max) // 2 if x < mid * mid: res = fun(x, d_min, mid) else: res = fun(x, mid, d_max) return res return fun(x, 1, x) print(mySqrt(2000000000000))
true
f87328e58228e7fd3e3d16ffd999638ff38cf8f9
AlanRufuss007/Iceberg
/python day1.py
319
4.125
4
num1 = 10 num2 = 20 sum = num1+num2 print("sum of {0} and {1} is {2}".format(num1,num2,sum)) num1 = input("Enter the number:") num2 = input("/n Enetr the number:") sum = float(num1)+float(num2) print("The sum of {0} and {1} is {2}".format(num1,num2,sum)) a = 10 b = 20 maximum = max(a,b) print(maximum)
true
f7c446009fd894559fb63c4a6b928ad6fc4a61e1
eddy-v/flotsam-and-jetsam
/checkaba.py
1,114
4.21875
4
# eddy@eddyvasile.us # how to check validity of bank routing number (aba) # multiply the first 8 digits with the sequence 3, 7, 1, 3, 7, 1, 3, 7 and add the results # the largest multiple of 10 of the sum calculated above must be equal to the 9th digit (checkDigit) import math def validateABA(aba): checkDigit=int(aba[8]) digitSum= \ int(aba[0])*3+ \ int(aba[1])*7+ \ int(aba[2])+ \ int(aba[3])*3+ \ int(aba[4])*7+ \ int(aba[5])+ \ int(aba[6])*3+ \ int(aba[7])*7 if digitSum==0: digitSum=10 #For a more elegant soution use lists or arrays #Find the highest multiple of 10 of the digitSum temp = (math.floor(digitSum/10)*10)+10; validDigit=temp-digitSum; if validDigit==checkDigit: return True else: return False aba=input("Enter the 9 didigit bank routing nuber (e.g. 121000248): ") if aba.isalpha() or len(aba) != 9: print ('Sorry... 9 digit numeric input required\n') else: if (validateABA(aba)): print(aba,' is a valid bank routing number\n') else: print(aba,' is NOT a valid routing number\n')
true
084af05776f7ae422b74a67e08f68046b7acbd8c
AhirraoShubham/ML-with-Python
/variables.py
1,771
4.65625
5
########################################################################## # Variabels in Python # # * Variables are used to store information to be referenced and # manipulated in computer program. They also provide a way of labeling # data with a decriptive name, so our progams can be understood more # clearly by the reader and ourselves. # * It is helpful to think of variables as containers that hold information # * Their sole purpose is to label and store data in memory. This data can # can then be used throughout our program # * As Python is Dynamically typed language there is no need to use # data types explicitly while creating the variable. # * Depends on the value that we initialise interpreter decides its data # type and allocates memory accordingly. # ############################################################################ # Consider below application which demonstrate different ways in which we # can create variabels. print("--- (-: Learn Python with Mr.Ahirrao :-) ---") print("Demonstration of variable in Python") no = 11 # Considered as Integer name = "Mr.Ahirrao" # Considered as String fValue = 3.14 # Considered as Float cValue = 10+5j # Considered as Complex number eValue = 7E4 # Considered as Scintific number where E indicates power of 10 bigValue = 123456789 print(no) print("String is "+name) print(fValue) print(cValue) print(eValue) print(bigValue) #We can use type function to get data type of variable print("--- Get DataType of any variable using type funcation ---") print(type(no)) print(type(name)) print(type(fValue)) print(type(cValue)) print(type(eValue)) print(type(bigValue)) #Save and run file for output
true
cf6db1cfb7ba5ebff8bf62f9d55eb93071f03e5f
noserider/school_files
/speed2.py
539
4.125
4
#speed program speed = int(input("Enter speed: ")) #if is always the first statement if speed >= 100: print ("You are driving dangerously and will be banned") elif speed >= 90: print ("way too fast: £250 fine + 6 Points") elif speed >= 80: print ("too fast: £125 + 3 Points") elif speed >= 70: print ("Please adhere to the speed limits") elif speed >= 60: print ("Perfect") elif speed <= 30: print ("You are driving too slow") #else is always the last statement else: print ("No action needed")
true
8dcdef576c7fb51962fc4c2537742c92f51976f5
noserider/school_files
/sleep.py
580
4.125
4
#int = interger #we have two variable defined hourspernight & hoursperweek hourspernight = input("How many hours per night do you sleep? ") hoursperweek = int(hourspernight) * 7 print ("You sleep",hoursperweek,"hours per week") #round gives a whole number answer or a specific number of decimal points hourspermonth = float(hoursperweek) * 4.35 hourspermonth = round(hourspermonth,2) print ("You sleep",hourspermonth,"hours per month") hoursperyear = float(hourspermonth) * 12 hoursperyear = round(hoursperyear,2) print ("You sleep",hoursperyear,"hours per year")
true
a3b6246985aa7ea86a440da73a96cefdd4eb6dc3
noserider/school_files
/sleep1.py
291
4.1875
4
hourspernight = input("How many hours per night do you sleep? ") hoursperweek = int(hourspernight) * 7 print ("You sleep",hoursperweek,"hours per week") hourspermonth = float(hoursperweek) * 4.35 hourspermonth = round(hourspermonth) print ("You sleep",hourspermonth,"hours per month")
true
1fb48b796d55cd2988bfb74060178f327b6b549e
helectron/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-append_write.py
282
4.28125
4
#!/usr/bin/python3 '''module 2-append_write Function: append_write(filename="", text="") ''' def append_write(filename="", text=""): '''Function to append a text in a file''' with open(filename, mode="a", encoding="utf-8") as myFile: return myFile.write(text)
true
89f6aaf3951880cbacbf717942940359860c5cc7
bdsh-14/Leetcode
/max_sum_subarray.py
615
4.21875
4
''' Given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous subarray of size ‘k’ Input: [2, 1, 5, 1, 3, 2], k=3 Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3] educative.io ''' def max_sum(k, nums): windowStart = 0 windowSum = 0 max_sum = 0 for windowEnd in range(len(nums)): windowSum += nums[windowEnd] if windowEnd >= k-1: max_sum = max(max_sum, windowSum) windowSum -= nums[windowStart] windowStart += 1 return max_sum a = max_sum(3, [2, 1, 5, 1, 3, 2]) print(a)
true
0fa2259f7b692512ccfd9fc074ffd8640762853a
racer97/ds-class-intro
/python_basics/class02/exercise_6.py
2,246
4.25
4
''' Edit this file to complete Exercise 6 ''' def calculation(a, b): ''' Write a function calculation() such that it can accept two variables and calculate the addition and subtraction of it. It must return both addition and subtraction in a single return call Expected output: res = calculation(40, 10) print(res) >>> (50, 30) Arguments: a: first number b: second number Returns: sum: sum of two numbers diff: difference of two numbers ''' # code up your solution here summation = a + b diff = a - b return summation, diff def triangle_lambda(): ''' Return a lambda object that takes in a base and height of triangle and computes the area. Arguments: None Returns: lambda_triangle_area: the lambda ''' return lambda base, height: .5 * base * height def sort_words(hyphen_str): ''' Write a Python program that accepts a hyphen-separated sequence of words as input, and prints the words in a hyphen-separated sequence after sorting them alphabetically. Expected output: sort_words('green-red-yellow-black-white') >>> 'black-green-red-white-yellow' Arguments: hyphen_str: input string separated by hyphen Returns: sorted_str: string in a hyphen-separated sequence after sorting them alphabetically ''' # code up your solution here words = hyphen_str.split('-') words.sort() hyphen = '-' sorted_hyphen_str = hyphen.join(words) return sorted_hyphen_str def perfect_number(n): ''' Write a Python function to check whether a number is perfect or not. A perfect number is a positive integer that is equal to the sum of its proper positive divisors. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Example: 6 is a perfect number as 1+2+3=6. Also by the second definition, (1+2+3+6)/2=6. Next perfect number is 28=1+2+4+7+14. Next two perfect numbers are 496 and 8128. Argument: number: number to check Returns: perfect: boolean, True if number is perfect ''' # code up your answer here if n < 1: return 'Invalid Number' if n == 1: return True list2 = [1] for i in range(2, n // 2 + 1): if n % i == 0: list2.append(i) return n == sum(list2) if __name__ == '__main__': pass
true
30132cd72458b94cd244412d9dcdc108a5674c6f
yatikaarora/turtle_coding
/drawing.py
282
4.28125
4
#to draw an octagon and a nested loop within. import turtle turtle= turtle.Turtle() sides = 8 for steps in range(sides): turtle.forward(100) turtle.right(360/sides) for moresteps in range(sides): turtle.forward(50) turtle.right(360/sides)
true
f0962e44eee61bfcb7524c68c346c7fb620269ec
EllipticBike38/PyAccademyMazzini21
/es_ffi_01.py
1,128
4.34375
4
# Write a function insert_dash(num) / insertDash(num) / InsertDash(int num) that will insert dashes ('-') between each two odd numbers # in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number. # Note that the number will always be non-negative (>= 0). def insertDash(num): sNum = str(num) ans = '' for c in range(len(sNum)-1): ans += sNum[c] if int(sNum[c]) % 2 == 1 and int(sNum[c+1]) % 2 == 1: ans += '-' if int(sNum[c]) % 2 == 0 and int(sNum[c+1]) % 2 == 0: ans += '+' ans += sNum[-1] return ans def insertDash2(num): sNum = str(num) ans = '' for c in range(len(sNum)-1): ans += sNum[c] cond1, cond2 = int(sNum[c]) % 2, int(sNum[c+1]) % 2 if cond1 and cond2: ans += '-' if not(cond1 or cond2): ans += '+' ans += sNum[-1] return ans while 1: try: a = int(input('inserire un intero lungo\n')) break except: print('Vorrei un intero') print(insertDash(a))
true
ba6e0574e900be6eed7368ef339d1c1407ea1450
noahmarble/Ch.05_Looping
/5.0_Take_Home_Test.py
2,949
4.28125
4
''' HONOR CODE: I solemnly promise that while taking this test I will only use PyCharm or the Internet, but I will definitely not ask another person except the instructor. Signed: ______________________ 1. Make the following program work. ''' print("This program takes three numbers and returns the sum.") total = 0 for i in range(3): x = int(input("Enter a number: ")) total += x print("The total is:", total) ''' 2. Write a Python program that will use a FOR loop to print the even numbers from 2 to 100, inclusive. ''' for i in range(2,101,2): print(i) ''' 3. Write a program that will use a WHILE loop to count from 10 down to, and including, 0. Then print the words Blast off! Remember, use a WHILE loop, don't use a FOR loop. ''' i = 10 while i > -1: print (i) i-=1 print("Blast Off!") ''' 4. Write a program that prints a random integer from 1 to 10 (inclusive). ''' import random number = random.randrange(1,11) print(number) ''' 5. Write a Python program that will: * Ask the user for seven numbers * Print the total sum of the numbers * Print the count of the positive entries, the number entries equal to zero, and the number of negative entries. Use an if, elif, else chain, not just three if statements. ''' ''' number1 = int(input("give me a number:")) number2 = int(input("give me a number:")) number3 = int(input("give me a number:")) number4 = int(input("give me a number:")) number5 = int(input("give me a number:")) number6 = int(input("give me a number:")) number7 = int(input("give me a number:")) sumofnumbers = number1+number2+number3+number4+number5+number6+number7 print("sum of numbers", sumofnumbers) positive = 0 zero = 0 negative = 0 if number1 >= 1: positive += 1 elif number1 == 0: zero += 1 else: negative += 1 if number2 >= 1: positive += 1 elif number2 == 0: zero += 1 else: negative += 1 if number3 >= 1: positive += 1 elif number3 == 0: zero += 1 else: negative += 1 if number4 >= 1: positive += 1 elif number4 == 0: zero += 1 else: negative += 1 if number5 >= 1: positive += 1 elif number5 == 0: zero += 1 else: negative += 1 if number6 >= 1: positive += 1 elif number6 == 0: zero += 1 else: negative += 1 if number7 >= 1: positive += 1 elif number7 == 0: zero += 1 else: negative += 1 print("number of positive:", positive) print("number of zeros:", zero) print("number f negatives:", negative) ''' positive = 0 zero = 0 negative = 0 sumofnumbers = 0 for i in range (7): number1 = int(input("give me a number:")) if number1 >= 1: positive += 1 elif number1 == 0: zero += 1 else: negative += 1 i+=1 sumofnumbers += number1 print("sum of numbers", sumofnumbers) print("number of positive:", positive) print("number of zeros:", zero) print("number of negatives:", negative)
true
c83665d8eb9bcff974737e4705bb285b8b3384cf
FFFgrid/some-programs
/单向链表/队列的实现.py
1,528
4.125
4
class _node: __slots__ = '_element','_next'#用__slots__可以提升内存应用效率 def __init__(self,element,next): self._element = element #该node处的值 self._next = next #下一个node的引用 class LinkedQueue: """First In First Out""" def __init__(self): """create an empty queue""" self._head = None self._tail = None self._size = 0 def __len__(self): """Return the number of thr elements in the stack""" return self._size def is_empty(self): """Return True if the stack is empty""" return self._size == 0 def first(self): """Return(don't remove the element at the front of the queue )""" if self.is_empty(): print('Queue is empty') else: return self._head._element def dequeue(self): """Remove and return the first element of the queue""" if self.is_empty(): print('Queue is empty') ans = self._head._element self._head = self._head._next self._size -= 1 if self.is_empty(): self._tail = None return ans def enqueue(self,e): """Add an element to the back of the queue""" newest = self._Node(e,None) #this node will be the tail node if self.is_empty(): self._head = newest else: self._tail._next = newest self._tail = newest #Update reference to tail node self._size += 1
true
3081b981b3c1cc909ea8a84005bb3a47150af8db
Kelsi-Wolter/practice_and_play
/interview_cake/superbalanced.py
2,487
4.1875
4
# write a function to see if a tree is superbalanced(if the depths of any 2 leaf nodes # is <= 1) class BinaryTreeNode(object): '''sample tree class from interview cake''' def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self.left = BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = BinaryTreeNode(value) return self.right def is_superbalanced(self): '''Check if there are any leafs with difference > 1''' # find two leafs with difference > 1 # traverse tree to find leafs # do BFS to find depths of leafs (queue) - NOPE # do DFS to find leafs quickest, then use short-circuit to quit program # once a difference of greater than 1 is found nodes_to_check = [root] depth = 1 min_leaf_depth = 0 max_leaf_depth = 0 while nodes_to_check: current = nodes_to_check.pop() current_node = current[0] if current_node.left or current_node.right != None: nodes_to_check.append((current.left, depth), (current.right, depth)) depth += 1 else: node_depth = current[1] if min == 0: set min else: if node_depth < min: if min - node_depth > 1 or max - node_depth > 1: return False else: min = depth else depth > max: if max - min > 1: return False else: max = depth # Pseudocode guide # check for children, # if children --> go to those children and continue, depth = 2 # if children (self.left & self.right) == None --> # depth = current depth # and see if it is greater than or less than min/max # update as appropriate # continue until all nodes have been checked # edge cases: # tree of one node # super balanced tree # super unbalanced tree
true
d7955a29d3177efa8b6f558a9a26bd3a7c5f2c61
mulualem04/ISD-practical-4
/ISD practical4Q8.py
282
4.15625
4
# ask the user to input their name and # asign it with variable name name=input("your name is: ") # ask the user to input their age and # asign it with variable age age=int(input("your age is: ")) age+=1 # age= age + 1 print("Hello",name,"next year you will be",age,"years old")
true
25405511319bff04521132f09d027eb1bedc6e7a
MahidharMannuru5/DSA-with-python
/dictionaryfunctions.py
1,826
4.5625
5
1. str(dic) :- This method is used to return the string, denoting all the dictionary keys with their values. 2. items() :- This method is used to return the list with all dictionary keys with values. # Python code to demonstrate working of # str() and items() # Initializing dictionary dic = { 'Name' : 'Nandini', 'Age' : 19 } # using str() to display dic as string print ("The constituents of dictionary as string are : ") print (str(dic)) # using str() to display dic as list print ("The constituents of dictionary as list are : ") print (dic.items()) 3. len() :- It returns the count of key entities of the dictionary elements. 4. type() :- This function returns the data type of the argument # Python code to demonstrate working of # len() and type() # Initializing dictionary dic = { 'Name' : 'Nandini', 'Age' : 19, 'ID' : 2541997 } # Initializing list li = [ 1, 3, 5, 6 ] # using len() to display dic size print ("The size of dic is : ",end="") print (len(dic)) # using type() to display data type print ("The data type of dic is : ",end="") print (type(dic)) # using type() to display data type print ("The data type of li is : ",end="") print (type(li)) 5. copy() :- This function creates the shallow copy of the dictionary into other dictionary. 6. clear() :- This function is used to clear the dictionary contents. # Python code to demonstrate working of # clear() and copy() # Initializing dictionary dic1 = { 'Name' : 'Nandini', 'Age' : 19 } # Initializing dictionary dic3 = {} # using copy() to make shallow copy of dictionary dic3 = dic1.copy() # printing new dictionary print ("The new copied dictionary is : ") print (dic3.items()) # clearing the dictionary dic1.clear() # printing cleared dictionary print ("The contents of deleted dictionary is : ",end="") print (dic1.items())
true
0bfff01de4d4b739f08c6d5499734d9039df55fc
octavian-stoch/Practice-Repository
/Daily Problems/July 21 Google Question [Easy] [Matrix].py
1,618
4.15625
4
#Author: Octavian Stoch #Date: July 21, 2019 #You are given an M by N matrix consisting of booleans that #represents a board. Each True boolean represents a wall. Each False boolean #represents a tile you can walk on. #Given this matrix, a start coordinate, and an end coordinate, #return the minimum number of steps required to reach the end coordinate from the start. #If there is no possible path, then return null. You can move up, left, down, and right. #You cannot move through walls. You cannot wrap around the edges of the board. import random def numSteps(): testMatrix = [['F','F','F','F','F'] , ['F','F','F','F','F'] , ['F','F','F','F','F'] , ['F','F','F','F','F']] def makeMatrix(n, m): #randomly Generate a matrix with values n and m between 1 and 10 #n = column #m = row columnMatrix = [] matrix = [] print (n, m) for makecolumns in range(n): #create columns columnMatrix.append('F') #print(columnMatrix) for makerows in range(m): #create the rows by copying the list and making a bunch of mini lists field = [] #make new lists each time for j in range(n): if random.randrange(1,100) >= 50: field.append('T') else: field.append('F') matrix.append(field) #clear it every time matrix.append(columnMatrix.copy()) print ('\n'.join([' '.join(row) for row in matrix])) #random number between 1 and 100 to change each value in matrix to 'T', if >=50 then 'T' else none if __name__ == "__main__": makeMatrix(random.randrange(1,10), random.randrange(1,10)) #very inneficient because of two for loops O(2n) :(
true
8ed67ae3d95f7ab983bd9b4d2374ac60bf1d44cb
tonycao/CodeSnippets
/python/1064python/test.py
1,882
4.125
4
import string swapstr = "Hello World!" result = "" for c in swapstr: if c.islower(): result += c.upper() elif c.isupper(): result += c.lower() else: result += c print(result) string1 = input("Enter a string: ") string2 = input("Enter a string: ") string1_changed = string1[1:-1] string2_changed = string2[1:-1] string3 = string1_changed + string2_changed print(string3) new_string3 = "" for char in string3: if char.isalpha(): new_string3 = new_string3 + char*3 print(new_string3) # 6) #function of encode: def ROT13(line): """encode the line""" #shift_amount = 13 count = 0 encoded_str = '' for char in line: #count is the index of char, we need find the relationship between char # index number and the shift_amount index,'(count-1)%shift_amount' is # used to get the index of shift_amount count += 1 k = 13 if char.isalpha(): if char.isupper(): char_cal=ord(char)-ord('A') char_upper= chr(int((char_cal+k)%26)+ord('A')) encoded_str = encoded_str + char_upper elif char.islower(): char_cal2=ord(char)-ord('a') char_lower=chr(int((char_cal2+k)%26)+ord('a')) encoded_str = encoded_str + char_lower else: encoded_str = encoded_str + char return encoded_str string = input("Enter message: ") string = string.strip() result = ROT13(string) print(result) str = ROT13(result) print(str) # 7) string1 = input("Enter a long string: ") length = len(string1) ntweet = int((length - 1) / 132) + 1; for i in range(ntweet): print("({0:2d}/{1:2d}) ".format(i+1, ntweet), end="") if (i+1)*132 < length: print(string1[i*132 : (i+1) * 132]) else: print(string1[i*132 : :])
true
d7f42953edff49b748c99be05a79759fa6b994fc
zk18051/ORS-PA-18-Homework02
/task2.py
361
4.125
4
print('Convert Kilometers To Miles') def main(): user_value = input('Enter kilometers:') try: float(user_value) print(float(user_value),'km') except: print(user_value, 'is not a number. Try again.') return main() user_miles = float(user_value) * 0.62137 print(user_value, 'km is', user_miles, 'miles') main()
true
b49a8155088c794799e763a3d43d12bd5fba57d6
alokjani/project-euler
/e4.py
845
4.3125
4
# A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. # # Find the largest palindrome made from the product of two 3-digit numbers. def reverse(num): return int(str(num)[::-1]) def isPalindrome(num): if num == reverse(num): return True return False smallest_3_digit_num = 100 largest_3_digit_num = 999 largest_palindrome = 0 for i in range(smallest_3_digit_num,largest_3_digit_num): for j in range(smallest_3_digit_num, largest_3_digit_num): num = i * j if isPalindrome(num): if num > largest_palindrome: largest_palindrome = num print "%d x %d = %d" % (i,j,largest_palindrome) print "largest palindrome that is a product of two 3 digit numbers is %d" % (largest_palindrome)
true
ee3f43d9120efc1037d5de4aefe93bcd4ea9fcad
DomfeLacre/zyBooksPython_CS200
/module3/AutoServiceInvoice/AutoServiceInvoice1_with_dict.py
2,232
4.25
4
# Output a menu of automotive services and the corresponding cost of each service. print('Davy\'s auto shop services') # Creat dict() to store services : prices servicePrices = { 'Oil change' : 35, 'Tire rotation' : 19, 'Car wash' : 7, 'Car wax' : 12 } print('Oil change -- $35') print('Tire rotation -- $19') print('Car wash -- $7') print('Car wax -- $12') # Prompt the user for two services from the menu. serviceOne = str(input('\nSelect first service: \n')) serviceTwo = str(input('\nSelect second service: \n')) # Check to see if input is a dash (-). If so append 'No service' : 0 to the servicesPrices[] dict() if serviceOne == '-': servicePrices['No service'] = 0 # Set the value of serviceOne to str 'No service' to achieve required assignment output serviceOne = 'No service' else: serviceOne = serviceOne # Check to see if input is a dash (-). If so append 'No service' : 0 to the servicesPrices[] dict() if serviceTwo == '-': servicePrices['No service'] = 0 # Set the value of serviceTwo to str 'No service' to achieve required assignment output serviceTwo = 'No service' else: serviceTwo = serviceTwo # Output an invoice for the services selected. Output the cost for each service and the total cost. print('\n') print('Davy\'s auto shop invoice\n') # Condition to check to see if a dash(-) was entered for serviceOne input if serviceOne == 'No service': print('Service 1: %s' % serviceOne) elif serviceOne in servicePrices: print('Service 1: %s, $%d' % (serviceOne, servicePrices[serviceOne])) else: servicePrices[serviceOne] = 0 print('Service 1: We do not provide the service that you have requested.') # Condition to check to see if a dash(-) was entered for serviceTwo input if serviceTwo == 'No service': print('Service 2: %s' % serviceTwo) elif serviceTwo in servicePrices: print('Service 2: %s, $%d' % (serviceTwo, servicePrices[serviceTwo])) else: servicePrices[serviceTwo] = 0 print('Service 2: We do not provide the service that you have requested.') # Add total using the values from the servicePrices dict() serviceTotal = servicePrices[serviceOne] + servicePrices[serviceTwo] print('\nTotal: $%d' % serviceTotal)
true
0a17bfb11cdda597d527c25d658ee78bf727ad90
DomfeLacre/zyBooksPython_CS200
/module7/MasterPractice_List_Dicts.py
670
4.125
4
##### LISTS ##### # Accessing an Index of a List based on user input of a number: Enter 1 -5 ageList = [117, 115, 99, 88, 122] # Ways to to get INDEX value of a LIST: print(ageList.index(99)) # --> 2 # Use ENUMERATE to get INDEX and VALUE of LIST: for index, value in enumerate(ageList): print(index) print('My index is %d and my index value is %d' % (index, value)) # REMEMBER Lists are 0 Index so if user input wants the value of 1 in the list that is EQUAL to 0: userInput = 2 print('The user wants the number %d value in the list so we need to access the list accordingly: ' % userInput) print('%d is equal to %d' % (userInput, ageList[userInput - 1]))
true
3b3c1110fd920f34e35dbc55beb38d9b3ecb16cc
calvinjlzhai/Mini_quiz
/Mini_quiz.py
2,737
4.28125
4
#Setting score count score = 0 #Introducation for user taking the quiz print("Welcome to the quiz! Canadian Edition!\n") #First question with selected answers provided answer1 = input("Q1. What is the capital of Canada?" "\na. Toronto\nb. Ottawa\nc. Montreal\nd.Vancouver\nAnswer: ") # Account for the different input the user enters when request if answer1 == "b" or answer1 == "B" or answer1 == "Ottawa" or answer1 == "ottawa": score += 1 print("You are correct!\n") #Print the output for correct input, this concept repeats for next question else: print("Incorrect, the answer is Ottawa.\n") #Print the output for incorrect input, this concept repeats for next question print("Current Score: "+ str(score) + "\n") #The score is counted after this question and continue until end of page for final score answer2 = input("Q2. Which Canadian province has the highest population?" "\na. Manitoba\nb. British Columbia\nc. Quebec\nd. Ontario\nAnswer: ") if answer2 == "d" or answer2 == "D" or answer2 == "Ontario" or answer2 == "ontario": score += 1 print("You are correct\n") else: print("Incorrect, the answer is Ontario!\n") print("Current Score: "+str(score) + "\n") answer3 = input("Q3. What is the national animal of Canada?" "\na. Moose\nb. Grizzly Bear\nc. Beaver\nd. Beluga Whale\nAnswer: ") if answer3 == "c" or answer3 == "C" or answer3 == "Beaver" or answer3 == "beaver": score += 1 print("You are correct\n") else: print("Incorrect, the answer is Beaver!\n") print(score) answer4 = input("Q4. What is the capital city of Ontario?" "\na. York\nb. Toronto\nc. Hamilton\nd. Peterborough\nAnswer: ") if answer4 == "b" or answer4 == "B" or answer4 == "Toronto" or answer4 == "toronto": score += 1 print("You are correct\n") else: print("Incorrect, the answer is Toronto!\n") print("Current Score: "+ str(score) + "\n") answer5 = input("Q5. What province did not join Canada until 1949?" "\na. Quebec\nb. British Columbia\nc. Newfoundland and Labrador\nd. Saskatchewan\nAnswer: ") if answer5 == "c" or answer5 == "C" or answer5 == "Newfoundland and Labrador" or answer5 == "newfoundland and labrador": score += 1 print("You are correct\n") else: print("Incorrect, the answer is Newfoundland and Labrador!\n") print("Current Score: "+ str(score) + "\n") if score >=5: print("Excellent! " + str(score) + " /5") #Output when user score 4 and above elif score >=3: print("Good job, almost there.." + str(score) + "/5") #Output when user score or equal to 3 else: print("Need to study more! " + str(score) + "/5") #Output when user score 3 and below
true
256990003e5d17856435c73e2faac0e495a2001f
DavidQiuUCSD/CSE-107
/Discussions/Week1/OTP.py
2,104
4.375
4
import random #importing functions from Lib/random """ Author: David Qiu The purpose of this program is to implement Shannon's One-Time Pad (OTP) and to illustrate the correctness of the encryption scheme. OTP is an example of a private-key encryption as the encryption key (K_e) is equal to the decryption key (K_d) and both are kept secret from any adversary. The scheme itself can be described as a tuple of three algorithms: Key Generation, Encryption, and Decryption. The key generation algorithm is dependent on a security parameter, which describes how long (bitwise) the key is. Both encryption and decryption algorithm involve XOR'ing the message/ciphertext with the key. """ PARAMETER = 100 def keyGen(p): """ :param p: security paramter :output k: a number randomly chosen in the keyspace {0,1}^k, assigned to be K_e and K_d """ k = random.randint(0, 2**p-1) # ** is the operator for exponetiation return k def Enc(m, k): """ :param m: the message to be encrypted, whose bitlength must also be equal to the security parameter :param k: encryption key, K_e, generated by the key generation algorithm :output c: ciphertext corresponding to encrypting the message """ c = m ^ k # ^ is the operator for bitwise XOR return c def Dec(c, k): """ :param c: the ciphertext to be decrypted, whose bitlength must also be equal to the security parameter :param k: decryption key, K_d, generated by the key generation algorithm :output m: message corresponding to decrypting the ciphertext """ m = c ^ k return m """ now to show that the above functions are correct. We will encrypt a random message and verify that decrypting the corresponding ciphertext will reveal the same message """ key = keyGen(PARAMETER) message = random.randint(0, 2**PARAMETER-1) #print(message) ciphertext = Enc(message, key) response = Dec(ciphertext, key) #print(response) if response == message: print("Success") else: print("Something went wrong")
true
15f91012d9614d46fe03d9b4ff7b83dd53ad31b5
vihahuynh/CompletePythonDeveloper2021
/break-the-ice-with-python/question81.py
321
4.21875
4
""" By using list comprehension, please write a program to print the list after removing numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. """ my_lst = [12,24,35,70,88,120,155] # using filter print(list(filter(lambda i: i % 35, my_lst))) # using comprehensive print([i for i in my_lst if i % 35])
true
9cc284d8bb87873882c68440c1ee19f0d4bcf094
vihahuynh/CompletePythonDeveloper2021
/break-the-ice-with-python/question4.py
336
4.1875
4
""" Input: Write a program which accepts a sequence of comma-separated numbers from console Output: generate a list and a tuple which contains every number.Suppose the following input is supplied to the program """ seq = input('Please in out a sequence of comma-separated numbers\n') print(seq.split(",")) print(tuple(seq.split(",")))
true
154f1639865eb98d55ea566ccb0894b949ad14d3
vihahuynh/CompletePythonDeveloper2021
/break-the-ice-with-python/question28.py
291
4.15625
4
""" Define a function that can receive two integer numbers in string form and compute their sum and then print it in console. """ def sum_2_num(): num1 = input('Input the first number: \n') num2 = input('Input the second number: \n') print(int(num1) + int(num2)) sum_2_num()
true
0800b959b8ff2a1687b1c883135a06d5cec4776c
Pritheeev/Practice-ML
/matrix.py
1,665
4.1875
4
#getting dimension of matrix print "enter n for nxn matrix" n = input() matrix1 = [] matrix2 = [] #taking elements of first matrix print "Enter elements of first matrix" for i in range(0,n): #taking elements of first column print "Enter elements of ",i,"column, seperated by space" #raw_input().split() will split the string #'1 2 34'.split() will give ['1', '2', '34'] #map will convert its elements into integers [1, 2, 34] matrix1.append(map(int,raw_input().split())) print "Matrix 1 is",matrix1 #taking elements of second matrix print "Enter elements of second matrix" for i in range(0,n): #Similar to input taken for 1 matrix print "Enter elements of ",i,"column, seperated by space" matrix2.append(map(int,raw_input().split())) print "Matrix 2 is",matrix2 #adding add_matrix = [] for i in range(0,n): a = [] for j in range(0,n): #making a addition matrix's column to append #making a 1D matrix with elements as sum of elements of #respective columns of both matrices a.append(matrix1[i][j]+matrix2[i][j]) add_matrix.append(a) print "Addition of matrix is",add_matrix #multiplication multi_matrix = [] for i in range(0,n): a = [] for j in range(0,n): summ = 0 for k in range(0,n): summ = summ+(matrix1[i][k]*matrix2[k][j]) a.append(summ) multi_matrix.append(a) print "matrix1 x matrix 2 =",multi_matrix #transpose of matrix1 tr_matrix=[] for i in range(0,n): a = [] for j in range(0,n): #matrix1[j][i] will give row of matrix 1 #we are making it column of new matrix a.append(matrix1[j][i]) tr_matrix.append(a) print "Transpose of matrix 1 is",tr_matrix
true
a586bcfe643f3d205136714172bf386a7b8c0e1f
wmaxlloyd/CodingQuestions
/Strings/validAnagram.py
1,380
4.125
4
# Given two strings s and t, write a function to determine if t is an anagram of s. # For example, # s = "anagram", t = "nagaram", return true. # s = "rat", t = "car", return false. # Note: # You may assume the string contains only lowercase alphabets. # Follow up: # What if the inputs contain unicode characters? How would you adapt your solution to such case? # s = "anagram" t = "nagrama" print "sorting" print True if sorted(s) == sorted(t) else False print "Using a hash map" sHash = {} tHash = {} anagram = True if len(s) == len(t) else False if anagram: for i in xrange(len(s)): if s[i] not in sHash: sHash[s[i]] = 1 else: sHash[s[i]] += 1 if t[i] not in tHash: tHash[t[i]] = 1 else: tHash[t[i]] += 1 for key in sHash: try: if sHash[key] != tHash[key]: anagram = False break except: anagram = False break print anagram print "For all Unicode" anagram = True if len(s) == len(t) else False sHash = {} tHash = {} print sHash, tHash if anagram: for i in xrange(len(s)): sUniKey = ord(s[i]) tUniKey = ord(t[i]) if sUniKey in sHash: sHash[sUniKey] += 1 else: sHash[sUniKey] = 1 if tUniKey in tHash: tHash[tUniKey] += 1 else: tHash[tUniKey] = 1 print sHash, tHash for key in sHash: try: if sHash[key] != tHash[key]: anagram = False break except: anagram = False break print anagram
true
54f9eee09ecc211fc0cc378746ceb92c6ca76c8b
wdlsvnit/SMP-2017-Python
/smp2017-Python-maulik/extra/lesson8/madLibs.py
909
4.40625
4
#! python3 #To read from text files and let user add their own text anywhere the word- #ADJECTIVE, NOUN, ADVERB or VERB import re,sys try: fileAddress=input("Enter path of file :") file = open(fileAddress) except FileNotFoundError: print("Please enter an existing path.") sys.exit(1) fileContent = file.read() file.close() print(fileContent) findRegex = re.compile(r'''ADJECTIVE|NOUN|ADVERB|VERB''') fo=findRegex.search(fileContent) while(fo != None): print("Enter " + fo.group().lower() + ":") replacement=input() replaceRegex=re.compile(fo.group()) fileContent=replaceRegex.sub(replacement,fileContent,count=1) fo=findRegex.search(fileContent) newFileAddress=input("Enter path of new file:") print("") file=open(newFileAddress,"w") file.write(fileContent) file.close() print("Following text written to new file at " + newFileAddress) print(fileContent)
true
b18cb0ad7ea82d7658bfb957eec60bb047c55971
darkknight161/crash_course_projects
/pizza_toppings_while.py
513
4.21875
4
prompt = "Welcome to Zingo Pizza! Let's start with Toppings!" prompt += "\nType quit at any time when you're done with your pizza masterpiece!" prompt += "\nWhat's your name? " name = input(prompt) print(f'Hello {name}!') toppings = [] topping = "" while topping != 'quit': topping = input('Name a topping to add: ') if topping == 'quit': break else: toppings.append(topping) print(f"Got it, {name}! Here's a run down of what you've ordered:") for value in toppings: print(value)
true
640c1b68233d7fe7ee1cdc0a44b30dd0afce9c1b
umangag07/Python_Array
/array manipulation/changing shape.py
1,019
4.625
5
""" Changing shapes 1)reshape() -:gives a new shape without changing its data. 2)flat() -:return the element given in the flat index 3)flatten() -:return the copied array in 1-d. 4)ravel() -:returns a contiguous flatten array. """ import numpy as np #1 array_variable.reshape(newshape) a=np.arange(8) b=a.reshape(2,2,2) print("The original array-:",a) print("Chnaged array-:",b) #2 array_variable.flat(int) a=np.arange(8) b=a.flat[3] print("The original array-:",a) print("Element of the flat index is",b) #3 array_variable.flatten() a=np.arange(8).reshape(2,2,2) b=a.flatten() print("The original array-:",a) print("Flatten array in 1-d -:",b) #4 """ array_variable.ravel(order) order can be-'F' fortran style 'K' flatten as elemnets occure in the memory""" a=np.array([[7,8,9,2,3],[1,5,0,4,6]]) b=a.ravel() c=a.ravel(order='F') print("The original array-:",a) print("Array after ravel -:",b) print("Array returned in fortran style-:",c)
true
31050593b4252bf94fb491e37e0a0628017d2b69
90-shalini/python-edification
/collections/tuples.py
785
4.59375
5
# Tuples: group of items num = (1,2,3,4) # IMUTABLE: you can't update them like a list print(3 in num) # num[1] = 'changed' # will throw error # Faster than list, for the data which we know we will not change use TUPLE # tuple can be a key on dictionary # creating/accessing -> () or tuple xyz = tuple(('a', 'b')) print("tuple created using tuple: ", xyz) #dictionary.items() returns a tuple of key:value in dictionary months = ('Jan', 'Feb', 'March', 'April', 'June', 'July', 'Aug') #ITERATING over tuples, using loops for month in months: print(month) #Tuple Methods: counting = (1,2,3,4,5,3,4,5,6,4,5,3,6) #count print('Count of element passed in function: ', counting.count(5)) #index print("Index of element:", counting.index(3)) # Nested tuples # can do slicing like lists
true
3aa3292bad982d13aa181250c738804b14af68ca
ssenthil-nathan/DSA
/linkedlistdelwithkey.py
1,628
4.21875
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def Delete(self, key): temp = self.head #traverse till the last Node while(temp is not None): #if head itself holds the key if (temp.data == key): #make the head node as the next node self.head = temp.next #free the memory temp = None else: while(temp is not None): if (temp.data == key): break #store the value of previous node in prev variable. prev = temp temp = temp.next #if it is not return if (temp == None): return #make the next of the previous variable as the next of key node. prev.next = temp.next temp = None def printList(self): temp = self.head while(temp is not None): print(temp.data) temp = temp.next if __name__ == '__main__': llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) llist.head.next = second second.next = third third.next = None llist.push(8) llist.Delete(8) llist.printList()
true
61739837cf983d73229378376144c6465d798813
sevresbabylone/python-practice
/quicksort.py
744
4.34375
4
"""Quicksort""" def quicksort(array, left, right): """A method to perform quicksort on an array""" if left < right: pivot = partition(array, left, right) quicksort(array, left, pivot-1) quicksort(array, pivot+1, right) def partition(array, left, right): """Returns new pivot after partitioning array elements according to current pivot""" for index in range(left, right): if array[index] <= array[right]: array[left],array[index] = array[index],array[left] left += 1 array[left],array[right] = array[right],array[left] return left UNSORTED_ARRAY = [9, 7, 5, 11, 12, 2, 14, 3, 10, 6] quicksort(UNSORTED_ARRAY, 0, len(UNSORTED_ARRAY) - 1) print(UNSORTED_ARRAY)
true
f853cecddcac4e12ec8d8d2f60e01e80ad840f98
mclavan/Work-Maya-Folder
/2014-x64/prefs/1402/if_01_notes.py
1,239
4.5625
5
''' Lesson - if statements ''' ''' Basic if statement if condition: print 'The condition is True.' ''' if True: print 'The condition is True.' if False: print 'The condition is True' ''' What is the condition? 2 == 2 2 == 3 ''' ''' Operators == Equals != Not Equals > Greater Than >= Greater Than or equal to < Less Than <= Less Than or equal to ''' if 2 == 2: print '2 is equal to 2.' if 2 != 3: print '2 is not equal to 3.' ''' Using multiple conditions and or not ''' if 2 == 2 and 2 != 3: print 'Both conditions are True.' if 2 == 2 and 2 == 3: print 'Both conditions are True.' if 2 == 2 or 2 == 3: print 'Both conditions are True.' ''' What if I want to react to False? else statement ''' if 2 == 3: print 'The condition is True.' else: print 'The condition is False.' ''' What if I want to have multiple paths? elif statement. ''' ''' about command pm.about() # os=True returns operating system # windows=True returns true if currently on windows. # macOs=True returns true if currently on osx. ''' if pm.about(windows=True): print 'You are using a computer with windows.' elif pm.about(macOs=True): print 'You are using a computer with osx.' else: print 'You are using a different os.'
true
4560ae75b9c66bbb4cf36973f48db46b620e10a8
pedronora/exercism-python
/prime-factors/prime_factors.py
458
4.125
4
def factors(value): factors_list = [] # Divisible by 2: while value % 2 == 0: factors_list.append(2) value = value / 2 # Divisible by other primes numbers: sqrt = int(value**0.5) for i in range(3, sqrt + 1, 2): while value % i == 0: factors_list.append(i) value = value / i # If value is prime if value > 2: factors_list.append(value) return factors_list
true
fd7a963ec1bbba262d7f0cb3348995198a805674
isobelyoung/Week4_PythonExercises
/Saturday_Submission/exercise_loops.py
2,201
4.15625
4
# Q1 print("***QUESTION 1***") # Sorry Hayley - I had already written this bit before our class on Tuesday so didn't use the same method you did! all_nums = [] while True: try: if len(all_nums) == 0: num = int(input("Enter a number! ")) all_nums.append(num) else: num = int(input("Enter another number, or press enter: ")) all_nums.append(num) except ValueError: break sum_nums = sum(all_nums) print(f"The total sum of your numbers is {sum_nums}!") # Q2 print("***QUESTION 2***") mailing_list = [ ["Roary", "roary@moth.catchers"], ["Remus", "remus@kapers.dog"], ["Prince Thomas of Whitepaw", "hrh.thomas@royalty.wp"], ["Biscuit", "biscuit@whippies.park"], ["Rory", "rory@whippies.park"] ] for i in range(len(mailing_list)): print(mailing_list[i][0] + ": " + mailing_list[i][1]) # Q3 print("***QUESTION 3***") names = [] name_1 = input("Hi there! Type your name: ") names.append(name_1) name_2 = input("Thanks for that! What's your mum's name? ") names.append(name_2) name_3 = input("Last one - what's your dad's name? ") names.append(name_3) for x in names: print(x) # Q4 print("***QUESTION 4***") groceries = [ ["Baby Spinach", 2.78], ["Hot Chocolate", 3.70], ["Crackers", 2.10], ["Bacon", 9.00], ["Carrots", 0.56], ["Oranges", 3.08] ] customer_name = input("Hi there! Thanks for visiting our store. What's your name? ") ind = 0 for x in groceries: n = int(input(f"How many units of {groceries[ind][0]} did you buy? ")) groceries[ind].append(n) ind += 1 receipt_width = 28 print() print("Your receipt is as follows: ") print() header = "Izzy's Food Emporium" print(header.center(receipt_width, '=')) total_cost = [] for i in range(len(groceries)): cost = groceries[i][1] * groceries[i][2] total_cost.append(cost) # space_width = receipt_width - len(groceries[i][0]) - 8 # print("{}".format(groceries[i][0]) + " " * space_width + "${:.2f}".format(cost)) print(f"{groceries[i][0]:<20} ${cost:>5.2f}") print("=" * receipt_width) receipt_sum = sum(total_cost) sum_str = "${:>5.2f}".format(receipt_sum) print(f"{sum_str:>27}") # print(sum_str.rjust(receipt_width, ' '))
true
e6e3fe4c8e42ba41bfdabdc0df75ef1d40584fb8
rigzinangdu/python
/practice/and_or_condition.py
984
4.3125
4
# We have to see [and] [or] conditions in pythons : #[and] remember if both the conditions true than output will be true !!! if it's one of condition wrong than it's cames false ----> !! #[or] remember one of the condition if it's true than its will be came true conditions -----> !! #<-----[and]------> name = "python" pass1 = "abc123456" username = input("Enter the username : ") password = input("Enter your password : ") if username == name and password == pass1: print("Line A") print("Login Successfully") else: print("invalid username and password") #<-----[and]------> #<-----[or]------> name = "python" pass1 = "abc123456" username = input("Enter the username : ") password = input("Enter your password : ") if username == name or password == pass1: print("Line A") print("Login Successfully") else: print("invalid username and password") #<-----[or]------>
true
ca6f741a9a9300c892550aa72f17e1bcbb8197cf
Marwan-Mashaly/ICS3U-Weekly-Assignment-02-python
/hexagon_perimeter_calculator.py
461
4.3125
4
#!/usr/bin/env python3 # Created by Marwan Mashaly # Created on September 2019 # This program calculates the perimeter of a hexagon # with user input def main(): # this function calculates perimeter of a hexagon # input sidelength = int(input("Enter sidelength of the rectangle (cm): ")) # process perimeter = 6*sidelength # output print("") print("Perimeter is {}cm ".format(perimeter)) if __name__ == "__main__": main()
true
269fa0433fc048b50a8f24cc449a278c8b0b959c
kyumiouchi/python-basic-to-advanced
/11.73. Commun Errors.py
2,023
4.25
4
""" Common Errors It is important to understand the error code SyntaxError - Syntax error- not part of Python language """ # printf('Geek University') # NameError: name 'printf' is not defined # print('Geek University') # 1) Syntax Error # 1 # def function: # SyntaxError: invalid syntax # print('Geek University') # 2 # None = 1 # SyntaxError: can't assign to keyword # 3 # return # SyntaxError: 'return' outside function # 2) Name Error -> Variable or Function is not defined # a. # print(geek) # NameError: name 'geek' is not defined # b. # geek() # NameError: name 'geek' is not defined # c. # a = 18 # # if a < 10: # msg = 'Is great than 10' # # print(msg) # NameError: name 'msg' is not defined # 3 - Type Error -> function/operation/action # a. # print(len(5)) # TypeError: object of type 'int' has no len() # b. # print('Geek' + []) # TypeError: must be str, not list # 4 - IndexError - element of list wrong and or index data type # list_n = ['Geek'] # a. # print(list_n[2]) # IndexError: list index out of range # b. # print(list_n[0][10]) # IndexError: list index out of range # tuple_n = ('Geek',) # print(tuple_n[0][10]) # IndexError: string index out of range # 5) Value Error -> function/operation build-in argument with wrong type # Smaples # a. # print(int('42')) # print(int('GEek')) # ValueError: invalid literal for int() with base 10: 'GEek' # 6) Key Error-> Happen when try to access a dictionary with a key that not exist # a. # dic = {} # print(dic['geek']) # KeyError: 'geek' # 7) AttributeError -> variable do not have attribute/function # a. # tuple_n = (11, 2, 31, 4) # print(tuple_n.sort()) # AttributeError: 'tuple' object has no attribute 'sort' # 8) IndentationError -> not respect the indentation od 4 spaces # a. # def new_function(): # print("Geek") # IndentationError: expected an indented block # for i in range(10): # i+1 # IndentationError: expected an indented block # OBS: Exception == Error # Important to read the output error
true
631632c5fd1c857d8ec88288d114f5ca499a6a46
elgun87/Dictionary
/main.py
1,211
4.25
4
# Created empty dictionary to add word and then to check if the word in the dictionary # If yes print the meaning of the word ''' dictionary = {} while True: word = input("Enter the word : ") if word in dictionary: #checking if the word in the list print(f'I have this word in my dictionary : {dictionary[word]}') else: add = input("I dont have this word meaning.Please add the meaning : ") dictionary [word] = add ''' ## In this program asking the name of the user then inserting his age. ''' check_list = {} #Created empty dictionary while True: name = input("What is your name : ") if name in check_list: #Checking if the name in the check_list.If yes print the check_list print(f'I found you in the system.Your age is {check_list[name]}') continue number = int(input("what is your age : ")) # asking his age check_list[name] = number ask = input("Enter the name to find your age : ") #asking his name to find how old is he if ask in check_list: print(check_list[name]) else : print('We dont have your in our system ') number = int(input("what is your age : ")) check_list [ask] = number '''
true
704045f6eaaa5c51d088b11ceb7877a7cf69b2d3
hannahmclarke/python
/dice_roll.py
1,199
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue May 21 21:02:54 2019 @author: Hannah """ """ Program will roll a pair of dice (number of sides will be randomly determined) and ask the user to guess the total value, to determine who wins Author: Hannah """ from random import randint from time import sleep def get_sides(): sides = randint(4, 8) return sides def get_user_guess(): guess = int(input("Make your guess: ")) return guess def roll_dice(number_of_sides): number_of_sides = get_sides() first_roll = randint(1, number_of_sides) second_roll= randint(1, number_of_sides) max_val = number_of_sides * 2 print ("Maximum possible value is %d" % (max_val)) guess = get_user_guess() if guess > max_val: print ("Guess is too high") else: print ("Rolling...") sleep(2) print ("First roll is a %d" % (first_roll)) sleep(2) print ("...and the second roll is %d" % (second_roll)) sleep(2) total_roll = first_roll + second_roll print ("Total is... %d" % (total_roll)) print ("Result...") sleep(1) if guess == total_roll: print ("Nice work! Winner!!") else: print ("Aha you lose!") roll_dice(get_sides())
true
18440ad27f90f49a1c08f5df08ffe73d743d6967
Lanottez/IC_BA_2020
/1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses02/ses02_extra.py
2,174
4.4375
4
def middle_of_three(a, b, c): """ Returns the middle one of three numbers a,b,c Examples: >>> middle_of_three(5, 3, 4) 4 >>> middle_of_three(1, 1, 2) 1 """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW return ... def sum_up_to(n): """ Returns the sum of integers from 1 to n Examples: >>> sum_up_to(1) 1 >>> sum_up_to(5) 15 """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW return ... def square_root_heron(x, epsilon=0.01): """ Find square root using Heron's algorithm Parameters: x: integer or float epsilon: desired precision, default value epsilon = 0.01 if not specified Returns: the square root value, rounded to two decimals the number of iterations of the algorithm run Example use: >>> y, c = square_root_heron(20) >>> print(y, c) 4.47 4 """ # DON'T CHANGE ANYTHING ABOVE # UPDATE CODE BELOW guess = x/2 # Make initial guess # Loop until squared value of guess is close to x while abs(guess*guess - x) >= epsilon: guess = (guess + x/guess)/2 # Update guess using Heron's formula return round(guess, 2), ... # replace the dots with the final number of iterations def square_root_bisection(x, epsilon=0.01): """ Find square root using bisection search Parameters: x: integer or float epsilon: desired precision, default value epsilon = 0.01 if not specified Returns: the square root value, rounded to two decimals the number of iterations of the algorithm run Example use: >>> y, c = square_root_bisection(20) >>> print(y, c) 4.47 9 """ # DON'T CHANGE ANYTHING ABOVE # UPDATE CODE BELOW low = 0.0 high = max(1.0, x) # Why are we doing this? What would happen for x=0.5? guess = (low + high)/2 # First guess at midpoint of low and high while abs(guess*guess - x) >= epsilon: if guess*guess < x: low = ... # update low else: high = ... # update high guess = ... # new guess at midpoint of low and high return ..., ...
true
8ee4f7214d13842468a03b05f7fdd25e3947c7fc
Lanottez/IC_BA_2020
/1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses02/ses02.py
1,057
4.375
4
def sum_of_squares(x, y): """ Returns the sum of squares of x and y Examples: >>> sum_of_squares(1, 2) 5 >>> sum_of_squares(100, 3) 10009 >>> sum_of_squares(-1, 0) 1 >>> x = sum_of_squares(2, 3) >>> x + 1 14 """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW THIS return x^2+y^2 # REPLACE THIS LINE WITH YOUR CODE def print_grade(mark, grade_high, grade_low): """ Prints out 'distinction', 'pass', or 'fail' depending on mark If mark is at least grade_high, prints 'distinction' Else if mark is at least grade_low, prints 'pass' Else prints 'fail' Examples: >>> grade_high = 70 >>> grade_low = 50 >>> print_grade(20, grade_high, grade_low) fail >>> print_grade(61, 70, 50) pass >>> print_grade(90, 80, 60) distinction """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW THIS if mark >= grade_high: print("distinction") elif mark >= grade_low: print("pass") else: print("fail")
true
0c143e6c44d259294ada8ee2cda95c37f74a15ff
Lanottez/IC_BA_2020
/1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses06/ses06_extra.py
1,525
4.5625
5
def caesar_cipher_encrypt(str_to_encrypt, n): """ Encrypt string using Caesar cipher by n positions This function builds one of the most widely known encryption techniques, _Caesar's cipher_. This works as follows: you should be given a string str_to_encrypt and an encoding integer n, which then be used to replace each initial letter to the encrypted one by simply shifting the letter by n positions. Parameters: str_to_encrypt: string n: shift parameter Returns: n-encrypted string Examples: >>> caesar_cipher_encrypt('a', 1) 'b' >>> caesar_cipher_encrypt('abc', 1) 'bcd' >>> caesar_cipher_encrypt('abc', 4) 'efg' >>> caesar_cipher_encrypt('thisistherealdeal', 6) 'znoyoyznkxkgrjkgr' """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW THIS alphabet = 'abcdefghijklmnopqrstuvwxyz' def caesar_cipher_decrypt(str_to_decrypt, n): """ Decrypt Caesar cipher by n positions Parameters: str_to_decrypt: string n: shift parameter Returns: n-decrypted string Examples: >>> caesar_cipher_decrypt('b', 1) 'a' >>> caesar_cipher_decrypt('bcd', 1) 'abc' >>> caesar_cipher_decrypt('efg', 4) 'abc' >>> caesar_cipher_decrypt('znoyoyznkxkgrjkgr', 6) 'thisistherealdeal' """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW THIS alphabet = 'abcdefghijklmnopqrstuvwxyz'
true
a858fbfb5b2570d28a04edf7ef7d99fae6cd1038
mcwiseman97/Programming-Building-Blocks
/adventure_game.py
1,829
4.1875
4
print("You started a new game! Congratulations!") print() print("You have just had a very important phone call with a potential employer.") print("You have been in search of a new job that would treat you better than you had been at your last place of emplyement.") print("John, the employer, asked you to submit to him your desired salary by 5pm today.") print() salary = int(input("What salary do you with to obtain in this job? ")) print() print("Some time later...") print("Thank you for submiting your desired wages! I see that you are looking for", salary,"dollars. ") print() if salary > 75000: print("We reviewed the slary that you presented and are sorry that we cannot provide that amount for you.") print("However we would like to offer you 6500. Would you be interested in this amount?") high_salary = input("YES or NO: ") if high_salary == "yes": print("Great, We look forward to working with you! We have just sent you an email with a document you need to sign before you come into work on monday.") elif high_salary == "no": print("You said no") elif salary >= 45001: print("Good news! We have accepted your request for,", salary, "!") print("We will send you an email with a document to sign before you start work on monday.") elif salary <= 45000: print("Are you sure you don't want to ask for more than,", salary,"?") low_salary = input("YES or NO: ") if low_salary == "yes": print("Upon reviewing your request, we have determined that we will offer you the job, at out starting salary for this position.") print("You will recieve an email shortly. Please sign the document, which will indicate that you accept the job position.") elif low_salary == "no": salary = int(input("What salary do you with to obtain in this job? ")) else: print("TRY AGAIN")
true
26eeca2fda332e7113887da66b91edf8ad362a2c
nerminkekic/Guessing-Game
/guess_the_number.py
912
4.4375
4
# Write a programme where the computer randomly generates a number between 0 and 20. # The user needs to guess what the number is. # If the user guesses wrong, tell them their guess is either too high, or too low. import random # Take input from user guess = int(input("Guess a number between 0 and 20! ")) # Number of guesses tracking guess_count = 1 # Generate random number randomNumb = random.randrange(20) # Allow user to guess again if first guess is not correct # Also check for conditions and let user know if they guessed high or low while guess != randomNumb: guess_count += 1 if guess < randomNumb: print("You guessed low!") guess = int(input("Try another guess. ")) elif guess > randomNumb: print("Your guessed high!") guess = int(input("Try another guess. ")) print("You have guessed correct. YOU WIN!") print(f"Total number of guesses: {guess_count}")
true