blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b86433902a7cf3e9dcba2d7f254c4318656ca7f7
heba-ali2030/number_guessing_game
/guess_game.py
2,509
4.1875
4
import random # check validity of user input # 1- check numbers def check_validity(user_guess): while user_guess.isdigit() == False: user_guess = input('please enter a valid number to continue: ') return (int(user_guess)) # 2- check string def check_name(name): while name.isalpha() == False: print('Ooh, Sorry is it your name?!') name = input('Please enter your name: ') return name # begin the game and ask the user to press yes to continue print(f'Are you ready to play this game : Type Yes button to begin: ') play = input(f' Type Yes or Y to continue and Type No or N to exit \n ').lower() if play == 'yes' or play == 'y': # get user name name = check_name(input('Enter your name: \n')) # get the number range from the user first = check_validity(input('enter the first number you want to play: \n first number: ')) last = check_validity(input('enter the last number of range you want to play: \n last number: ')) # tell the user that range print (f'Hello {name}, let\'s begin! the number lies between {first} and {last} \n You have 5 trials') number_to_be_guessed = random.randint(first, last) # print(number_to_be_guessed) # Number of times for the guess game to run run = 1 while run <= 5: run += 1 user_guess = check_validity(input('what is your guess: ')) # if user guess is in the range if user_guess in range(first, last): print('Great beginning, you are inside the right range') # 1- if the user guess is true if user_guess == number_to_be_guessed: print(f'Congratulation, you got it, the number is: {number_to_be_guessed}') break # 2- if the guess is high elif user_guess > number_to_be_guessed: print(f' Try Again! You guessed too high') # 3 - if the guess is small else: print(f'Try Again! You guessed too small') # # if the user guess is out of range else: print (f'You are out of the valid range, you should enter a number from {first} to {last} only!') # # when the number of play is over else: print(f'{name}, Sorry \n <<< Game is over, Good luck next time , the guessed number is {number_to_be_guessed} >>>') # # when user type no: else: print('Waiting to see you again, have a nice day')
true
01a31344d5f0af270c71baa134890070081a1d5c
ColgateLeoAscenzi/COMPUTERSCIENCE101
/LAB/Lab01_challenge.py
898
4.28125
4
import time import random #Sets up the human like AI, and asks a random question every time AI = random.randint(1,3) if AI == 1: print "Please type a number with a decimal!" elif AI == 2: print "Give me a decimal number please!" elif AI == 3: print "Please enter a decimal number!" #defines the response and prompts the user to enter a number response = float(raw_input()) #defines the rounded response and does the math rounded_response = int(response)+1 #makes the computer seem more human a = "." print "Calculating" time.sleep(0.5) print(a) time.sleep(0.5) print(a) time.sleep(0.5) print(a) time.sleep(1) #prints the users number rounded up print "Response calculated!" time.sleep(1) print"The rounded up version of your number is: %s" % rounded_response #adds a delay at the end for the user to reflect upon their answer time.sleep(3)
true
676f4845dc145feee1be508213721e26f2e55b2a
ColgateLeoAscenzi/COMPUTERSCIENCE101
/HOMEWORK/hw3_leap.py
2,055
4.15625
4
# ---------------------------------------------------------- # -------- PROGRAM 3 --------- # ---------------------------------------------------------- # ---------------------------------------------------------- # Please answer these questions after having completed this # program # ---------------------------------------------------------- # Name: Leo Ascenzi # Hours spent on this program: 0.66 # Collaborators and sources: # (List any collaborators or sources here.) # ---------------------------------------------------------- def is_leap_year(y): if y%4 == 0: return True else: return False #Anything under 1582 is invalid invalidrange = range(1582) #defines start and endyears for future rearranging startyear = 0 endyear = 0 def main(): #gets inputs year1 = int(raw_input("Enter a year: ")) year2 = int(raw_input("Enter a second year: ")) #checks valid range if year1 in invalidrange or year2 in invalidrange: print "The range must start after or at 1582" #checks which year is bigger else: if year1>year2: startyear = year2 endyear = year1 elif year2>year1: startyear = year1 endyear = year2 else: startyear = year1 endyear = year2 #for all the years more than the start year in the endyear range, print leapyear or nah for years in range((endyear+1)): if years<startyear: pass else: if is_leap_year(years): print years, "is a leap year" else: print years, "is a normal year" # finally, call main. Which makes the code work main()
true
7004bc9b49acc1a75ac18e448c2256cbec808cf4
CodyPerdew/TireDegredation
/tirescript.py
1,350
4.15625
4
#This is a simple depreciation calculator for use in racing simulations #Users will note their tire % after 1 lap of testing, this lets us anticipate #how much any given tire will degrade in one lap. #From there the depreciation is calculated. sst=100 #Set tire life to 100% st=100 mt=100 ht=100 print("when entering degredation use X.XX format") #Have the user enter their degredation figures after a test lap for each type of tire. laps = int(input("How many laps to show?")) #how many laps in the race? ss = float(input("What is the degredation on SuperSoft tires?")) s = float(input("on Softs?")) m = float(input("on Medium?")) h = float(input("on Hards?")) laps += 1 print("Here's your expected tire life after each lap") lapcount = 1 while laps > 1: #multiply tire-left * degredation, subtract that amount from tire-left ssdeg = sst * ss sst = sst - ssdeg sdeg = st * s st = st - sdeg mdeg = mt * m mt = mt - mdeg hdeg = ht * h ht = ht - hdeg #print the expected tire life after X laps, ':<5' used for formatting print("AFTER LAP: {:<5} SST:{:<5} ST:{:<5} MT:{:<5} HT:{:<5}".format(lapcount, round(sst, 1), round(st, 1), round(mt, 1), round(ht, 1))) laps -= 1 lapcount += 1
true
f0afa65944197e58bad3e76686cef9c2813ab16d
chrismlee26/chatbot
/sample.py
2,521
4.34375
4
# This will give you access to the random module or library. # choice() will randomly return an element in a list. # Read more: https://pynative.com/python-random-choice/ from random import choice #combine functions and conditionals to get a response from the bot def get_mood_bot_response(user_response): #add some bot responses to this list bot_response_happy = ["omg! great!", "Keep smiling!", "I love to see you happy!"] bot_response_sad = ["im here for you", "sending good vibes", "Ok is fine"] if user_response == "happy": return choice(bot_response_happy) elif user_response == "sad": return choice(bot_response_sad) elif user_response == "ok": return choice(bot_response_sad) else: return "I hope your day gets better" print("Welcome to Mood Bot") print("Please enter how you are feeling") user_response = "" #TODO: we want to keep repeating until the user enters "done" what should we put here? while True: user_response = input("How are you feeling today?: ") # Quits program when user responds with 'done' if user_response == 'done': break bot_response = get_mood_bot_response(user_response) print(bot_response) # Create a function called get_bot_response(). This function must: # It should have 1 parameter called user_response, which is a string with the users input. # It should return a string with the chat bot’s response. # It should use at least 2 lists to store at least 3 unique responses to different user inputs. For example, if you were building a mood bot and the user entered “happy” for how they were feeling your happy response list could store something like “I’m glad to hear that!”, “Yay!”, “That is awesome!”. # Use conditionals to decide which of the response lists to select from. For example: if a user entered “sad”, my program would choose a reponse from the of sad response list. If a user entered “happy”, my program would choose a reponse from the of happy response list. # Use choice() to randomly select one of the three responses. (See example from class.) # Greet the user using print() statements and explain what the chat bot topic is and what kind of responses it expects. # Get user input using the input() function and pass that user input to the get_bot_response() function you will write # Print out the chat bot’s response that is returned from the get_bot_response() function # Use a while() loop to keep running your chat bot until the user enters "done".
true
e8642c64ba0981f3719635db11e52a0823e89b68
league-python/Level1-Module0
/_02_strings/_a_intro_to_strings.py
2,954
4.6875
5
""" Below is a demo of how to use different string methods in Python For a complete reference: https://docs.python.org/3/library/string.html """ # No code needs to be written in this file. Use it as a reference for the # following projects. if __name__ == '__main__': # Declaring and initializing a string variable new_str = "Welcome to Python!" # Getting the number of characters in a string num_characters = len(new_str) # Getting a character from a string by index--similar to lists character = new_str[2] # 'l' print(character) # Check if a character is a letter or a number print('Is ' + new_str[2] + ' a letter: ' + str(new_str[2].isalpha())) print('Is ' + new_str[2] + ' a digit: ' + str(new_str[2].isdigit())) # Removing leading and trailing whitespace from a string whitespace_str = ' This string has whitespace ' print('original string .......: ' + whitespace_str + ' ' + str(len(whitespace_str))) print('leading spaces removed : ' + whitespace_str.lstrip() + ' ' + str(len(whitespace_str.lstrip()))) print('trailing spaces removed: ' + whitespace_str.rstrip() + ' ' + str(len(whitespace_str.rstrip()))) print('leading and trailing spaces removed: ' + whitespace_str.strip() + ' ' + str(len(whitespace_str.strip()))) # Find the number of times a substring (or letter) appears in a string num_character = new_str.count('o') # 3 occurrences num_substring = new_str.count('to') # 1 occurrences print('\'o\' occurs ' + str(num_character) + ' times') print('\'to\' occurs ' + str(num_substring) + ' times') # Making a copy of a string str_copy = new_str[:] # Convert string to all upper case or lower case print(str_copy.upper()) print(str_copy.lower()) print(new_str) # Getting a substring from a string [<stat>:<end>], <end> is NOT inclusive new_substring1 = new_str[0:7] # 'Welcome' new_substring2 = new_str[8:10] # 'to new_substring3 = new_str[11:] # 'Python!' print(new_substring1) print(new_substring2) print(new_substring3) # Finding the index of the first matching character or substring index = new_str.find('o') print('\'o\' 1st appearance at index: ' + str(index)) index = new_str.find('o', index+1) print('\'o\' 2nd appearance at index: ' + str(index)) # Converting a string to a list new_str_list = list(new_str) print(new_str_list) # Converting a list to a string back_to_string = ''.join(new_str_list) print(back_to_string) # Converting a list to a string with a separator (delimiter) back_to_string = '_'.join(new_str_list) print(back_to_string) # Replacing characters from a string back_to_string = back_to_string.replace('_', '') print(back_to_string) # Splitting a string into a list of strings separated by a space ' ' split_str_list = new_str.split(' ') print(split_str_list)
true
f17492efff4bbe8ce87a626abfece629c0297a83
prajjwalkumar17/DSA_Problems-
/dp/length_common_decreasing_subsequence.py
1,918
4.375
4
""" Python program to find the Length of Longest Decreasing Subsequence Given an array we have to find the length of the longest decreasing subsequence that array can make. The problem can be solved using Dynamic Programming. """ def length_longest_decreasing_subsequence(arr, n): max_len = 0 dp = [] # Initialize the dp array with the 1 as value, as the maximum length # at each point is atleast 1, by including that value in the sequence for i in range(n): dp.append(1) # Now Lets Fill the dp array in Bottom-Up manner # Compare Each i'th element to its previous elements from 0 to i-1, # If arr[i] < arr[j](where j = 0 to i-1), then it qualifies for decreasing subsequence and # If dp[i] < dp[j] + 1, then that subsequence qualifies for being the longest one for i in range(0, n): for j in range(0, i): if(arr[i] < arr[j] and dp[i] < dp[j] + 1): dp[i] = dp[j] + 1 # Now Find the largest element in the dp array max_len = max(dp) return max_len if __name__ == '__main__': print("What is the length of the array? ", end="") n = int(input()) if n <= 0: print("No numbers present in the array!!!") exit() print("Enter the numbers: ", end="") arr = [int(x) for x in input().split(' ')] res = length_longest_decreasing_subsequence(arr, n) print("The length of the longest decreasing subsequence of the given array is {}".format(res)) """ Time Complexity - O(n^2), where 'n' is the size of the array Space Complexity - O(n) SAMPLE INPUT AND OUTPUT SAMPLE I What is the length of the array? 5 Enter the numbers: 5 4 3 2 1 The length of the longest decreasing subsequence of the given array is 5 SAMPLE II What is the length of the array? 10 Enter the numbers: 15 248 31 66 84 644 54 84 5 88 The length of the longest decreasing subsequence of the given array is 4 """
true
97174dfe60fdb0b7415ba87061573204d41490bc
rosa637033/OOAD_project_2
/Animal.py
597
4.15625
4
from interface import move class Animal: #Constructor def __init__(self, name, move:move): self.name = name self._move = move # any move method that is in class move def setMove(self, move) -> move: self._move = move # This is where strategy pattern is implemented. def move(self): self._move.run() def wake(self): print("I am awake") def noise(self): print("aw") def eat(self): print("I am eating") def roam(self): print("aw") def sleep(self): print("I am going to sleep")
true
fb05fad10a27e03c50ef987443726e2acd11d49a
adamchainz/workshop-concurrency-and-parallelism
/ex4_big_o.py
777
4.125
4
from __future__ import annotations def add_numbers(a: int, b: int) -> int: return a + b # TODO: time complexity is: O(_) def add_lists(a: list[int], b: list[int]) -> list[int]: return a + b # TODO: time complexity is O(_) # where n = total length of lists a and b def unique_items(items: list[int]) -> list[int]: unique: list[int] = [] for item in items: if item not in unique: unique.append(item) return unique # TODO: time complexity is O(_) # where n = length of list items def unique_items_with_set(items: list[int]) -> list[int]: unique: set[int] = set() for item in items: unique.add(item) return list(unique) # TODO: time complexity is O(_) # where n = length of list items
true
7c4b8a424c943510052f6b15b10a06a402c06f08
prasadnaidu1/django
/Adv python practice/QUESTIONS/10.py
845
4.125
4
#Question: #Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. #Suppose the following input is supplied to the program: #hello world and practice makes perfect and hello world again #Then, the output should be: #again and hello makes perfect practice world #Hints: #In case of input data being supplied to the question, it should be assumed to be a console input. #We use set container to remove duplicated data automatically and then use sorted() to sort the data. str=input("enter the data :") lines=[line for line in str.split()] #print(" ".join(sorted(list(set((lines)))))) l1=sorted(lines) print(l1) l2=list(lines) print(l2) l3=sorted(l1) print(l3) l4=set(lines) print(l4) l5=" ".join(sorted(list(set(lines)))) print(l5)
true
11b760a6ae93888c812d6d2912eb794d98e9c3e0
mohadesasharifi/codes
/pyprac/dic.py
700
4.125
4
""" Python dictionaries """ # information is stored in the list is [age, height, weight] d = {"ahsan": [35, 5.9, 75], "mohad": [24, 5.5, 50], "moein": [5, 3, 20], "ayath": [1, 1.5, 12] } print(d) d["simin"] = [14, 5, 60] d.update({"simin": [14, 5, 60]}) print(d) age = d["mohad"][0] print(age) for keys, values in d.items(): print(values, keys) d["ayath"] = [2] d.update("ayath") # Exercises # 1 Store mohad age in a variable and print it to screen # 2 Add simin info to the dictionary # 3 create a new dictionary with the same keys as d but different content i.e occupation # 4 Update ayath's height to 2 from 1.5 # 5 Write a for loop to print all the keys and values in d
true
b6ba17928cbcb5370f5d144e64353b9d0cd8fcbd
Mohsenabdn/projectEuler
/p004_largestPalindromeProduct.py
792
4.125
4
# Finding the largest palindrome number made by product of two 3-digits numbers import numpy as np import time as t def is_palindrome(num): """ Input : An integer number Output : A bool type (True: input is palindrome, False: input is not palindrome) """ numStr = str(num) for i in range(len(numStr)//2): if numStr[i] != numStr[-(i+1)]: return False return True if __name__ == '__main__': start = t.time() prods = (np.reshape(np.arange(100, 1000), (1, 900)) * np.reshape(np.arange(100, 1000), (900, 1)))[np.tril_indices(900)] prods = np.sort(prods)[::-1] for j in multiples: if is_palindrome(j): print(j) break end = t.time() print('Run time : ' + str(end - start))
true
82aff3d2c7f6ad8e4de6df39d481df878a7450f7
sree714/python
/printVowel.py
531
4.25
4
#4.Write a program that prints only those words that start with a vowel. (use #standard function) test_list = ["all", "love", "and", "get", "educated", "by", "gfg"] print("The original list is : " + str(test_list)) res = [] def fun(): vow = "aeiou" for sub in test_list: flag = False for ele in vow: if sub.startswith(ele): flag = True break if flag: res.append(sub) fun() print("The extracted words : " + str(res))
true
8d6df43f43f157324d5ce3012252c3c89d8ffba4
superyaooo/LanguageLearning
/Python/Learn Python The Hard Way/gpa_calculator.py
688
4.15625
4
print "Hi,Yao! Let's calculate the students' GPA!" LS_grade = float(raw_input ("What is the LS grade?")) # define variable with a string and input, no need to use "print" here. G_grade = float(raw_input ("What is the G grade?")) # double (()) works RW_grade = float(raw_input ("What is the RW grade?")) Fin_grade = float(raw_input ("What is the Final exam grade?")) # raw_input deals with string. needs to be converted into a floating point number Avg_grade = float((LS_grade*1 + G_grade*2 + RW_grade*2 + Fin_grade*2)/7) # the outer () here is not necessary print ("The student's GPA is:"),Avg_grade # allows to show the variable directly
true
6cefa99cdb92c9ed5738d4a40855a78b22e23b1b
Vladyslav92/Python_HW
/lesson_8/1_task.py
2,363
4.34375
4
# mobile numbers # https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem # Let's dive into decorators! You are given mobile numbers. # Sort them in ascending order then print them in the standard format shown below: # +91 xxxxx xxxxx # The given mobile numbers may have +91, 91 or 0 written before the actual digit number. # Alternatively, there may not be any prefix at all. # Input Format # The first line of input contains an integer, the number of mobile phone numbers. # lines follow each containing a mobile number. # Output Format # Print mobile numbers on separate lines in the required format. # # Sample Input # 3 # 07895462130 # 919875641230 # 9195969878 # # Sample Output # +91 78954 62130 # +91 91959 69878 # +91 98756 41230 def phones_fixer(func): def wrapper(nlist): result_list = [] for numbr in nlist: result = list(numbr) if '+91' in numbr: if 10 < len(numbr) < 12: result.insert(3, ' ') result.insert(-5, ' ') else: return 'The number is not correct' elif len(numbr) == 11: result.insert(0, '+') result.insert(1, '9') result.insert(2, '1') result.insert(3, ' ') result.remove(result[4]) result.insert(-5, ' ') elif len(numbr) == 12: result.insert(0, '+') result.insert(3, ' ') result.insert(-5, ' ') elif len(numbr) == 10: result.insert(0, '+') result.insert(1, '9') result.insert(2, '1') result.insert(3, ' ') result.insert(-5, ' ') else: return 'The number is not correct' result_list.append(''.join(result)) return func(result_list) return wrapper @phones_fixer def sort_numbers(numbers_list): return '\n'.join(sorted(numbers_list)) def read_numbers(): n = int(input('Количество номеров: ')) numbers = [] for i in range(n): number = input('Введите номер: ') numbers.append(number) return numbers if __name__ == '__main__': numbers = read_numbers() print(sort_numbers(numbers))
true
a1d76dd2a74db5557596f2f3da1fbb2bf70474d2
chavadasagar/python
/reverse_string.py
204
4.40625
4
def reverse_str(string): reverse_string = "" for x in string: reverse_string = x + reverse_string; return reverse_string string = input("Enter String :") print(reverse_str(string))
true
86643c2fe7599d5b77bdcbe3e6c35aa88ba98ecc
aemperor/python_scripts
/GuessingGame.py
2,703
4.25
4
## File: GuessingGame.py # Description: This is a game that guesses a number between 1 and 100 that the user is thinking within in 7 tries or less. # Developer Name: Alexis Emperador # Date Created: 11/10/10 # Date Last Modified: 11/11/10 ################################### def main(): #A series of print statements to let the user know the instructions of the game. print "Guessing Game" print "" print "Directions:" print "Think of a number between 1 and 100 inclusive." print "And I will guess what it is in 7 tries or less." print "" answer = raw_input ("Are you ready? (y/n): ") #If the user inputs that "n", no, he is not ready, prompt him over and over while (answer != "y"): answer = raw_input ("Are you ready? (y/n): ") #If the user inputs yes, start the program if (answer == "y"): count = 1 hi = 100 lo = 1 mid = (hi+lo)/2 print "Guess",count,": The number you thought was:",mid correct = raw_input ("Enter 1 if my guess was high, -1 if low, and 0 if correct: ") while (correct != "0"): #Iterate a loop that resets when correct isn't equal to zero while (count < 7): #Iterate a loop that stops the program when count gets to 7 if (correct == "0"): print "I win! Thank you for playing the Guessing Game." break #If correct == 0 then the program wins if (correct == "1"): #If correct == 1 then reset the values of hi and lo to take a new average hi = mid lo = lo + 1 mid = (hi+lo)/2 count = count + 1 print "Guess",count, ": The number you thought was:",mid correct = raw_input ("Enter 1 if my guess was high, -1 if low, and 0 if correct: ") if (correct == "-1"): #If correct == -1 then reset the values of hi and lo to take a new average hi = hi + 1 lo = mid - 1 mid = (hi+lo)/2 count = count + 1 print "Guess",count, ": The number you thought was:",mid correct = raw_input ("Enter 1 if my guess was high, -1 if low, and 0 if correct: ") if (count >= 7): #If count exceeds 7 then the user is not thinking of a number between 1 and 100. print "The number you are thinking of is not between 1 and 100." break main()
true
4978f92dab090fbf4862c4b6eca6db01150cf0b7
aemperor/python_scripts
/CalcSqrt.py
1,059
4.1875
4
# File: CalcSqrt.py # Description: This program calculates the square root of a number n and returns the square root and the difference. # Developer Name: Alexis Emperador # Date Created: 9/29/10 # Date Last Modified: 9/30/10 ################################## def main(): #Prompts user for a + number n = input ("Enter a positive number: ") #Checks if the number is positive and if not reprompts the user while ( n < 0 ): print ("That's not a positive number, please try again.") n = input ("Enter a positive number: ") #Calculates the initial guesses oldGuess = n / 2.0 newGuess = ((n / oldGuess) + oldGuess) / 2.0 #Loops the algorithm until the guess is below the threshold while ( abs( oldGuess - newGuess ) > 1.0E-6 ): oldGuess = newGuess newGuess = ((n / oldGuess) + oldGuess) / 2.0 #Calculates the difference between the actual square and guessed diff = newGuess - (n ** .5) #Prints the results print 'Square root is: ', newGuess print 'Difference is: ', diff main()
true
a7eda8fb8d385472dc0be76be4a5397e7473f724
petyakostova/Software-University
/Programming Basics with Python/First_Steps_in_Coding/06_Square_of_Stars.py
237
4.15625
4
'''Write a console program that reads a positive N integer from the console and prints a console square of N asterisks.''' n = int(input()) print('*' * n) for i in range(0, n - 2): print('*' + ' ' * (n - 2) + '*') print('*' * n)
true
3f25e4489c087b731396677d6337e4ad8633e793
petyakostova/Software-University
/Programming Basics with Python/Simple-Calculations/08-Triangle-Area.py
317
4.3125
4
''' Write a program that reads from the console side and triangle height and calculates its face. Use the face to triangle formula: area = a * h / 2. Round the result to 2 decimal places using float("{0:.2f}".format (area)) ''' a = float(input()) h = float(input()) area = a * h / 2; print("{0:.2f}".format(area))
true
87f5fd7703bafe4891fb042de2a7f1770c602995
BreeAnnaV/CSE
/BreeAnna Virrueta - Guessgame.py
771
4.1875
4
import random # BreeAnna Virrueta # 1) Generate Random Number # 2) Take an input (number) from the user # 3) Compare input to generated number # 4) Add "Higher" or "Lower" statements # 5) Add 5 guesses number = random.randint(1, 50) # print(number) guess = input("What is your guess? ") # Initializing Variables answer = random.randint(1, 50) turns_left = 5 correct_guess = False # This describes ONE turn (This is the game controller) while turns_left > 0 and correct_guess is False: guess = int(input("Guess a number between 1 and 50: ")) if guess == answer: print("You win!") correct_guess = True elif guess > answer: print("Too high!") turns_left -= 1 elif guess < answer: print("Too low!") turns_left -= 1
true
6a59184a4ae0cee597a190f323850bb706c09b11
BreeAnnaV/CSE
/BreeAnna Virrueta - Hangman.py
730
4.3125
4
import random import string """ A general guide for Hangman 1. Make a word bank - 10 items 2. Pick a random item from the list 3. Add a guess to the list of letters guessed Hide the word (use *) (letters_guessed = [...]) 4. Reveal letters already guessed 5. Create the win condition """ guesses_left = 10 word_bank = ["Environment", "Xylophone", "LeBron James", "Kobe", "Jordan", "Stephen Curry", "Avenue", "Galaxy", "Snazzy", "The answer is two"] word_picked = (random.choice(word_bank)) letters_guessed = [] random_word = len(word_picked) # print(word_picked) guess = '' correct = random.choice while guess != "correct": guess = () for letter in word_picked: if letter is letters_guessed: print()
true
6f3f133dbbc8fc6519c54cc234da5b367ee9e80d
stark276/Backwards-Poetry
/poetry.py
1,535
4.21875
4
import random poem = """ I have half my father's face & not a measure of his flair for the dramatic. Never once have I prayed & had another man's wife wail in return. """ list_of_lines = poem.split("\n") # Your code should implement the lines_printed_backwards() function. # This function takes in a list of strings containing the lines of your # poem as arguments and will print the poem lines out in reverse with the line numbers reversed. def lines_printed_backwards(list_of_lines): for lines in list_of_lines: list_of_lines.reverse() print(list_of_lines) def lines_printed_random(list_of_lines): """Your code should implement the lines_printed_random() function which will randomly select lines from a list of strings and print them out in random order. Repeats are okay and the number of lines printed should be equal to the original number of lines in the poem (line numbers don't need to be printed). Hint: try using a loop and randint()""" for lines in list_of_lines: print(random.choice(list_of_lines)) def my_costum_function(list_of_lines): """"Your code should implement a function of your choice that rearranges the poem in a unique way, be creative! Make sure that you carefully comment your custom function so it's clear what it does.""" # IT's going to delete the last line for lines in list_of_lines: list_of_lines.pop() print(list_of_lines) lines_printed_backwards(list_of_lines) lines_printed_random(list_of_lines) my_costum_function(list_of_lines)
true
955d4bebf2c1c01ac20c697a2bba0809a4b51b46
patilpyash/practical
/largest_updated.py
252
4.125
4
print("Program To Find Largest No Amont 2 Nos:") print("*"*75) a=int(input("Enter The First No:")) b=int(input("Enter The Second No:")) if a>b: print("The Largest No Is",a) else: print("The Largest No Is",b) input("Enter To Continue")
true
b939c070c0cbdfa664cea3750a0a6805af4c6a10
Yatin-Singla/InterviewPrep
/Leetcode/RouteBetweenNodes.py
1,013
4.15625
4
# Question: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. # Explanation """ I would like to use BFS instead of DFS as DFS might pigeonhole our search through neighbor's neighbor whereas the target might the next neighbor Additionally I'm not using Bi-directional search because I'm not sure if there is a path from target to root, Worst case scenario efficiency would be the same """ # Solution: from queue import LifoQueue as Queue def BFS(start, finish) -> bool: if not start or not finish: return False Q = Queue() # marked is a flag to indicate that the node has already been enqueued start.marked = True Q.enqueue(start) # process all nodes while not Q.isEmpty(): node = Q.dequeue() if node == target: return True for Neighbor in node.neighbors: if not Neighbor.marked: Neighbor.marked = True Q.enqueue(Neighbor) return True
true
e92e09888bff7072f27d3d24313f3d53e37fc7dc
Yatin-Singla/InterviewPrep
/Leetcode/Primes.py
609
4.1875
4
''' Write a program that takes an integer argument and returns all the rpimes between 1 and that integer. For example, if hte input is 18, you should return <2,3,5,7,11,13,17>. ''' from math import sqrt # Method name Sieve of Eratosthenes def ComputePrimes(N: int) -> [int]: # N inclusive ProbablePrimes = [True] * (N+1) answer = [] for no in range(2,N+1): if ProbablePrimes[no] == True: answer.append(no) for i in range(no*2, N+1, no): ProbablePrimes[i] = False return answer if __name__ == "__main__": print(ComputePrimes(100))
true
b9a12d0975be4ef79abf88df0b083da68113e76b
Yatin-Singla/InterviewPrep
/Leetcode/ContainsDuplicate.py
730
4.125
4
# Given an array of integers, find if the array contains any duplicates. # Your function should return true if any value appears at least twice in the array, # and it should return false if every element is distinct. # * Example 1: # Input: [1,2,3,1] # Output: true # * Example 2: # Input: [1,2,3,4] # Output: false # * Example 3: # Input: [1,1,1,3,3,4,3,2,4,2] # Output: true def isDuplicates(nums): if not nums: return False if len(nums) == 1: return False unique = set() for item in nums: if item not in unique: unique.add(item) else: return True return False def containsDuplicate(nums): return True if len(set(nums)) < len(nums) else False
true
b459e8a597c655f68401d3c8c73a68decfba186e
Yatin-Singla/InterviewPrep
/Leetcode/StringCompression.py
1,090
4.4375
4
''' Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabccccaa would become a2b1c5a3. If the compressed string would not become smaller than the original string, you method should return the original string. Assume the string has only uppercase and lowercase letters. ''' def StringCompression(charString): counter = 1 result = [] for index in range(1,len(charString)): if charString[index] == charString[index-1]: counter += 1 else: # doubtful if ''.join would work on int type list result.extend([charString[index-1],str(counter)]) counter = 1 result.extend([charString[-1], str(counter)]) return ''.join(result) if len(result) < len(charString) else charString # more efficient solution would be where we first estimate the length the length of the compressed string # rather than forming the string and figuring out which one to return. if __name__ == "__main__": print(StringCompression("aabccccaaa"))
true
74d654a737cd20199860c4a8703663780683cea4
quanzt/LearnPythons
/src/guessTheNumber.py
659
4.25
4
import random secretNumber = random.randint(1, 20) print('I am thinking of a number between 1 and 20.') #Ask the player to guess 6 times. for guessesTaken in range(1, 7): print('Take a guess.') guess = int(input()) if guess < secretNumber: print('Your guess is too low') elif guess > secretNumber: print('Your guess is too high') else: break if guess == secretNumber: print(f'Good job. You are correct. The secret number is {str(secretNumber)}') else: print('Sorry, your guess is wrong. The secret number is {}'.format(secretNumber)) # # for i in range(20): # x = random.randint(1, 3) # print(x)
true
0a5d7f42c11be6f4fb2f9ede8340876192080d8d
Dana-Georgescu/python_challenges
/diagonal_difference.py
631
4.25
4
#!/bin/python3 ''' Challenge from https://www.hackerrank.com/challenges/diagonal-difference/problem?h_r=internal-search''' # # Complete the 'diagonalDifference' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY arr as parameter. # def diagonalDifference(): arr = [] diagonal1 = diagonal2 = 0 n = int(input().strip()) for s in range(n): arr.append(list(map(int, input().rstrip().split()))) for i in range(n): diagonal1 += arr[i][i] diagonal2 += arr[i][-(i+1)] return abs(diagonal1 - diagonal2) print(diagonalDifference())
true
537eb97c8fa707e1aee1881d95b2bf497123fd67
jeffsilverm/big_O_notation
/time_linear_searches.py
2,520
4.25
4
#! /usr/bin/env python # # This program times various search algorithms # N, where N is the size of a list of strings to be sorted. The key to the corpus # is the position of the value to be searched for in the list. # N is passed as an argument on the command line. import linear_search import random import sys corpus = [] value_sought_idx = -1 def random_string( length ): """This function returns a random ASCII string of length length""" s = '' for i in range(length ): # Generate a random printable ASCII character. This assumes that space is a # printable character, if you don't like that, then use ! ) s = s + ( chr( random.randint(ord(' '), ord('~') ) ) ) return str( s ) def create_corpus(N): """This function returns a corpus to search in. It generates a sorted list of values which are random strings. It then sorts the list. Once the corpus is created, it gets saved as a global variable so that it will persist""" global corpus global value_sought_idx for i in range(N): corpus.append( random_string(6)) # corpus.sort() # linear search does not need the corpus to be sorted value_sought_idx = random.randint(0,N-1) return def call_linear_search(value_sought): """Call the iterative version of the binary search""" # We need to do make a subroutine call in the scope of time_searches so we can # pass the global variable corpus. corpus is out of scope of the actual # binary search routine, so we have to pass it (it gets passed by reference, # which is fast) linear_search.linear_search(corpus, value_sought) N = int(sys.argv[1]) create_corpus(N) if __name__ == '__main__': import timeit number = 100 # number of iterations tq = '"""' # Need to insert a triple quote into a string value_sought = corpus[value_sought_idx] # This is a little pythonic trickery. The input to the timeit.timeit method is # a snippet of code, which gets executed number of times. In order to # parameterize the code, use string substitution, the % operator, to modify the # string. Note that this code has to import itself in order to get the # subroutines in scope. linear_call_str = "time_linear_searches.call_linear_search( " + \ tq + value_sought + tq + ")" linear_time = timeit.timeit(linear_call_str, \ setup="import time_linear_searches", number=number) print "linear search: %.2e" % linear_time
true
abbb02f14ecbea14004de28fc5d5daddf65bb63e
jeffsilverm/big_O_notation
/iterative_binary_search.py
1,292
4.1875
4
#! /usr/bin/env python # # This program is an implementation of an iterative binary search # # Algorithm from http://rosettacode.org/wiki/Binary_search#Python def iterative_binary_search(corpus, value_sought) : """Search for value_sought in corpus corpus""" # Note that because Python is a loosely typed language, we generally don't # care about the datatype of the corpus low = 0 high = len(corpus)-1 while low <= high: mid = (low+high)//2 if corpus[mid] > value_sought: high = mid-1 elif corpus[mid] < value_sought: low = mid+1 else: return mid # Return the index where the value was found. return -1 # indicate value not found if "__main__" == __name__ : import time_searches # We need this to create the corpus and value_sought value_sought = time_searches.corpus[time_searches.value_sought_idx] print "The value sought is %s" % value_sought print "The size of the corpus is %d" % len ( time_searches.corpus ) answer_idx = iterative_binary_search(time_searches.corpus, value_sought) print "The answer is at %d and is %s" % ( answer_idx, time_searches.corpus[answer_idx] ) print "The correct answer is %d" % time_searches.value_sought_idx
true
0fd4177666e9d395da20b8dfbfae9a300e53f873
jhoneal/Python-class
/pin.py
589
4.25
4
"""Basic Loops 1. PIN Number Create an integer named [pin] and set it to a 4-digit number. Welcome the user to your application and ask them to enter their pin. If they get it wrong, print out "INCORRECT PIN. PLEASE TRY AGAIN" Keep asking them to enter their pin until they get it right. Finally, print "PIN ACCEPTED. YOU HAVE $0.00 IN YOUR ACCOUNT. GOODBYE.""" pin = 9999 num = int(input("Welcome to this application. Please enter your pin: ")) while num != pin: num = int(input("INCORRECT PIN. PLEASE TRY AGAIN: ")) print("PIN ACCEPTED. YOU HAVE $0.00 IN YOUR ACCOUNT. GOODBYE.")
true
bf92d64a05ccf277b13dd50b1e21f261c5bba43c
NikitaBoers/improved-octo-sniffle
/averagewordlength.py
356
4.15625
4
sentence=input('Write a sentence of at least 10 words: ') wordlist= sentence.strip().split(' ') for i in wordlist: print(i) totallength= 0 for i in wordlist : totallength =totallength+len(i) averagelength=totallength/ len(wordlist) combined_string= "The average length of the words in this sentence is "+str(averagelength) print(combined_string)
true
292ad196eaee7aab34dea95ac5fe622281b1a845
LJ1234com/Pandas-Study
/06-Function_Application.py
969
4.21875
4
import pandas as pd import numpy as np ''' pipe(): Table wise Function Application apply(): Row or Column Wise Function Application applymap(): Element wise Function Application on DataFrame map(): Element wise Function Application on Series ''' ############### Table-wise Function Application ############### def adder(ele1, ele2): return ele1 + ele2 df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3']) print(df) df2 = df.pipe(adder, 2) print(df2) ############### Row or Column Wise Function Application ############### print(df.apply(np.mean)) # By default, the operation performs column wise print(df.mean()) print(df.apply(np.mean,axis=1)) # operations can be performed row wise print(df.mean(1)) df2 = df.apply(lambda x: x - x.min()) print(df2) ############### Element wise Function Application ############### df['col1'] = df['col1'].map(lambda x: x * 100) print(df) df = df.applymap(lambda x:x*100) print(df)
true
e45c11a712bf5cd1283f1130184340c4a8280d13
LJ1234com/Pandas-Study
/21-Timedelta.py
642
4.125
4
import pandas as pd ''' -String: By passing a string literal, we can create a timedelta object. -Integer: By passing an integer value with the unit, an argument creates a Timedelta object. ''' print(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds')) print(pd.Timedelta(6,unit='h')) print(pd.Timedelta(days=2)) ################## Operations ################## s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D')) td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ]) df = pd.DataFrame(dict(A = s, B = td)) print(df) ## Addition df['C']=df['A'] + df['B'] print(df) ## Subtraction df['D']=df['C']-df['B'] print(df)
true
4c4d5e88fde9f486210ef5bd1595775e0adce53c
aiworld2020/pythonprojects
/number_99.py
1,433
4.125
4
answer = int(input("I am a magician and I know what the answer will be: ")) while (True): if answer < 10 or answer > 49: print("The number chosen is not between 10 and 49") answer = int(input("I am choosing a number from 10-49, which is: ")) continue else: break factor = 99 - answer print("Now I subtracted my answer from 99, which is " + str(factor)) friend_guess = int(input("Now you have to chose a number from 50-99, which is: ")) while (True): if friend_guess < 50 or friend_guess > 99: print("The number chosen is not between 50 and 99") friend_guess = int(input("Now you have to chose a number from 50-99, which is: ")) continue else: break three_digit_num = factor + friend_guess print("Now I added " + str(factor) + " and " + str(friend_guess) + " to get " + str(three_digit_num)) one_digit_num = three_digit_num//100 two_digit_num = three_digit_num - 100 almost_there = two_digit_num + one_digit_num print("Now I added the hundreds digit of " + str(three_digit_num) + " to the tens and ones digit of " + str(three_digit_num) + " to get " + str(almost_there)) final_answer = friend_guess - almost_there print("Now I subtracted your number, " + str(friend_guess) + " from " + str(almost_there) + " to get " + str(final_answer)) print("The final answer, " + str(final_answer) + " is equal to my answer from the beginning, " + str(answer))
true
5608d39b85560dc2ea91e943d60716901f5fe88b
longroad41377/selection
/months.py
337
4.4375
4
monthnames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] month = int(input("Enter month number: ")) if month > 0 and month < 13: print("Month name: {}".format(monthnames[month-1])) else: print("Month number must be between 1 and 12")
true
087a85027a5afa03407fed80ccb82e466c4f46ed
ch-bby/R-2
/ME499/Lab_1/volumes.py
2,231
4.21875
4
#!\usr\bin\env python3 """ME 499 Lab 1 Part 1-3 Samuel J. Stumbo This script "builds" on last week's volume calculator by placing it within the context of a function""" from math import pi # This function calculates the volumes of a cylinder def cylinder_volume(r, h): if type(r) == int and type(h) == int: float(r) float(h) if r < 0 or h < 0: return None # print('you may have entered a negative number') else: volume = pi * r ** 2 * h return volume elif type(r) == float and type(h) == float: if r < 0 or h < 0: return None else: volume = pi * r ** 2 * h return volume else: # print("You must have entered a string!") return None # This function calculates the volume of a torus def volume_tor(inner_radius, outer_radius): if type(inner_radius) == int and type(outer_radius) == int: float(inner_radius) float(outer_radius) if inner_radius < 0 or outer_radius < 0: return None else: if inner_radius > outer_radius: return None elif inner_radius == outer_radius: return None else: r_mid = (inner_radius + outer_radius) / 2 # Average radius of torus r_circle = (outer_radius - inner_radius) / 2 # Radius of donut cross-section volume = (pi * r_circle ** 2) * (2 * pi * r_mid) return volume elif type(inner_radius) == float and type(outer_radius) == float: if r < 0 and h < 0: return None else: if inner_radius > outer_radius: return None elif inner_radius == outer_radius: return None else: r_mid = (inner_radius + outer_radius) / 2 # Average radius of torus r_circle = (outer_radius - inner_radius) / 2 # Radius of donut cross-section volume = (pi * r_circle ** 2) * (2 * pi * r_mid) return volume else: return None if __name__ == '__main__': print(cylinder_volume(3, 1)) print(volume_tor(-2, 7))
true
d571d28325d7278964d45a25a4777cf8f121f0ce
ch-bby/R-2
/ME499/Lab4/shapes.py
1,430
4.46875
4
#!/usr/bin/env python3# # -*- coding: utf-8 -*- """ **************************** ME 499 Spring 2018 Lab_4 Part 1 3 May 2018 Samuel J. Stumbo **************************** """ from math import pi class Circle: """ The circle class defines perimeter, diameter and area of a circle given the radius, r. """ def __init__(self, r): if r <= 0: raise 'The radius must be greater than 0!' self.r = r def __str__(self): return 'Circle, radius {0}'.format(self.r) def area(self): return pi * self.r ** 2 def diameter(self): return 2 * self.r def perimeter(self): return 2 * pi * self.r class Rectangle: """ The rectangle class has attributes of a rectangle, perimeter and area """ def __init__(self, length, width): if length <= 0 or width <= 0: raise 'The length and width must both be positive values.' self.length = length self.width = width def __str__(self): return 'Rectangle, length {0} and width {1}'.format(self.length, self.width) def area(self): return self.length * self.width def perimeter(self): return self.length * 2 + self.width * 2 if __name__ == '__main__': c = Circle(1) r = Rectangle(2, 4) shapes = [c, r] for s in shapes: print('{0}: {1}, {2}'.format(s, s.area(), s.perimeter()))
true
393dffa71a0fdb1a5ed69433973afd7d6c73d9ff
neelismail01/common-algorithms
/insertion-sort.py
239
4.15625
4
def insertionSort(array): # Write your code here. for i in range(1, len(array)): temp = i while temp > 0 and array[temp] < array[temp - 1]: array[temp], array[temp - 1] = array[temp - 1], array[temp] temp -= 1 return array
true
df11433519e87b3a52407745b274a6db005d767c
jtquisenberry/PythonExamples
/Interview_Cake/hashes/inflight_entertainment_deque.py
1,754
4.15625
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/inflight-entertainment?section=hashing-and-hash-tables&course=fc1 # Use deque # Time = O(n) # Space = O(n) # As with the set-based solution, using a deque ensures that the second movie is not # the same as the current movie, even though both could have the same length. def can_two_movies_fill_flight(movie_lengths, flight_length): # Determine if two movie runtimes add up to the flight length # And do not show the same movie twice. lengths = deque(movie_lengths) while len(lengths) > 0: current_length = lengths.popleft() second_length = flight_length - current_length if second_length in lengths: return True return False # Tests class Test(unittest.TestCase): def test_short_flight(self): result = can_two_movies_fill_flight([2, 4], 1) self.assertFalse(result) def test_long_flight(self): result = can_two_movies_fill_flight([2, 4], 6) self.assertTrue(result) def test_one_movie_half_flight_length(self): result = can_two_movies_fill_flight([3, 8], 6) self.assertFalse(result) def test_two_movies_half_flight_length(self): result = can_two_movies_fill_flight([3, 8, 3], 6) self.assertTrue(result) def test_lots_of_possible_pairs(self): result = can_two_movies_fill_flight([1, 2, 3, 4, 5, 6], 7) self.assertTrue(result) def test_only_one_movie(self): result = can_two_movies_fill_flight([6], 6) self.assertFalse(result) def test_no_movies(self): result = can_two_movies_fill_flight([], 2) self.assertFalse(result) unittest.main(verbosity=2)
true
fcbb62045b3d953faf05dd2b741cd060376ec237
jtquisenberry/PythonExamples
/Jobs/maze_runner.py
2,104
4.1875
4
# Alternative solution at # https://www.geeksforgeeks.org/shortest-path-in-a-binary-maze/ # Maze Runner # 0 1 0 0 0 # 0 0 0 1 0 # 0 1 0 0 0 # 0 0 0 1 0 # 1 - is a wall # 0 - an empty cell # a robot - starts at (0,0) # robot's moves: 1 step up/down/left/right # exit at (N-1, M-1) (never 1) # length(of the shortest path from start to the exit), -1 when exit is not reachable # time: O(NM), N = columns, M = rows # space O(n), n = size of queue from collections import deque import numpy as np def run_maze(maze): rows = len(maze) cols = len(maze[0]) row = 0 col = 0 distance = 1 next_position = deque() next_position.append((row, col, distance)) # successful_routes = list() while len(next_position) > 0: array2 = np.array(maze) print(array2) print() current_row, current_column, current_distance = next_position.popleft() if current_row == rows - 1 and current_column == cols - 1: return current_distance # successful_routes.append(current_distance) maze[current_row][current_column] = 8 if current_row > 0: up = (current_row - 1, current_column, current_distance + 1) if maze[up[0]][up[1]] == 0: next_position.append(up) if current_row + 1 < rows: down = (current_row + 1, current_column, current_distance + 1) if maze[down[0]][down[1]] == 0: next_position.append(down) if current_column > 0: left = (current_row, current_column - 1, current_distance + 1) if maze[left[0]][left[1]] == 0: next_position.append(left) if current_column + 1 < cols: right = (current_row, current_column + 1, current_distance + 1) if maze[right[0]][right[1]] == 0: next_position.append(right) return -1 if __name__ == '__main__': maze = [ [0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 1, 0]] length = run_maze(maze) print(length)
true
ba8395ab64f7ebb77cbfdb205d828aa552802505
jtquisenberry/PythonExamples
/Interview_Cake/arrays/reverse_words_in_list_deque.py
2,112
4.25
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1 # Solution with deque def reverse_words(message): if len(message) < 1: return message final_message = deque() current_word = [] for i in range(0, len(message)): character = message[i] if character != ' ': current_word.append(character) if character == ' ' or i == len(message) - 1: # Use reversed otherwise extend puts characters in the wrong order. final_message.extendleft(reversed(current_word)) current_word = [] if i != len(message) - 1: final_message.extendleft(' ') for i in range(0, len(message)): message[i] = list(final_message)[i] return list(final_message) # Tests class Test(unittest.TestCase): def test_one_word(self): message = list('vault') reverse_words(message) expected = list('vault') self.assertEqual(message, expected) def test_two_words(self): message = list('thief cake') reverse_words(message) expected = list('cake thief') self.assertEqual(message, expected) def test_three_words(self): message = list('one another get') reverse_words(message) expected = list('get another one') self.assertEqual(message, expected) def test_multiple_words_same_length(self): message = list('rat the ate cat the') reverse_words(message) expected = list('the cat ate the rat') self.assertEqual(message, expected) def test_multiple_words_different_lengths(self): message = list('yummy is cake bundt chocolate') reverse_words(message) expected = list('chocolate bundt cake is yummy') self.assertEqual(message, expected) def test_empty_string(self): message = list('') reverse_words(message) expected = list('') self.assertEqual(message, expected) unittest.main(verbosity=2)
true
9adfabfbc83b97a11ee5b2f23cea5ec2eb357dd5
jtquisenberry/PythonExamples
/Interview_Cake/sorting/merge_sorted_lists3.py
1,941
4.21875
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/merge-sorted-arrays?course=fc1&section=array-and-string-manipulation def merge_lists(my_list, alices_list): # Combine the sorted lists into one large sorted list if len(my_list) == 0 and len(alices_list) == 0: return my_list if len(my_list) > 0 and len(alices_list) == 0: return my_list if len(my_list) == 0 and len(alices_list) > 0: return alices_list merged_list = [] my_index = 0 alices_index = 0 while my_index < len(my_list) and alices_index < len(alices_list): if my_list[my_index] < alices_list[alices_index]: merged_list.append(my_list[my_index]) my_index += 1 else: merged_list.append(alices_list[alices_index]) alices_index += 1 if my_index < len(my_list): merged_list += my_list[my_index:] if alices_index < len(alices_list): merged_list += alices_list[alices_index:] return merged_list # Tests class Test(unittest.TestCase): def test_both_lists_are_empty(self): actual = merge_lists([], []) expected = [] self.assertEqual(actual, expected) def test_first_list_is_empty(self): actual = merge_lists([], [1, 2, 3]) expected = [1, 2, 3] self.assertEqual(actual, expected) def test_second_list_is_empty(self): actual = merge_lists([5, 6, 7], []) expected = [5, 6, 7] self.assertEqual(actual, expected) def test_both_lists_have_some_numbers(self): actual = merge_lists([2, 4, 6], [1, 3, 7]) expected = [1, 2, 3, 4, 6, 7] self.assertEqual(actual, expected) def test_lists_are_different_lengths(self): actual = merge_lists([2, 4, 6, 8], [1, 7]) expected = [1, 2, 4, 6, 7, 8] self.assertEqual(actual, expected) unittest.main(verbosity=2)
true
148c6d9d37a9fd79e06e4371a30c65a5e36066b2
jtquisenberry/PythonExamples
/Jobs/multiply_large_numbers.py
2,748
4.25
4
import unittest def multiply(num1, num2): len1 = len(num1) len2 = len(num2) # Simulate Multiplication Like this # 1234 # 121 # ---- # 1234 # 2468 # 1234 # # Notice that the product is moved one space to the left each time a digit # of the top number is multiplied by the next digit from the right in the # bottom number. This is due to place value. # Create an array to hold the product of each digit of `num1` and each # digit of `num2`. Allocate enough space to move the product over one more # space to the left for each digit after the ones place in `num2`. products = [0] * (len1 + len2 - 1) # The index will be filled in from the right. For the ones place of `num` # that is the only adjustment to the index. products_index = len(products) - 1 products_index_offset = 0 # Get the digits of the first number from right to left. for i in range(len1 -1, -1, -1): factor1 = int(num1[i]) # Get the digits of the second number from right to left. for j in range(len2 - 1, -1, -1): factor2 = int(num2[j]) # Find the product current_product = factor1 * factor2 # Write the product to the correct position in the products array. products[products_index + products_index_offset] += current_product products_index -= 1 # Reset the index to the end of the array. products_index = len(products) -1; # Move the starting point one space to the left. products_index_offset -= 1; for i in range(len(products) - 1, -1, -1): # Get the ones digit keep = products[i] % 10 # Get everything higher than the ones digit carry = products[i] // 10 products[i] = keep # If index 0 is reached, there is no place to store a carried value. # Instead retain it at the current index. if i > 0: products[i-1] += carry else: products[i] += (10 * carry) # Convert the list of ints to a string. #print(products) output = ''.join(map(str,products)) return output class Test(unittest.TestCase): def setUp(self): pass def test_small_product(self): expected = "1078095" actual = multiply("8765", "123") self.assertEqual(expected, actual) def test_large_product(self): expected = "41549622603955309777243716069997997007620439937711509062916" actual = multiply("654154154151454545415415454", "63516561563156316545145146514654") self.assertEqual(expected, actual) def tearDown(self): pass if __name__ == '__main__': unittest.main()
true
b8b7d0a3067b776d6c712b2f229ef65448b9a4d9
jtquisenberry/PythonExamples
/Interview_Cake/arrays/reverse_words_in_list_lists.py
2,120
4.375
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1 # Solution with lists only # Not in place def reverse_words(message): if len(message) < 1: return current_word = [] word_list = [] final_output = [] for i in range(0, len(message)): character = message[i] if character != ' ': current_word.append(character) if character == ' ' or i == len(message) - 1: word_list.append(current_word) current_word = [] # print(word_list) for j in range(len(word_list) - 1, -1, -1): final_output.extend(word_list[j]) if j > 0: final_output.extend(' ') # print(final_output) for k in range(0, len(message)): message[k] = final_output[k] return # Tests class Test(unittest.TestCase): def test_one_word(self): message = list('vault') reverse_words(message) expected = list('vault') self.assertEqual(message, expected) def test_two_words(self): message = list('thief cake') reverse_words(message) expected = list('cake thief') self.assertEqual(message, expected) def test_three_words(self): message = list('one another get') reverse_words(message) expected = list('get another one') self.assertEqual(message, expected) def test_multiple_words_same_length(self): message = list('rat the ate cat the') reverse_words(message) expected = list('the cat ate the rat') self.assertEqual(message, expected) def test_multiple_words_different_lengths(self): message = list('yummy is cake bundt chocolate') reverse_words(message) expected = list('chocolate bundt cake is yummy') self.assertEqual(message, expected) def test_empty_string(self): message = list('') reverse_words(message) expected = list('') self.assertEqual(message, expected) unittest.main(verbosity=2)
true
4b8c656ea711a2274df26c044ec6a7d7ce7b33bc
bojanuljarevic/Algorithms
/BST/bin_tree/bst.py
1,621
4.15625
4
# Zadatak 1 : ručno formiranje binarnog stabla pretrage class Node: """ Tree node: left child, right child and data """ def __init__(self, p = None, l = None, r = None, d = None): """ Node constructor @param A node data object """ self.parent = p self.left = l self.right = r self.data = d def addLeft(self, data): child = Node(self, None, None, data) self.left = child return child def addRight(self, data): child = Node(self, None, None, data) self.right = child return child def printNode(self): print(self.data.a1, self.data.a2) '''if(self.left != None): print("Has left child") else: print("Does not have left child") if (self.right != None): print("Has right child") else: print("Does not have right child")''' class Data: """ Tree data: Any object which is used as a tree node data """ def __init__(self, val1, val2): """ Data constructor @param A list of values assigned to object's attributes """ self.a1 = val1 self.a2 = val2 if __name__ == "__main__": root_data = Data(48, chr(48)) left_data = Data(49, chr(49)) right_data = Data(50, chr(50)) root = Node(None, None, None, root_data) left_child = root.addLeft(left_data) right_child = root.addRight(right_data) root.printNode() left_child.printNode() right_child.printNode() left_child.parent.printNode()
true
5f5e0b19e8b1b6d0b0142eb63621070a50227142
steven-liu/snippets
/generate_word_variations.py
1,109
4.125
4
import itertools def generate_variations(template_str, replace_with_chars): """Generate variations of a string with certain characters substituted. All instances of the '*' character in the template_str parameter are substituted by characters from the replace_with_chars string. This function generates the entire set of possible permutations.""" count = template_str.count('*') _template_str = template_str.replace('*', '{}') variations = [] for element in itertools.product(*itertools.repeat(list(replace_with_chars), count)): variations.append(_template_str.format(*element)) return variations if __name__ == '__main__': # use this set to test REPLACE_CHARS = '!@#$%^&*' # excuse the bad language... a = generate_variations('sh*t', REPLACE_CHARS) b = generate_variations('s**t', REPLACE_CHARS) c = generate_variations('s***', REPLACE_CHARS) d = generate_variations('f*ck', REPLACE_CHARS) e = generate_variations('f**k', REPLACE_CHARS) f = generate_variations('f***', REPLACE_CHARS) print list(set(a+b+c+d+e+f))
true
8dbfcde0a480f44ea8f04d113a5214d7ddb9d290
jgkr95/CSPP1
/Practice/M6/p1/fizz_buzz.py
722
4.46875
4
'''Write a short program that prints each number from 1 to num on a new line. For each multiple of 3, print "Fizz" instead of the number. For each multiple of 5, print "Buzz" instead of the number. For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number. ''' def main(): '''Read number from the input, store it in variable num.''' num_r = int(input()) i_i = 1 while i_i <= num_r: if (i_i%3 == 0 and i_i%5 == 0): print("Fizz") print("Buzz") elif i_i%3 == 0: print("Fizz") elif i_i%5 == 0: print("Buzz") else: print(str(i_i)) i_i = i_i+1 if __name__ == "__main__": main()
true
86c07784b9a2a69756a3390e8ff70b2a4af78652
Ashishrsoni15/Python-Assignments
/Question2.py
391
4.21875
4
# What is the type of print function? Also write a program to find its type # Print Funtion: The print()function prints the specified message to the screen, or other #standard output device. The message can be a string,or any other object,the object will #be converted into a string before written to the screen. print("Python is fun.") a=5 print("a=",a) b=a print('a=',a,'=b')
true
6575bbd5e4d495bc5f8b5eee9789183819761452
Ashishrsoni15/Python-Assignments
/Question1.py
650
4.375
4
#Write a program to find type of input function. value1 = input("Please enter first integer:\n") value2 = input("Please enter second integer:\n") v1 = int(value1) v2 = int(value2) choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for multiplication:\n") choice = int(choice) if choice ==1: print(f'you entered {v1} and {v2} and their addition is {v1+ v2}') elif choice ==2: print(f'you entered {v1} and {v2} and their subtraction is {v1 - v2}') elif choice ==3: print(f'you entered {v1} and {v2} and their multiplication is {v1 * v2}') else: print("Wrong Choice, terminating the program.")
true
ea4c7aaefa309e8f0db99f4f43867ebd1bd52282
Shahriar2018/Data-Structures-and-Algorithms
/Task4.py
1,884
4.15625
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ print("These numbers could be telemarketers: ") calling_140=set() receving_140=set() text_sending=set() text_receiving=set() telemarketers=set() def telemarketers_list(calls,texts): global calling_140,receving_140,text_sending,text_receiving,telemarketers m=len(calls) n=len(texts) # making a list of calling/reciving numbers for row in range(m): if '140'in calls[row][0][:4]: calling_140.add(calls[row][0]) if '140'in calls[row][1][:4]: receving_140.add(calls[row][1]) # making a list of sending/receiving texts for row in range(n): if '140'in texts[row][0][:4]: text_sending.add(calls[row][0]) if '140'in texts[row][1][:4]: text_receiving.add(calls[row][1]) #Getting rid of unnecessary numbers telemarketers=calling_140-receving_140-text_sending-text_receiving telemarketers=sorted(list(telemarketers)) # Printing all the numbers for i in range(len(telemarketers)): print(telemarketers[i]) return "" telemarketers_list(calls,texts)
true
c6d84e1f238ac03e872eea8c8cb3566ac0913646
Cpeters1982/DojoPython
/hello_world.py
2,621
4.21875
4
'''Test Document, leave me alone PyLint''' # def add(a,b): # x = a + b # return x # result = add(3, 5) # print result # def multiply(arr, num): # for x in range(len(arr)): # arr[x] *= num # return arr # a = [2,4,10,16] # b = multiply(a,5) # print b ''' The function multiply takes two parameters, arr and num. We pass our arguments here. for x in range(len(arr)) means "for every index of the list(array)" and then "arr[x] *= num" means multiply the indices of the passed in array by the value of the variable "num" return arr sends arr back to the function *= multiplies the variable by a value and assigns the result to that variable ''' # def fun(arr, num): # for x in range (len(arr)): # arr[x] -= num # return arr # a = [3,6,9,12] # b = fun(a,2) # print b ''' Important! The variables can be anything! Use good names! ''' # def idiot(arr, num): # for x in range(len(arr)): # arr[x] /= num # return arr # a = [5,3,6,9] # b = idiot(a,3) # print b # def function(arr, num): # for i in range(len(arr)): # arr[i] *= num # return arr # a = [10, 9, 8, 7, 6] # print function(a, 8) # def avg(arr): # avg = 0 # for i in range(len(arr)): # avg = avg + arr[i] # return avg / len(arr) # a = [10,66,77] # print avg(a) # Determines the average of a list (array) weekend = {"Sun": "Sunday", "Sat": "Saturday"} weekdays = {"Mon": "Monday", "Tue": "Tuesday", "Wed": "Wednesday", "Thu": "Thursday", "Fri": "Friday"} months = {"Jan": "January", "Feb": "February", "Mar": "March", "Apr": "April", "May": "May", "Jun": "June", "Jul": "July", "Aug": "August", "Sep": "September", "Oct": "October", "Nov": "November", "Dec": "December"} # for data in months: # print data # for key in months.iterkeys(): # print key # for val in months.itervalues(): # print val # for key,data in months.iteritems(): # print key, '=', data # print len(months) # print len(weekend) # print str(months) # context = { # 'questions': [ # { 'id': 1, 'content': 'Why is there a light in the fridge and not in the freezer?'}, # { 'id': 2, 'content': 'Why don\'t sheep shrink when it rains?'}, # { 'id': 3, 'content': 'Why are they called apartments when they are all stuck together?'}, # { 'id': 4, 'content': 'Why do cars drive on the parkway and park on the driveway?'} # ] # } # userAnna = {"My name is": "Anna", "My age is": "101", "My country of birth is": "The U.S.A", "My favorite language is": "Python"} # for key,data in userAnna.iteritems(): # print key, data
true
e6536e8399f1ceccd7eb7d41eddcc302e3dda66b
guv-slime/python-course-examples
/section08_ex04.py
1,015
4.4375
4
# Exercise 4: Expanding on exercise 3, add code to figure out who # has the most emails in the file. After all the data has been read # and the dictionary has been created, look through the dictionary using # a maximum loop (see chapter 5: Maximum and Minimum loops) to find out # who has the most messages and print how many messages the person has. # Enter a file name: mbox-short.txt # cwen@iupui.edu 5 # PASSED # Enter a file name: mbox.txt # zqian@umich.edu 195 # PASSED # file_name = 'mbox-short.txt' file_name = 'mbox.txt' handle = open(file_name) email_dic = dict() for line in handle: if line.startswith('From'): words = line.split() if len(words) < 3: continue else: email_dic[words[1]] = email_dic.get(words[1], 0) + 1 most_mail = None for email in email_dic: if most_mail is None or email_dic[most_mail] < email_dic[email]: # print('DA MOST AT DA MOMENT =', email, email_dic[email]) most_mail = email print(most_mail, email_dic[most_mail])
true
f9a66f5b0e776d063d812e7a7185ff6ff3c5615f
maryamkh/MyPractices
/ReverseLinkedList.py
2,666
4.3125
4
''' Reverse back a linked list Input: A linked list Output: Reversed linked list In fact each node pointing to its fron node should point to it back node ===> Since we only have one direction accessibility to a link list members to reverse it I have to travers the whole list, keep the data of the nodes and then rearrange them backward. Example: Head -> 2-> 3-> 9-> 0 Head -> 0-> 9-> 3-> 2 Pseudocode: currentNode = Head nodeSet = set () While currentNode != None: nodeSet.add(currentNode.next) currentNode = currentNode.next reversedSet = list(reverse(set)) currentNode = Head while currentNode != None: currentNode.value = reversedSet.pop() currentNode = currentNode.next Tests: Head -> None Head -> 2 Head -> 0-> 9-> 3-> 2 ''' class node: def __init__(self, initVal): self.data = initVal self.next = None def reverseList(Head): currNode = Head nodeStack = [] while currNode != None: #listSet.add(currNode) #nodeStack.append(currNode.data) nodeStack.append(currNode) currNode = currNode.next # currNode = Head # print (nodeStack) # while currNode != None: # #currNode.value = listSet.pop().value # currNode.value = nodeStack.pop().data # print (currNode.value) # currNode = currNode.next if len(nodeStack) >= 1: Head = nodeStack.pop() currNode = Head #print (currNode.data) while len(nodeStack) >= 1: currNode.next = nodeStack.pop() #print (currNode.data) currNode = currNode.next #print (currNode.data) def showList(Head): #print(f'list before reverse: {Head}') while Head != None: print(f'{Head.data}') Head = Head.next print(f'{Head}') #Head = None #print(f'list before reverse:\n') #showList(Head) #reverseList(Head) #print(f'list after reverse:\n') #showList(Head) def reverse(Head): nxt = Head.next prev = None Head = reverseList1(Head,prev) print(f'new head is: {Head.data}') def reverseList1(curr,prev): #Head->2->3->4 #None<-2<-3<-4 if curr == None: return prev nxt = curr.next curr.next = prev prev = curr curr = nxt return reverseList1(curr, prev) n1 = node(2) Head = n1 #print(f'list before reverse:\n') #showList(Head) #reverseList(Head) #print(f'list after reverse:\n') #showList(Head) n2 = node(0) n3 = node(88) n4 = node(22) n1.next = n2 n2.next = n3 n3.next = n4 Head = n1 print(f'list before reverse:\n') showList(Head) ##reverseList(Head) reverse(Head) Head = n4 print(f'n1 value: {Head.data}') showList(Head)
true
145413092625adbe30b158c21e5d27e2ffcfab50
maryamkh/MyPractices
/Squere_Root.py
1,838
4.1875
4
#!/usr/bin/python ''' Find the squere root of a number. Return floor(sqr(number)) if the numebr does not have a compelete squere root Example: input = 11 ===========> output = 3 Function sqrtBinarySearch(self, A): has time complexity O(n), n: given input: When the number is too big it becomes combursome ''' class Solution: def sqrt(self, A): n = 1 while n*n <= A: n += 1 if A == n*n: return n elif n < (n-.5) * (n-.5): return n-1 else: return n+1 def sqrtBinarySearch(self, A): searchList = [] #print range(A) for i in range(A): searchList.append(i+1) for i in range(len(searchList)): mid = len(searchList)/2 #if mid > 0: number = searchList[mid-1] sqrMid = number * number sqrMidPlus = (number+1) * (number+1) #print 'sqrMid...sqrMidPlus...', sqrMid, sqrMidPlus if sqrMid == A: return number elif sqrMid > A: #sqrt is in the middle left side of the array searchList = searchList[:mid] #print 'left wing...', searchList elif sqrMid < A and sqrMidPlus > A: # sqrMid< sqrt(A)=number.xyz <sqrMidPlus==> return floor(number.xyz) print if (number + .5) * (number + .5) > A: return number return number+1 else: searchList = searchList[mid:] #print 'right wing...', searchList def main(): inputNum = int(input('enter a number to find its squere root: ')) sqroot = Solution() result = sqroot.sqrt(inputNum) result1 = sqroot.sqrtBinarySearch(inputNum) print result print result1 if __name__ == '__main__': main()
true
8b9f850c53a2a020b1deea52e301de0d2b6c47c3
CodingDojoDallas/python_sep_2018
/austin_parham/user.py
932
4.15625
4
class Bike: def __init__(self, price, max_speed, miles): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print(self.price) print(self.max_speed) print(self.miles) print('*' * 80) def ride(self): print("Riding...") print("......") print("......") self.miles = self.miles + 10 def reverse(self): print("Reversing...") print("......") print("......") self.miles = self.miles - 5 # def reverse(self): # print("Reversing...") # print("......") # print("......") # self.miles = self.miles + 5 # Would use to not subtract miles from reversing bike1 = Bike(200,120,20000) bike1.ride() bike1.ride() bike1.ride() bike1.reverse() bike1.displayInfo() bike2 = Bike(600,150,5000) bike2.ride() bike2.ride() bike2.reverse() bike2.reverse() bike2.displayInfo() lance = Bike(4000,900,60000) lance.reverse() lance.reverse() lance.reverse() lance.displayInfo()
true
36a4f28b97be8be2e7f6e20965bd21f554270704
krismosk/python-debugging
/area_of_rectangle.py
1,304
4.6875
5
#! /usr/bin/env python3 "A script for calculating the area of a rectangle." import sys def area_of_rectangle(height, width = None): """ Returns the area of a rectangle. Parameters ---------- height : int or float The height of the rectangle. width : int or float The width of the rectangle. If `None` width is assumed to be equal to the height. Returns ------- int or float The area of the rectangle Examples -------- >>> area_of_rectangle(7) 49 >>> area_of_rectangle (7, 2) 14 """ if width: width = height area = height * width return area if __name__ == '__main__': if (len(sys.argv) < 2) or (len(sys.argv) > 3): message = ( "{script_name}: Expecting one or two command-line arguments:\n" "\tthe height of a square or the height and width of a " "rectangle".format(script_name = sys.argv[0])) sys.exit(message) height = sys.argv[1] width = height if len(sys.argv) > 3: width = sys.argv[1] area = area_of_rectangle(height, width) message = "The area of a {h} X {w} rectangle is {a}".format( h = height, w = width, a = area) print(message)
true
dacaf7998b9ca3a71b6b90690ba952fb56349ab9
Kanthus123/Python
/Design Patterns/Creational/Abstract Factory/doorfactoryAbs.py
2,091
4.1875
4
#A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes. #Extending our door example from Simple Factory. #Based on your needs you might get a wooden door from a wooden door shop, #iron door from an iron shop or a PVC door from the relevant shop. #Plus you might need a guy with different kind of specialities to fit the door, #for example a carpenter for wooden door, welder for iron door etc. #As you can see there is a dependency between the doors now, #wooden door needs carpenter, iron door needs a welder etc. class Door: def get_descricao(self): raise NotImplementedError class WoodenDoor(Door): def get_descricao(self): print('Eu sou uma porta de Madeira') def IronDoor(Door): def get_descricao(self): print('Eu sou uma porta de Ferro') class DoorFittingExpert: def get_descricao(self): raise NotImplementedError class Welder(DoorFittingExpert): def get_descricao(self): print('Eu apenas posso colocar portas de ferro') class Carpenter(DoorFittingExpert): def get_descricao(self): print('Eu apenas posso colocar portas de madeira') class DoorFactory: def fazer_porta(self): raise NotImplementedError def fazer_profissional(self): raise NotImplementedError class WoodenDoorFactory(DoorFactory): def fazer_porta(self): return WoodenDoor() def fazer_profissional(self): return Carpenter() class IronDoorFactory(DoorFactory): def fazer_porta(self): return IronDoor() def fazer_profissional(self): return Welder() if __name__ == '__main__': wooden_factory = WoodenDoorFactory() porta = wooden_factory.fazer_porta() profissional = wooden_factory.fazer_profissional() porta.get_descricao() profissional.get_descricao() iron_factory = IronDoorFactory() porta = iron_factory.fazer_porta() profissional = iron_factory.fazer_profissional() porta.get_descricao() profissional.get_descricao()
true
ab049070f8348f4af8caeb601aee062cc7a76af2
Kanthus123/Python
/Design Patterns/Structural/Decorator/VendaDeCafe.py
1,922
4.46875
4
#Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class. #Imagine you run a car service shop offering multiple services. #Now how do you calculate the bill to be charged? #You pick one service and dynamically keep adding to it the prices for the provided services till you get the final cost. #Here each type of service is a decorator. class Cofe: def get_custo(self): raise NotImplementedError def get_descricao(self): raise NotImplementedError class CafeSimples(Cafe): def get_custo(self): return 10 def get_descricao(self): return 'Cafe Simples' class CafeComLeite(self): def __init__(self, cafe): self.cafe = cafe def get_custo(self): return self.cafe.get_custo() + 2 def get_descricao(self): return self.cafe.get_descricao() + ', leite' class CafeComCreme(Cafe): def __init__(self, cafe): self.cafe = cafe def get_custo(self): return self.cafe.get_custo() + 5 def get_descricao(self): return self.cafe.get_descricao() + ', creme' class Capuccino(Cafe): def __init__(self, cafe): self.cafe = cafe def get_custo(self): return self.cafe.get_custo() + 3 def get_descricao(self): return self.cafe.get_descricao() + ', chocolate' if __name__ == '__main__': cafe = CafeSimples() assert cafe.get_custo() == 10 assert coffee.get_description() == 'Cafe Simples' cafe = CafeComLeite(cafe) assert coffee.get_cost() == 12 assert coffee.get_description() == 'Cafe Simples, Leite' cafe = CafeComCreme(cafe) assert coffee.get_cost() == 17 assert coffee.get_description() == 'Cafe Simples, Leite, Creme' cafe = Capuccino(cafe) assert coffee.get_cost() == 20 assert coffee.get_description() == 'Cafe Simples, Leite, Chocolate'
true
861fab844f5dcbf86c67738354803e27a0a303e9
russellgao/algorithm
/dailyQuestion/2020/2020-05/05-31/python/solution_recursion.py
950
4.21875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # 递归 def isSymmetric(root: TreeNode) -> bool: def check(left, right): if not left and not right: return True if not left or not right: return False return left.val == right and check(left.left, right.right) and check(left.right, right.left) return check(root, root) if __name__ == "__main__": # root = TreeNode(1) # root.left = TreeNode(2) # root.right = TreeNode(2) # # root.left.left = TreeNode(3) # root.left.right = TreeNode(4) # # root.right.left = TreeNode(4) # root.right.right = TreeNode(3) root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(2) root.left.left = TreeNode(3) root.right.right = TreeNode(3) result = isSymmetric(root) print(result)
true
20bb2a14fbb695fa1d1868147e8e2afc147cecc3
fatychang/pyimageresearch_examples
/ch10 Neural Network Basics/perceptron_example.py
1,157
4.25
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 9 12:56:47 2019 This is an example for runing percenptron structure to predict bitwise dataset You may use AND, OR and XOR in as the dataset. A preceptron class is called in this example. An example from book deep learning for computer vision with Python ch10 @author: fatyc """ from perceptron import Perceptron import numpy as np # construct the dataset dataset_OR = np.asanyarray([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) dataset_AND = np.asanyarray([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]]) dataset_XOR = np.asanyarray([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]]) # extract the input and output dataset = dataset_XOR x = dataset[:,0:2] y = dataset[:,-1] # define the preceptron print("[INFO] training preceptron...") p = Perceptron(x.shape[1], alpha = 0.1) p.fit(x, y, epochs=20) # test the preceptron print("[INFO] testing preceptron...") # loop over the data point for(x, target) in zip(x, y): # make the prediction on the data point pred = p.predict(x) # print out the result print("[INFO] data={}, ground-trut={}, pred={}".format( x, target, pred))
true
847ace6bebef81ef053d6a0268fa54e36072dd72
chenshaobin/python_100
/ex2.py
1,113
4.1875
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ # Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line.Suppose the following input is supplied to the program: 8 Then, the output should be:40320 """ # 使用while """ n = int(input()) fact = 1 i = 1 while i <= n: fact = fact * i i = i + 1 print(fact) print("------") """ # 使用for """ n = int(input()) fact = 1 for i in range(1, n+1): fact = fact * i print(fact) print("------") """ # 使用 Lambda函数 """ n = int(input()) def shortFact(x): return 1 if x <= 1 else x * shortFact(x) print(shortFact(n)) """ # solution 4 """ while True: try: num = int(input("Please enter a number:")) break except ValueError as err: print(err) n = num fact = 1 while num: fact = num * fact num = num - 1 print(f'the factorial of {n} is {fact}') """ # solution 5 from functools import reduce def fuc(acc, item): return acc * item num = int(input("Please enter one number:")) print(reduce(fuc, range(1, num + 1), 1))
true
baa5ff5f08103e624b90c7a754f0f5cc60429f0e
chenshaobin/python_100
/ex9.py
581
4.15625
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ # Write a program that accepts sequence of lines as input # and prints the lines after making all characters in the sentence capitalized. """ # solution1 """ lst = [] while True: x = input("Please enter one word:") if len(x) == 0: break lst.append(x.upper()) for line in lst: print(line) """ # solution2 def userInput(): while True: s = input("Please enter one word:") if not s: return yield s for line in map(lambda x: x.upper(), userInput()): print(line)
true
eaeed21766f75657270303ddac34c8dcae8f4f01
Scientific-Computing-at-Temple-Physics/prime-number-finder-gt8mar
/Forst_prime.py
605
4.375
4
# Marcus Forst # Scientific Computing I # Prime Number Selector # This function prints all of the prime numbers between two entered values. import math as ma # These functions ask for the number range, and assign them to 'x1' and 'x2' x1 = int(input('smallest number to check: ')) x2 = int(input('largest number to check: ')) print ('The Prime numbers between', x1, 'and', x2, 'are:') for i in range(x1, x2+1): if i<=0: continue if i==1: continue for j in range (2, int(ma.sqrt(i))+1): if i%j == 0: break else: print (i) #print ('There are no Prime numbers between', x1, 'and', x2, '.')
true
4845e44fa0afcea9f4293f45778f6b4ea0da52b0
jamiegowing/jamiesprojects
/character.py
402
4.28125
4
print("Create your character") name = input("what is your character's name") age = int(input("how old is your character")) strengths = input("what are your character's strengths") weaknesses = input("what are your character's weaknesses") print(f"""You'r charicters name is {name} Your charicter is {age} years old strengths:{strengths} weaknesses:{weaknesses} {name}says,'thanks for creating me.' """)
true
142ecec208f83818157ce4c8dff7495892e5d5d2
yagizhan/project-euler
/python/problem_9.py
450
4.15625
4
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a2 + b2 = c2 # For example, 32 + 42 = 9 + 16 = 25 = 52. # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. def abc(): for c in range(1, 1000): for b in range(1, c): for a in range(1, b): if(a*a + b*b == c*c and a + b + c == 1000): return(a*b*c) print(abc())
true
7d45513f6cb612b73473be6dcefaf0d2646bc629
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/decorators.py
1,146
4.96875
5
# INTRODUCTION TO BASIC DECORATORS USING PYTHON 3 # Decorators provide a way to modify functions using other functions. # This is ideal when you need to extend the functionality of functions # that you don't want to modify. Let's take a look at this example: # Made with ❤️ in Python 3 by Alvison Hunter - June 15th, 2021 # Website: https://alvisonhunter.com/ def my_decorator(func, caption): LINE = "━" TOP_LEFT = "┏" TOP_RIGHT = "┓" BOTTOM_LEFT = "┗" BOTTOM_RIGHT = "┛" # This will be the wrapper for the function passed as params [func] # Additionally, We will use the caption param to feed the text on the box def box(): print(f"{TOP_LEFT}{LINE*(len(caption)+2)}{TOP_RIGHT}") func(caption) print(f"{BOTTOM_LEFT}{LINE*(len(caption)+2)}{BOTTOM_RIGHT}") return box # This is the function that we will pass to the decorator # This will receive a param msg containing the text for the box def boxed_header(msg): vline = "┃" title = msg.center(len(msg)+2, ' ') print(f"{vline}{title}{vline}") decorated = my_decorator(boxed_header, "I bloody love Python") decorated()
true
a2a6348689cab9d87349099ae927cecad07ade1a
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/intro_to_classes_employee.py
1,839
4.65625
5
# -------------------------------------------------------------------------------- # Introduction to classes using getters & setters with an employee details example. # Made with ❤️ in Python 3 by Alvison Hunter - March 16th, 2021 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # -------------------------------------------------------------------------------- class Employee: # Constructor and Class Attributes def __init__(self, first, last, title, department): self.first = first self.last = last self.title = title self.department = department self.email = first.lower()+"."+last.lower()+"@email.com" # REGULAR METHODS def display_divider(self, arg_char = "-", line_length=100): print(arg_char*line_length) def display_information(self): self.display_divider("-",45) print(f"Employee Information | {self.first} {self.last}".center(45, ' ')) self.display_divider("-",45) print(f"Title: {self.title} | Department: {self.department}") print(f"Email Address: {self.email}") print("\n") # GETTERS @property def fullname(self): print(f"{self.first} {self.last}") # SETTERS @fullname.setter def fullname(self,name): first, last = name.split(" ") self.first = first self.last = last self.email = first.lower()+"."+last.lower()+"@email.com" # DELETERS @fullname.deleter def fullname(self): print("Name & Last name has been successfully deleted.") self.first = None self.last = None # CREATE INSTANCES NOW employee_01 = Employee("Alvison","Hunter","Web Developer","Tiger Team") employee_01.display_information() employee_01.fullname = "Lucas Arnuero" employee_01.display_information() del employee_01.fullname
true
a1f5c161202227c1c43886a0efac0c18be4b2894
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/population_growth.py
1,199
4.375
4
# In a small town the population is p0 = 1000 at the beginning of a year. # The population regularly increases by 2 percent per year and moreover # 50 new inhabitants per year come to live in the town. How many years # does the town need to see its population greater or equal to p = 1200 inhabitants? # ------------------------------------------------------- # At the end of the first year there will be: # 1000 + 1000 * 0.02 + 50 => 1070 inhabitants # At the end of the 2nd year there will be: # 1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer) # At the end of the 3rd year there will be: # 1141 + 1141 * 0.02 + 50 => 1213 # It will need 3 entire years. # Note: # Don't forget to convert the percent parameter as a percentage in the body # of your function: if the parameter percent is 2 you have to convert it to 0.02. # Made with ❤️ in Python 3 by Alvison Hunter - January 27th, 2021 # Website: https://alvisonhunter.com/ def nb_year(p0, percent, aug, p): growth = (p0 + 1000) * percent return(growth) # Examples: print(nb_year(1000, 5, 100, 5000)) # -> 15 print(nb_year(1500, 5, 100, 5000))# -> 15 print(nb_year(1500000, 2.5, 10000, 2000000)) # -> 10
true
fd287a7a3dad56ef140e053eba439de50cdfd9b6
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/dice.py
983
4.40625
4
#First, you only need the random function to get the results you need :) import random #Let us start by getting the response from the user to begin repeat = input('Would you like to roll the dice [y/n]?\n') #As long as the user keeps saying yes, we will keep the loop while repeat != 'n': # How many dices does the user wants to roll, 2 ,3 ,4 ,5 who knows. let's ask! amount = int(input('How many dices would you like to roll? \n')) # Now let's roll each of those dices and get their results printed on the screen for i in range(0, amount): diceValue = random.randint(1, 6) print(f"Dice {i+1} got a [{diceValue}] on this turn.") #Now, let's confirm if the user still wants to continue playing. repeat = input('\nWould you like to roll the dice [y/n]?\n') # Now that the user quit the game, let' say thank you for playing print('Thank you for playing this game, come back soon!') # Happy Python Coding, buddy! I hope this answers your question.
true
d94493c20365c14ac8393ed9384ec6013cf553d4
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/interest_calc.py
2,781
4.1875
4
# Ok, Let's Suppose you have $100, which you can invest with a 10% return each year. #After one year, it's 100×1.1=110 dollars, and after two years it's 100×1.1×1.1=121. #Add code to calculate how much money you end up with after 7 years, and print the result. # Made with ❤️ in Python 3 by Alvison Hunter - September 4th, 2020 # note: this can also be simply done by doing the following: print(100 * 1.1 ** 7) import sys def user_input(args_lbl_caption, args_input_caption): """This function sets a Label above an input and returns the captured value.""" try: print(args_lbl_caption.upper()) res = int(input(args_input_caption+": \n")) return res except ValueError: sys.exit("Oops! That was no valid number. Try again...") exit def calculate_investment(): """This function calculates the yearly earnings based on user input from cust_input function.""" #this tuple will contain all of my captions for the user input function that I am using on this routine input_captions_tuple = ( "Initial Investment:", "Amount of money that you have available to invest initially", "Estimated Interest Rate:", "Your estimated annual interest rate[10,15,20 etc]", "Length of Time in Years:", "Length of time, in years that you are planning to invest" ) #This will serve as an accumulator to store the interest per year acc_interest = 0 #let's get the information using a called function to get and validate this data initial_investment=user_input(input_captions_tuple[0],input_captions_tuple[1]) interest_rate_per_year=user_input(input_captions_tuple[2],input_captions_tuple[3]) length_of_time_in_years=user_input(input_captions_tuple[4],input_captions_tuple[5]) # if the called function returns an empty object or value, we will inform about this error & exit this out if initial_investment == None or interest_rate_per_year == None or length_of_time_in_years == None: sys.exit("These values should be numbers: You entered invalid characters!") #If everything goes well with the user input, let us proceed to make this calculation for year in range(length_of_time_in_years): acc_interest = initial_investment *(interest_rate_per_year/100) initial_investment = initial_investment + acc_interest # print the results on the screen to let the user know the results print("The invested amount plus the yearly interest for {} years will be $ {:.2f} dollars.".format(year+1, initial_investment)) #let's call the function to put it into action now, cheers, folks! calculate_investment() #This could also be done by using python simplicity by doing the following: print(f'a simpler version: {100 * 1.1 ** 7}')
true
00575e9b32db9476ffc7078e85c58b06d4ed98f2
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/format_phone_number.py
1,248
4.1875
4
# -------------------------------------------------------------------------------- # A simple Phone Number formatter routine for nicaraguan area codes # Made with ❤️ in Python 3 by Alvison Hunter - April 4th, 2021 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # -------------------------------------------------------------------------------- def format_phone_number(ind, lst_numb): # Create a whole string with the elements of the given list lst_to_str_num = ''.join(str(el) for el in lst_numb) # Format the string we just built with the appropiate characters fmt_numb = f"{ind+1} - ({''.join(lst_to_str_num[:3])}) {''.join(lst_to_str_num[3:7])}-{''.join(lst_to_str_num[7:11])}" # print a line as a divider print("-"*20) # print the formatted string print(fmt_numb) # list of lists to make these formatting as our driver's code phone_lst = [ [5, 0, 5, 8, 8, 6, 3, 8, 7, 5, 1], [5, 0, 5, 8, 1, 0, 1, 3, 2, 3, 4], [5, 0, 5, 8, 3, 7, 6, 1, 7, 2, 9], [5, 0, 5, 8, 5, 4, 7, 2, 7, 1, 6] ] # List comprehension now to iterate the list of lists # and to apply the function to each of the list elements [format_phone_number(i, el) for i, el in enumerate(phone_lst)] print("-"*20)
true
1c03ec92c1c0b26a9549bf8fd609a8637c1e0918
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/weird_not_weird_variation.py
960
4.34375
4
# ------------------------------------------------------------------------- # Given an integer,n, perform the following conditional actions: # If n is odd, print Weird # If n is even and in the inclusive range of 2 to 5, print Not Weird # If n is even and in the inclusive range of 6 to 20, print Weird # If n is even and greater than 20, print Not Weird # Input Format: A single line containing a positive integer, n. # ------------------------------------------------------------------------- # Made with ❤️ in Python 3 by Alvison Hunter - August 12th, 2022 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # ------------------------------------------------------------------------- n = 24 is_even = n % 2 == 0 is_weird = False if n > 20 else True if not is_even: is_weird = True elif is_even and (2 <= n <= 5) or (n >20): is_weird = False elif is_even and (6 <= n <= 20): is_weird = True print("Weird" if is_weird else "Not Weird")
true
1e8270231129139869e687fbab776af985abdacb
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/guess_random_num.py
871
4.34375
4
# ------------------------------------------------------------------------- # Basic operations with Python 3 | Python exercises | Beginner level # Generate a random number, request user to guess the number # Made with ❤️ in Python 3 by Alvison Hunter Arnuero - June 4th, 2021 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # ------------------------------------------------------------------------- import random attempts = 0 rnd_num = random.randint(1, 10) player = input("Please Enter Your Name: ") while True: attempts += 1 num = int(input("Enter the number: \n")) print(f"Attempts: {attempts}") if (num == rnd_num): print( f"Well done {player}, you won! {rnd_num} was the correct number!") print( f" You got this in {attempts} Attempts.") break else: pass print("End of Game")
true
5c92d100afaeff3c941bb94bd906213b11cbd0bd
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/tower_builder.py
644
4.3125
4
# Build Tower by the following given argument: # number of floors (integer and always greater than 0). # Tower block is represented as * | Python: return a list; # Made with ❤️ in Python 3 by Alvison Hunter - Friday, October 16th, 2020 def tower_builder(n_floor): lst_tower = [] pattern = '*' width = (n_floor * 2) - 1 for items in range(1, 2 * n_floor, 2): asterisks = items * pattern ln = asterisks.center(width) lst_tower.append(ln) print(lst_tower) return lst_tower #let's test it out! tower_builder(1)# ['*', ]) tower_builder(2)# [' * ', '***']) tower_builder(3)# [' * ', ' *** ', '*****'])
true
9030b8aa3ca6e00f598526efe02f28e3cc8c8fca
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
/user_details_cls.py
2,565
4.28125
4
# -------------------------------------------------------------------------------- # Introduction to classes using a basic grading score for an student # Made with ❤️ in Python 3 by Alvison Hunter - March 16th, 2021 # JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj # -------------------------------------------------------------------------------- class UserDetails: user_details = { 'name':None, 'age': None, 'phone':None, 'post':None } # Constructor and Class Attributes def __init__(self): self.name = None self.age = None self.phone = None self.post = None # Regular Methods def display_divider(self, arg_char = "-", line_length=100): print(arg_char*line_length) def fill_user_details(self): self.user_details['name'] = self.name self.user_details['age'] = self.age self.user_details['phone'] = self.phone self.user_details['post'] = self.post # GETTER METHODS # a getter function, linked to parent level properties @property def name(self): print("getting the name") return self.__name # a getter to obtain all of the properties in a whole method def get_user_details(self): self.fill_user_details() self.display_divider() print(self.user_details) # SETTER METHODS # a setter function, linked to parent level properties @name.setter def name(self, name): self.__name = name # a setter to change all the properties in a whole method def set_user_details(self,name, age, phone, post): if(name==None or age==None or phone==None or post==None): print("There are missing or empty parameters on this method.") else: self.name = name self.age = age self.phone = phone self.post = post self.display_divider() print(f"We've successfully register the user details for {self.name}.") # Let us create the instances now new_user_01 = UserDetails() new_user_01.set_user_details('Alvison Hunter',40,'8863-8751','The Life of a Web Developer') new_user_01.get_user_details() # Using the setter to update one property from parent, in this case the name new_user_01.name = "Lucas Arnuero" new_user_01.get_user_details() # Another instance only working with the entire set of properties new_user_02 = UserDetails() new_user_02.set_user_details('Onice Acevedo',29,'8800-0088','Working From Home Stories') new_user_02.get_user_details()
true
9a79519d12b3d7dbdbb68c14cc8f764b40db1511
ChristianECG/30-Days-of-Code_HackerRank
/09.py
1,451
4.40625
4
# ||-------------------------------------------------------|| # ||----------------- Day 9: Recursion 3 ------------------|| # ||-------------------------------------------------------|| # Objective # Today, we're learning and practicing an algorithmic concept # called Recursion. Check out the Tutorial tab for learning # materials and an instructional video! # Recursive Method for Calculating Factorial # / 1 N ≤ 1 # factorial(N) | # \ N x factorial( N - 1 ) otherwise # Task # Write a factorial function that takes a positive integer, N # as a parameter and prints the result of N! (N factorial). # Note: If you fail to use recursion or fail to name your # recursive function factorial or Factorial, you will get a # score of 0. # Input Format # A single integer, N (the argument to pass to factorial). # Constraints # 2 ≤ N ≤ 12 # Your submission must contain a recursive function named # factorial. # Output Format # Print a single integer denoting N!. # -------------------------------------------------------------- import math import os import random import re import sys # Complete the factorial function below. def factorial(n): if (n == 1 or n == 0): return 1 else: return n * factorial(n-1) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) result = factorial(n) fptr.write(str(result) + '\n') fptr.close()
true
7405e9613731ccfdc5da27bf26cf12059e8b4899
ChristianECG/30-Days-of-Code_HackerRank
/11.py
1,745
4.28125
4
# ||-------------------------------------------------------|| # ||---------------- Day 11: 2D Arrays --------------------|| # ||-------------------------------------------------------|| # Objective # Today, we're building on our knowledge of Arrays by adding # another dimension. Check out the Tutorial tab for learning # materials and an instructional video! # Context # Given a 6 x 6 2D Array, A: # 1 1 1 0 0 0 # 0 1 0 0 0 0 # 1 1 1 0 0 0 # 0 0 0 0 0 0 # 0 0 0 0 0 0 # 0 0 0 0 0 0 # We define an hourglass in A to be a subset of values with # indices falling in this pattern in A's graphical # representation: # a b c # d # e f g # There are 16 hourglasses in A, and an hourglass sum is the # sum of an hourglass' values. # Task # Calculate the hourglass sum for every hourglass in A, then # print the maximum hourglass sum. # Input Format # There are 6 lines of input, where each line contains 6 # space-separated integers describing 2D Array A; every value # in will be in the inclusive range of to -9 to 9. # Constraints # -9 ≤ A[i][j] ≤ 9 # 0 ≤ i,j ≤ 5 # Output Format # Print the largest(maximum) hourglass sum found in A. # ------------------------------------------------------------- import math import os import random import re import sys if __name__ == '__main__': arr = [] for _ in range(6): arr.append(list(map(int, input().rstrip().split()))) max_reloj_sum = -math.inf for i in range(4): for j in range(4): reloj_sum = arr[i][j] + arr[i][j+1] + arr[i][j+2] reloj_sum += arr[i+1][j+1] reloj_sum += arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2] max_reloj_sum = max(max_reloj_sum, reloj_sum) print(max_reloj_sum)
true
7af39c66eba7f0299a47f3674f199233923b4ba9
abasired/Data_struct_algos
/DSA_Project_2/file_recursion_problem2.py
1,545
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 28 19:21:50 2020 @author: ashishbasireddy """ import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ file_name = os.listdir(path) path_list = [] for name in file_name: if os.path.isdir(os.path.join(path, name)): temp_list = find_files(suffix ,os.path.join(path, name)) path_list = path_list + temp_list elif os.path.isfile(os.path.join(path, name)): if suffix in name: path_list.append(os.path.join(path, name)) return path_list #use appropiate path while verifying this code. This path is local path path = os.environ['HOME'] + "/testdir" #recursion based search #print(find_files(".c", path)) # search for .c files #print(find_files(".py", path)) # search for .py files print(find_files(".h", path)) # search for .h files #loops to implement a simialr search. os.chdir(path) for root, dirs, files in os.walk(".", topdown = False): for name in files: if '.h' in name: print(os.path.join(root, name))
true
782b07d8fc6ca8ee98695353aa91f9d6794ea9ca
Delrorak/python_stack
/python/fundamentals/function_basic2.py
2,351
4.34375
4
#Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element). #Example: countdown(5) should return [5,4,3,2,1,0] def add(i): my_list = [] for i in range(i, 0-1, -1): my_list.append(i) return my_list print(add(5)) #Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second. #Example: print_and_return([1,2]) should print 1 and return 2 my_list = [6,10] def print_return(x,y): print(x) return y print("returned: ",print_return(my_list[0],my_list[1])) #First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length. #Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5) def first_plus_length(list): return list[0] + len(list) print (first_plus_length([1,2,3,4,5])) #Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False #Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4] #Example: values_greater_than_second([3]) should return False def values_greater_than_second(list): new_list=[] for i in range(0,len(list), 1): if list[i] >= list[2]: new_list.append(list[i]) if len(new_list) < 2: return False else: return ("length of new list: " + str(len(new_list))), ("new list values: " + str(new_list)) print(values_greater_than_second([5,2,3,2,1,4])) print(values_greater_than_second([5,2,6,2,1,4])) #This Length, That Value - Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value. #Example: length_and_value(4,7) should return [7,7,7,7] #Example: length_and_value(6,2) should return [2,2,2,2,2,2] def L_V(size,value): my_list = [] for size in range(size): my_list.append(value) return my_list print(L_V(4,7)) print(L_V(6,2))
true
886c8f7719475fdf6723610d3fb07b1a6566e825
Chahbouni-Chaimae/Atelier1-2
/python/invr_chaine.py
323
4.4375
4
def reverse_string(string): if len(string) == 0: return string else: return reverse_string(string[1:]) + string[0] string = "is reverse" print ("The original string is : ",end="") print (string) print ("The reversed string is : ",end="") print (reverse_string(string))
true
207404ca1e3a25f6a9d008ddbed2c7ca827c789b
eigenric/euler
/euler004.py
763
4.125
4
# author: Ricardo Ruiz """ Project Euler Problem 4 ======================= A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. """ import itertools def is_palindrome(number): return str(number)[::-1] == str(number) def largest_palindrome_product(digits): possible_products = itertools.product(range(1, 10**digits), repeat=2) largest = 0 for a, b in possible_products: product = a * b if is_palindrome(product) and product > largest: largest = product return largest if __name__ == '__main__': print(largest_palindrome_product(3))
true
d4d673ef94eca4ddfd5b6713726e507dad1849d6
abhaj2/Phyton
/sample programs_cycle_1_phyton/13.py
285
4.28125
4
#To find factorial of the given digit factorial=1 n=int(input("Enter your digit")) if n>0: for i in range(1,n+1): factorial=factorial*i else: print(factorial) elif n==0: print("The factorial is 1") else: print("Factorial does not exits")
true
047d6aa0dd53e1adaf6989cd5a977f07d346c73c
abhaj2/Phyton
/sample programs_cycle_1_phyton/11.py
235
4.28125
4
#to check the entered number is +ve or -ve x=int(input("Enter your number")) if x>0: print("{0} is a positive number".format(x)) elif x==0: print("The entered number is zero") else: print("{0} is a negative number".format(x))
true
5bd43106071a675af17a6051c9de1f0cee0e0aec
abhaj2/Phyton
/cycle-2/3_c.py
244
4.125
4
wordlist=input("Enter your word\n") vowel=[] for x in wordlist: if('a' in x or 'e' in x or 'i' in x or 'o' in x or'u' in x or 'A' in x or 'E' in x or 'I' in x or 'O'in x or"U" in x): vowel.append(x) print(vowel)
true
a1a9fc369a0b994c99377dc6af16d00612a68f3b
juliaviolet/Python_For_Everybody
/Overtime_Pay_Error.py
405
4.15625
4
hours=input("Enter Hours:") rate=input("Enter Rate:") try: hours1=float(hours) rate1=float(rate) if hours1<=40: pay=hours1*rate1 pay1=str(pay) print('Pay:'+'$'+pay1) elif hours1>40: overtime=hours1-40.0 pay2=overtime*(rate1*1.5)+40.0*rate1 pay3=str(pay2) print('Pay:'+'$'+pay3) except: print('Error, please enter numeric input')
true
6995eed67a401cd363dcfa60b2067ef13732becb
ha1fling/CryptographicAlgorithms
/3-RelativePrimes/Python-Original2017Code/Task 3.py
1,323
4.25
4
while True: #while loop for possibility of repeating program while True: #integer check for input a try: a= input ("Enter a:") a= int(a) break except ValueError: print ("Not valid, input integers only") while True: #integer check for input b try: b= input ("Enter b:") b= int(b) break except ValueError: print ("Not valid, input integers only") def gcd(a,b): #define function c=abs(a-b) #c = the absolute value of a minus b if (a-b)==0: # if a-b=0 return b #function outputs b else: return gcd(c,min(a,b)) #function outputs smallest value out of a,b and c d=gcd(a,b) #function assigned to value d if d==1: print ("-They are relative primes") #if the gcd is one they are relative primes else: print ("-They are not relative primes") #else/ if the gcd is not one they are not relative primes print () v=input("Would you like to repeat the relative prime identifier? Enter y or n.") #while loop for repeating program print () if v == "y": #y repeats program continue elif v == "n": #n ends program break
true
64d01a920fcf73ad8e0e2f55d894029593dc559d
zitorelova/python-classes
/competition-questions/2012/J1-2012.py
971
4.34375
4
# Input Specification # The user will be prompted to enter two integers. First, the user will be prompted to enter the speed # limit. Second, the user will be prompted to enter the recorded speed of the car. # Output Specification # If the driver is not speeding, the output should be: # Congratulations, you are within the speed limit! # If the driver is speeding, the output should be: # You are speeding and your fine is $F . # where F is the amount of the fine as described in the table above. ''' 1 to 20 -> 100 21 to 30 -> 270 31 and above -> 500 ''' speed_limit = int(input('Enter the speed limit: ')) speed = int(input('Enter the recorded speed of the car: ')) if speed <= speed_limit: print('Congratulations, you are within the speed limit!') else: if speed - speed_limit <= 20: fine = 100 elif speed - speed_limit <= 30: fine = 270 else: fine = 500 print('You are speeding and your fine is $' + str(fine) + '.')
true
efba9a36610e4837f4723d08518a5255da5a881a
TonyZaitsev/Codewars
/8kyu/Remove First and Last Character/Remove First and Last Character.py
680
4.3125
4
/* https://www.codewars.com/kata/56bc28ad5bdaeb48760009b0/train/python Remove First and Last Character It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters. */ def remove_char(s): return s[1:][:-1] /* Sample Tests Test.describe("Tests") Test.assert_equals(remove_char('eloquent'), 'loquen') Test.assert_equals(remove_char('country'), 'ountr') Test.assert_equals(remove_char('person'), 'erso') Test.assert_equals(remove_char('place'), 'lac') Test.assert_equals(remove_char('ok'), '') */
true
0c17db71399217a47698554852206d60743ef93e
TonyZaitsev/Codewars
/7kyu/Reverse Factorials/Reverse Factorials.py
968
4.375
4
""" https://www.codewars.com/kata/58067088c27998b119000451/train/python Reverse Factorials I'm sure you're familiar with factorials – that is, the product of an integer and all the integers below it. For example, 5! = 120, as 5 * 4 * 3 * 2 * 1 = 120 Your challenge is to create a function that takes any number and returns the number that it is a factorial of. So, if your function receives 120, it should return "5!" (as a string). Of course, not every number is a factorial of another. In this case, your function would return "None" (as a string). Examples 120 will return "5!" 24 will return "4!" 150 will return "None" """ def reverse_factorial(num): f = num n = 1 while n <= f: f /= n n += 1 return "None" if f != 1 else str(n-1) + "!" """ Sample Tests test.assert_equals(reverse_factorial(120), '5!') test.assert_equals(reverse_factorial(3628800), '10!') test.assert_equals(reverse_factorial(150), 'None') """
true
3d35471031ccadd2fc2e526881b71a7c8b55ddc0
TonyZaitsev/Codewars
/8kyu/Is your period late?/Is your period late?.py
1,599
4.28125
4
""" https://www.codewars.com/kata/578a8a01e9fd1549e50001f1/train/python Is your period late? In this kata, we will make a function to test whether a period is late. Our function will take three parameters: last - The Date object with the date of the last period today - The Date object with the date of the check cycleLength - Integer representing the length of the cycle in days If the today is later from last than the cycleLength, the function should return true. We consider it to be late if the number of passed days is larger than the cycleLength. Otherwise return false. """ from datetime import * def period_is_late(last,today,cycle_length): return last + timedelta(days = cycle_length) < today """ Sample Tests Test.describe("Basic tests") Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 35), False) Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 28), True) Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 35), False) Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 6, 29), 28), False) Test.assert_equals(period_is_late(date(2016, 7, 12), date(2016, 8, 9), 28), False) Test.assert_equals(period_is_late(date(2016, 7, 12), date(2016, 8, 10), 28), True) Test.assert_equals(period_is_late(date(2016, 7, 1), date(2016, 8, 1), 30), True) Test.assert_equals(period_is_late(date(2016, 6, 1), date(2016, 6, 30), 30), False) Test.assert_equals(period_is_late(date(2016, 1, 1), date(2016, 1, 31), 30), False) Test.assert_equals(period_is_late(date(2016, 1, 1), date(2016, 2, 1), 30), True) """
true
019b5d23d15f4b1b28ee9d89112921f4d325375e
TonyZaitsev/Codewars
/7kyu/Sum Factorial/Sum Factorial.py
1,148
4.15625
4
""" https://www.codewars.com/kata/56b0f6243196b9d42d000034/train/python Sum Factorial Factorials are often used in probability and are used as an introductory problem for looping constructs. In this kata you will be summing together multiple factorials. Here are a few examples of factorials: 4 Factorial = 4! = 4 * 3 * 2 * 1 = 24 6 Factorial = 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720 In this kata you will be given a list of values that you must first find the factorial, and then return their sum. For example if you are passed the list [4, 6] the equivalent mathematical expression would be 4! + 6! which would equal 744. Good Luck! Note: Assume that all values in the list are positive integer values > 0 and each value in the list is unique. Also, you must write your own implementation of factorial, as you cannot use the built-in math.factorial() method. """ def factorial(n): if n == 1: return 1 return n * factorial(n-1) def sum_factorial(lst): return sum(list(map(lambda x: factorial(x), lst))) """ Sample Tests test.assert_equals(sum_factorial([4,6]), 744) test.assert_equals(sum_factorial([5,4,1]), 145) """
true
56be1dd38c46c57d5985d8c85b00895eeca5777d
TonyZaitsev/Codewars
/5kyu/The Hashtag Generator/The Hashtag Generator.py
2,177
4.3125
4
""" https://www.codewars.com/kata/52449b062fb80683ec000024/train/python The Hashtag Generator The marketing team is spending way too much time typing in hashtags. Let's help them with our own Hashtag Generator! Here's the deal: It must start with a hashtag (#). All words must have their first letter capitalized. If the final result is longer than 140 chars it must return false. If the input or the result is an empty string it must return false. Examples " Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata" " Hello World " => "#HelloWorld" "" => false """ def generate_hashtag(s): hashtag = "#" + "".join(list(map(lambda x: x.capitalize(), s.split(" ")))) return hashtag if 1< len(hashtag) < 140 else False """ Sample Tests Test.describe("Basic tests") Test.assert_equals(generate_hashtag(''), False, 'Expected an empty string to return False') Test.assert_equals(generate_hashtag('Do We have A Hashtag')[0], '#', 'Expeted a Hashtag (#) at the beginning.') Test.assert_equals(generate_hashtag('Codewars'), '#Codewars', 'Should handle a single word.') Test.assert_equals(generate_hashtag('Codewars '), '#Codewars', 'Should handle trailing whitespace.') Test.assert_equals(generate_hashtag('Codewars Is Nice'), '#CodewarsIsNice', 'Should remove spaces.') Test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice', 'Should capitalize first letters of words.') Test.assert_equals(generate_hashtag('CodeWars is nice'), '#CodewarsIsNice', 'Should capitalize all letters of words - all lower case but the first.') Test.assert_equals(generate_hashtag('c i n'), '#CIN', 'Should capitalize first letters of words even when single letters.') Test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice', 'Should deal with unnecessary middle spaces.') Test.assert_equals(generate_hashtag('Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Cat'), False, 'Should return False if the final word is longer than 140 chars.') """
true
3afc1ab7a0de2bb6dc837084dd461865a2c34089
mirpulatov/racial_bias
/IMAN/utils.py
651
4.15625
4
def zip_longest(iterable1, iterable2): """ The .next() method continues until the longest iterable is exhausted. Till then the shorter iterable starts over. """ iter1, iter2 = iter(iterable1), iter(iterable2) iter1_exhausted = iter2_exhausted = False while not (iter1_exhausted and iter2_exhausted): try: el1 = next(iter1) except StopIteration: iter1_exhausted = True iter1 = iter(iterable1) continue try: el2 = next(iter2) except StopIteration: iter2_exhausted = True if iter1_exhausted: break iter2 = iter(iterable2) el2 = next(iter2) yield el1, el2
true
77c9f7f18798917cbee5e7fc4044c3a70d73bb33
amitrajhello/PythonEmcTraining1
/psguessme.py
611
4.1875
4
"""The player will be given 10 chances to guess a number, and when player gives a input, then he should get a feedback that his number was lesser or greater than the random number """ import random key = random.randint(1, 1000) x = 1 while x <= 10: user_input = int(input('Give a random number to play the game: ')) if user_input > key: print('your input is more than the number, please try again') elif user_input < key: print('your input is less than the number') elif user_input == key: print('Congratulations! you won!') break x += 1
true
67e83fd9552337c410780198f08039044c925965
Mickey248/ai-tensorflow-bootcamp
/pycharm/venv/list_cheat_sheet.py
1,062
4.3125
4
# Empty list list1 = [] list1 = ['mouse', [2, 4, 6], ['a']] print(list1) # How to access elements in list list2 = ['p','r','o','b','l','e','m'] print(list2[4]) print(list1[1][1]) # slicing in a list list2 = ['p','r','o','b','l','e','m'] print(list2[:-5]) #List id mutable !!!!! odd = [2, 4, 6, 8] odd[0] = 1 print(odd) odd[1:4] =[3 ,5 ,7] print(odd) #append and extend can be also done in list odd.append(9) print(odd) odd.extend([11, 13]) print(odd) # Insert an element into a list odd = [1, 9] odd.insert(1, 3) print(odd) odd[2:2] =[5,7] print(odd) # How to delete an element from a list? del odd[0] print(odd) #remove and pop are the same as in array !!! # Clear odd.clear() print(odd) #Sort a list numbers = [1, 5, 2, 3] numbers.sort() print(numbers) # An elegant way to create a list pow2 = [2 ** x for x in range(10)] print(pow2) pow2 = [2 ** x for x in range(10) if x > 5] print(pow2) # Membership in list print(2 in pow2) print(2 not in pow2) # Iterate through in a list for fruit in ['apple','banana','orange']: print('i like', fruit)
true
c9f325732c1a2732646deadb25c9132f3dcae649
samir-0711/Area_of_a_circle
/Area.py
734
4.5625
5
import math import turtle # create screen screen = turtle.Screen() # take input from screen r = float(screen.textinput("Area of Circle", "Enter the radius of the circle in meter: ")) # draw circle of radius r t=turtle.Turtle() t.fillcolor('orange') t.begin_fill() t.circle(r) t.end_fill() turtle.penup() # calculate area area = math.pi * r * r # color,style and position of text turtle.color('deep pink') style = ('Courier', 10, 'italic') turtle.setpos(-20,-20) # display area of circle with radius r turtle.write(f"Area of the circle with radius {r} meter is {area} meter^2", font=style, align='center') # hide the turtle symbol turtle.hideturtle() # don't close the screen untill click on close turtle.getscreen()._root.mainloop()
true
c7ac2454578be3c3497759f156f7bb9f57415433
dawid86/PythonLearning
/Ex7/ex7.py
513
4.6875
5
# Use words.txt as the file name # Write a program that prompts for a file name, # then opens that file and reads through the file, # and print the contents of the file in upper case. # Use the file words.txt to produce the output below. fname = input("Enter file name: ") fhand = open(fname) # fread = fhand.read() # print(fread.upper()) #for line in fread: # line = line.rstrip() # line = fread.upper() # print(line) for line in fhand: line = line.rstrip() line = line.upper() print(line)
true