blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
9d1bd51c680c5b02d9add39bae19cb43a6b6dda6
BayanbaevIlyas/Lesson1
/Lesson2/Lesson3/list2.py
1,696
4.15625
4
films = [['Назат в Будущее',1985,'ПРИКЛЮЧЕНИЕ', 9], ['Тор: Рагнарек', 2017, 'Фантастика',9], ['Матрица', 1998, 'Боевик',10], ['Телохранитель киллера', 2017, 'Комедия', 9], ['нтерстерла', 2014, 'фантастика', 10]] number = 0 while number != 5: print ('Введите 1 - показать фильмы по названия') print ('2 - показать фильмы по жанру') print ('3 - добавить фильм') print ('4 - удалить фильм') print ('5 - Выйти из программы') number = int(input()) if number == 1: name = input('Введите показать фильмы:') for film in films: if film[0] == name: print(film) elif number == 2: name = input('показать фильмы по жанру:') for film in films: if film[2] == name: print(film) elif number == 3: name = input('добавить фильм:') year = int(input('Введите год выхода')) genre = input ('Введите жанр') rate = int(input('Введите рейтинг')) films.append([name, year, genre, rate]) print('фильм добавлен') elif number == 4: name = input('удалить фильм') for film in films: if film[0] == name: films.remove(film) print ('фильм удален') print (films) elif number == 5: print('пока') else: print('такого числа нет')
false
99c0537d2988eceebc89c32b6e2dd5cb58776b56
wmalgoire/learning.python
/02.courses/01.pluralsight-python-fundamentals/02.modularity/words.py
1,232
4.28125
4
#!/user/bin/env python3 """Retrieve and print words from a url Usage: python3 words.py <URL> Comments: Code from Pluralsight Python Fundamentals course """ from urllib.request import urlopen import sys def fetch_words(url): """Fetch a list of words from a URL Args: url: The URL of a UTF-8 document Returns: A list of string containing the words from the document """ with urlopen(url) as story: story_words = [] for line in story: # urlopen returns bytes (b'string') and not unicode string line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) return story_words def print_items(items): """Print a list of items Args: items: the list of items """ for word in items: print(word) def main(url): """main function when running the script Args: url: The URL of a UTF-8 document """ print_items(fetch_words(url)) # When executing the script: if __name__ == "__main__": if len(sys.argv) == 1: main("https://github.com/wmalgoire/learning.python") else: main(sys.argv[1])
true
dad48efc179fb8dd430631a7d2399ac4d3fd4ed0
AyebakuroOruwori/KaggleAug30daysChallenge
/Day_4_Challenge.py
467
4.21875
4
#Many programming languages have sign available as a built-in function. Python doesn't, but we can define our own! #In the cell below, define a function called sign which takes a numerical argument and returns -1 if it's negative, 1 if it's positive, and 0 if it's 0. # Your code goes here. Define a function called 'sign' def sign(num): if num < 0: return -1 elif num > 0: return 1 else: return 0 # Check your answer q1.check()
true
557a04e94cb1da1e7f3f55e91646f1b499b87687
ThiagoGoldschmidt1/Basic_Python
/task_3.2.py
1,049
4.1875
4
# This function chekcs if a number is prime def is_prime(n): #1 isnt a prime number, but its kind of an exeption to the rule if n == 1: return False else: #Checks in the range from 2 to our n -1 for i in range(2,n-1): #If it is not divisible by this number if n % i != 0: #check the next one continue else: #if it is divisible, its not a prime number return False #If it went through the whole range wihtout finding one number that it is divisible by, its a prime number return True #takes an input and turns it into an integer so we can use it inour function num = int(input('Please input a numnber: ')) def prime_detector(num): #checks in this range, starts with 1 since we dont want to check 0 for number in range(1,num +1): if is_prime(number) == True: print(f"{number} is a prime.") else: print(f"{number} is not a prime.") prime_detector(num)
true
d5f32ac9209b97c8614701615a60c890eed681e0
vrushparva/Tranning.Reposittory
/learnpython/temp.py
655
4.15625
4
# # num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # # # my_list = [n*n for n in num] # # print(my_list) # # for i in my_list: # print(i) ##############################################33 # # # # # def square_numbers(nums): # # results = [] # for n in nums: # # results.append(n * n) # yield (n*n) # # # nums = [1, 2, 3, 4, 5] # my_nums = square_numbers([1, 2, 3, 4, 5]) # # # print(next(my_nums)) # print(next(my_nums)) # print(next(my_nums)) # print(next(my_nums)) # print(next(my_nums)) # my_nums = (n*n for n in [1, 2, 3]) # for i in my_nums: # print(i) # print(list(my_nums)) ##############################################33
false
862bb4740c45c90271ed45c48222778b1b89159a
Renatosdb/Python---CodeAcademy
/NumberGuess.py
1,498
4.71875
5
""" TITLE: NumberGuess.py UNIT: 4 AUTHOR: Renato Lima Wanna play a game? In this project, we'll build a program that rolls a pair of dice and asks the user to guess a number. Based on the user's guess, the program should determine a winner. If the user's guess is greater than the total value of the dice roll, they win! Otherwise, the computer wins. The program should do the following: - Randomly roll a pair of dice - Add the values of the roll - Ask the user to guess a number - Compare the user's guess to the total value - Decide a winner (the user or the program) - Inform the user who the winner is """ from random import randint from time import sleep def get_user_guess(): user_guess = int(raw_input("Guess a number: ")) return user_guess def roll_dice(number_of_sides): first_roll = randint(1, number_of_sides) second_roll = randint(1, number_of_sides) max_val = number_of_sides * 2 print "The maximum possible value is: " + str(max_val) sleep(1) user_guess = get_user_guess() if user_guess > max_val: print "No guessing higher than the maximum possible value!" return else: print "Rolling..." sleep(2) print "The first value is: %d" % first_roll sleep(1) print "The second value is: %d" % second_roll sleep(1) total_roll = first_roll + second_roll print total_roll print "Result..." if user_guess > total_roll: print "You won!" return else: print "You lost, try again." return roll_dice(6)
true
c633c2d1c2e8a1f50489fa99c21762c4225cfdc1
leosbarai/pythonbrasil
/decisionstructure/15_triangle.py
1,100
4.25
4
def triangle(): print("********************************** ") print(" Triangulo! ") print("********************************** ") try: left_side = float(input("Informe o lado esquerdo do triângulo: ")) right_side = float(input("Informe o lado direito do triângulo: ")) base = float(input("Informe a base do triângulo: ")) sum_left = left_side + right_side sum_right = right_side + base sum_base = base + left_side if sum_left < base or sum_right < left_side or sum_base < right_side: print('O valor informado não corresponde a um triângulo!') elif left_side == right_side and left_side == right_side and right_side == base: print('É um Triângulo Equilátero!') elif left_side == right_side or left_side == right_side or right_side == base: print('É um Triângulo Isósceles!') else: print('É um Triângulo Escaleno!') except ValueError: print('Valor informado está inválido!') if __name__ == "__main__": triangle()
false
3ec0f37c2f23534522c2ed2d4e4a71fdf7cb8b57
niojam/pr01
/hello.py
922
4.125
4
"""Kodune töö nr 1.""" def main(): """1.Programm küsib sisendit: (input).""" name = input("What's your name? ") if name == "": print("Name was not inserted!") school = input("Where do you study? ") if school == "": print("School was not inserted!") print(name + ", welcome to " + school) def ex01(): """2.Arvuta kehamassi indeks kasutades sisendit (input).""" mass = float(input("Palun sisestage oma mass (kg): ")) height = float(input("Palun sisestage oma pikkus (m): ")) kehamassiindeks = mass / height ** 2 if kehamassiindeks > 25.0: keha = "ülekaaluline" elif kehamassiindeks < 18.5: keha = "alakaaluline" elif kehamassiindeks >= 18.5 and kehamassiindeks <= 24.9: keha = "normaalkaal" print(str(kehamassiindeks) + ", " + str(keha)) if __name__ == '__main__': main() ex01()
false
26ba483d2e7306976627407e2dfcb5c972cc12a2
manzanoy1/craps-
/craps-/craps-/craps.py
2,072
4.1875
4
#Yanira Manzano #21/10/2019 #Project: Craps! import random import sys print("""Hello player! Welcome to Craps! Play Game or Quit?""") option = input('> ') def coins(): coins(int(input())) def bet(): bet(int(input())) def choice(): choice(input()) if option == "play game": username = input("Please enter your name:") print(f"Welcome {username}, to craps!") print("Enter your coins that you will have.") coins = int(input('> ')) elif option == "quit": sys.exit() while coins > 0 and bet > 0: print("Okay, how much do you want to bet on this round?") bet = int(input("> ")) roll = random.randint(2, 12) print(f"You have rolled {roll}.") if roll == 7 or roll == 11: print(f"Hey {username}, you won! :D") coins = coins + bet print(f"{username} have now {coins} on his/her pocket.") elif roll == 2 or roll == 3 or roll == 12: print(f"Aw you lost this time, {username}. :(") coins = coins - bet print(f"{username} have now {coins} on his/her pocket.") else: print(f"You just encountered with {roll}. In this case you have to roll that value again to win, else you lose.") print(f"Don't lose hope, {username}!") encounter = roll if roll == encounter: coins = coins + bet print(f"{username}! You won this bet with the roll of {roll}!") print(f"{username} have now {coins} on his/her pocket.") else: coins = coins - bet print(f"Damn {username}, you lost this bet with the roll of {roll}.") print(f"{username} have now {coins} on his/her pocket.") print(f"Would you like to play again, {username}?") choice = input('> ') if choice == "yes": if bet > coins: print(f"{username}, you just bet more than you have in your pocket. So I have to end here. Goodbye {username}.") elif choice == "no": print(f"Well see ya, {username}!") sys.exit() else: bet = 0
true
54a835496941d0892e5dcff0a3c255f1a64c6e20
marcinbot/misc
/python/regex.py
2,405
4.3125
4
''' Given a simple regular expressions supporting: - lowercase letters a-z - a dot operator - a star operator Write a method that checks if the word matches a regex ''' ''' A class representing a single regular expression token (letter, dot, or star) ''' class Token(): def __init__(self, char, is_star = False): if len(char) != 1: raise Exception() if char != '.' and (ord(char) < 97 or ord(char) > 122): raise Exception() self.char = char self.is_star = is_star def __str__(self): if self.is_star: return '*({0})'.format(self.char) return self.char def __repr__(self): return self.__str__() @property def is_char(self): return not self.is_star and self.char != '.' @property def is_dot(self): return self.char == '.' and not self.is_star def matches(self, char): return self.char == '.' or self.char == char ''' Converts regex string into a list of tokens ''' def tokenize(regex): result = [] token = None for char in regex: if (char == '*'): if len(result) == 0: raise Exception() prev_token = result.pop() if prev_token.is_star: raise Exception() token = Token(prev_token.char, True) else: token = Token(char) result.append(token) return result ''' Given a star token and a list of remaining tokens, check for match ''' def match_star(star_token, tokens, word): i = 0 while True: if match_here(tokens, word[i:]): return True char = word[i] i += 1 if i > len(word) or not star_token.matches(char): return False return False ''' Given a list of tokens and a string word check for match ''' def match_here(tokens, word): if len(tokens) == 0: return len(word) == 0 token = tokens[0] if token.is_star: return match_star(token, tokens[1:], word) if len(word) == 0: return False char = word[0] if token.matches(char): return match_here(tokens[1:], word[1:]) return False ''' Entry point, given a string regex and a string word, check for match ''' def is_match(regex, word): tokens = tokenize(regex) return match_here(tokens, word) print(is_match('a*ab', 'aaab'))
false
47fee6338438408c6eae201adb3d5fe60db79ce9
dngo13/ENPM661
/Project 0/source.py
2,354
4.1875
4
import math # Part 1 Practice my_list = [] for i in range(10): i = i+1 i = math.pow(i, 2) my_list.append(i) print(my_list) my_list.sort(reverse=True) print(my_list) my_list.pop(-3) my_list.pop(-3) print(my_list) # Part 2 empty_tuple = () print(empty_tuple) tup = 'python', 'geeks' print(tup) tup1 = (0, 1, 2, 3) tup2 = ('python', 'geek') print(tup1+tup2) tup3 = (tup1, tup2) print(tup3) tup3 = ('python',)*3 print(tup3) # Code for converting a list and a string into a tuple list1 = [0, 1, 2] print(tuple(list1)) print(tuple('python')) # string 'python' # python code for creating tuples in a loop tup = ('ENPM661',) n = 5 # Number of time loop runs for i in range(int(n)): tup = (tup,) print(tup) # Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Creating a Dictionary # with Integer Keys Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\nDictionary with the use of Integer Keys: ") print(Dict) # Creating a Dictionary # with Mixed keys Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("\nDictionary with the use of Mixed Keys: ") print(Dict) # Creating a Dictionary # with dict() method Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'}) print("\nDictionary with the use of dict(): ") print(Dict) # Creating a Dictionary # with each item as a Pair Dict = dict([(1, 'Geeks'), (2, 'For')]) print("\nDictionary with each item as a pair: ") print(Dict) # Creating a Nested Dictionary # as shown in the below image Dict = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}} print(Dict) # Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Adding elements one at a time Dict[0] = 'Geeks' Dict[2] = 'For' Dict[3] = 1 print("\nDictionary after adding 3 elements: ") print(Dict) # Adding set of values # to a single Key Dict['Value_set'] = 2, 3, 4 print("\nDictionary after adding 3 elements: ") print(Dict) # Updating existing Key's Value Dict[2] = 'Welcome' print("\nUpdated key value: ") print(Dict) # Adding Nested Key value to Dictionary Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}} print("\nAdding a Nested Key: ") print(Dict)
false
181c283e5ce2f6749514fd8d40479ebffbf64a3f
Jaydenmay-040/software-basics
/intro-python/main.py
302
4.5
4
# Task 2 Sample Solution radius = input("Please enter the radius: ") _PI = 3.14 area = _PI * int(radius)**2 print("The area of a circle is: " + str(area)) # Calculate the circumference circumference = 2 * _PI * int(radius) print("The circumference of a cirlce of a circle is: " + str(circumference))
true
a5ff2b9b0149deca9ac59be8f3481885e8002fe2
BhuiyanMH/Python3
/Experiment/PythonFunctions.py
1,662
4.46875
4
# def function_name(parameters): # """dicstring""" # statements def greet(name): '''this function greet someone with the given name''' print("Hello, "+ name+ ". Good Morning!") greet("Kamal") #if no return statement, the function will return a 'None' object # variable declared outside the function can be read inside the function #if we want to change the value, the varable needed to be declared as 'global' #Default arg #if we have a defult arg, all the args right of it must be default def greet2(name, msg="Good morning"): print("Hello "+name+", "+msg) greet2("Sazzad") greet2("Sazzad", "Good Night") #Python allows function to be called using keyword arguments #in that case order of arguments doen't matters greet2(msg="Good Evening", name="Mejbah") #Arbitary arguments: * is used before the parameter name, # arguments gets wrapped into a tuple def greet(*names): for name in names: print("hello ", name) greet("Afnan", "Joyeta") #Python Anonymous or Lambda function: can have any number of arguments #and simgle expresson, the expression is evaluated and returned #lamda arguments : expression #it cal be use solely or filter() or map() function #Python filter(): takes a function and list of argements, the function is # called with all the items in the list and a new list is returned contained # for which the function evaluates to true myList = [1, 5, 4, 3, 6] newList = list(filter(lambda x:(x%2==0), myList)) print(newList) #map() is the same except that, returned list contains the elements returned by the func my_list = [1, 5, 4, 6] new_list = list(map(lambda x: x**2, my_list)) print(new_list)
true
7c094a8c36311fb8b3c2046e17f17fd4b54f4d0d
kesav21/project-euler
/python/p019
1,391
4.21875
4
#!/usr/bin/python3 import itertools as it months = { 1: 31, 2: {"nonleap": 28, "leap": 29}, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31, } # days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] days = ["tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "monday"] def main(): # the range of years you want to count over years = range(1901, 2001) # the day on the beginning of the count # ex: 1 jan 1901 was a tuesday first_day = "tuesday" print(get_count(years, first_day)) def get_count(years, first_day): """ TODO: use first_day somehow """ count = 0 daycount = 0 for year in years: for month in range(1, 12 + 1): maxdays = get_max_days(month, year) for date in range(1, maxdays + 1): if daycount % 7 == 5 and date == 1: count += 1 daycount += 1 return count def get_max_days(month, year): if month == 2: if is_leap_year(year): return months[month]["leap"] return months[month]["nonleap"] return months[month] def is_leap_year(year): return ( (year % 4 == 0) and (year % 100 != 0) or (year % 100 == 0 and year % 400 == 0) ) if __name__ == "__main__": main()
false
93f06a2663d6f8e485c54f5803688f9cd7e7256a
melissa1824-cmis/melissa1824-cmis-cs2
/oneguess.py
947
4.125
4
import random import math def output(number1, number2,): return """ I'm thinking of a number from {} to {}. """. format(number1, number2) def result(target, guess, offby): if target > guess: print """ The target was {}. Your guess was {}. That's under by {}. """. format(target, guess, offby) elif target == guess: print """ The target was {}. Your guess was {}. You're a mind reader! """. format(target, guess, offby) else: print """ The target was {}. Your guess was {}. That's over by {}. """. format(target, guess, offby) def main(): number1 = int(raw_input("What is the minimum number? ")) number2 = int(raw_input("What is the maximum number? ")) print output(number1, number2) guess = int(raw_input("What do you think it is? ")) target = random.randint(int(number1), int(number2)) offby = abs(int(target) - int(guess)) result(target, guess, offby) main()
true
86b5a4fe00659e0524582801b56aa8016c7a9dc3
junzhougriffith/test
/PyLab/W1B5.py
2,372
4.1875
4
##//////////////////////////// PROBLEM STATEMENT ////////////////////////////// ## A website requires the users to input username and password to // ## register. Write a program to check the validity of password input by // ## users. Following are the criteria for checking the password: 1. At least // ## 1 letter between [a-z] 2. At least 1 number between [0-9] 1. At least 1 // ## letter between [A-Z] 3. At least 1 character from [0@] 4. Minimum // ## length of transaction password: 6 5. Maximum length of transaction // ## password: 12 Your program should accept a sequence of colon separated // ## passwords and will check them according to the above criteria. Passwords // ## that match the criteria are to be printed, each separated by a comma. // ## Example If the following passwords are given as input to the program: // ## ABd1234@1:a F1#:2w3E*:2We3345 Then, the output of the program should be: // ## ABd1234@1 // ##///////////////////////////////////////////////////////////////////////////// ## 1. At least 1 letter between [a-z] def check_lower_case(cand_password): for ch in cand_password: if "a" <= ch and ch <= "z": return True return False ## 2. At least 1 letter between [A-Z] def check_upper_case(cand_password): for ch in cand_password: if "A" <= ch and ch <= "Z": return True return False ## 3. At least 1 number between [0-9] def check_digits(cand_password): for ch in cand_password: if "0" <= ch and ch <= "9": return True return False ## 4. Minimum length of transaction password: 6, Maximum length of transaction password: 12 def check_length(cand_password): return len(cand_password) >= 6 and len(cand_password) <= 12 ## check candidate password def check_cand_password(cand_password): return check_lower_case(cand_password) and check_upper_case(cand_password) and check_digits(cand_password) and check_length(cand_password) ############################################################################33 s = input() while(len(s) > 0): colon_loc = s.find(':') if colon_loc == -1: break cand_password = s[:colon_loc] s = s[colon_loc+1:len(s)] if check_cand_password(cand_password): print(cand_password)
true
1904c577d1920710e6a78f0d6b2d7b48b52a4003
junzhougriffith/test
/PyLab/W163.py
1,987
4.15625
4
##///////////////////////// PROBLEM STATEMENT ////////////////////////// ## Given three ints, a b c, one of them is small, one is medium and // ## one is large. Print True if the three values are evenly spaced, // ## so the difference between small and medium is the same as the // ## difference between medium and large. // ## 2 4 6 -> True // ## 4 6 2 -> True // ## 4 6 3 -> False // ##////////////////////////////////////////////////////////////////////// ''' a = int(input()) b = int(input()) c = int(input()) if a - b == b - c : print(True) elif a - c == c - b: print(True) elif c - a == a - b: print(True) else: print(False) ''' a = int(input()) b = int(input()) c = int(input()) # find largest int, assign to l if a > b and a > c: # a >= b and a >= c: because the input may be like 4, 4, 2, in this case, if without '=', no value will assing to l according to the three 'if' conditions. l = a if b > a and b > c: # b >= a and b >= c: (similar reason to the first 'if' statement l = b if c > a and c > b: # c >= a and c >= b: l = c # find median int, assign to m if (a > b and a < c) or (a > c and a < b): # (a >= b and a <= c) or (a >= c and a <= b): m = a if (b > a and b < c) or (b > c and b < a): #(b >= a and b <= c) or (b >= c and b <= a): m = b if (c > a and c < b) or (c > b and c < a): #(c >= a and c <= b) or (c >= b and c <= a): m = c # find smallest int, assign to s if (a < b and a < c): # (a <= b and a <= c): s = a if (b < a and b < c): # (b <= a and b <= c): s = b if (c < a and c < b): # (c <= a and c <= b): s = c # calculation the difference between s, m & l if l - m == l - s: # this line should be l - m == m - s: print(True) else: print(False) Thanks
false
880aa3ac591ce5ec1b5078be66162844a4f6beaa
Hero48/htbmi
/bmi.py
612
4.15625
4
# Attributes print("Welcome to Heroz Tech BMI calculator") Name = input( "what is your name ? ") Age = int( input("Your age ? ")) Height = float(input("What is your height ? ")) Weight = float(input("What is your Weight ? ")) # abreviations a = Name b = Age c = Height d = Weight #calculation x = d/ c**2 # results output print("Your BMI is = " , x) if x < 18: print(a , "you are under weight") if 18.5 < x < 25.1: print(a , "you have a normal weight") if 25 < x <30.1: print(a , "you are overweight") if x > 30: print(a , "You are obese") print("Thank you for using htBMI")
true
f14c0e7691ead4e3f5084d14bbaad03233e8d84c
scottdono/CompSci_Year2
/Python Programming/LabTest_01_11_2018/Lab Test.py
2,365
4.125
4
# Function: Write a Python program that will prompt the user for a number, and print all the Kaprekar numbers # from 10 to that number. # Use functions where appropriate to structure your code. # Author: Scott Donnelly # Date: 01/11/18 # Compiler used: PyCharm # Functions def Kaprekar_range(): user_input = input("Enter a top limit (Inclusive):\n") user_input = int(user_input) # making the variable an int print("The list of all Kaprikar numbers from ", 10, "to", user_input, "is: \n") for i in range(10, user_input + 1): # Get the digits from the square in a list: sqr = i ** 2 digits = str(sqr) # Now loop from 1 to length of the number - 1, sum both sides and check length = len(digits) for x in range(1, length): left = int("".join(digits[:x])) right = int("".join(digits[x:])) if (left + right) == i: print(" " + str(i)) def Kaprekar_check(): num_check = input("Enter the number that you would like to check:\n") num_check = int(num_check) for i in range(num_check, num_check + 1): # Get the digits from the square in a list: sqr = i ** 2 digits = str(sqr) # Now loop from 1 to length of the number - 1, sum both sides and check length = len(digits) for x in range(1, length): left = int("".join(digits[:x])) right = int("".join(digits[x:])) if (left + right) == num_check: print(num_check, "is a Kaprekar number because when you square it you get", sqr) print("This can be split into", left, "and", right, "which then adds up to", num_check) elif (left + right) != num_check: print(num_check, "is not a Kaprekar number") break # leave the loop # Main function # Menu to choice which function you want print("1. Check if a number is a Kaprekar number\n") print("2. See the list of Kaprekar numbers within a specified range\n") choice = input("Please enter the number that corresponds to what option you want:\n") choice = int(choice) # making the variable an int if choice == 1: # Call function Kaprekar_range() elif choice == 2: Kaprekar_check() else: print("Invalid input\n")
true
bb5e0ed9de07ed5ceed587ee5c67990fedd83a06
63CK0/DojoAssignments-2
/Python/fun-functions.py
562
4.21875
4
def odd_even(): count = 0 for i in range(1,2001): count += 1 if count %2 == 0: print "Number is ", count ,". This is an even number." else: print "Number is", count,"."," This is an odd number." odd_even() 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 def layered_multiples(arr): new_array = [] for x in arr: val_arr = [] for i in range(0,x): val_arr.append(1) new_array.append(val_arr) return new_array x = layered_multiples(multiply([2,4,5],3)) print x
false
aec7209a2812b4ee1e67bfda442c5420c1fe5e10
63CK0/DojoAssignments-2
/Python/tuple.py
716
4.4375
4
tuple_data = ('physics', 'chemistry', 1997, 2000) tuple_num = (1, 2, 3, 4, 5 ) tuple_letters = "a", "b", "c", "d" dog = ("Canis Familiaris", "dog", "carnivore", 12) print dog[2] """ max(sequence) returns the largest value in the sequence sum(sequence) return the sum of all values in sequence enumerate(sequence) used in a for-loop context to return two-item-tuple for each item in the sequence indicating the index followed by the value at that index. map(function, sequence) applies the function to every item in the sequence you pass in. Returns a list of the results. min(sequence) returns the lowest value in a sequence. sorted(sequence) returns a sorted sequence """
true
3b61886216de0b6767b48899f856554cd68bb885
nehapokharel/Beeflux_Test
/Question9.py
394
4.28125
4
class Dog: kind = 'canine' def __init__(self, name): self.name = name # instance variable unique to each instance d = Dog('Fido') e = Dog('Buddy') print(d.kind) #output = canine print(d.type) #'Dog' object has no attribute 'type' so it will give an error print(e.kind) #canine print(e.type) #'Dog' object has no attribute 'type' so it will give an error
true
da800179ee0b00e9d8cb5569dfba519ea6e03edb
manohar-kanduri-vst-au4/Deck_Of_Cards-
/cards.py
2,720
4.3125
4
import random class Card(): """ The Card class represents a single playing card and is initialised by passing a suit and number. """ def __init__(self, suit, number): """ This is a default constructor used to initialise instance variables or attributes for Card object """ self._suit = suit self._number = number def __repr__(self): """This method is used to represent a output in better manner or understandable form """ return (self._number + " of " + self._suit) @property def suit(self): """This method is used to get the suit value(as getter method)""" return self._suit @suit.setter def suit(self,suit): """This method is used to set the values to suit variable (like setter method) """ if suit in ["hearts", "clubs", "diamonds", "spades"]: self._suit = suit.upper() else: print("This is not a suit") @property def number(self): """ This method is used to get values of number variable """ return self._number @number.setter def number(self,number): """ This method is used to set values for number variable """ if number in [str(i) for i in range(2,11)] + ['J', 'Q', 'K', 'A']: self._number = number class Deck(): """ The Deck class represents a list of total 52 playing cards The Deck class represents a deck of playing cards in order. """ def __init__(self): """ This is a default constructor used to initialise instance variables or attributes for Deck object """ self._cards = [] self.populate() print(self._cards) def populate(self): """ This method is used to populate the deck of cards with all 52 cards in the order 2-10, J,Q,K,A, hearts, clubs, diamonds, spades""" suits = ["hearts", "clubs", "diamonds", "spades"] numbers = [str(n) for n in range(2,11)]+["J", "Q", "K", "A"] self._cards = [ Card(s,n) for s in suits for n in numbers ] def shuffle(self): """ Shuffle the deck into a random order of playing cards """ random.shuffle(self._cards) def deal(self, no_of_cards): """ Deals(and removes) a number of cards from the deck Returns : list of Card objects """ dealt_cards = [] for i in range(no_of_cards): dealt_card = self._cards.pop(0) dealt_cards.append(dealt_card) return dealt_cards def __repr__(self): cards_in_deck = len(self._cards) return "Deck of " + str(cards_in_deck) + " cards" deck = Deck() print(deck)
true
6382029ec9d3d7dc127cf1dea2b69724aaba601c
greenfox-velox/szemannp
/week-03/day-2/36.py
336
4.21875
4
# write a function that reverses a list my_list = [3, 4, 5, 6, 7] # def list_reverse(input_list): # input_list.reverse() # return input_list # # print(list_reverse(my_list)) def revert(input): reverse = [] for i in range(len(input)-1, -1, -1): reverse += [input[i]] return reverse print(revert(my_list))
true
eb501fab4c06831eba99c90ed35647f06b2a72fb
greenfox-velox/szemannp
/week-03/day-2/39.py
332
4.25
4
names = ['Zakarias', 'Hans', 'Otto', 'Ole'] # create a function that returns the shortest string # from a list def short_string_func(input_list): for i in range(len(input_list)): if len(input_list[i - 1]) > len(input_list[i]): minLength = input_list[i] return minLength print(short_string_func(names))
true
b340a274e6ab2239857d6d37db71dd1a1103f980
greenfox-velox/szemannp
/week-03/day-2/37.py
408
4.125
4
numbers = [3, 4, 5, 6, 7] # write a function that filters the odd numbers # from a list and returns a new list consisting # only the evens def sort_list_funct(input_list): newList = [] for i in range(len(input_list)): if input_list[i] % 2 != 0: i += 1 else: newList.append(input_list[i]) i += 1 return newList print(sort_list_funct(numbers))
true
5d701c223ad649798181b79b36cace2e82443f1b
davidpvilaca/prog1
/exercicios/exercicio_pratico_2.py
500
4.1875
4
# 22/10/2014 # Exercício prático 2 # # Convertendo temperatura em Fahrenheit para Celsius # def main(): #Declarando variável fahrenheit = 0.0 celsius = 0.0 #Definindo valor das variáveis fahrenheit = float (input ('Digite a temperatura em Fahrenheit para conversão:')) #Conversão celsius = (5/9)*(fahrenheit-32) #Mostrando o resultado print ('%.1f graus Fahrenheit correspondem a %.2f graus Celsius.' %(fahrenheit,celsius) ) if __name__ == '__main__': main()
false
b06f0d995d95b56931cc8f3a702af2e74fef652b
davidpvilaca/prog1
/listas/lista 1/ex8.py
1,437
4.28125
4
# EXERCÍCIO - LABORATÓRIO - 08 # # DAVID PANTALEÃO VILAÇA | TADEU DA PENHA MORAES JUNIOR # # Escreva um programa que leia 10 valores inteiros e encontre o maior e o menor dentre esses valores. # O programa deve mostrar o resultado dos valores encontrados na tela. # Observacao: use um comando # de repeticao. #funcao main def main(): print ('DESCUBRA O MAIOR INTEIRO DIGITANDO 10 NUMEROS ABAIXO:') #print inicial/informacao #declaracao de variaveis num, aux, aux2, contador = 0,0,0,0 #entrada de dados contador = 1 #contador comecando com o valor 1 #num recebe um numero inteiro do teclado num = int(input('%d - Insira um valor: ' %(contador))) aux = num aux2 = num #processamento while contador < 10: #enquanto o contador for menor if aux < num: #se a aux for maior que o numero ela recebera o numero aux = num print ('\nO maior valor por enquanto é: %d\n' %(aux) ) #mostra o resultado como no enunciado if aux2 > num: aux2 = num print ('\nO menor valor por enquanto é: %d\n' %(aux2) ) #mostra o resultado como no enunciado contador += 1 #contador como condicao de parada do while num = int(input('%d - Insira um valor: ' %(contador))) #entrada dos proximos numeros dentro do loop print ('\n\nO maior valor informado e %d\n O menor valor informado e %d' %(aux,aux2) ) #impressao do resultado final return 0 #fim main if __name__ == '__main__': main() #fim if
false
ac0e0ff76ae087fd066b4dc7eaab38b614f93a99
zshahid1/Helpful
/Python project/WhileLoops.py
916
4.15625
4
import random # WHILE LOOPS ------------- # While loops are used when you don't know ahead of time how many # times you'll have to loop random_num = random.randrange(0, 100) while (random_num != 15): print(random_num) random_num = random.randrange(0, 100) # An iterator for a while loop is defined before the loop i = 0; while (i <= 20): if (i % 2 == 0): print(i) elif (i == 9): # Forces the loop to end all together break # else: # Shorthand for i = i + 1 # i += 1 # Skips to the next iteration of the loop # continue # i += 1 class Animal: __name = "" __height = 0 __weight = 0 __sound = 0 def __init__(self, name, height, sound): self.__name = name self.__height = height self.__weight = weight def set_name(self, name): self.__name = name def get_name(self): return self.__name
true
2b0af513d64f851c96f29d6ecb3e5cf46fefd3df
yurii-fylonych/matrix_python
/array_problem_2_16.py
239
4.15625
4
array = [] N = int(input('Enter number of rows = ')) M = int(input('Enter number of columns = ')) for row in range(N): array.append([]) for column in range(M): array[row].append(row + 1) for row in array: print(row)
true
834b54d7eea6bda0ebd3559f56c504b993a580ac
VirtualEvan/Practicas_ALS
/Clase2/operadores_prefijos.py
1,300
4.125
4
def evaluate(all): """ Evaluete expressions with prefix operands :param l: A given list whit to operands for each operator :return: Result number of eval """ def is_operator(op): """ Determinate if is a string is operator or not :param op: A string operand/operator :return: True if operator, False otherwise """ return True if op in ['+', '-', '*', '/'] else False l = all[0] pos = all[1] if pos >= len(l): return -1 operator = l[pos] pos += 1 # Operator1 if is_operator(operator): all[1] = pos print("Evaluar operador 1: ", l[1:]) op1 = evaluate(all) else: op1 = l[pos] pos += 1 # Operator2 if is_operator(operator): all[1] = pos print("Evaluar operador 1: ", l[1:]) op2 = evaluate(all) else: op2 = l[pos] pos += 1 expression = op1 + operator + op2 print(expression) return str(eval(expression)) l = "+ - 4 2 3".split() # print("Expresion:", l) # print("Resultado:", evaluate(l)) l = "+ 1 - 5 * 2 4".split() # print("Expresion: ",l ) # print("Resultado:", evaluate(l)) exp = "+ - 4 * 6 1 8".split() l = [exp, 0] print("Expresion: ",l) print("Resultado:", evaluate(l))
true
5706dd0e01b7e8fb8b1a32553efe4234a54acd09
SougatSarangi/BasicPythonPrograms
/Neg-Pos_Number_Arrangement.py
995
4.21875
4
''' PROBLEM STATEMENT: An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers. Examples : Input : -12, 11, -13, -5, 6, -7, 5, -3, -6 Output: -12 -13 -5 -7 -3 -6 11 6 5 Note: Order of elements is not important here. ''' # FUNCTION DEFINATION def rearrange(arr): ZERO = 0 neg_array = [] pos_array = [] # looping the array to find -ve and +ve values # Keep all -ve values in one list and # all +ve values in another list # Append both the list for i in range(len(arr)): if arr[i] < ZERO: neg_array.append(arr[i]) else: pos_array.append(arr[i]) arr = neg_array + pos_array return arr # MAIN FUNCTION if __name__ == "__main__": inputList = [] inputList = [int(item) for item in input("Enter array: ").split()] print(rearrange(inputList))
true
620c78363bc81e91a4526a2e5ccdad01c5b05303
Alex-YuZ/Calculate-days-between-dates
/cal_days_helper.py
2,605
4.46875
4
def next_day(year, month, day): """ Calculate the value of next day given a date consisted of year, month and day. Params: ------- year: int. Value of year given a certain date. month: int. Value of month given a certain date. day: int. Value of year given a certain date. Returns: -------- int: Ouptput the value of day """ if day < days_in_month(year, month): return year, month, day + 1 elif month < 12: return year, month + 1, 1 else: return year + 1, 1, 1 def is_valid_input(year1, month1, day1, year2, month2, day2): """ Check whether the first three args is before the last three in terms of input validity. Params: ------- year1: int. The number of the year as start. month1: int. The number of the month as start. day1: int. The number of day as start. year2: int. The number of the year as end. month2: int. The number of the month as end. day2: int. The number of day as end. Returns: ------- boolean: True/False. True is valid for inputs and vice versa. """ if year1 < year2: return True elif year1 == year2: if month1 < month2: return True elif month1 == month2: return day1 < day2 return False return False def is_leap(year): """ Check a given value of year is a leap year or not. Params: ------- year: int. The value of a given year. Returns: -------- boolean: True if the given year is a leap year and vice versa. """ if year % 4 == 0: if year % 100 == 0: return year % 400 == 0 return True return False def days_in_month(year, month): """ Calculate how many days there are in a given month. Params: ------- year: int. The value of year for a given date. month: int. The value of month for a given date. Returns: ------- int. For month in [1,3,5,7,8,10,12], return 31 days. For month in [4,6,9,11], return 30 days. For month of February, return 29 if a leap year, otherwise, return 28 if a common year. """ if month in [4, 6, 9, 11]: return 30 elif month == 2: if is_leap(year): # check if the given year is a leap or not. return 29 else: return 28 else: return 31
true
d96f6a1611f2427e12f4bcb8a880dd1154fba24c
MadTofu22/MCTC_Python_Assignments
/Lab Assignment/Functions Lab/test.py
551
4.15625
4
def Outer(): def Inner(): print("Hi") Inner() Outer() import math print(math.sin(math.pi)) print(math.sin(math.radians(90))) print(math.sin(math.radians(180))) print(math.sin(math.radians(270))) def temp_convert(degree,unit): '''(float, string) -> degree, unit return value in opposite unit (f -> c and vice versa) >>>temp_convert(32,f) 0 c >>>temp_convert(100,c) 212 f ''' if unit==("f"): return (((degree-32) * (5/9), "c")) if unit==("c"): return (((degree+32)* (9/5), "f"))
true
24bed1d82ffb22c7a122611b98b045f724c54cf9
xiaodongdreams/sword-for-offer
/chapter_2/section_3/9_implement_queue.py
1,681
4.15625
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2019/3/9 3:28 PM # @Author : xiaoliji # @Email : yutian9527@gmail.com """ 用两个栈实现队列 test 1 >>> q1 = MyQueue1() >>> q1.push(1) >>> q1.push(2) >>> q1.peek() 1 >>> q1.pop() 1 >>> q1.empty() False # test q2 >>> q2 = MyQueue2() >>> q2.push(1) >>> q2.push(3) >>> q2.peek() 1 >>> q2.pop() 1 >>> q2.peek() 3 >>> q2.empty() False >>> q2.pop() 3 """ class MyQueue1: """ push: O(1), pop/peek: O(n) 使用一个入栈用来接收数据,使用一个出栈用来返回数据。 """ def __init__(self): self.in_stack, self.out_stack = [], [] def push(self, x: int) -> None: self.in_stack.append(x) def move(self) -> None: if self.out_stack == []: while self.in_stack: self.out_stack.append(self.in_stack.pop()) def pop(self) -> int: self.move() return self.out_stack.pop() def peek(self) -> int: self.move() return self.out_stack[-1] def empty(self) -> bool: return self.in_stack == self.out_stack == [] class MyQueue2: """ push: O(n), pop/peek: O(1) """ def __init__(self): self.s1, self.s2 = [], [] def push(self, x: int) -> None: while self.s1: self.s2.append(self.s1.pop()) self.s1.append(x) while self.s2: self.s1.append(self.s2.pop()) def pop(self) -> int: return self.s1.pop() def peek(self) -> int: return self.s1[-1] def empty(self) -> bool: return not self.s1
false
d8531b05179919a6d67cde1d095421285182745a
hperezv/100DaysofCode-Python
/Day-107/even_num_in_list.py
1,286
4.34375
4
#!/usr/bin/env python3 # https://leetcode.com/problems/find-numbers-with-even-number-of-digits/submissions/ """ 1295. Find Numbers with Even Number of Digits - Easy # Given an array nums of integers, return how many of them contain an even number of digits. # Example 1: Input: nums = [12,345,2,6,7896] Output: 2 # Explanation: 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 digit (odd number of digits). 7896 contains 4 digits (even number of digits). Therefore only 12 and 7896 contain an even number of digits. # Example 2: Input: nums = [555,901,482,1771] Output: 1 # Explanation: Only 1771 contains an even number of digits. #Constraints: 1 <= nums.length <= 500 1 <= nums[i] <= 10^5 """ class Solution: def findNumbers(self, nums): even_num = [] if len(nums) < 1 and len(nums) >= 500: print("The list does not meet the constraints!") else: for i in nums: if len(str(i)) % 2 == 0: even_num.append(i) else: pass print(even_num) return len(even_num) test = Solution() test.findNumbers([12, 345, 2, 6, 7896])
true
0cc73e19c891b40a2c7c31cbc92224758ae4e6ed
hperezv/100DaysofCode-Python
/Day-092/last_names.py
477
4.21875
4
#!/usr/bin/env python3 """ 1. Create a list of author names from the string. 2. Create a second list with the last names of the authors. """ authors = "Audre Lorde, Gabriela Mistral, Jean Toomer, An Qi, Walt Whitman, Shel Silverstein, Carmen Boullosa, Kamala Suraiyya, Langston Hughes, Adrienne Rich, Nikki Giovanni" # 1. Author names as a list author_names = authors.split(",") print(author_names) # 2. Last names of Authors author_last_names = [] for name in author_names: author_last_names.append(name.split(" ")[-1]) print(author_last_names)
true
a01e49119dba537c03d7ee2a26cd08155a8deb2f
hperezv/100DaysofCode-Python
/Day-109/leap_year.py
917
4.28125
4
#!/usr/bin/env python3 # HackerRank Problem # https://www.hackerrank.com/challenges/write-a-function/problem # Source: Wikipedia - https://en.wikipedia.org/wiki/Leap_year # The following pseudocode determines whether a year is a leap year or a common year # in the Gregorian calendar (and in the proleptic Gregorian calendar before 1582). # The year variable being tested is the integer representing the number of the year # in the Gregorian calendar. # if (year is not divisible by 4) then(it is a common year) # else if (year is not divisible by 100) then(it is a leap year) # else if (year is not divisible by 400) then(it is a common year) # else (it is a leap year) def is_leap(year): leap = False if year % 4 != 0: pass elif year % 100 != 0: leap = True elif year % 400 != 0: leap = False else: leap = True print(leap) return leap is_leap(2000)
true
52c2d2422db0b88a5905a6a85fcfc9f6a2c6d739
PyMonar/python-learn
/2_fx.py
1,983
4.21875
4
# Learn Python # 2. 函数 # By Monar ############################################ # 函数 ############################################ # 内置函数 # abs() 取绝对值 # cmp(a, b) a < b: -1, a == b: 0, a > b: 1 # 数据类型转换 # int() # float() # str() # bool() # 定义函数 def my_abs(x): if not isinstance(x, (int, float)): raise TypeError("Bad operand type") if x >= 0: return x else: return -x def doNothing(): pass print my_abs(-1) # print my_abs('A') # 函数可以返回多个值 def move(x, y): x += 1 y += 1 return x, y # 返回的是一个tuple,只不过括号可以省略 x, y = move(3, 4) print "(x, y) is (%d, %d)" % (x, y) # 函数的参数 # 定义默认参数 def my_power(x, n = 2): s = 1 while n > 0: n -= 1 s *= x return s print my_power(5) print my_power(2, 3) def enroll(name, gender, age = 6, city = 'Beijing'): print 'name:', name print 'gender:', gender print 'age:', age print 'city:', city enroll('Bob', 'M', 7) enroll('Adam', 'M', city = 'Tianjin') # 注意:默认参数必须指向不可变对象,否则会有问题。 # 可变参数 def calc(*numbers): sum = 0 for x in numbers: sum += x return sum print "the sum of (1, 2, 3, 4, 5) is", calc(1, 2, 3, 4, 5) # *加上tuple或者列表可以将其解构成参数列表 nums = [1, 2, 3, 4, 5, 6] print "the sum of (1, 2, 3, 4, 5, 6) is", calc(*nums) # 关键字参数 def person(name, age, **kw): print "name:", name, ",age:", age, ",other:", kw person('Monar', 26, city = 'Beijing', job = 'FE') # 参数组合 def func(a, b, c=0, *args, **kw): print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw args = (1, 2, 3, 4) kw = {'x': 99} func(*args, **kw) # a = 1 b = 2 c = 3 args = (4,) kw = {'x': 99} # 递归 def fact(n): if n == 1: return n else: return n * fact(n - 1) print "5! is", fact(5)
false
0244fcbeb343c726d6837fe980535c5a8704d624
PaulMEdwards/LambdaSchool_Sprint27_Week53_cs-module-project-iterative-sorting
/src/iterative_sorting/iterative_sorting.py
2,771
4.3125
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements # print(f"start:\t{arr}") for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) # Your code here # print(f"curr:\t{arr[i]}") for j in range(i+1, len(arr)): # print(f"check:\t{arr[j]}\tsmall?:\t{arr[j] < arr[smallest_index]}") if arr[j] < arr[smallest_index]: smallest_index = j # print(f"small:\t{arr[smallest_index]}") # TO-DO: swap # Your code here temp = arr[i] arr[i] = arr[smallest_index] arr[smallest_index] = temp # print(f"end:\t{arr}") return arr # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): # Your code here swapped = True lastUnsorted = len(arr) + 1 # print(f"\nlen:\t{lastUnsorted - 1}") # loop through indexes while swapped: # print(f"\nbegin:\t{arr}") swapped = False # compare neighbors for right in range(1, lastUnsorted - 1): # swap if neighbors out of order (WRT each other) left = right - 1 # print(f"\tfor {right} in range(1, {lastUnsorted - 1}):\tleft:\t{arr[left]}\tright:\t{arr[right]}\tswap?:\t{arr[left] > arr[right]}") if arr[left] > arr[right]: temp = arr[left] arr[left] = arr[right] arr[right] = temp # print(f"swap!:\t{arr}") swapped = True # break # increment 1 index at a time lastUnsorted -= 1 # print(f"reduced limit") # we are done if/when a loop results in no swaps # print(f"\nend:\t{arr}\n") # achievable in a single loop? # YES? return arr ''' STRETCH: implement the Counting Sort function below Counting sort is a sorting algorithm that works on a set of data where we specifically know the maximum value that can exist in that set of data. The idea behind this algorithm then is that we can create "buckets" from 0 up to the max value. This is most easily done by initializing an array of 0s whose length is the max value + 1 (why do we need this "+ 1"?). Each buckets[i] then is responsible for keeping track of how many times we've seen `i` in the input set of data as we iterate through it. Once we know exactly how many times each piece of data in the input set showed up, we can construct a sorted set of the input data from the buckets. What is the time and space complexity of the counting sort algorithm? ''' def counting_sort(arr, maximum=None): # Your code here return arr
true
92a49eb2eff45dc449858267ea855d00f23ed750
quetzaluz/TranscodeSF
/lecture06/itemcounter.py
2,019
4.21875
4
# Your goal is to make ItemCounter work with the sample code below. # You can change ItemCounter as much as you'd like. # Consider using __getitem__ or __setitem__ functions to make ItemCounter # behave like a dictionary. # See: http://docs.python.org/2/reference/datamodel.html#object.__getitem__ # See: http://docs.python.org/2/reference/datamodel.html#object.__setitem__ # You should write this code # __getitem_ x[key] (self,key) # __setitem__ is like x[key] = value (self,key,value) """ class ItemCounter(object): def __init__(self): dict = {} def __getitem__(self, key): dict.append(key[) def __setitem__(self, key, value): if key == value: # Some sample code for you counter = ItemCounter() for x in [1, 2, 3, 3, 3, 5, 6]: counter[x] += 1 print "There are %d 3's in the list" % counter[3] """ ##Teacher solution: class ItemCounter(object): def __init__(self): self._d = {} def __getitem__(self, key): if key in self._d: return self._d[key] # at this point you can append the key, or you can... return 0 def __setitem__(self, key, value): self._d[key] = value counter = ItemCounter() for x in [1, 2, 3, 3, 3, 5, 6]: counter[x] += 1 print "There are %d 3's in the list" % counter[3] # OUTPUT: #There are 3 3's in the list #>> print counter._d #{1: 1, 2: 1, 3: 3, 5: 1, 6: 1} # Alternative solution with ItemCounter is-a dictionary rather than has-a dictionary class ItemCounter(dict): def __getitem__(self, key): if key in self: return dict.__getitem__(self, key) #dict called to overide definition above #alternative: return super(self, ItemCounter).__getitem__(self, key) Good if you change what you're deriving from. return 0
true
2cf5b7ca6dedee13cb83821ec98817e67c6ec6f5
dortegaoh/CodeWars-Python-solutions
/cw_prefill_array.py
767
4.125
4
##Create the function prefill that returns an array of n elements that all have the same value v. See if you can do this without using a loop. ## ##You have to validate input: ## ##v can be anything (primitive or otherwise) ##if v is ommited, fill the array with undefined ##if n is 0, return an empty array ##if n is anything other than an integer or integer-formatted string (e.g. '123') that is >=0, throw a TypeError ##When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function. def prefill(n,v='undefined'): if str(n).isdigit()==True: return [v for _ in range(int(n))] else: raise TypeError('%s is invalid'%(n)) #example print prefill(0.6,5)
true
b032788751354aa83655b203298e6b8e81170427
kien-ha/school
/SYSC1005/Lab 4/filters.py
1,388
4.1875
4
""" SYSC 1005 A Fall 2014 Lab 4 - Part 3. """ from Cimpl import * #-------------------------------------- # This function was presented in class: def grayscale(img): """ Convert the specified picture into a grayscale image. """ for pixel in img: x, y, col = pixel r, g, b = col # Use the shade of gray that has the same brightness as the pixel's # original color. brightness = (r + g + b) // 3 gray = create_color(brightness, brightness, brightness) set_color(img, x, y, gray) def negative(img): """ Creates a negative image by changing red, green and blue components to their opposite """ for pixel in img: x, y, col = pixel r, g, b = col rv = 255 - r gv = 255 - g bv = 255 - b col = create_color (rv, gv, bv) set_color (img, x, y, col) def weighted_grayscale(img): """ Makes image grayscaled but takes human eye perception into account """ for pixel in img: x, y, col = pixel r, g, b = col brightness = ( (r * 0.299) + (g * 0.587) + (b * 0.114) ) gray = create_color (brightness, brightness, brightness) set_color(img, x, y, gray)
true
6c9b88af44819e0a10b0f3dd0591d48d926d6490
smilereptile/python
/udemy/hello_you.py
486
4.375
4
# Ask user for name name = input("Your name?: ") print(type(name)) # Ask user for age age = input("Your age?: ") print(type(age)) # Ask user for city city = input("Your city?: ") print(type(city)) # Ask user what they enjoy love = input("What do you love doing?: ") print(type(love)) # Create output text string = """Your name is {} and you are {} years old. You live in {} and you just love {}""" output = string.format(name,age,city,love) # Print output to screen print(output)
false
3235095d845c0fda88c1f3821605f8db09f7b0bf
noueilaty/digitalcrafts
/week1/day3/temperature_converter.py
914
4.4375
4
# Ask the user the temperature in Celcius # temp_celcius = raw_input("Enter temperature in celcius > ") # # print("You entered {}".format(temp_celcius)) # # # To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32. # temp_to_farenheit = (int(temp_celcius) * 1.8 + 32) # # print("{0} degrees Celcius converted to Farenheit is {1} degrees".format(temp_celcius, temp_to_farenheit)) ############################ # def convert_celcius_to_farenheit(celcius): # farenheit = celcius * 1.8 + 32 # print("You entered {} degrees celcius.".format(celcius)) # print("{0} degrees Celcius is {1} degrees Farenheit.".format(celcius, farenheit)) import temperature_helper as t celcius = int(raw_input("Enter temperature in celcius > ")) t.convert_celcius_to_farenheit(celcius) # convert_celcius_to_farenheit(celcius) # modules - Separating code into files for resuability.
true
721e655a099f46f2a22d6aab51dbcf02e411b61b
noueilaty/digitalcrafts
/week1/day4/Largest Number.py
305
4.40625
4
# Given an list of numbers, print the largest of the numbers. numbers = [1, 2, 3, 5, 6, 11, 1, 4] def find_largest_number(nums): largest_number = 0 for num in nums: if num > largest_number: largest_number = num return largest_number print(find_largest_number(numbers))
true
ef5bb006214f01281433964ecdd26cc63c7dfc6d
noueilaty/digitalcrafts
/week1/day3/prime_calculator.py
446
4.15625
4
input_num = input("Enter a number to check if it's prime or not > ") def isPrime(num): # If the number is divisible by ONLY 'itself AND 1', it's a prime number. Otherwise, it's not a prime number. captured_numbers = [] for p in range(2, num + 1): for i in range(2, p): if p % i == 0: break else: captured_numbers.append(p) print(captured_numbers) isPrime(int(input_num))
true
815e1396f72073c4b3d7c8710811fc213020bbfe
noueilaty/digitalcrafts
/week2/day1/Assignments/Assignment 1 - Objects and Classes.py
2,561
4.40625
4
print('----------------------------') # Basics class Person(object): def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone self.friends = [] self.greeting_count = 0 self.people_greeted = [] def greet(self, other_person): print('Hello {0}, I am {1}'.format(other_person.name, self.name)) self.greeting_count += 1 # If the person being greeted is not in the people_greeted list, then add them. if other_person not in self.people_greeted: self.people_greeted.append(other_person) def print_contact_info(self): print('{0}\'s email: {1}, {0}\'s phone number: {2}'.format(self.name, self.email, self.phone)) def add_friend(self, friend): self.friends.append(friend) def num_friends(self): friends = 0 for friend in self.friends: friends += 1 print(friends) def __repr__(self): print(self.name, self.email, self.phone) def num_unique_people_greeted(self): print("{0} has greeted {1} people.".format(self.name, len(self.people_greeted))) sonny = Person("Sonny", "sonny@hotmail.com", "483-385-4948") jordan = Person("Jordan", "jordan@aol.com", "495-586-4356") Person.greet(sonny, jordan) Person.greet(jordan, sonny) print(sonny.email, sonny.phone) print(jordan.email, jordan.phone) print('----------------------------') # Make your own class: class Vehicle(object): def __init__(self, make, model, year): self.make = make self.model = model self.year = year def print_info(self): print('{0} {1} {2}'.format(self.make, self.model, self.year)) car = Vehicle('Nissan', 'Leaf', 2015) print(car.make, car.model, car.year) # Add a method # Add a a print_info() method to the Vehicle class. It will print out the vehicle's information. car.print_info() # Add a method 2: # Go back to the person class. Add a print_contact_info method to the Person class that will print out the contact info for an object instance of Person. sonny.print_contact_info() # Add an instance variable (attribute) jordan.friends.append(sonny) sonny.friends.append(jordan) # add an add_friend method: # added to line 16-17 jordan.add_friend(sonny) # Add a num_friends method: jordan.num_friends() # Count number of greetings: print(sonny.greeting_count) sonny.greet(jordan) sonny.greet(jordan) print(sonny.greeting_count) # __repr__ jordan # Bonus Challenge: sonny.num_unique_people_greeted() jordan.num_unique_people_greeted()
true
9c7c863944004af7ed19a6a68d8545173a473d06
NirajNair/Foobar-Challenge
/fuel-injection-perfection.py
2,316
4.21875
4
""" Fuel Injection Perfection ========================= Commander Lambda has asked for your help to refine the automatic quantum antimatter fuel injection system for her LAMBCHOP doomsday device. It's a great chance for you to get a closer look at the LAMBCHOP - and maybe sneak in a bit of sabotage while you're at it - so you took the job gladly. Quantum antimatter fuel comes in small pellets, which is convenient since the many moving parts of the LAMBCHOP each need to be fed fuel one pellet at a time. However, minions dump pellets in bulk into the fuel intake. You need to figure out the most efficient way to sort and shift the pellets down to a single pellet at a time. The fuel control mechanisms have three operations: 1) Add one fuel pellet 2) Remove one fuel pellet 3) Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets) Write a function called solution(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits. For example: solution(4) returns 2: 4 -> 2 -> 1 solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1 Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here. -- Python cases -- Input: solution.solution('15') Output: 5 Input: solution.solution('4') Output: 2 """ import math def solution(n): n=int(n) print(efficientPath(n)) def efficientPath(n): res = 0 while(n!=1): if isPowerOfTwo(n) != 0: power = int(isPowerOfTwo(n)) res += power return res elif(n%2==0): n=n/2 elif ((n+1)/2) % 2 == 1: n-=1 else: n+=1 res+=1 return res def Log(x): if x == 0: return False; return (math.log10(x) / math.log10(2)); def isPowerOfTwo(n): if math.ceil(Log(n)) == math.floor(Log(n)): return math.ceil(Log(n)) else: return 0 solution(63)
true
dc4d6666bdc4a3349a6006f6bc28091127c89f7d
annasedlar/python_practice
/dictionaries.py
2,157
4.5
4
# Dictionary Exercises # Exercise 1 # Given the following dictionary, representing a mapping from names to phone numbers: # phonebook_dict = { # 'Alice': '703-493-1834', # 'Bob': '857-384-1234', # 'Elizabeth': '484-584-2923' # } # Write code to do the following: # Print Elizabeth's phone number. # Add a entry to the dictionary: Kareem's number is 938-489-1234. # Delete Alice's phone entry. # Change Bob's phone number to '968-345-2345'. # Print all the phone entries. # In this exercise, are you using dynamic keys or fixed keys? # Exercise 2: Nested Dictionaries # ramit = { # 'name': 'Ramit', # 'email': 'ramit@gmail.com', # 'interests': ['movies', 'tennis'], # 'friends': [ # { # 'name': 'Jasmine', # 'email': 'jasmine@yahoo.com', # 'interests': ['photography', 'tennis'] # }, # { # 'name': 'Jan', # 'email': 'jan@hotmail.com', # 'interests': ['movies', 'tv'] # } # ] # } # Write a python expression that gets the email address of Ramit. # Write a python expression that gets the first of Ramit's interests. # Write a python expression that gets the email address of Jasmine. # Write a python expression that gets the second of Jan's two interests. # In this exercise, are you using dynamic keys or fixed keys? # Letter Summary # Write a letter_histogram function that takes a word as its input, and returns a dictionary containing the tally of how many times each letter in the alphabet was used in the word. For example: # >>> letter_histogram('banana') # {'a': 3, 'b': 1, 'n': 2} # In this exercise, are you using dynamic keys or fixed keys? # Word Summary # Write a word_histogram function that takes a paragraph of text as its input, and returns a dictionary containing the tally of how many times each letter in the alphabet was used in the text. For example: # >>> word_histogram('To be or not to be') # {'to': 2, 'be': 2, 'or': 1, 'not': 1} # In this exercise, are you using dynamic keys or fixed keys? # Bonus Challenge # Given a histogram tally (one returned from either letter_histogram or word_summary), print the top 3 words or letters.
true
3f21a8bbd80ebe99ddb0f0a448218f449421cfab
bhanuka1998/Data-Structures-and-Algorithms---APIIT
/buble_sort.py
486
4.125
4
def bubble_sort(current_list): for s in range(len(current_list)): for i in range(len(current_list) - 1): if current_list[i] > current_list[i+1]: current_list[i], current_list[i+1] = current_list[i+1], current_list[i] print(i) print(current_list) print("Sorted list is", current_list) list_1 = [1, 3, 4, 6, 5, 7, 8, 2, 10, 9] list_2 = [23, 22, 26, 28, 30, 24, 27, 21, 25, 29] bubble_sort(list_1) bubble_sort(list_2)
false
fc702e6abf85bcc419b2f49ca51a037be8f9a5fe
alvarohenriquecz/Curso-Python-Guanabara
/Mundo 3/Aula 04 - 19/Código 02 - Variáveis Compostas (Dicionários).py
548
4.15625
4
filme = {'titulo' : 'Star Wars', 'ano' : 1977, 'diretor' : 'George Lucas'} # Cria um dicionario "filme" com 3 chaves (keys) e 3 valores (values) print(filme.keys()) # exibe as chaves do dicionario "filme" print(filme.values()) # exibe os valores do dicionario "filme" print(filme.items()) # exibe os itens (chave + valor) do dicionario "filme" for k, v in filme.items(): # Para cada chave (k) e o valor (v) nos itens do dicionario "filme"... print(f'O {k} e {v}') # Exibe formatado a chave (k) atual o seu respectivo valor (v)
false
1896a787512d0b5ab1ba76ba0616ba530c71a99e
alvarohenriquecz/Curso-Python-Guanabara
/Mundo 2/Aula 01 - 12/Desafio 037.py
699
4.125
4
""" DESAFIO 037: Conversor de Bases Numericas Escreva um programa que leia u numero inteiro qualquer e peca para o usuario escolher a base de conversao: - 1 para Binario - 2 para Octal - 3 para Hexadecimal """ num = int(input('Digite um numero inteiro: ')) print('Para qual base voce deseja converter {}?'.format(num)) conv = int(input('Digite 1 para binario, 2 para octal ou 3 para hexadecimal: ')) if conv == 1: print('{} em binario e igual a {}'.format(num, bin(num))) elif conv == 2: print('{} em octal e igual a {}'.format(num, oct(num))) elif conv == 3: print('{} em hexadecimal e igual a {}'.format(num, hex(num))) else: print('Valor Invalido! Digite um numero de 1 a 3. ')
false
3cc18376701257806d32bca019311964b9683df6
alvarohenriquecz/Curso-Python-Guanabara
/Mundo 2/Aula 01 - 12/Desafio 039.py
1,341
4.25
4
""" Desafio 029: Alistamento Militar Faca um programa que leia o ano de nascimento de um jovem e informe de acordo com a sua idade , se ele ainda vai se alistar ao servico militar, se e a hora de e alistar, ou se ja passou do tempo do alistamento. Seu programa tambem devera mostrar o tempo que falta ou que passou do prazo. """ from datetime import date atual = date.today().year genero = str(input('Voce e homem ou mulher? Digite H para HOMEM e M para MULHER: ')).upper().strip() if genero == 'H': nas = int(input('Em que ano voce nasceu (ex: 1999)? ')) ani = str(input('Este ano voce ja fez aniversario? Digite S para SIM e N para NAO: ')).upper().strip() if ani == 'N' or ani == 'NAO' or ani == 'NÃO': idade = atual - nas - 1 else: idade = atual - nas print('Entao voce tem {} anos, correto?'.format(idade)) if idade == 18: print('Este ano voce deve se alistar no servico militar!') elif idade < 18: print('Ainda falta(m) {} ano(s) para voce se alistar no servico militar !'.format(18 - idade)) elif idade > 18: print('Ja passou {} ano(s) do tempo para voce se alistar no servico militar!'.format(idade -18)) elif genero == 'M': print('Como voce e mulher, nao precisara se alistar no servico militar!') else: print('Escolha invalida! Tente novamente.')
false
0a1b09b39e351d4a28f5d55ee54c27a15c1d7f48
alvarohenriquecz/Curso-Python-Guanabara
/Mundo 1/Aula 09/Desafio 022.py
668
4.28125
4
""" Desafio 022: Analisador de Textos Crie um programa que leia o nome completo de uma pessoa e mostre: > O nome com todas as letras maiusculas e minusculas. > Quantas letras ao todo (sem onsiderar os espacos). > Quantas letas tem o primeiro nome. """ nome = input('Digite seu nome completo: ') nome_sem_espacos = len(nome) - nome.count(' ') primeiro_nome = len(nome.split()[0]) print('\nNome em letras maiusculas: {}'.format(nome.upper())) print('Nome em letras minusculas: {}'.format(nome.lower())) print('Quantidade total de letras (sem contar os espacos): {}'.format(nome_sem_espacos)) print('Quantidade de letras do primeiro nome: {}'.format(primeiro_nome))
false
9e8c9561f9bef46d675f080d3106b909159e7d16
SamanehGhafouri/HackerRankProblemsSolved
/Sorting/bubble_sort.py
1,080
4.21875
4
# Given an array of integers, sort the array in ascending order using # the Bubble Sort algorithm above. Once sorted, print the following three lines: # 1. Array is sorted in numSwaps swaps., where numSwaps is the number of swaps that took place. # 2. First Element: firstElement, where firstElement is the first element in the sorted array. # 3. Last Element: lastElement, where lastElement is the last element in the sorted array. # Hint: To complete this challenge, you must add a variable that # keeps a running tally of all swaps that occur during execution. def countSwaps(a): sorted_a = False count_swaps = 0 while not sorted_a: sorted_a = True for i in range(len(a) - 1): if a[i] > a[i + 1]: sorted_a = False a[i], a[i + 1] = a[i + 1], a[i] count_swaps += 1 print(f"Array is sorted in {count_swaps} swaps.") print(f"First Element: {a[0]}") print(f"Last Element: {a[-1]}") if __name__ == '__main__': arr = [9, 2, 4, 1, 6, 33, 11, 88, 0, 5] print(countSwaps(arr))
true
b600cf9caf52a9786cf624e73cf6f6d7b646b6cd
SamanehGhafouri/HackerRankProblemsSolved
/mars_exploration.py
538
4.25
4
# Mars Exploration # A space explorer's ship crashed on Mars! They send a series of SOS messages to Earth for help. # Letters in some of the SOS messages are altered by cosmic radiation during transmission. # Given the signal received by Earth as a string,s , determine # how many letters of the SOS message have been changed by radiation. def mars_exploration(s): count = 0 for i in range(len(s)): if s[i] != "SOS"[i%3]: count += 1 return count s = input() result = mars_exploration(s) print(result)
true
d24c668e8abe7185c33553dbb8676148c4b2fe7f
judigunkel/Exercicios-Python
/Mundo 1/ex026.py
454
4.15625
4
""" 26 - Faça um programa que leia uma frase pelo teclado e mostre: Quantas vezes aparece a letra "A" Em que posição ela aparece pela primeira vez Em que posição ela aparece pela última vez """ frase = input('Digite uma frase: ').strip().upper() print(f'A letra A aparece {frase.count("A")} vezes.\n' f'A primeira letra A apareceu na posição {frase.find("A") + 1}\n' f'A última letra A apareceu na posição {frase.rfind("A") + 1}')
false
03f81dbd062e3e7694493e44db31f0ab76b4662c
judigunkel/Exercicios-Python
/Mundo 1/ex006.py
433
4.15625
4
""" Crie um algoritmo que leia um número e mostre seu dobro, triplo e raíz quadrada """ # importando a função sqrt (raíz quadrada) da biblioteca math from math import sqrt n = int(input('Digite um número inteiro: ')) print(f'O dobro de \033[35m{n}\033[m é \033[31m{n * 2}\033[m') print(f'O triplo de \033[35m{n}\033[m é \033[33m{n * 3}\033[m') print(f'A raíz quadrada de \033[35m{n}\033[m é \033[34m{sqrt(n):.1f}\033[m')
false
173cedb05736535715d8df75b5b06fa95558fed4
judigunkel/Exercicios-Python
/Mundo 1/ex008.py
496
4.34375
4
""" Escreva um programa que leia um valor em metros e o exiba convertido em cm e mm """ dist = float(input('Uma distância em metros: ')) print('\033[33m=*=\033[m'*11) print(f'A medida de {dist}m corresponde a:') print('\033[33m=*=\033[m'*11) print(f'\033[36m{dist/1000:.2f} km\033[m') print(f'\033[36m{dist/100:.2f} hm\033[m') print(f'\033[36m{dist/10:.2f} dam\033[m') print(f'\033[35m{dist*10:.2f} dm\033[m') print(f'\033[35m{dist*100:.2f} cm\033[m') print(f'\033[35m{dist*1000:.2f} mm\033[m')
false
b55958caf29fa3b2e6c8c5c2736d431946671f42
chmcphoy/LPTHW
/ex18.py
674
4.15625
4
def print_tre(arg1, arg2, arg3): print "arg1: %r, arg2: %r, arg3: %r" % (arg1, arg2, arg3) # This one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # That args* is actually pointless. We can just do this: def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) # Example of one argument def print_one(arg1): print "arg1: %r" % arg1 # No arguments def print_none(): print "Nothing here." # Assign values to arguments. print_tre("Three","Two", "Ett") print_two("Chuma","Mcphoy") print_two_again("Chuma","Mcphoy") print_one("Mezzi") print_none()
true
9023757a4d08351719a791a933929c435c0ddb96
ajitjha393/OSTL-FINAL
/q4.py
1,804
4.125
4
class Employee(object): #--Class Variable----# empcount = 0 def __init__(self,Id,dept,experience,salary): self.Id = Id self.dept = dept self.experience = experience self.salary = salary def setname(self,name): self.name = name def display(self): #-----C style format for printing ------# #-----Makes it more cleaner and cooler----# print('%-15s %-15s %-15s %-15s %-15s'%(self.name,self.Id,self.dept,self.experience,self.salary)) @classmethod def set_emp_count(cls): cls.empcount += 1 employee_list = [] def Insert_employee(): name,Id,dept,experience,salary = input('Enter the name,id,dept,experience,salary of Employee : ').split(',') employee_list.append(Employee(Id,dept,experience,salary)) Employee.set_emp_count() employee_list[-1].setname(name) #---- -1 means last element --------# def display_list_of_employees(): print('%-15s %-15s %-15s %-15s %-15s'%('NAME','ID','DEPARTMENT','EXPERIENCE','SALARY')) for i in range(len(employee_list)): employee_list[i].display() def display_avg_salary(): avg = 0 for emp in employee_list: avg = avg + int(emp.salary) print('Average salary => ',avg/Employee.empcount) while(True): print(''' 1. Insert an employee to the list 2. Display list of employees 3. Display total number of employees 4. Display Avg salary 5. Exit ''') choice = int(input('Enter a choice : ')) if(choice == 1): Insert_employee() elif(choice == 2): display_list_of_employees() elif(choice == 3): print('Total number of employees => ',Employee.empcount) elif(choice == 4): display_avg_salary() elif(choice == 5): break
true
a5c74c9e92d7aa4a382b1ea20950e5dc1685a7b6
zeeshanzahoor/DPinPython
/PString/SwapCases.py
351
4.15625
4
def SwapCases(str): swapped = "" for ch in str: if ch.islower(): swapped+=ch.upper() elif ch.isupper(): swapped+=ch.lower() else: swapped+=ch return swapped; if __name__ == "__main__" : input = input("Enter something : ") swapped = SwapCases(input) print(swapped)
false
2b82e4efc4bea865c5f056d4b0ba6084f76fd6d8
tarsir/corpus-tools
/scripts/split_by_seps.py
1,257
4.125
4
#!/usr/bin/python test_string = "Hello, what? How;never! egads you are here" separators = [',', ' ', '.', '?', '!', ';', '\n'] start = "<START_OF_SENT>" def divideBySeps(inp_string = test_string, sep_list = separators, include_seps = True): piece_list = [] cur_piece = "" for character in inp_string: if character in sep_list: if len(cur_piece) > 0: piece_list.append(cur_piece) if include_seps: piece_list.append(character) cur_piece = "" else: cur_piece += character piece_list.append(cur_piece) return piece_list def combineSeps(inp_list, sep_list = separators): pos = 0 final_list = [] cur_seps = "" while pos < len(inp_list): if inp_list[pos] in sep_list: while pos < len(inp_list) and inp_list[pos] in sep_list: cur_seps += inp_list[pos] pos += 1 final_list.append(cur_seps) cur_seps = "" else: final_list.append(inp_list[pos]) pos += 1 return final_list if __name__=="__main__": print divideBySeps() print combineSeps(divideBySeps()) print "".join(combineSeps(divideBySeps())[0:(2*3 -1)])
false
b7559d5a9b8428fb9baf30a3170a68adc0d629f7
SixingYan/algorithm
/278FirstBadVersion.py
1,660
4.125
4
""" You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. # The isBadVersion API is already defined for you. # @param version, an integer # @return a bool # def isBadVersion(version): """ """ Comments 不用递归,用循环 """ """ My """ class Solution(object): def firstBadVersion(self, n): """ :type n: int :rtype: int """ return self.fbv(1,n) def fbv(self, left, right): if not left < right: return left cent = int((left + right)/2) if isBadVersion(cent): return self.fbv(left, cent) else: return self.fbv(cent+1, right) """ Fast """ class Solution(object): def firstBadVersion(self, n): """ :type n: int :rtype: int """ start = 1 end = n checking = (end + start)/2 while (end != start): #停止条件是两者相等,和我一样 if isBadVersion(checking): end = checking else: start = checking + 1 checking = (end+start)/2 return start
true
a4b2595786c0bbb94c47720455dc444727ecf96f
SixingYan/algorithm
/007ReverseInteger.py
1,506
4.25
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ """ Comments """ """ My """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x == 0: return 0 if x < 0: x = self.change(-x) if -x < -1 * 2**31: res = 0 else: res = -x else: res = self.change(x) if res > 2 ** 31 - 1: res = 0 return res def change(self, x): nums = list(str(x)) nums.reverse() while nums[0] == '0': nums.pop(0) return int(''.join(str(p) for p in nums)) """ Fast """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ bsign = 1 if x < 0: bsign = -1 x = -x res = 0 maxv = 2 ** 31 while x != 0: res = res * 10 + x % 10 if res > maxv or (res == maxv and bsign == -1): return 0 x = x / 10 return bsign * res
true
6f5d4c9a833a193737ca5984dc4698b8e671ce8f
SixingYan/algorithm
/070ClimbingStairs.py
925
4.15625
4
""" You are climbing a stair case. It takes n steps to reach to the top. """ """ Comments """ """ My """ class Solution(object): def climbStairs(self, n): # 我自己的解法,递归,答案正确但是超时了 """ :type n: int :rtype: int """ return self.step(n) def step(self, n): if n == 1: # only left 1 return 1 elif n == 2: # only left 2 return 2 else: return self.step(n-1) + self.step(n-2) def func2(self, n): # 找到有规律的数列 a = [1,1] for i in range(n-1): a.append(a[i]+a[i+1]) return a[-1] """ Fast """ class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ res = [0, 1, 2] for i in range(3, n+1, 1): res.append(res[i-1] + res[i-2]) return res[n]
false
98fb1dd976d30c8372d63e81936d23c81f9acd89
gsudarshan1990/PythonSampleProjects
/Python/Functions2.py
1,477
4.40625
4
#Creating a Sample function for Salutation def print_hello(name): ''' This function prints the name :param name: name :return: no return type ''' print("Hello "+name) #Calling the function print_hello("sudarshan") #Creating a function with return value def add_two_numbers(num1,num2): return num1+num2 #Calling the function and storing the result value result=add_two_numbers(5,11) #Printing the result print(result) #Using the Help function to get information about the function help(print_hello) #Check whether the word 'Dog' is present in the string mystring='Dog is a pet animal' def dog_check(string): ''' Check whether word exists in a String :param string: a string is provided :return: Boolean ''' if 'Dog' in string: return True else: return False result=dog_check(mystring) print(result) #Above function is written in a simple way def dog_check(string): return 'Dog' in string print(dog_check(mystring)) #Example of Pig Latin """ if word starts with vowel, add 'ay' to end if word does not start with vowel, put first letter at the end,then add 'ay' Example: word->ordway apple->appleay """ def pig_latin(word): first_letter=word[0] list_vowels=['a','e','i','o','u'] presence_of_vowel=first_letter in list_vowels if presence_of_vowel: word=word+'ay' else: word=word[1:]+word[0]+'ay' print(word) pig_latin('word') pig_latin('apple')
true
e216ec685acce4f60cb39856f8f5132645887e8d
gsudarshan1990/PythonSampleProjects
/Python/Dictionary/DictionaryExample4.py
1,323
4.28125
4
""" Folow the steps bellow: -Create a new dictionary called prices using {} format like the example above. Put these values in your prices dictionary: "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 Loop through each key in prices. For each key, print out the key along with its price and stock information. Print the answer in the following format: apple price: 2 stock: 0 Let's determine how much money you would make if you sold all of your food. Create a variable called total and set it to zero. Loop through the prices dictionaries.For each key in prices, multiply the number in prices by the number in stock. Print that value into the console and then add it to total. Finally, outside your loop, print total. """ prices = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3} stock_list =[2,0,4,6] for keys in prices: if keys =='banana': print(keys+':'+str(prices[keys])) print('Stock:2') if keys == 'apple': print(keys + ':' + str(prices[keys])) print('Stock:0') if keys == 'orange': print(keys + ':' + str(prices[keys])) print('Stock:4') if keys == 'pear': print(keys + ':' + str(prices[keys])) print('Stock:6') total=0 for keys, i in zip(prices,range(0,len(stock_list))): total += prices[keys]*stock_list[i] print(total)
true
5aeea60551a2ddcc7c245d9a9029d05c81ebb092
gsudarshan1990/PythonSampleProjects
/Python/rangereverseorder.py
202
4.21875
4
#normal order for i in range(1,10): print(i) print("The above is normal order") for i in range(10,0,-1): print(i) print('The above is reverse order') for i in range(10,0,-2): print(i)
true
9c4ed71b91c9ab6ea87b2b1c975609dd39910c63
gsudarshan1990/PythonSampleProjects
/Python/Welcome.py
1,838
4.28125
4
#Print the statements print('Hello, my name is sudarshan and i am new to python i think i will be able to perform my projects in python very well') print('Good morning') #Assingement of variables with values fruit ='apple' fruit2='orange' #Printing the variables print (fruit) print(fruit2) #Double quotes inside the single quotes text1='she said, "That is a great tasting apple!"' print(text1) #Double quotes inside the single quotes text2='"How are you"' print(text2) #Single quotes inside the double quotes text3="That's is a great tasting apple" print(text3) #Double quotes using the escape sequence text4="She said that, \" It is a fantastic year\"" print(text4) #Single quotes using the escape sequence text5='she said that \'it is a fantastic year\'' print (text5) # Strings with indexes first_letter='apple'[0] print(first_letter) last_letter='apple'[4] print (last_letter) first_letter1=fruit[0] print(first_letter1) last_letter1=fruit[4] print(last_letter1) print(fruit[2]) # Length of the Strings- len() function fruit_len=len(fruit) print(fruit_len) print(len(fruit2)) print(len('strawberry')) #Object methods fruit3='grape' print(fruit3.upper()) #Object methods fruit4='PINEAPPLE' print(fruit4.lower()) print('I '+'like '+'python.') print('I'+'like'+'python') print('s'*10) first ='I' middle='like' last='python' sentence=first+' '+middle+' '+last print(sentence) year =1990 sentence='My name is sudarshan and i was born in the year ' print(sentence+str(year)) print('I {} python this is a {} string'.format('love', 'formatted' )) print('I {0} {1}. {1} {0}s me'.format('love', 'python')) first='I' middle='love' last='python' print(str(2)+' {} {} {}'.format(first,middle,last)) version=3 print (str(1)+'. I like python version '+str(version)) print('{}. I like python version {}'.format(2,version))
true
d627b2ef923d338d1420d02b254d80136a61d11e
gsudarshan1990/PythonSampleProjects
/PythonExercise2/ListComprehension2.py
316
4.65625
5
""" Use List Comprehension to create a list of the first letters of every word in the string below: str='Create a list of the first letters of every word in this string' """ str='Create a list of the first letters of every word in this string' mylist3=str.split() list4=[word[0] for word in mylist3] print(list4)
true
91af2175e934b6de0fc2cf239fdc42f6b3062c11
gsudarshan1990/PythonSampleProjects
/Tuples/Count_Number_Emails.py
1,314
4.21875
4
""" Exercise 1: Revise a previous program as follows: Read and parse the “From” lines and pull out the addresses from the line. Count the num- ber of messages from each person using a dictionary. After all the data has been read, print the person with the most commits by creating a list of (count, email) tuples from the dictionary. Then sort the list in reverse order and print out the person who has the most commits. Sample Line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Enter a file name: mbox-short.txt cwen@iupui.edu 5 Enter a file name: mbox.txt zqian@umich.edu 195 """ filename=input('Enter the file name') try: filehandle=open(filename) except IOError as argument: print(argument) if filename == '': print('According to argument empty file doesnot exist') else: print(f'According to argument {filename} file doesnot exist') exit() email_dictionary=dict() for line in filehandle: line=line.rstrip() words=line.split() if len(words)<3: continue if not line.startswith('From'): continue email_dictionary[words[1]]=email_dictionary.get(words[1],0)+1 print(email_dictionary) Flipped_list=list() for key,value in email_dictionary.items(): Flipped_list.append((value,key)) sorted_list=sorted(Flipped_list,reverse=True) print(sorted_list[0])
true
5ac96ee9c4f70fea4d9ac2b97d635aa202b24b39
Suu1314/Python
/data_structures/2_mutabilidad_y_alias.py
742
4.25
4
# -*- coding: utf-8 -*- # ------------- Mutacion y referencias ------------- c1 = 'Hola' c2 = c1 # Otra referencia a la cadena print (c1) print (c2) print (c2[1]) #c1[0] = 'B' # operacion no permitida #c1[0] = c2 # operacion no permitida c1 = 'Bola' # Nueva cadena creada # Al imprimir las cadenas, ya no son iguales, no apuntan a la misma información print (c1) print (c2) # ------------- Listas ------------- lista = ['H', 'o', 'l', 'a'] lista2 = lista # Otra referencia a la lista print (lista) lista[0] = 'B' lista2[0] = 'Y' # Al imprimir las listas, las dos referencias apuntan a la misma informacion print (lista) print (lista2) def mutarLista(lista): lista[3] = 'G' mutarLista(lista) print (lista)
false
b03bd9aa84beda12892548517c65ac8f45a4a99d
verisimilitude20201/dsa
/Stack_Queue_Bag/Queue/Array/circular_queue.py
2,474
4.25
4
""" Approach: -------- Using front and rear pointers we will treat an array as a circular array and wound back front and rear pointers whenever they get past the end of the array Main conditions 1. Enqueue a. front == rear == -1. Array is empty. Reassign both of them to 0 and insert element at rear. b. If 1.a is not true, Increment rear by (rear + 1) % length of array and reassign element at rear c. Check if (rear + 1) % length of array is equal to front. If yes, the array is full. 2. Dequeue: a. Check if front == rear. If so only one element is left and so get it, and set both front and rear to -1 before returning it. b. Access the data in array at front and set it to None. Increment front as (front + 1) % length of array. Return the data at front. c. Check if array is empty viz. front == rear == -1. Raise an exception if so. Complexity: ---------- Time: O(1) ~ O(N): We are traversing the array both ways front and rear. Since we ignore the constants, this has a linear time complexity. Space: O(N): Where N is the size of the queue. Advantages ---------- Helps to avoid wastage of space in queue. """ class CircularQueue: def __init__(self, initial_capacity=4): self._data = [None] * initial_capacity self._front = -1 self._rear = -1 def enqueue(self, element): if self.is_empty(): self._front = 0 self._rear = 0 self._data[self._rear] = element elif self.is_full(): raise Exception("Queue is full") else: self._rear = (self._rear + 1) % len(self._data) self._data[self._rear] = element def dequeue(self): if self._front == self._rear: data = self._data[self._front] self._front = self._rear = -1 return data elif self.is_empty(): raise Exception("Queue is empty") else: data = self._data[self._front] self._data[self._front] = None self._front = (self._front + 1) % len(self._data) return data def is_empty(self): return self._front == -1 and self._rear == -1 def is_full(self): return (self._rear + 1) % len(self._data) == self._front cq = CircularQueue() cq.enqueue(1) cq.print_queue() cq.enqueue(2) cq.print_queue() cq.enqueue(3) cq.print_queue() cq.enqueue(4) print(cq.dequeue()) print(cq.dequeue()) print(cq.dequeue()) print(cq.dequeue())
true
c00e41e217babd137298f53c3982809c7cc45013
jeremiahsoyebo/CIS-2348
/Homework_1/Coding_Problem_1.py
610
4.21875
4
print('Enter the current date by month, day, and year\n' 'Month: ') currentMonth = int(input()) print('Day:') currentDay = int(input()) print('Year:') currentYear = int(input()) print('Enter your birthday by month, day, and year\n' 'Month: ') birthdayMonth = int(input()) print('Day:') birthdayDay = int(input()) print('Year:') birthdayYear = int(input()) userAge = currentYear - birthdayYear - ((currentMonth, currentDay) < (birthdayMonth, birthdayDay)) print('You are', userAge, 'years old.') if (currentMonth == birthdayMonth) and (currentDay == birthdayDay): print('Happy Birthday!')
false
a32b8d5ff9d8d449cebb93762e9529753bd9db2e
BedirT/Python-Class-2019
/AFTER CLASS/L7 - Lists&Tuples in Python-Part 2.py
1,317
4.5
4
""" Lecture 7: Lists & Tuples Part 2 Momentum Learning Introduction to Python M. Bedir Tapkan """ # Prepending or Appending Items to a List ls = ['a', 'b', 'c'] ls += ['d', 'f'] print(ls) ls = ['a', 'b', 'c'] ls = ['d', 'f'] + ls print(ls) # You can't append one item, you have to append a list # ls += 20 # Wrong ls += [20] print(ls) # Methods That Modify a List # append # ls.append(<obj>) ls = [1, 2, 3] ls.append(4) print(ls) # We also can append a list ls.append([5, 6]) print(ls) # extend # ls.extend(<obj>) ls = [1, 2, 3] ls.extend([5, 6]) print(ls) # insert # ls.insert(<index>, <obj>) ls = [1, 2, 3] ls.insert(1, 4) print(ls) # remove ls = [1, 2, 3] ls.remove(2) print(ls) # pop(index=-1) ls = [1, 2, 3] print(ls.pop()) print(ls) ls = [1, 2, 3, 2, 5] ls.pop(1) print(ls) # Lists are dynamic. ls = [1, 2, 3, 2, 5] ls[3] = 4 print(ls) ls.remove(2) print(ls) # Python Tuples t = ('a', 'b', 'c') print(t) print(type(t)) print(t[0]) print(t[0:2]) print(t[::-1]) # Unlike lists tuples are immutable # t[0] = 'd' t = (2) print(t) print(type(t)) t = (2,) print(type(t)) # Tuple Assignment, Packing, and Unpacking t = (1, 2, 3) print(type(t)) t = 1, 2, 3 print(type(t)) t = 1, print(type(t)) t = 1, 2, 3, 4 print(t) print(type(t)) one, two, three, four = t print(one) # one, two, three = t print(type(one))
false
48e5689467c29791160656c43a5237c4140ceffe
BedirT/Python-Class-2019
/PREP/L3 - Variables in Python.py
452
4.15625
4
""" Lecture 3: Variables in Python Momentum Learning Introduction to Python M. Bedir Tapkan """ # Variable Assignement # n = 300 # Chained Var Assignment # a = b = c = 200 # Variable Types in Python # Object References # Multi References # Object Identity # id(n) # Variable Names # name = "Bob" # Age = 54 # has_W2 = True # print(name, Age, has_W2) # 1099_filed = False # Camel Case, Pascal Case, Snake Case # Reserved Words (Keywords) # 33 # for = 3
true
263420783b127b05df6042adc69b84d381be22f9
ja32776/Election_Analysis
/Python_practice.py
2,866
4.3125
4
counties = ["Arapahoe", "Denver", "Jefferson"] if counties[1]=='Denver': print(counties[1]) counties =["Arapahoe", "Denver", "Jefferson"] if "El Paso" in counties: print("El Paso is in the lsit of counties.") else: print("El Paso is not the list of counties.") counties = ["Arapahoe", "Denver", "Jefferson"] if "El Paso" in counties: print("El Paso is in the list of counties.") else: print("El Paso is not the list of counties.") if "Arapahoe" in counties and "El Paso" in counties: print("Arapahoe and El Paso are in the list of counties.") else: print("Arapahoe or El Paso is not in the list of counties.") if"Arapahoe" in counties or "El Paso" in counties: print("Arapahoe or El Paso is in the list of counties.") else: print("Arapahoe and El Paso are not in the list of counties.") if "Arapahoe" in counties and "El Paso" not in counties: print("Only Arapahoe is in the list of counties.") else: print("Arapahoe is in the list of counties and El Paso is not in the list of counties. ") for county in counties: print(county) x=range(4) for n in x: print(n) counties_dict = {"Arapahoe":422829, "Denver":463353, "Jefferson":432438} for county in counties_dict: print(county) for county in counties_dict.keys(): print(county) for voters in counties_dict.values(): print(voters) for county in counties_dict: print(counties_dict[county]) for county in counties_dict: print(counties_dict.get(county)) counties_dict = {"Arapahoe":369237, "Denver":413229, "Jefferson":390222} for county, voters in counties_dict.items(): print(county + " county has " + str(voters)+" registered voters.") for county, voters in counties_dict.items(): print(f"{county} county has {voters} registered voters.") candidate_votes=int(input("How many votes did the candidate get in the election?")) total_votes=int(input("What is the total number of votes in the election?")) message_to_candidate = ( f"You received {candidate_votes} number of votes." f"The total number of votes in the election was {total_votes}." f"You received {candidate_votes/total_votes * 100}% of the total votes." ) print(message_to_candidate) candidate_votes=int(input("How many votes did the candidate get in the election?")) total_votes=int(input("What is the total number of votes in the election?")) message_to_candidate = ( f"You received {candidate_votes:,} number of votes." f"The total number of votes in the election was {total_votes:,}." f"You received {candidate_votes/total_votes * 100:.2f}% of the total votes." ) print(message_to_candidate) #Import the datetime class from the datetime module. import datetime #Use the now() attribute on the datetime class to get the present time. now= datetime.datetime.now() #Print the present time. print("The time right now is", now)
false
b97fb55c9e858b6be9d87efe2863beb02aa8888c
babeal/udacity-ai-intro-course
/scripts/q_generate_messages.py
1,060
4.34375
4
names = input("Enter names separated by commas: ").split(",") assignments = input("Enter assignment counts separated by commas: ").split(",") grades = input("Enter grades separated by commas: ").split(",") data = zip(names, assignments, grades) # message string to be used for each student # HINT: use .format() with this string in your for loop message = "Hi {},\n\nThis is a reminder that you have {} assignments left to \ submit before you can graduate. You're current grade is {} and can increase \ to {} if you submit all assignments before the due date.\n\n" # write a for loop that iterates through each set of names, assignments, and grades to print each student's message for item in data: #print(item) print(message.format(item[0], item[1], item[2], int(item[2]) + 2*int(item[1]))) # the solution is much more elegant than mine, since it destructures the tuple in the for statement. # for name, assignment, grade in zip(names, assignments, grades): # print(message.format(name, assignment, grade, int(grade) + int(assignment)*2))
true
fcb7c9255a8eff6d8da6f89043bb60d8b3564a8b
alinanananana/-
/lab2-2.py
809
4.4375
4
# Целые числа и числа с плавающей точкой являются одними из самых распространенных в языке Python number = 9 print(type(number)) # Вывод типа переменной number float_number = 9.0 # Создайте ещё несколько переменных разных типов и осуществите вывод их типов # Существует множество функций, позволяющих изменять тип переменных. # Изучите такие функции как int(), float(), str() и последовательно примените их к переменным, созданным ранее. integer_number = int(float_number) print(integer_number)
false
d9f52fc6d56a08cfd312183d82fbff255549c8fd
GhillieDhu/ProjectEuler
/Euler0022/names_scores.py
1,228
4.15625
4
from typing import List from itertools import count def read_names() -> List[str]: import os.path scriptpath = os.path.dirname(__file__) name_file_path = os.path.join(scriptpath, 'p022_names.txt') with open(name_file_path) as name_file: names: str = name_file.read() ns: List[str] = [n.replace('"', '') for n in names.split(',')] return sorted(ns) def numerate(string): return sum([ord(s) - 64 for s in string]) if __name__ == '__main__': ''' Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 * 53 = 49714. What is the total of all the name scores in the file? ''' names = read_names() numerals = [numerate(name) for name in names] print(sum(n * c for n, c in zip(numerals, count(1))))
true
d9e2b7d461db2a6c7d460de8d628d27f78b1ccb3
jwndlng/sec-themed-stuff
/algorithms/graph/bfs.py
1,391
4.34375
4
""" This is a sample implementation of Breadth First Search (BFS) - For the graph we will be using an adjaceny list - We will just walk through a mark the nodes as visited """ import secrets from queue import Queue # Nodes in graph n = 13 # adjaceny list adl = {} adl[0] = [1, 9] adl[1] = [0, 8] adl[2] = [3, 12] adl[3] = [2, 4, 5, 7] adl[4] = [3] adl[5] = [3, 6] adl[6] = [5, 7] adl[7] = [3, 6, 8, 10, 11] adl[8] = [1, 7, 9] adl[9] = [0, 8] adl[10] = [7, 11] adl[11] = [7, 10] adl[12] = [2] def shortest_path(s, e): """ The function will return the shortest path between two nodes """ path = bfs(s) next = path[e] shortest_path = [e, next] while next != s: next = path[next] if next is None: return [] shortest_path.append(next) shortest_path.reverse() return shortest_path def bfs(s): visited = [False for i in range(0, n)] path = [None for i in range(0, n)] q = Queue() q.put(s) visited[s] = True while not q.empty(): next = q.get() for neighbor in adl[next]: if not visited[neighbor]: visited[neighbor] = True path[neighbor] = next q.put(neighbor) return path def main(): print(f"Starting BFS with Node 0") path = shortest_path(0, 12) print(path) if __name__ == "__main__": main()
true
a5d35a8fcbef15ecca1e8b389a16ebe6f13b9759
Sabryfattah/Python
/MISC/c.py
1,046
4.4375
4
""" Scientific Calculator Enter equation in normal way to get result: e.g.: pi * sin 90 - sqrt 81 Functions available: + (addition), - (subtraction), * (multiplication) / (division), % (percentage), sine (sin(rad)), cosine (cos(rad)), tangent (tan(rad)), sqrt(n) (square root), pi (3.141) """ import math import re import argparse import sys class Calc: def __init__(self): self.parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__, usage="calc [string of equation]") self.parser.add_argument('string', nargs='+', help="string of equation") self.args=self.parser.parse_args() def calc(self, k): np = [] for op in k: if op[0].isalpha(): np.append("math.{}".format(op)) else: np.append("{}".format(op)) s = " ".join(np) s = re.sub(r' (\d+)', r'(\1)', s) s = re.sub(r'\^', r'**', s) print(s) k = eval(s) return k #====================================================== if __name__ == "__main__": c = Calc() k = c.args.string print(c.calc(k))
false
6be1d6a2bae08f80c189aeee67a348090a47d087
Amangondaliya555/PyAtbash
/AtBash.py
749
4.125
4
decrypted_msg = [] alphabet = "abcdefghijklmnopqrstuvwxyz" tebahpla = "zyxwvutsrqponmlkjihgfedcba" print('<---Please select one of the options given below--->\n') Value = int(input('1 : Encryption\n2 : Decryption\n-->')) if (Value == 1): message = input("Please Enter Your MESSAGE (Plain Text) : ") message = message.lower() word1 = message.translate({ord(x): y for (x, y) in zip(tebahpla, alphabet)}) print("Encrypted Message : ", word1) elif Value == 2: message = input("Please Enter Your MESSAGE (Cipher Text) : ") message = message.lower() word2 = message.translate({ord(x): y for (x, y) in zip(alphabet, tebahpla)}) print("Decrypted Message : ", word2) else: print('Please Select the valid Option')
false
5fc5e6660ac1f2c1173e8eefe33ff729fd574590
SaulBurgos/saulburgos.github.io
/practices/2020/python/OOP/inheritance.py
1,132
4.1875
4
# super class, python call in that way to the parents classes class Rectangulo: def __init__(self, base, altura): self.base = base self.altura = altura def area(self): return self.base * self.altura # you inherit passing the super class class Cuadrado(Rectangulo): def __init__(self, lado): # get the reference to the super class super().__init__(lado, lado) # polimorfismo es modificar un comportamiento en herencia class Persona: def __init__(self, nombre): self.nombre = nombre def avanza(self): print('Ando caminando') class Ciclista(Persona): def __init__(self, nombre): super().__init__(nombre) # you can overwrite method that were in inherit def avanza(self): print('Ando moviendome en mi bicicleta') def main(): rectangulo = Rectangulo(base=3, altura=4) print(rectangulo.area()) cuadrado = Cuadrado(lado=5) print(cuadrado.area()) persona = Persona('David') persona.avanza() ciclista = Ciclista('Daniel') ciclista.avanza() if __name__ == '__main__': main()
false
700c71ca859a7e4477bd41eb045e909e8997008d
wuyongqiang2017/AllCode
/day29/隐藏.py
1,067
4.34375
4
# class A: # __N=0 #类的数据属性就应该是共享的,但是语法上是可以把类的数据属性设置成私有的如__N,会变形成_A__N # def __init__(self): # self.__X=10 #变形为self._A__X # def __foo(self):#变形为_A__foo # print("from A") # def bar(self): # self.__foo()#只有在类内部才可以通过__foo的形式访问到 # # a = A() # # print(a.__dict__)#{'_A__X': 10} # # print(A.__dict__)#可以查看属性名有没有被改为_*__*的形式 # print(a._A__N) # print(a._A__X) # a._A__foo() # a.bar() # #正常情况 # class A: # def fa(self): # print("from A") # def test(self): # self.fa()#b.fa # class B(A): # def fa(self): # print("from B") # b = B() # b.test()#from B # #把fa定义成私有的,即__fa # class A: # def __fa(self): #_A__fa # print("from A") # def test(self): # self.__fa() #_A__fa # class B(A): # def __fa(self): # print("from B") # b = B() # print(b.__dict__) # print(b._B__fa()) # b.test()#from A
false
16fac806538d415fe5b4d3c56b1f079e08c9973c
bsdcfp/leetcode
/two_pointers/88_merge_sorted_array.py
997
4.25
4
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # # Note: # # The number of elements initialized in nums1 and nums2 are m and n respectively. # You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. # Example: # # Input: # nums1 = [1,2,3,0,0,0], m = 3 # nums2 = [2,5,6], n = 3 # # Output: [1,2,2,3,5,6] class Solution: def merge(self, nums1: list, m: int, nums2: list, n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ lo = m-1 hi = m+n-1 ano = n-1 while ano >= 0: if lo < 0: nums1[hi] = nums2[ano] hi -= 1 ano -= 1 continue if nums2[ano] >= nums1[lo]: nums1[hi] = nums2[ano] hi -= 1 ano -= 1 else: nums1[hi] = nums1[lo] lo -= 1 hi -= 1 print(nums1) s = Solution() s.merge([1,2,3,0,0,0], 3, [2,5,6], 3)
true
8b90545b98d8f06d2810b39f4472babf06f86fce
jaecheolkim99/CodingPlayground
/LeetCode/Merge Sorted Array.py
2,065
4.1875
4
""" https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/580/week-2-january-8th-january-14th/3600/ [BEST] class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ ### i is pointer of nums1 and j is pointer of nums2 ### i, j = 0, 0 nums1_copy = nums1[:] nums1[:] = [] ### add the smallest one in num2 or num1_copy into nums1 ### while i<m and j<n: if nums1_copy[i] < nums2[j]: nums1.append(nums1_copy[i]) i += 1 else: nums1.append(nums2[j]) j += 1 ### if there are still elements to add ### while i < m: nums1.append(nums1_copy[i]) i+=1 while j < n: nums1.append(nums2[j]) j += 1 """ class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ i = 0 j = 0 origin = m + n while i + j < m + n: if i == m: while len(nums1) != i: nums1.pop() nums1.append(nums2[j]) j += 1 i += 1 m += 1 elif j == n: i += 1 elif nums1[i] > nums2[j]: nums1.insert(i, nums2[j]) j += 1 i += 1 m += 1 else: i += 1 while len(nums1) != origin: nums1.pop() return nums1 if __name__ == "__main__": s = Solution() print(s.merge([1,2,3,0,0,0], 3, [2,5,6], 3)) print(s.merge([2,0], 1, [1], 1))
false
2616bcab3ca03b869d0cb7a7001f722837856aac
vargas88hugo/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
685
4.5625
5
#!/usr/bin/python3 """ This module provides a print_square function The function works by printing a square """ def print_square(size): """ This is a function that prints a square Args param1 (size): size of the square Raise: TypeError: size must be an integer ValueError: size must be greater than zero """ if not isinstance(size, int): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") if size == 0: return for i in range(size): k = 0 for j in range(size): print("#", end="") if k != size - 1: print()
true
921f28da8b5be611291e17fef9e41226a1cb8f9f
vargas88hugo/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,343
4.34375
4
#!/usr/bin/python3 """ This module provides a matrix_divided function Basically it is a function for divide that divides a matrix """ def matrix_divided(matrix, div): """ This is a function for divide the elements of a matrix Args: param1 (matrix): list of lists of integers or floats param2 (div): integer number for divide Raises: TypeError: the elements of the matrix must be a integer or float TypeError: Each row of the matrix must have the same size TypeError: div must be a integer or float number ZeroDivisionError: div can't equal to zero Returns: A new divided matrix """ str1 = "matrix must be a matrix (list of lists) of integers/floats" for row in matrix: for col in row: if not isinstance(col, (int, float)): raise TypeError(str1) else: col = int(col) n = len(matrix[0]) for row in matrix: if len(row) != n: raise TypeError("Each row of the matrix must have the same size") if not isinstance(div, (int, float)): raise TypeError("div must be a number") if div == 0: raise ZeroDivisionError("division by zero") a = matrix[:] a = list(map(lambda x: list(map(lambda y: round(y / div, 2), x)), matrix)) return a
true
3f124a32a2ed984d693a494155073835343d8b25
ksdivesh/python-bone
/oop-class.py
1,106
4.5625
5
#python object oriented programming #A class is blueprint for creating instances. We have multiple instances of a class. #Class contains members and methods. #Instance variable contain data that has unique instance. class Employee: #constructor def __init__(self, first, last, email, pay): #self recieves the instance at the first argument automatically self.first = first self.last = last self.pay = pay self.email = email def fullname(self): return '{} {}'.format(self.first, self.last) # emp1 = Employee() # emp2 = Employee() # the way below is the manual assignment # emp1.first = 'John' # emp1.last = 'Doe' # emp1.email = 'johndoe@mail.com' # emp1.pay = 1000 # # emp2.first = 'Naman' # emp2.last = 'Kumar' # emp2.email = 'naman@gmail.com' # emp2.pay = 2000 # print(emp1.first) # print(emp2.last) #when we create the instance then, init method will be called automatically, emp1 will passed in as self and then it will set all of these attributes emp1 = Employee('Divesh', 'Kumar', 'diveshkrsharma@gmail.com', 1000) # print(emp1.fullname()) print(Employee.fullname(emp1))
true
edecc5e273d3308fe1bca8a5b167625ef17df1dc
jpconnors/Codeacademy
/format_function.py
1,443
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 19 19:59:12 2020 @author: JP """ def poem_title_card(poet, title): poem_desc = "The poem \"{}\" is written by {}.".format(title, poet) return poem_desc def poem_description(publishing_date, author, title, original_work): poem_desc = "The poem {title} by {author} was originally published in {original_work} in {publishing_date}.".format(publishing_date = publishing_date, author = author, title = title, original_work = original_work) return poem_desc author = "Shel Silverstein" title = "My Beard" original_work = "Where the Sidewalk Ends" publishing_date = "1974" my_beard_description = poem_description(publishing_date, author, title, original_work) print(my_beard_description) ''' Over this lesson you’ve learned: .upper(), .title(), and .lower() adjust the casing of your string. .split() takes a string and creates a list of substrings. .join() takes a list of strings and creates a string. .strip() cleans off whitespace, or other noise from the beginning and end of a string. .replace() replaces all instances of a character/string in a string with another character/string. .find() searches a string for a character/string and returns the index value that character/string is found at. .format() and f-strings allow you to interpolate a string with variables. Well I’ve been stringing you along for long enough, let’s get some more practice in! '''
true
4c9d8b17288c947e0cb5c63773161d2c69443a48
jpconnors/Codeacademy
/classes_constructors.py
327
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 27 16:51:10 2020 @author: JP """ #Classes and Constructors class Circle: pi = 3.14 # Add constructor here: def __init__(self, diameter): print("New circle with diameter: {diameter}".format(diameter=diameter)) teaching_table = Circle(36)
true
8fe35cb6662e912b49dd7ea26cfabc7efcfdad85
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/david_russo/lesson3/slicing_lab.py
2,501
4.34375
4
#!/usr/bin/env python # set up test strings and test tuples a_string = "this is a string" a_longer_string = "I met a traveller from an antique land Who said: Two vast and trunkless legs of stone" a_tuple = (2, 54, 13, 12, 5, 32) a_longer_tuple = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71) # 1) Write a function that exchanges the first and last items in a sequence def exchange_first_and_last(seq): if type(seq) == str: print(seq[-1]+seq[1:]+seq[0]) if type(seq) == tuple: new_seq = [] for i in range(0, len(seq)): if i == 0: new_seq.append(seq[-1]) elif i == len(new_seq) - 1: new_seq.append(seq[0]) else: new_seq.append(seq[i]) print(new_seq) exchange_first_and_last(a_string) exchange_first_and_last(a_longer_string) exchange_first_and_last(a_tuple) exchange_first_and_last(a_longer_tuple) # 2) Write a function that removes every other item from the sequence def omit_every_other(seq): if type(seq) == str: new_seq = "" for i in range(0, len(seq)): if i % 2 == 0: new_seq += seq[i] print(new_seq) if type(seq) == tuple: new_seq = [] for i in range(0, len(seq)): if i % 2 == 0: new_seq.append(seq[i]) print(new_seq) omit_every_other(a_string) omit_every_other(a_longer_string) omit_every_other(a_tuple) omit_every_other(a_longer_tuple) # 3) Write a function that removes the first and last 4 elements of a sequence, # and returns every other element in between def trim_four_either_side_return_every_other(seq): relevant_seq = seq[4:-4:2] print(relevant_seq) trim_four_either_side_return_every_other(a_longer_string) trim_four_either_side_return_every_other(a_longer_tuple) # 4) Write a function that reverses the elements of the sequence with just slicing def reverse_elements(seq): print(seq[::-1]) reverse_elements(a_string) reverse_elements(a_longer_string) reverse_elements(a_tuple) reverse_elements(a_longer_tuple) # 5) Write a function that orders list as the middle third, last third, and first third of the list def order_middle_last_first(seq): if(type(seq) == str): print(seq[round(len(seq)/3):2*round(len(seq)/3)] + seq[2*round(len(seq)/3):] + seq[:round(len(seq)/3)]) if(type(seq) == tuple): new_seq = seq[round(len(seq)/3):2*round(len(seq)/3)] + seq[2*round(len(seq)/3):] + seq[:round(len(seq)/3)] print(new_seq) order_middle_last_first(a_string) order_middle_last_first(a_longer_string) order_middle_last_first(a_tuple) order_middle_last_first(a_longer_tuple)
false
bbf9c1731b448c624424883cd3b74c5f32f52055
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/Aron/Module_3/Lists.py
2,581
4.1875
4
# Lists #Series 1 # Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches” fruit=["Apples", "Pears", "Oranges", "Peaches"] # Display the list (plain old print() is fine…) print(fruit) #Ask the user for another fruit and add it to the end of the list response = input("What fruit should we add: ") fruit.append(response) # Display the list print(fruit) # Ask the user for a number and display the number back to the user and the fruit corresponding to that number (on a 1-is-first basis). Remember that Python uses zero-based indexing, so you will need to correct. response_number = input("What number of the index should we grab?: ") fruit[(n-1):n] #fruit.pop(n-1) # Add another fruit to the beginning of the list using “+” and display the list fruit2 = ["Lemon"] + fruit print(fruit2) # Add another fruit to the beginning of the list using insert() and display the list fruit.insert(0,"Lime") print(fruit) #Display all the fruits that begin with “P”, using a for loop for list in fruit: if "P" in list: print(list) #Series 2 # Display the list print(fruit) #Remove the last fruit from the list fruit.pop(-1) #Display the list print(fruit) #Ask the user for a fruit to delete, find it and delete it. #(Bonus: Multiply the list times two. Keep asking until a match is found. Once found, delete all occurrences.) rmfruit = input("What fruit should we remove: ") #Series3 #Ask the user for input displaying a line like “Do you like apples?” for each fruit in the list (making the fruit all lowercase). for fruit in fruits: result = input("Do you like {:s}?".format(fruit.lower())) if result == 'n': fruits.remove(fruit) else: result = input("Do you like {:s}?".format(fruit.lower())) if result == 'y' print fruits for i in range(len(fruits) -1, -1, -10: #For each “no”, delete that fruit from the list. #For any answer that is not “yes” or “no”, prompt the user to answer with one of those two values (a while loop is good here) new_fruit=fruit[:] for item in fruit: while True: result = input('Do you like {:s}(y/n)?'.format(item)) if result == 'y': print('great') break elif result == 'n': print('Deleting {:s}'.format(item)) new_fruit.remove(item) break print(new_fruit) #Display the list. #Series4 #Make a copy of the list and reverse the letters in each fruit in the copy. #Delete the last item of the original list. Display the original list and the copy.
true
6ba7ca1c416e8d7c390ff2f63b4c3dac4185b623
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/PhongT/lesson03/list_lab.py
2,896
4.25
4
""" Lesson 03 List Lab Exercise """ def series_1(fruit_list): print('----- Series 1 ----- ') # Ask the user for another fruit and add it to the end of the list item = input("Enter another fruit?: ") fruit_list.append(item) print(fruit_list) # Ask the user for a number and display the number back to the user and the fruit corresponding to that number item_number = int(input("what fruit number to display?: ")) print('Fruit number ', item_number, ' : ', end='') print(fruit_list[item_number-1]) # todo check for out of range index # Add another fruit to the beginning of the list using “+” and display the list. print('Add Banana to the beginning of the list') another_fruit1 = ['Banana'] fruit_list = another_fruit1 + fruit_list print(fruit_list) # Add another fruit to the beginning of the list using insert() and display the list. print('Add Avocado to the beginning of the list') another_fruit2 = 'Avocado' fruit_list.insert(0,another_fruit2) print(fruit_list) def series_2(fruit_list): print('----- Series 2 ----- ') print(fruit_list) # Remove the last fruit from the list. item = fruit_list.pop() print('Remove last item', item) print(fruit_list) # Ask the user for a fruit to delete, find it and delete it item = input("Enter fruit to remove?: ") fruit_list.remove(item) print(fruit_list) def series_3(fruit_list): """ Ask the user for input displaying a line like “Do you like apples?” for each fruit in the list. For each "no", delete that fruit from the list. For any answer that is not 'yes" or 'no', prompt the user to answer with one of those two values (a while loop is good here) Display the list. :param fruit_list: """ print('----- Series 3 ----- ') print(fruit_list) for fruit in fruit_list: response = input("Do you like: %s (please answer 'yes' or 'no')?: " % fruit) if response == 'no': while fruit in fruit_list: fruit_list.remove(fruit) elif response == 'yes': pass print("Remaining fruit list ", fruit_list) def series_4(fruit_list): print('----- Series 4 ----- ') print(fruit_list) reverse_fruit_list = [] print('Reverse the letters in each fruit in the copy') for item in fruit_list: reverse_fruit_list.append(item[::-1]) print(reverse_fruit_list) print("Delete the last item of the original list. Display the original list and the copy") fruit_list.pop() print(fruit_list) print(reverse_fruit_list) if __name__ == "__main__": fruit_list = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(fruit_list) series_1(fruit_list) series_2(fruit_list) series_3(fruit_list) fruit_list = ['Apples', 'Pears', 'Oranges', 'Peaches'] series_4(fruit_list)
true
d3c213ee060e03ffc5ddbcde3bb1aa3804d02869
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/Kenneth_Murray/lesson3/slicing/slicing.py
2,554
4.15625
4
def exchange_first_last(seq): """returns a sequence with the first and last characters swapped""" first = seq[0] mid = seq[1:-1] last = seq[-1] if type(seq) == str: return last + mid + first else: eos=len(seq) mid.insert(0,last) mid.insert(eos,first) return mid """testing the exchange function""" if __name__ == "__main__": string = "the string test is good" list = [1,2,3,4,5,6,7] assert exchange_first_last(list) == [7,2,3,4,5,6,1] assert exchange_first_last(string) == "dhe string test is goot" print ("the exchange test is complete") def return_every_other(seq, i=2): """returns every other character in a sequence""" return seq[::2] """testing "return_every_other" function""" if __name__ == "__main__": list = [1,2,3,4,5,6,7] assert return_every_other(list) == [1, 3, 5, 7] print("The return_every_other function test has competed successfully") def remove_some_with_step(seq, r=4, i=2): """This will remove the first and last four characters along with every other character.""" """A minimum of 10 characters are required.""" eos = len(seq) if len(seq) > 9: mid = seq[4:-4] return mid[::2] else: print("this requires a minimum of 10 characters") """testing remove_some_with_step""" if __name__ == "__main__": list = [0,1,2,3,4,5,16,17,8,9,10,12] string = "the string test is good" assert remove_some_with_step(list) == [4, 16] assert remove_some_with_step(string) == 'srn eti ' print("The remove_some_with_step test has competed successfully") def reverse_slice(seq): return seq[::-1] """testing reverse_slice""" if __name__ == "__main__": list = [0,1,2,3,4,5,16,17,8,9,10,12] string = "the string test is good" assert reverse_slice(list) == [12, 10, 9, 8, 17, 16, 5, 4, 3, 2, 1, 0] assert reverse_slice(string) == 'doog si tset gnirts eht' print("The reverse_slice test has competed successfully") def seq_shell_game(seq): """this will return the middle third first, the last third second and the first third last.""" """if the number of characters is not divisible by 3, the first third will be short""" length = len(seq) i = round(len(seq) / 3) first = seq[:i] mid = seq[i:-i] last = seq[length-i:] return mid + last + first """testing seq_shell_game""" if __name__ == "__main__": list = [0,1,2,3,4,5,16,17,8,9,10,12] string = "the string test is good" assert seq_shell_game(list) == [4, 5, 16, 17, 8, 9, 10, 12, 0, 1, 2, 3] assert seq_shell_game(string) == 'ng test is goodthe stri' print("The seq_shell_game test has competed successfully")
true
97f6af9a80e03826a2b36f9348114330a84286c8
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/vkis/lesson04/dict_lab.py
2,358
4.15625
4
# Lesson 04 - Dictionary and Set Lab # ================================================================= print("\n============ Dictionaries 1 ============") dict1 = {"name": "Chris", "city": "Seattle", "cake": "Chocolate"} print(dict1) # remove last dict1.popitem() print(dict1) dict1["fruit"] = "Mango" dict1.keys() dict1.values() print("Is ""cake"" a key of dict1? ", "cake" in dict1.keys()) print("Is ""Mango"" a value of dict1? ", "Mango" in dict1.values()) print("\n============ Dictionaries 2 ============") dict2 = {"name": "Chris", "city": "Seattle", "cake": "Chocolate"} print("Original dict2: ", dict2) # loop through dict2 with "key" = each key per loop for key in dict2.keys(): dict2[key] = dict2[key].lower().count('t') print("Dict2 with values = # of ""t""s", dict2) print("\n============ Sets 1 ============") s1 = set(range(1, 20 + 1)) s2 = s1.copy() s3 = s1.copy() s4 = s1.copy() # loop through s1 starting from 1 to last for index in range(1, len(s1) + 1): if index % 2 == 0: s2.remove(index) if index % 3 == 0: s3.remove(index) if index % 4 == 0: s4.remove(index) print("s1: ", s1, "\ns2: ", s2, "\ns3: ", s3, "\ns4: ", s4) print("Is s3 a subset of s2? ", s2.issubset(s3)) print("Is s4 a subset of s2? ", s2.issubset(s4)) print("\n============ Sets 2 ============") # DOES NOT WORK: set1 = (set(list("Python"))).add("i") not sure why? set1 = set(list("Python")) set1.add("i") set2 = frozenset(tuple(list("marathon"))) print("Set1: ", set1, "\nSet2: ", set2) print("Union of set1 & set2 is: ", set1.union(set2)) print("Intersection of set1 & set2 is: ", set1.intersection(set2)) print("\n============ File Lab ============") # print full path of all files in cd import os list_of_files = os.listdir() for n in range(len(list_of_files)): print("{}".format(os.path.abspath(list_of_files[n]))) # copy a file from source to destination (dont read content), binary ie. jpeg with open("pic.jpg", "rb") as f1: with open("pic2.jpg", "wb") as f2: while True: # read 1 byte at a time, read(1) always steps 1 head each time it's called char = f1.read(1) # if the end of the file has been reached f1.read() will return "" if char: f2.write(char) else: break f1.close() f2.close()
false
fa5538a088a9ce95f30d4559a8f61a69b80af062
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/marc_charbo/lesson03/list_lab.py
1,986
4.25
4
#!/usr/bin/env python3 import slicing as slg def fruit_list(fruits): print (fruits[:]) new_fruit = input('enter a fruit name: ') fruits.append(new_fruit) print (fruits[:]) pos_fruit = int(input('enter a number: ')) print (fruits[pos_fruit-1]) new_fruit = input('enter another fruit name: ') fruits.insert(0,new_fruit) print (fruits[:]) for fruit in fruits: if 'P' in fruit: print (fruit) return fruits def del_fruit_from_list(fruits): print (fruits) fruits = fruits[:-1] print (fruits) del_fruit = input('enter name of fruit you want to delete: ') fruits.remove(del_fruit) print (fruits) return fruits def query_user(fruits): for fruit in fruits: answer = input('do you like '+fruit.lower()+'? ') prompt = True while prompt: if answer.lower() == 'no': fruits.remove(fruit) prompt = False elif answer.lower() == 'yes': prompt = False else: answer = input('input only yes or no: ') def reverse(fruits): reverse_fruits = fruits[:] for idx, fruit in enumerate(reverse_fruits): reverse_fruits[idx] = slg.reversed(fruit) print (fruits[idx]) return reverse_fruits def main(): fruits = ['Apples', 'Pears', 'Oranges' ,'Peaches'] try: fruits = fruit_list(fruits) except: print ('error with series 1') try: fruits = del_fruit_from_list(fruits) except: print ('error with series 2') try: fruits = ['Apples', 'Pears', 'Oranges' ,'Peaches'] fruits = query_user(fruits) except: print ('error with series 3') try: fruits = ['Apples', 'Pears', 'Oranges' ,'Peaches'] reverse_fruits = reverse(fruits) print (fruits) print (reverse_fruits) except: print ('error with series 4') if __name__ == "__main__": main()
true