blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ce6f6114512ae2682c8902999118c08474da92fd
alanamckenzie/advent-of-code
/advent2017/code/utils.py
403
4.15625
4
def read_file(filename, line_delimiter='\n'): """Read the contents of a file :param str filename: full path to the text file to open :param line_delimiter: line delimiter used in the file :return: contents of the file, with one list item per line :rtype: list """ with open(filename, 'r') as fin: text = fin.read().strip() return text.split(line_delimiter)
true
36ac8905679118a796c0ea1e073b8f4c035f3246
campbellerickson/CollatzConjecture
/Collatz.py
540
4.25
4
print "Type '123' to start the program::", check = input() if check == 123: print "To what number would you like to prove the Collatz Conejecture?::" limit = input() int(limit) for x in xrange(1,limit+1): num=x original=x iterations=0 while num > 1: if (num % 2 == 0): num = num/2 iterations = iterations + 1 elif (num % 2 != 0): num = (num * 3) + 1 iterations = iterations + 1 print original, "is proven through", iterations, "iterations." print "The Collatz Conjecture is proven!"
true
a3ce178e270557e7711aa92a860f2d6820531dcc
KSSwimmy/python-problems
/csSumOfPostitive/main.py
776
4.125
4
# Given an array of integers, return the sum of all positive integers in an array def csSumOfPositive(input_arr): # Solution 1 sum = 0 for key, value in enumerate(input_arr): if value <= 0: continue else: sum += value return sum # Solution 2 ''' This uses a lambda function. It's like an anonymous JS function. lambda x is the argument and to the right side of : is the expression. input_arr is asking for numbers that are greate than zero, then create a list of numbers greater than zero. From there we sum the result and return the answer ''' result = list(filter(lambda x: x > 0, input_arr)) return sum(result) input_arr = ([1,2,3,-4,5]) print(csSumOfPositive(input_arr))
true
8c99e5d3a112f865f0d8c90f98be43ce6c1e7e01
moorea4870/CTI110
/P5HW2_GuessingGame_AvaMoore.py
817
4.28125
4
# Using random to create simple computer guessing game # July 5, 2018 # CTI-110 P5HW2 - Random Number Guessing Game # Ava Moore # use random module import random # set minimum and maximum values (1-100) MIN = 1 MAX = 100 def main(): #variable to control loop again = 'y' #until the user is finished, repeat while again == 'y' or again == 'Y': guess = int(input("Guess what the secret number is: ")) number = random.randint(1,100) #print("The number is",number) if guess < number: print("Too low, try again.") elif guess > number: print("Too high, try again.") else: print("Congratulations! You guess correctly!") again = input("Play again? (y for yes): ") main()
true
c565083b6d11e6bb8403b0e4c3083ea695a4f5fa
Hanjyy/python_practice
/conditional2.py
1,677
4.1875
4
''' purchase_price = int(input("What is the purchase price: ")) discount_price_10 = (10 /100 )* (purchase_price) final_price_10 = purchase_price - discount_price_10 discount_price_20 = (20/100) * (purchase_price) final_price_20 = purchase_price - discount_price_20 if purchase_price < 10: print("10%", final_price_10, discount_price_10) else: print("20%",final_price_20, discount_price_20) user_gender = input("Enter your gender: ") if user_gender == "M": print("You are not eligible") else: print("You are eligible") user_age = int(input("How old are you: ")) if user_age >= 10 and user_age <= 12: print("You are eligible to play on the team") else: print("You are not eligible to play on the team") gas_tank =int(input("What is your tank size in litres: ")) tank_percentage = int(input("What is the percentage of your tank: ")) km_litre = int(input("How many km/litre does your car get: ")) current_litre = (tank_percentage/100) * (gas_tank) distance_litre_can_go = (current_litre * km_litre) + 5 if distance_litre_can_go < 200: print(f"You can go another {distance_litre_can_go} km") print("The next gas station is 200 km away") print("Get gas now") else: print(f"You can go another {distance_litre_can_go} km") print("The next gas sation is 200 km away") print("You can wait for the next station") ''' password = "Anjola" pin = input("Enter a secret password: ") if pin == password: print("You're in") else: print("Ask the owner") print("Learn enough python to look at the code and figure out") '''Q = input("Enter any word: ") if Q.isupper() or Q.islower(): print("It is a fact")'''
true
20a497f0e1df4edff5d710df5b8fa4839998ca18
hihasan/Design-Patterns
/Python In these Days/practice_windows/com/hihasan/ListPractice.py
786
4.25
4
number=[1,2,3,4] #print list print(number) #Accessing Elements In A List print(number[0]) print(number[-1]) print(number[-2]) print(number[0]+number[2]) #changing, adding & removing elements names=["Hasan","Mamun","Al","Nadim"] names.append("Tasmiah") #When we append an item in the list, it will store in last print(names) names.insert(0,"Khan") #while inserting we need to specify the input postion then the stored value names.insert(0,"Hiumu") print(names) print("First Input Value in the List is: " +names[0].title()) print("Last Input Value in the List is : "+names[-1].title()) del names[4] print(names) del_name=names.pop() number.append(del_name) print("You add delete value in number list: "+int(number)) #delete an item and stored in other list. Need to study firther
true
fe0a64036e5a1317c0dcaaded3a332a6d33594a7
axecopfire/Pthw
/Exercises/Ex15_Reading_FIles/Reading_Files.py
1,392
4.5625
5
# Importing argv from the system module from sys import argv # argv takes two variables named filename and script script, filename = argv # The variable txt opens filename, which is an argv variable txt = open(filename) # filename is entered after this prompt, which is then assigned to the variable txt. At the same time this has to be a valid filename. In a better program we would add an exception saying something like can not find your file try again instead of exiting the program. print(f"Here's your file {filename}:") # The newly formed variable txt is then printed into the shell environment print(txt.read()) # The program continues with another prompting statement print("Type the filename again:") # This time instead of using argv we are using a custom input, which makes it look like it is in the python program also we are assigning file_again to this input file_again = input("> ") # That input then has the method open operated on it and assigned to the variable txt_again, so in actuality the file has not been opened. But instead just assigned to a variable txt_again = open(file_again) # This is where python reads the opened txt_again file and prints its contents. print(txt_again.read()) # In summary the process to print the contents of a file to the command shell is to open the file, read the file, then print what was read. txt.close() txt_again.close()
true
aa82cfb605e7cec0fff586fa9e24b9e8bf0df80e
NataliiaBidak/py-training-hw
/decorators.py
1,667
4.1875
4
"""Write a Decorator named after5 that will ignore the decorated function in the first 5 times it is called. Example Usage: @after5 def doit(): print("Yo!") # ignore the first 5 calls doit() doit() doit() doit() doit() # so only print yo once doit() please make a similar one, but that acceps times to skip as param (@after(<times_to_skip>)) ========================= Calculation in the following fib function may take a long time. Implement a Decorator that remembers old calculations so the function won't calculate a fib value more than once. Program Code: @memoize def fib(n): print("fib({})".format(n)) if n <= 2: return 1 else: return fib(n-1) + fib(n-2) Expected Output: fib(10) fib(9) fib(8) fib(7) fib(6) fib(5) fib(4) fib(3) fib(2) fib(1) 55 ======================= Write a decorator called accepts that checks if a function was called with correct argument types. Usage example: # make sure function can only be called with a float and an int @accepts(float, int) def pow(base, exp): pass # raise AssertionError pow('x', 10) ======================== Write a decorator called returns that checks that a function returns expected argument type. Usage example: @returns(str) def same(word) return word # works: same('hello') # raise AssertionError: same(10) ========================= Write a decorator named logger. It should log function calls and execution time (for example: function f was called w/ params <a, b> and took <time> to execute). Decorator may accept argument file - file to write logs to. If no param was provided - simply print logs to console. Decorator should be implemented as a class. """
true
b309163a54cb56b9f9c3b21795388a74658910fb
99zraymond/Daily-Lesson-Exercises
/Daily Exercise 02082018.py
770
4.34375
4
#Your Name - Python Daily Exercise - date of learning # Instructions - create a file for each of the daily exercises, answer each question seperately # 1. Write a statement that concatenates at least two variables (you can have more than 2 for this practice). # 2. Create a program that asks the user to enter their name and their age. # Print out a message addressed to them that tells them the year that they will turn 100 years old. Clue input() #3 Write a program that prints out the numbers from 1 to 20. # For multiples of three, print "usb" instead of the number and for the mulitiples of five, print "device". # For numbers which are multiples of both three and five, print "usb device". # Print a new line after each string or number.
true
505c59d5b7161eab01c637f144f7f3bf790f2bfb
manjunath2019/Python_7am_May_2019
/Operators/Membership.py
452
4.15625
4
""" in and not in are the membership operators in python Are used to test whether a value or variable is found in a sequence (String, List, Tuple, & Dictrionary) """ x_value = 'Guido Van Rossum' y_value = {1:'a',2:'b'} print(x_value) print(y_value) #a = input('Enter a Value : ') #print(a in x_value.lower()) print(1 in y_value) print('b' in y_value) print('R' not in x_value) # Account_Name = input('Enter Your Account Name : ') # print(Account_Name)
true
ba05240853d5865e4a57d9593bd3bcdf97696bb7
run-fourest-run/IteratorProtocol
/realpythonitertools/itertoolsintro.py
539
4.1875
4
'''itertools is a module that implements a number of iterator building blocks. Functions in itertools operate on iterators to produce more complex iterators''' test_list_0 = [95000,95000,95000,95000] test_list_1 = [117000,117000,121000,120000] test_list_2 = ['alex','joe','anthony','david'] '''zip example''' def see_zip_type(): return_iterator = zip(test_list_1,test_list_2) print(return_iterator) print(list(zip(test_list_1,test_list_0))) print (list(map(len,test_list_2))) print (list(map(sum,zip(test_list_1,test_list_0))))
true
e0d48e5df6768de714b9928cc4853cb92b121535
run-fourest-run/IteratorProtocol
/itertoolsdocs/chain.py
720
4.1875
4
import itertools ''' Make an iterator that returns elements from the first iterable until its exhausted. Then proceed to the next iterable, until all the iterables are exhausted. Used for treating consecutive sequences as a single sequence ''' def chain(*iterables): for it in iterables: for element in it: yield element def from_iterable(iterable): # itertools.chain.from_iterable(['abc','def']) -> a b c d e f for it in iterable: for element in it: yield element data1 = [10,20,30,40,50] data2 = [60,70,80,90,100] chained_data = itertools.chain(data1,data2) it = iter(data1) it1 = next(it) print(it1) it1 = next(it) print(it1) it2 = next(it) print(it1,it2)
true
ec7199c351470743b5ead5d6639229d283ecfca7
bc-uw/IntroPython2016
/students/bc-uw/session04/trigram.py
949
4.125
4
""" Trigram lab attempt. Version0.I don't understand what this is supposed to do """ import sys import string import random def sourceFile_to_list(input_file): """ list comprehension to iterate through source file lines and add them to textlist """ with open(input_file) as f: textlist = [line.strip().lower() for line in f] return textlist def makeTrigram(sourcelist): """ This function takes a list of words as input It then uses zip to merge words together and??? """ trigramzip = zip(sourcelist, sourcelist[1:], sourcelist[2:]) #I can iterate through this zip if __name__ == "__main__": #from solutions, taking filename as an arg try: filename = sys.argv[1] except IndexError: print("You must pass in a filename") sys.exit(1) #let's get the source file into a list sourceFile_to_list(filename) #let's split the list into words?
true
8f995f5ec8b53e07ea81997683fb7acd957a5acc
naymajahan/Object-Oriented-programming1
/python-regular-method.py
979
4.34375
4
#### object oriented programming in python class StoryBook: def __init__(self, name, price, authorName, authorBorne, no_of_pages): # setting the instance variables here self.name = name self.price = price self.authorName = authorName self.authorBorne = authorBorne self.publishingYear = 2020 self.no_of_pages = no_of_pages # Regular method 1 def get_book_info(self): print(f'The book name: {self.name}, price: {self.price}, authorName: {self.authorName}') # Regular method 2 def get_author_info(self): print(f'The author name: {self.authorName}, born : {self.authorBorne}') # creating an instance/object of the storyBook class book1 = StoryBook('hamlet', 350, 'Shakespeare', 1564, 500) book2 = StoryBook('The knite runner', 200, 'khalid hossini', 1965, 230) book1.get_book_info() book2.get_author_info() print(book1.name) print(book2.name) print(book1.publishingYear) print(book2.no_of_pages)
true
752cd493edac4ad35a04b1ce29c7b9449fe6d797
tarabrosnan/hearmecode
/lesson04/lesson04_events_deduplicate.py
986
4.125
4
# Challenge level: Beginner # Scenario: You have two files containing a list of email addresses of people who attended your events. # File 1: People who attended your Film Screening event # https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/film_screening_attendees.txt # # File 2: People who attended your Happy hour # https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/happy_hour_attendees.txt # # Note: You should create functions to accomplish your goals. # Goal 1: You want to get a de-duplicated list of all of the people who have come to your events. def deduplicate(file1, file2): with open(file1, 'r') as file1: file1_contents = file1.read().split('\n') with open(file2, 'r') as file2: file2_contents = file2.read().split('\n') dedupe = list(set(file1_contents+file2_contents)) return dedupe print deduplicate("film_screening_attendees.txt", "happy_hour_attendees.txt")
true
5cdfa102cff1c3210258e57c45eb8ba103e90481
RodiMd/Python
/RomanNumeralsRange.py
1,937
4.125
4
#Roman Numerals #prompt user to enter a value between 1 and 10. number = input('Enter a number between 1 and 10 ') number = float(number) def main(): if number == 1: print('The value entered ', number, 'has a roman equivalent of I') else: if number == 2: print('The value entered ', number, 'has a roman equivalent of II') else: if number == 3: print('The value entered ', number, 'has a roman equivalent of III') else: if number == 4: print('The value entered ', number, 'has a roman equivalent of IV ') else: if number == 5: print('The value entered ', number, 'has a roman equivalent of V ') else: if number == 6: print('The value entered ', number, 'has a roman equivalent of VI') else: if number == 7: print('The value entered ', number, 'has a roman equivalent of VII') else: if number == 8: print('The value entered ', number, 'has a roman equivalent of VIII') else: if number == 9: print('The value entered ', number, 'has a roman equivalent of IX') else: if number == 10: print('The value entered ', number, 'has a roman equivalent of X') else: print('Error: The value entered ', number, 'is outside the specified range') main()
true
19d948529b4da0ca728c55653e413629487b606f
RodiMd/Python
/MonthlyCarCost.py
690
4.1875
4
#Automobile Costs #ask user to input automobile costs including: loan payment #insurance, gas, oil, tires, maintenance. loanPayment = input('Enter auto monthly payment ') insurance = input('Enter insurance cost ') gas = input('Enter monthly gas cost ') oil = input('Enter monthly oil cost ') tires = input('Enter montly tires cost ') maintenance = input('Enter monthly maintenance cost ') oil = (1.0 / 3.0) * float(oil) tires = (1.0 / 24.0) * float(tires) def main(): totalMonthlyCost = float(loanPayment) + float(insurance) + float(gas) + float(oil) + float(tires) + float(maintenance) print ('Total monthly cost of a car %.2f ' %totalMonthlyCost) main()
true
19be8d9e73b668b2039865214c3bb7b1937c1924
RodiMd/Python
/convertKmToMiles.py
383
4.4375
4
#Kilometer Converter #write a program that converts km to mi #ask the user to enter a distance in km distanceKilometers = input('Enter a distance in km ') distanceKilometers = float(distanceKilometers) def conversionTokilometers(): miles = distanceKilometers * 0.6214 print ('The distance entered in kilometers is %.2f' %miles, 'miles') conversionTokilometers()
true
66079189a84d8cd1c08a3b9eee964f6a116395d4
h8rsha/tip-calculator
/main.py
441
4.125
4
if __name__ == '__main__': print("Welcome to the tip calculator.") total_bill = input("What was the total bill? ") tip_percentage = input("What percentage tip would you like to give? 10, 12 or 15? ") people_count = input("How many people to split the bill? ") total_amount = (float(total_bill) / int(people_count)) * (1 + 0.01 * float(tip_percentage)) print(f"Each person should pay : ${round(total_amount, 2)}")
true
b5e6f4348b9445639f2696caac83c9a761200cc0
zchiam002/vecmc_codes_zhonglin
/nsga_ii/nsga_ii_para_imple_evaluate_objective.py
2,310
4.15625
4
##Function to evaluate the objective functions for the given input vector x. x is an array of decision variables ##and f(1), f(2), etc are the objective functions. The algorithm always minimizes the objective function hence if ##you would like to maximize the function then multiply the function by negative one. def nsga_ii_para_imple_evaluate_objective (variable_values, num_obj_func, iteration_number): ##variable_values --- the array of variable values to be evaluated ##num_obj_func --- the nuber of objective functions to evaluate ##iteration_number --- a unique number so that saving the file name will be unique import numpy as np ##Creating a numpy array to store the objective function values objective_values = np.zeros((1, num_obj_func)) ##Iterating based on the number of objective functions to be evaluated for i in range (0, num_obj_func): objective_values[0,i] = kursawe_function_moo (variable_values, i) return objective_values ###################################################################################################################################################################################### ##Test functions ##This is the kursawe test function ## -5 <= x_i <= 5 ## 1 <= i <= 3 ## num_obj_func = 2 def kursawe_function_moo (x, obj_to_evaluate): ##x --- the list of variable values ##obj_to_evaluate --- the objective function to evaluate import math ##Determining the number of variables to be evaluated num_var = len(x) ##Determining which objective function to evaluate if obj_to_evaluate == 0: ret_obj = 0 for i in range (0, num_var-1): v1 = x[i] v2 = x[i+1] ret_obj = ret_obj + (-10 * math.exp(-0.2 * math.sqrt(pow(v1, 2) + pow(v2, 2)))) elif obj_to_evaluate == 1: ret_obj = 0 for i in range (0, num_var): v1 = x[i] if v1 < 0: ret_obj = ret_obj + (pow(-v1, 0.8) + (5 * math.sin(pow(v1, 3)))) else: ret_obj = ret_obj + (pow(v1, 0.8) + (5 * math.sin(pow(v1, 3)))) return ret_obj
true
5e4e2fdc4c1037667821e5f23ad88ccc62f7de18
Salcazul/ComputerElective
/Quiz2.py
622
4.21875
4
#Name name = raw_input("What is your name?") #Last Name last = raw_input("What is your last name?") #Class classname = raw_input("What class are you in?") #Year of birth year = input("What is your year of birth?") #Calculate current age age = 2015 - year print "You are", age, "years of age." #Computer grade 1S s1 = input("What is your first semester grade?") #Computer grade 2S s2 = input("What is your second semester grade?") #Calculate final grade final = (s1 + s2) / 2 #Print in a string name, lastname, class, final grade print "Your name is", name, last+". Your final grade in", classname, "is", final, "."
true
ed218f5025544474394bed9e161c987edd884a3e
yk2684/Codewars
/7kyu/Highest-and-Lowest.py
410
4.125
4
#In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number. #Example: #high_and_low("1 2 3 4 5") # return "5 1" #high_and_low("1 2 -3 4 5") # return "5 -3" #high_and_low("1 9 3 4 -5") # return "9 -5" def high_and_low(numbers): num_list = sorted([int(n) for n in numbers.split(' ')]) return "{} {}".format(num_list[-1], num_list[0])
true
89074f4afad000944e11ed9fcc508ecc69e42233
yk2684/Codewars
/8kyu/Return-negative.py
435
4.65625
5
#In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative? #Example: #make_negative(1); # return -1 #make_negative(-5); # return -5 #make_negative(0); # return 0 #Notes: #The number can be negative already, in which case no change is required. #Zero (0) can't be negative, see examples above. def make_negative( number ): return number if number <= 0 else -number
true
c4d957205efb049acc46b4cc892ef0fb32b8607f
Abdulkadir78/Python-basics
/q16.py
690
4.34375
4
''' Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. Suppose the following input is supplied to the program: 1, 2, 3, 4, 5, 6, 7, 8, 9 Then, the output should be: 1, 9, 25, 49, 81 ''' numbers = input('Enter comma separated sequence of numbers: ') temp_list = numbers.split(',') l = [] final_list = [] # this list is used just for converting the integer list 'l' to a comma separated string for number in temp_list: if int(number) % 2 != 0: l.append(int(number) ** 2) for number in l: # converting integer list 'l' to a string list final_list.append(str(number)) print(', '.join(final_list))
true
278c75115f7d16cbb3b881b0ea0ec90d22eca62a
Abdulkadir78/Python-basics
/q7.py
565
4.21875
4
''' Write a program which takes 2 digits, X, Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. Example Suppose the following inputs are given to the program: 3, 5 Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] ''' dimensions = input('Enter X,Y: ') l = dimensions.split(',') rows = int(l[0]) columns = int((l[1])) l2 = [] for i in range(rows): l3 = [] for j in range(columns): l3.append(i * j) l2.append(l3) print(l2)
true
f28b75916667124438f2c9e661078cf25ac70277
Abdulkadir78/Python-basics
/q35.py
663
4.15625
4
''' Please write a program which counts and prints the numbers of each character in a string input by console. Example: If the following string is given as input to the program: abcdefgabc Then, the output of the program should be: a, 2 b, 2 c, 2 d, 1 e, 1 f, 1 g, 1 ''' string = input('Enter a string: ') l = [] for character in string: if character not in l: l.append(character) print(f'{character}, {string.count(character)}') ''' ALTERNATE SOLUTION: dic = {} string = input('Enter a string: ') for character in string: dic[character] = dic.get(character, 0) + 1 print('\n'.join(['%s, %s' % (k, v) for k, v in dic.items()])) '''
true
911f65f6917f1b17ebc6cb8c325e650549fe2bc3
sapphacs13/python_basics
/syntax/functions.py
722
4.125
4
# Python uses white space. Everything you define or use has # to have the correct indentation. def adder(a, b): return a + b print adder(1, 2) # runs adder(1,2) and prints it (should print 3) def subtracter(a, b): return a - b print subtracter(3, 2) # runs the subtracter and prints (should print 1) # lets talk about the difference between print and return def adder2(a, b): print a + b adder2(1, 2) # prints 3. # Notice how we dont need to print this we only need to call it. # The downside is that we cannot save a variable like a = adder2(4, 5). # This is because the function only prints, it does not save anything. # Looking at the first adder function however: a = adder(4, 5) print a # prints 9
true
5e99a7b51a52f5301a2cb3bc65f019d52051982e
bigcat2014/Cloud_Computing
/Assignment 2/step2.py
615
4.21875
4
#!/usr/bin/python3 # # Logan Thomas # Cloud Computing Lab # Assignment 2 # # Capitalize the first letter of each word in the string and # take the sum of all numbers, not contained in a word, and # print the new string and the sum. def main(): total = 0.0 user_input = input("Please enter a string\n>> ") user_input = user_input.split() output = [] for word in user_input: try: total += float(word) output.append(word) except ValueError: output.append(word.capitalize()) output = ' '.join(output) print('"%s", the sum of numbers is %.3f' % (output, total)) if __name__ == "__main__": main()
true
1d92d87875f37503b14413d484e8656e426ac5d1
JoelBrice/PythonForEveryone
/ex3_03.py
439
4.21875
4
"""Check that the score is between the range and display the score level according to the score""" score = input("Enter Score: ") s = 0.0 try: s = float(score) except: print("Error out of range!") if s >=0 and s<=1: if s>= 0.9: print("A") elif s >=0.8: print("B") elif s>=0.7: print("C") elif s>=0.6: print("D") elif s<0.6: print("F") else: print("Out of range")
true
bcc25fa4698e6c2e3d8bdef4290d8cdbc90bc7bc
alberico04/Test
/main.py
2,845
4.25
4
#### Describe each datatype below:(4 marks) ## 4 = integer ## 5.7 = float ## True = boolean ## Good Luck = string #### Which datatype would be useful for storing someone's height? (1 mark) ## Answer: FLOAT #### Which datatype would be useful for storing someone's hair colour?(1 mark) ## Answer: STRING ####Create a variable tha will store the users name.(1 mark) name=input("Enter your name: ") ####Create a print statement that will print the first 4 characters of the person's name.(3 marks) print(name[0:4]) ####Convert the user's name to all uppercase characters and print the result name=name.upper() print(name) ####Find out how many times the letter A occurs in the user's name print(name.count("A")) #### Create a conditional statement to ask a user to enter their age. If they are older than 18 they receive a message saying they can enter the competition, if they are under 18, they receive a message saying they cannot enter the competition. age=int(input("enter your age:")) if age > 18: print("You can join the competition") else: print("You can not enter the competition") #### Create an empty list called squareNumbers (3 marks) squareNumbers=[] #### Square numbers are the solutions to a number being multiplied by itself( example 1 is a square number because 1 X 1 = 1, 4 is a square number because 2 X 2 = 4 ). ###Calculate the first 20 square numbers and put them in the list called squareNumbers. (With loop and .append 10 marks, without, Max 6 marks). squareNumbers.append(1) squareNumbers.append(2*2) squareNumbers.append(3*3) squareNumbers.append(4*4) squareNumbers.append(5*5) squareNumbers.append(6*6) squareNumbers.append(7*7) squareNumbers.append(8*8) squareNumbers.append(9*9) squareNumbers.append(10*10) squareNumbers.append(11*11) squareNumbers.append(12*12) squareNumbers.append(13*13) squareNumbers.append(14*14) squareNumbers.append(15*15) squareNumbers.append(16*16) squareNumbers.append(17*17) squareNumbers.append(18*18) squareNumbers.append(19*19) squareNumbers.append(20*20) ####Print your list (1 mark) print(squareNumbers) ####Create a variable called userSquare that asks the user for their favourite square number userSquare=int(input("Enter your favourite square number: ")) #### Add this variable to the end of your list called SquareNumbers squareNumbers.append(userSquare) print(squareNumbers) ### Create a variable called choice. This variable should choose a random element from your list. Print the variable called choice.(3 marks) import random choice=squareNumbers[random.randint(0,20)] if choice in squareNumbers: print(choice) ####Create another print statement that prints tha following output: The random square number is: XX, where XX is where the random square number chosen by the computer.(4 marks) print("The random square number is",choice)
true
4cb82d079ffac6a7d07d598ab27ebb14d840f9b7
abhilash1392/pythonBasicExercisesPart1
/exercise_5.py
292
4.25
4
"""5. Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them.""" first_name=input('Please enter your first name: ') last_name=input('Please enter your last name: ') print('Hello {} {}'.format(last_name,first_name))
true
e4975175bb97edd715411f62c8a168dfe32570eb
nbrahman/HackerRank
/03 10 Days of Statistics/Day08-01-Least-Square-Regression-Line.py
1,450
4.21875
4
''' Objective In this challenge, we practice using linear regression techniques. Check out the Tutorial tab for learning materials! Task A group of five students enrolls in Statistics immediately after taking a Math aptitude test. Each student's Math aptitude test score, x, and Statistics course grade, y, can be expressed as the following list of (x,y) points: 1. (95,85) 2. (85,95) 3. (80,70) 4. (70,65) 5. (60,70) If a student scored 80 an on the Math aptitude test, what grade would we expect them to achieve in Statistics? Determine the equation of the best-fit line using the least squares method, then compute and print the value of y when x=80. Input Format There are five lines of input; each line contains two space-separated integers describing a student's respective x and y grades: 95 85 85 95 80 70 70 65 60 70 If you do not wish to read this information from stdin, you can hard-code it into your program. Output Format Print a single line denoting the answer, rounded to a scale of 3 decimal places (i.e., 1.234 format). ''' # import library import statistics as st # Set data n = 5 x = [95, 85, 80, 70, 60] y = [85, 95, 70, 65, 70] meanX = st.mean(x) meanY = st.mean(y) x_s = sum([x[i] ** 2 for i in range(5)]) xy = sum([x[i]*y[i] for i in range(5)]) # Set the B and A b = (n * xy - sum(x) * sum(y)) / (n * x_s - (sum(x) ** 2)) a = meanY - b * meanX # Gets the result and show on the screen print (round(a + 80 * b, 3))
true
7d1e10a0303d71f3ff95a22bf44e2963b3745f22
nbrahman/HackerRank
/01 Algorithms/01 Warmup/TimeConversion.py
969
4.25
4
''' Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock. Input Format A single string containing a time in 12-hour clock format (i.e.: hh:mm:ss AM or hh:mm:ss PM ), where 01 <= hh <= 12 and 00 <= mm,ss <= 59. Output Format Convert and print the given time in 24-hour format, where 00 <= hh <= 23. Sample Input 07:05:45PM Sample Output 19:05:45 ''' if __name__ == '__main__': time = input().strip() arr = time.split(":") print ('{:02d}'.format(int(arr[0])%12 + (0 if arr[2][len(arr[ 2])-2:]=="AM" else 12))+":"'{:02d}'.format(int(arr[ 1]))+":"+'{:02d}'.format(int(arr[2][ 0:2])))
true
fd4be7ead12bb78ac455902f0721c2655643d7f4
nbrahman/HackerRank
/01 Algorithms/02 Implementation/Utopian-Tree.py
1,421
4.21875
4
''' The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter. Laura plants a Utopian Tree sapling with a height of 1 meter at the onset of spring. How tall will her tree be after N growth cycles? Input Format The first line contains an integer, T, the number of test cases. T subsequent lines each contain an integer, N, denoting the number of cycles for that test case. Constraints 1<=T<=10 0<=N<=60 Output Format For each test case, print the height of the Utopian Tree after N cycles. Each height must be printed on a new line. Sample Input 3 0 1 4 Sample Output 1 2 7 Explanation There are 3 test cases. In the first case (N=0), the initial height (H=1) of the tree remains unchanged. In the second case (N=1), the tree doubles in height and is 2 meters tall after the spring cycle. In the third case (N=4), the tree doubles its height in spring (H=2), then grows a meter in summer (H=3), then doubles after the next spring (H=6), and grows another meter after summer (H=7). Thus, at the end of 4 cycles, its height is 7 meters. ''' #!/bin/python3 import sys def calculateUtopianTreeHeight (t,n): h = 1 for i in range(0,n-1,2): h=(h*2)+1 if n>0 and n%2==1: h*=2 print(h) t = int(input().strip()) for a0 in range(t): n = int(input().strip()) calculateUtopianTreeHeight(t,n)
true
13c10b8411890edb52c47de0543427793125cd55
nbrahman/HackerRank
/01 Algorithms/02 Implementation/Circular-Array-Rotation.py
1,807
4.28125
4
''' John Watson performs an operation called a right circular rotation on an array of integers, [a0, a1, a2, an-1]. After performing one right circular rotation operation, the array is transformed from [a0, a1, a2, an-1] to [an-1, a0, a1, a2, an-2]. Watson performs this operation k times. To test Sherlock's ability to identify the current element at a particular position in the rotated array, Watson asks q queries, where each query consists of a single integer, m, for which you must print the element at index m in the rotated array (i.e., the value of am). Input Format The first line contains 3 space-separated integers, n, k, and q, respectively. The second line contains n space-separated integers, where each integer i describes array element ai (where 0 <= i <= n). Each of the subsequent lines contains a single integer denoting m. Constraints 1 <= n <= 10^5 1 <= ai <= 10^5 1 <= k <= 10^5 1 <= q <= 500 0 <= m <= n-1 Output Format For each query, print the value of the element at index m of the rotated array on a new line. Sample Input 0 3 2 3 1 2 3 0 1 2 Sample Output 0 2 3 1 Explanation 0 After the first rotation, the array becomes [3,1,2]. After the second (and final) rotation, the array becomes [2, 3, 1]. Let's refer to the array's final state as array b. For each query, we just have to print the value of bm on a new line: m = 0, so we print 2 on a new line. m = 1, so we print 3 on a new line. m = 2, so we print 1 on a new line. ''' if __name__ == '__main__': n, k, q = input().strip().split(' ') n, k, q = [int(n), int(k), int(q)] a = [int(a_temp) for a_temp in input().strip().split(' ')] b = [] for a0 in range(q): m = int(input().strip()) b.append (m) print ('Output') for i in b: print(a[(i-k)%len(a)])
true
5d0df4565c0a9c8ddd4442a609050631ae3310f9
kumarchandan/Data-Structures-Python
/3-linked_lists/c6_detect_loop_in_linked_list/main-floyd-algo.py
1,201
4.125
4
''' This is perhaps the fastest algorithm for detecting a linked list loop. We keep track of two iterators, onestep and twostep. onestep moves forward one node at a time, while twostep iterates over two nodes. In this way, twostep is the faster iterator. By principle, if a loop exists, the two iterators will meet. Whenever this condition is fulfilled, the function returns True. ''' from LinkedList import LinkedList # Floyd's Cycle Finding Algorithm def detect_loop(lst): # O(n) # Keep two iterators onestep = lst.get_head() twostep = lst.get_head() while onestep and twostep and twostep.next_element: # O(n) onestep = onestep.next_element # Moves one node at a time twostep = twostep.next_element.next_element # Skips a node if onestep == twostep: # Loop exists return True return False # ---------------------- lst = LinkedList() lst.insert_at_head(21) lst.insert_at_head(14) lst.insert_at_head(7) # Adding a loop head = lst.get_head() node = lst.get_head() for i in range(4): if node.next_element is None: node.next_element = head.next_element break node = node.next_element print(detect_loop(lst))
true
9985b32d8d79fb4bfde8d0ffbec712e5b88ac8d4
gomanish/Python
/Linked_List/add_and_delete_last_node.py
910
4.25
4
# Add and Delete Last Node in a linked list class Node: def __init__(self,val): self.value = val self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def printallnodeval(llist): temp=llist.head while temp: print temp.value temp=temp.next return def DeleteNode(head): temp=head while temp.next.next: temp=temp.next temp.next=None return head def InserteNode(head,tail,value): temp=Node(value) tail.next=temp return head # Creating Node a=Node(1) b=Node(2) c=Node(3) d=Node(4) e=Node(5) a.next = b b.next = c c.next = d d.next = e llist=LinkedList() llist.head = a llist.tail = e printallnodeval(llist) print 'after addition of Node' llist.head=InserteNode(llist.head,llist.tail,10) printallnodeval(llist) print 'Delete Node from tail of the linked list' llist.tail=DeleteNode(llist.head) printallnodeval(llist)
true
eae27424746c9423d92b345429cf1acb5d5656e9
gomanish/Python
/basic/threesquares.py
348
4.1875
4
'''Write a Python function threesquares(m) that takes an integer m as input and returns True. if m can be expressed as the sum of three squares and False otherwise. (If m is not positive, your function should return False.)''' def threesquares(n): if n<0: return False while(n%4==0): n=n/4 n=n-7 if(n%8==0): return False return True
true
39bcbe9d664219f56608744cc6e2b0e88261fa2a
carriehe7/bootcamp
/IfStatementBasics.py
1,118
4.125
4
# if statements basics part 1 salary = 8000 if salary < 5000: print('my salary is too low, need to change my job') else: print('salary is above 5000, okay for now') age = 30 if age > 50: print('you are above 50. you are a senior developer for sure') elif age > 40: print('your age is bigger than 40. you are a developer for some time, but if not, better late than never') elif age > 35: print('so you are more than 35yo, I might guess you are a developer') else: print("doesn't matter what age you are. let's code python") # if statements basic part 2 age = 30 name = 'James' # logical operator - 'and' if age > 20 and name == 'James': print('my name is James and I am over 20') else: print('default exit point') # logical operator - 'or' if age > 20 or name == 'James': print('my name is James and I am over 20') else: print('default exit point') # nested 'if' statement married = True if age > 20 and name == 'James': if married == True: print("good luck, it's gonna be a long happy ride") else: print('nested else') else: print('parent else')
true
e180350b63cc478a403a3df45cc5e781d70c5d5f
carriehe7/bootcamp
/TupleCollectionHW.py
1,642
4.5625
5
# 1. Create a ‘technological_terms’ tuple that will contain the following items: # a. python # b. pycharm IDE # c. tuple # d. collections # e. string technological_terms = ('python', 'pycharm IDE', 'tuple', 'collections', 'string') print('technological terms tuple collection : ' +str(technological_terms)) # 2. Print the following sentence using cell extraction to the needed cells: # “We are ninja developers. We write python code in pycharm IDE, and now practicing tuple collections topic, that contains string variables.” # Instructions: # a. Words marked in purple - usual extraction of cell by index # b. Words marked in yellow - extraction by negative cell index print('print sentence with cell extraction: We are ninja developers. We write ' +(technological_terms[0]) +' code in ' +(technological_terms[-4]) +', and now practicing ' +(technological_terms[2]) +' collections topic, that contains ' +(technological_terms[-1]) +' variables.') # 3. Insert the variables “float” and “list” into the tuple. Add them to the end of the collection # (Hint : We studied how to add new cells on ‘list - advanced’ lecture) technological_terms_list = list(technological_terms) technological_terms_list.append('float') technological_terms_list.append('list') technological_terms = tuple(technological_terms_list) print('add variables to collection : ' +str(technological_terms)) # 4. Create a single cell tuple with the number ‘1’ in it. Also, print out the ‘type’ of the data collection single_cell_tuple = (1,) print('single cell tuple : ' +str(single_cell_tuple)) print(type(single_cell_tuple))
true
572eb584fb562b811de2b73c517ed4fffbf5c8e2
mbonnemaison/Learning-Python
/First_programs/boolean_1.py
730
4.15625
4
""" def list_all(booleans): Return True if every item in the list is True; otherwise return False list_all([]) = True list_all([True]) = True list_all([False]) = False list_all([True, False, True]) = False raise Exception("TODO") """ def list_all(booleans): for bools in booleans: if not isinstance(bools, bool): raise TypeError("expected bool, got {}".format(type(bools))) if False not in booleans: print(True) else: print(False) #Examples to test the code above: list_all_test_cases = [[], [True], [False], [True, False, True], [True, True], ["Matt", "Mathilde"], [23, 4.3]] for x in list_all_test_cases: try: list_all(x) except TypeError as e: print(e)
true
2205eee999f0175dbb14cc40d239bd819fc83baa
KarenAByrne/Python-ProblemsSets
/fib.py
1,159
4.21875
4
# Karen Byrne # A program that displays Fibonacci numbers. def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i # Test the function with the following value. My name is Karen , so the first and last letter of my name (K+ N = 11 + 14) # give the number 25. The 25th Fibonacci number is 75025. # Fibonacci number 25 is 75025 # I had some issues. I followed the helpful thread so thanks to all contributors. x = 25 ans = fib(x) print("Fibonacci number", x, "is", ans) # Karen Byrne # A program that displays Fibonacci numbers using people's names. def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i name = "Byrne" first = name[0] last = name[-1] firstno = ord(first) lastno = ord(last) x = firstno + lastno ans = fib(x) print("My surname is", name) print("The first letter", first, "is number", firstno) print("The last letter", last, "is number", lastno) print("Fibonacci number", x, "is", ans)
true
c8cd572bde563d3cebd748dde843402cd1fb2077
camaral82/Python_Self_Study_MOSH
/Dictionary.py
506
4.28125
4
"""24/09/2020 - Thursday Dictionary Exercise Type a sequence of numbers and at the end transcript each element. In case of typing a character, show ! """ digits_mapping = {"1": "One", "2": "Two", "3": "Three", "4": "Four", "5": "Five", "6": "Six", "7": "Seven", "8": "Eight", "9": "Nine", "0": "Zero"} digits = input("Type your phone number: ") output = "" for ch in digits: output += digits_mapping.get(ch, "!") + " " print(output)
true
72663f0656ad734acee538dc6aa8f8d67256d49a
saileshkhadka/SearchingAlgorithm-in-Python
/LargestElementfromlistinLinearTime.py
2,475
4.1875
4
# Problem Description # The program takes a list and i as input and prints the ith largest element in the list. # Problem Solution # 1. Create a function select which takes a list and variables start, end, i as arguments. # 2. The function will return the ith largest element in the range alist[start… end – 1]. # 3. The base case consists of checking whether there is only one element in the list and if so, alist[start] is returned. # 4. Otherwise, the list is partitioned using Hoare’s partitioning scheme. # 5. If i is equal to the number of elements in alist[pivot… end – 1], call it k, then the pivot is the ith largest element. # 6. Otherwise, depending on whether i is greater or smaller than k, select is called on the appropriate half of the list. # Program/Source Code def select(alist, start, end, i): """Find ith largest element in alist[start... end-1].""" if end - start <= 1: return alist[start] pivot = partition(alist, start, end) # number of elements in alist[pivot... end - 1] k = end - pivot if i < k: return select(alist, pivot + 1, end, i) elif i > k: return select(alist, start, pivot, i - k) return alist[pivot] def partition(alist, start, end): pivot = alist[start] i = start + 1 j = end - 1 while True: while (i <= j and alist[i] <= pivot): i = i + 1 while (i <= j and alist[j] >= pivot): j = j - 1 if i <= j: alist[i], alist[j] = alist[j], alist[i] else: alist[start], alist[j] = alist[j], alist[start] return j alist = input('Enter the list of numbers: ') alist = alist.split() alist = [int(x) for x in alist] i = int(input('The ith smallest element will be found. Enter i: ')) ith_smallest_item = select(alist, 0, len(alist), i) print('Result: {}.'.format(ith_smallest_item)) # Program Explanation # 1. The user is prompted to enter a list of numbers. # 2. The user is then asked to enter i. # 3. The ith largest element is found by calling select. # 4. The result is displayed. # Runtime Test Cases # Case 1: # Enter the list of numbers: 3 1 5 10 7 2 -2 # The ith smallest element will be found. Enter i: 2 # Result: 7. # Case 2: # Enter the list of numbers: 5 4 3 2 1 # The ith smallest element will be found. Enter i: 5 # Result: 1. # Case 3: # Enter the list of numbers: 3 # The ith smallest element will be found. Enter i: 1 # Result: 3.
true
3f07333fe11b65981a4d530cc59ff45e42fe8225
ssaroonsavath/python-workplace
/conversion/conversion.py
977
4.25
4
''' Created on Jan 20, 2021 The objective is to make a program that can complete different conversions ''' #Use input() to get the number of miles from the user. ANd store #that int in a variable called miles. miles = input("How many miles would you like to convert?") #Convert miles to yards, using the following: #1 mile = 1760 #Store the value in a variable called yards and print it our with a #simple statement. yards = miles * 1760 print(str(miles)) + "convert to" + str(yards) + "yards." #conver miles to feet, using the following # 1 mile = 5280 feet. #Store the balue in a variable called feet and print it our with a #simple statement feet = miles * 5280 print(str(miles)) + "convert to" + str(feet) + "feet." #conver miles to inches, using the following: #1 mile = 63,360 feet #Store the value in a variable called inches and print it our with a #simple statement. inches = miles * 63360 print(str(miles)) + "convert to" + str(inches) + "inches."
true
7686831590125c15617128a0115e1a23b084d528
mayanderson/python-selenium-automation
/hw3_algorithms/algorithm_2.py
298
4.15625
4
def longestWord(): sentence = input('Please enter a sentence with words separated by spaces:') words = sentence.split() if len(words) == 0: return "" if len(words) == 1: return words[0] longest = "" for word in words: if len(word) > len (longest): longest = word return longest
true
658408212c2953a13931535581cbd34f9f446d83
chokrihamza/opp-with-python
/try_except.py
496
4.125
4
try: print(x) except: print("there is no value of x") try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") try: print(x) except: print("Something went wrong") finally: print("The 'try except' is finished") try: f = open("demofile.txt", 'w') f.write("Hello there") except: print("Something went wrong when writing to the file") finally: f.close() x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed")
true
7ddab1a480e5e4ab6d33ce0bec4039a590547973
Rohankrishna/Python_Scripting_Practice
/even_odd.py
383
4.15625
4
from math import sqrt n = int(input("enter a number ")) check = int(input("Enter the number with which we want to check ")) if n % 4 == 0: print("It is an even number and also a multiple of 4") elif n%2==0: print("It is an even number") else: print("It is an odd number") if(n%check==0): print(n, " is evenly divisible by ",check) else: print(n, "is not divisible by", check)
true
980b7a7e9e0eb54fdb5e45109285da68ca5dafec
brownd0g/Financial-Independence-Calculator
/Financial Independence Calculator.py
2,070
4.375
4
# This function is used to make sure user inputs a valid number for each question def validInput(question): UI = input(question) # The following will run until a positive real number is entered while True: try: num = float(UI) while num < 0: num = float(input("Error: Please enter a positive real number: ")) except ValueError: UI = input("Error: Please enter a positive real number: ") continue else: return num break # Use function to ask for input expenses = validInput("How much did you spend last year to support your current lifestyle? ") inf_rate = validInput("Please enter the expected inflation rate: ") savings = validInput("How much do you currently have saved for investment? ") interest = validInput("What is the expected average annual interest rate? ") test_years = int(validInput("How many years do you want to test? ")) # Print the header print("Year Remaining Balace") # For loop to calculate each year for x in range(0, test_years): if savings > 0: expenses = expenses + (expenses * inf_rate) # Adds inflation to expenses savings = savings - expenses # Subtracts expenses from savings savings = savings + (savings * interest) # Adds interest onto savings if (x+1) < 10: print("", x+1, " ", format(savings, '0.2f')) # Prints out current balance to two decimal places else: print("", x+1, " ", format(savings, '0.2f')) # Loses a space for formatting purposes else: print("Not financially independant!") # Waits for user input before exiting input("Press enter to exit") exit() print("Financially independant!") input("Press enter to exit") exit()
true
2c7883d2c464936c5fb2bfc6d6e62ccab313b6ce
ggsbv/pyWork
/compareDNA/AminoAlign.py
1,526
4.21875
4
#findLargest function finds and returns the largest DNA string def findLargest(AA1, AA2): largest = "" if len(AA1) >= len(AA2): largest = AA1 else: largest = AA2 return largest #align function compares two amino acid sequences and prints any differences (mutations) def align(AA1, AA2): index = 0 match = 0.0 alignment = [] largestAA = findLargest(AA1, AA2) print largestAA while index < len(largestAA): currentAA1 = AA1[index] currentAA2 = AA2[index] if currentAA1 != currentAA2: alignment.append("_") else: alignment.append("*") match += 1 index += 1 alignString = "".join(alignment) percent = round((match/len(largestAA))*100, 2) print "AA Sequence 1: " + AA1 print "AA Sequence 2: " + AA2 print '{:>15}'.format(alignString) print "Alignment: " + str(percent) AASeq1 = raw_input("Input first amino acid sequence to be compared. \nAlternatively you can type 'q' to quit. \n") AASeq2 = raw_input("Input second amino acid sequence to be compared. \nAlternatively type 'q' to quit. \n") while AASeq1 != "q" and AASeq2 != "q": align(AASeq1, AASeq2) AASeq1 = raw_input("Input first amino acid sequence to be compared. \nAlternatively you can type 'q' to quit. \n") AASeq2 = raw_input("Input second amino acid sequence to be compared. \nAlternatively type 'q' to quit. \n")
true
e7c0faf8127f813db4bd4599198c8f6eda8ff552
alexjohnlyman/Python-Exercises
/Inheritance.py
1,003
4.21875
4
# Inheritance # Is an "is a" relationship # Implicit Inheritance class Parent(object): def implicit(self): print "PARENT implicit()" def explicit(self): print "PARENT explicit()" def altered(self): print "PARENT altered()" class Child(Parent): def implicit(self): print "CHILD implicit()" def altered(self): print "CHILD, BEFORE PARENT altered()" super(Child, self).altered() # this will display "PARENT altered()". The 'super' takes 2 parameters super(class that you are trying to get the parent/super of, self) print "CHILD, AFTER PARENT altered()" # dad = Parent() # son = Child() # # # # dad.implicit() # # son.implicit() # # # # dad.explicit() # # son.explicit() # # dad.altered() # son.altered() class Cat(object): def speak(self): print "meow" class Lion(Cat): def speak(self): super(Lion, self).speak() print "roar" # felix = cat() leo = Lion() # felix.speak() leo.speak()
true
298ab47829b2875bca88208e9d87d2d1ceb8a96f
LinuxLibrary/Python
/Py-4/py4sa-LA/programs/04-Classes.py
864
4.28125
4
#!/usr/bin/python # Author : Arjun Shrinivas # Date : 03.05.2017 # Purpose : Classes in Python class Car(): def __init__(self): print "Car started" def color(self,color): print "Your %s car is looking awesome" % color def accel(self,speed): print "Speeding upto %s mph" % speed def turn(self,direction): print "Turning " + direction def stop(self): print "Stop" car1 = Car() print car1 print car1.color('Black Chevrolet Cobalt SS') print car1.accel(50) print car1.turn('Right') print car1.stop() class RaceCar(Car): def __init__(self,color): self.color = color self.top_speed = 200 print "%s race car has started with a top speed of %s" % (self.color, self.top_speed) def accel(self, speed): print "%s speeding up to %s mph very very fast" % (self.color, speed) car2 = RaceCar('Black Chevrolet Cobalt SS') print car2 print car2.accel(80) # END
true
97b7f50d9511e5acd7a86947b8bc5a367f4b589d
brookstawil/LearningPython
/Notes/7-16-14 ex1 Problem Square root calculator.py
935
4.3125
4
#7/16/14 #Problem: See how many odd integers can be subtracted from a given number #Believe it or not this actually gives the square root, the amount of integers need is the square root!! #number input num = int(input("Give me a number to square root! ")) num_begin = num #Loops through the subtractions #defines the start number we are subtracting num with #It also defines the start of the count for how many integers are needed subtracter = 1 ints_needed = 1 #Commenting out the print statements SIGNIFICANTLY increases speed #Loop while (num > subtracter): print(str(ints_needed) + ": The odd integer used is " + str(subtracter)) num = num - subtracter subtracter += 2 ints_needed += 1 #Prints the amount of integers needed print(str(ints_needed),"odd integers were needed ending at " + str(subtracter) + " which would make the number negative") print("The square root of",num_begin,"is",ints_needed)
true
2af694a25d9f9174581cd14f3eafad232b278f83
brookstawil/LearningPython
/Notes/7-14-14 ex6 Letter grades.py
525
4.125
4
#7-14-14 #Letter grades #Input the grade grade = input("What is the grade? ") grade = grade.upper() #Long way #if grade == "A": # print ("A - Excellent") #else: # if grade == "B": # print("B - good!") # else: # if grade == "C": # print("C - average") # else: # print =(grade,"other") #Short way #elif combines the else and if statement if grade == "A": print("A - Excellent!") elif grade == "B": print("B - Good!") elif grade == "C": print("C - average")
true
ec1f9eb074b9429219c410c902a440cea069377e
brookstawil/LearningPython
/Notes/7-31-14 ex1 Determine whether a number (N) is prime.py
958
4.1875
4
#7/31/14 #Determine whether a number (N) is prime or not #We only have to check numbers up to the integer square root of N. import math #This determines whether n is prime #INPUT - a number to check #OUTPUT - Ture if it is prime or False if is is not def is_prime(n): is_it_prime = True #We start with an assumption that it is prime divisor = 2 #This is the first divisor while (divisor <= math.sqrt(n)): #We use a while loop because we don't know how many iterations are needed #Is it divisible? if (n % divisor == 0): #Its divisible is_it_prime = False break #Stops checking divisor += 1#Try the next divisor return is_it_prime def main(): how_many_primes = 1000 counter_primes = 0 n = 2 while(counter_primes < how_many_primes): if is_prime(n) == True: counter_primes += 1 print("%8d" % n,end = "") n += 1 main()
true
d85e661fcc6f61c320b8502dde6c185d5a50f78a
Struth-Rourke/cs-module-project-algorithms
/moving_zeroes/moving_zeroes.py
787
4.34375
4
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): # instantiating an empty, new_arr new_arr = [] # loop over items in the array for i in arr: # if the value of the item in the array is not zero if i != 0: # append the value to the list new_arr.append(i) # loop over the items again, seperately (second occasion) for j in arr: # if the value of the item in the array IS zero if j == 0: # append it to the list new_arr.append(j) return new_arr if __name__ == '__main__': # Use the main function here to test out your implementation arr = [0, 3, 1, 0, -2] print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
true
3a9aaa5e252c042a99972e7a7146e17a9ddae7e4
parandkar/Python_Practice
/brick_game.py
933
4.15625
4
""" This is a solution to the problem given at https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/bricks-game-5140869d/ Patlu and Motu works in a building construction, they have to put some number of bricks N from one place to another, and started doing their work. They decided , they end up with a fun challenge who will put the last brick. They to follow a simple rule, In the i'th round, Patlu puts i bricks whereas Motu puts ix2 bricks. There are only N bricks, you need to help find the challenge result to find who put the last brick. Input: First line contains an integer N. Output: Output "Patlu" (without the quotes) if Patlu puts the last bricks ,"Motu"(without the quotes) otherwise. """ N = int(input()) round = 1 while N > (round * 3): N -= (round * 3) round += 1 if N/round > 1.000: print("Motu") else: print("Patlu")
true
efccbfe53442920f68dba5e07a6de8f05ded48a4
parandkar/Python_Practice
/seat.py
733
4.1875
4
""" This is a solution to the problem given at https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/seating-arrangement-1/ """ # Using dictionaries to deduce the front seats and seat type facing_seats = {1:11, 2:9, 3:7, 4:5, 5:3, 6:1, 7:-1, 8:-3, 9:-5, 10:-7, 11:-9, 0:-11} seat_types = {1:'WS', 0:'WS', 2:'MS', 5:'MS', 3:'AS', 4:'AS'} # Get the number of inputs T = int(input()) # Getting the N inputs and strring them in an array N_Array = [] # get the facing seat numbers and seat types for n in range(0, T): N_Array.append(int(input())) for seat in N_Array: print(seat + facing_seats[seat%12], end=' ') print(seat_types[seat%6])
true
625c2fb420c9fb2670a4bf01db08aaa52ccc5080
parandkar/Python_Practice
/count-divisors.py
694
4.1875
4
""" This is a solution to the problem given at https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/count-divisors/ You have been given 3 integers - l, r and k. Find how many numbers between l and r (both inclusive) are divisible by k. You do not need to print these numbers, you just have to find their count. Input Format The first and only line of input contains 3 space separated integers l, r and k. Output Format Print the required answer on a single line. """ I, r, k = map(int, input().split()) num_of_divisors = 0 for i in range(I, r+1): if i%k == 0: num_of_divisors += 1 print(num_of_divisors)
true
a4cfcbfcad47b05b4257e2251ba015f2226761ae
chuene-99/Python_projects
/mostwords.py
410
4.25
4
#program that counts the most common words in a text file. file=open(input('enter file name: ')) list_words=list() dict_words=dict() for line in file: line=line.rstrip() line=line.split() for word in line: dict_words[word]=dict_words.get(word,0)+1 for k,v in dict_words.items(): list_words.append((v,k)) list_words.sort(reverse=True) for v,k in list_words: print(k,v)
true
a6c81c911cda7b995456e893b71b400713a8c34d
ry-blank/Module-7
/basic_list.py
878
4.53125
5
""" Program: basic_list_assignment Author: Ryan Blankenship Last Date Modified: 10/6/2019 The purpose of this program is to take user input then display it in a list. """ def make_list(): """ function to return list of user input from function get_input() :return: returns list of user input """ number_list = [] attempts = 3 for a in range(attempts): try: user_num = int(get_input()) except ValueError: print("Please enter numbers only.") else: number_list.insert(len(number_list), user_num) return number_list def get_input(): """ function to prompt user for input :return: returns a string """ user_num = input("Please enter a number to add to your list: ") return user_num if __name__ == '__main__': print(make_list())
true
8d022903c89a5f24d5b99aba8e273ecdce4c2bb2
Hail91/Algorithms
/recipe_batches/recipe_batches.py
1,683
4.125
4
#!/usr/bin/python import math test_recipe = { 'milk': 100, 'butter': 50, 'flour': 5 } # Test for PT test_ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 } # Test for PT def recipe_batches(recipe, ingredients): batches = 0 # Initalize a batches variable to zero while True: # Using a while loop to keep the loop running <--- Should probably refactor this as while True is not very clear. for value in recipe: # Loop over recipe dictionary grabbing values out. if value not in ingredients: # If there is a value in recipes that is not in ingredients, break out of the loop and return batches. return batches elif recipe[value] > ingredients[value]: # Otherwise, if the value exists in both dictionaries, but there is not enough in the ingredients dict, then break and return batches. return batches else: # Otherwise, that means you have enough of that "Value(ingredient)", so subtract the amount required in recipes from the ingredients dict for that specifc ingredient. ingredients[value] -= recipe[value] batches += 1 # Increment batches by 1 once you've completed one full loop through the recipes dict where all conditions are passing. recipe_batches(test_recipe, test_ingredients) # Test for PT if __name__ == '__main__': # Change the entries of these dictionaries to test # your implementation with different inputs recipe = { 'milk': 100, 'butter': 50, 'flour': 5 } ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 } print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
true
e1fbb0394458201d27b22d8df48b5df97b5e31c1
ShabnamSaidova/basics
/dogs.py
2,438
4.46875
4
class Dog(): """A simple attempt to model a dog""" def __init__(self, name, age): """Initialize name and age attributes.""" self.name = name self.age = age def sit(self): """Simulate a dog sitting in response to a command.""" print(self.name.title() + " is now sitting. ") def roll_over(self): """Simulate rolling over in response to a command.""" print(self.name.title() + " rolled over!") mydog = Dog('Bob', 6) yourdog = Dog('willie', 5) mydog.sit() mydog.roll_over() print("Your dog's name is " + yourdog.name.title() + ".") print("Your dog is " + str(yourdog.age) + " years old. ") print("My dog is " + str(mydog.age) + " years old. ") yourdog.sit() print("\nExercise 9-1") # 9-1. Restaurant: Make a class called Restaurant. The __init__() method for # Restaurant should store two attributes: a restaurant_name and a cuisine_type. # Make a method called describe_restaurant() that prints these two pieces of # information, and a method called open_restaurant() that prints a message indi- # cating that the restaurant is open. # Make an instance called restaurant from your class. Print the two attri- # butes individually, and then call both methods. class Restaurant(): """Restaurant should store two attributes: a restaurant_name and a cuisine_type.""" def __init__(self, name, cuisine): self.name = name.title() self.cuisine = cuisine.title() def describe_restaurant(self): message = f"{self.name} serves wonderful {self.cuisine} ." print(f"\n{message}") def open_restaurant(self): message = f"{self.name} is now open!" print(f"\n{message}") restaurant = Restaurant('Luigi', 'pizza') print(restaurant.name) print(restaurant.cuisine) restaurant.describe_restaurant() restaurant.open_restaurant() class Car(): """A simple attempt to represent a car.""" def __init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() my_new_car = Car('audi', 'q5', 2014) print(my_new_car.get_descriptive_name())
true
cb5b3c72a8482ce9be3b8b4991527eeada7c27fd
Marcus-Mosley/ICS3U-Unit4-03-Python
/squares.py
1,024
4.40625
4
#!/usr/bin/env python3 # Created by Marcus A. Mosley # Created on October 2020 # This program finds the squares of all natural numbers preceding the # number inputted by the user def main(): # This function finds the squares of all natural numbers preceding the # number inputted by the user # Input counter = 0 square = 0 natural_string = input("Enter a natural number (To Find Sqaure 0 to N): ") print("") # Process & Output try: natural_integer = int(natural_string) except Exception: print("You have not inputted an integer, please input an integer" " (natural number)!") else: if natural_integer <= 0: print("You have not inputted a positive number, please input a" " positive number!") else: for counter in range(natural_integer+1): square = counter**2 print("The square of {0} is {1}".format(counter, square)) if __name__ == "__main__": main()
true
b18eda77ffe0121752bb93beb291eab3184f0df2
Udayin/Flood-warning-system
/floodsystem/flood.py
1,586
4.25
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 24 18:01:03 2017 @author: Rose Humphry """ from floodsystem.utils import sorted_by_key def stations_level_over_threshold(stations, tol): ''' a function that returns a list of tuples, where each tuple holds (1) a station at which the latest relative water level is over tol and (2) the relative water level at the station. The returned list should be sorted by the relative level in descending order.''' stations_over_threshold = [] for station in stations: if type(station.relative_water_level()) == float: if station.relative_water_level() > tol: station_tup = (station.name, station.relative_water_level()) stations_over_threshold.append(station_tup) stations_over_threshold.sort() return stations_over_threshold def stations_highest_rel_level(stations, N): '''A function that takes a list of stations and returns a list of the N stations at which the water level, relative to the typical range, is highest. The list should be sorted in descending order by relative level.''' most_at_risk_stations = [] for station in stations: if type(station.relative_water_level()) == float: x = station.relative_water_level() most_at_risk_stations += [(station, float("{0:.6f}".format(x)))] else: pass sorted_most_at_risk_stations = sorted_by_key(most_at_risk_stations, 1, True) return sorted_most_at_risk_stations[:N]
true
fd5982d54adcca536876f48003c814f73ea227f6
G3Code-CS/Algorithms
/making_change/making_change.py
2,643
4.375
4
#!/usr/bin/python import sys def making_change(amount, denominations): # we can initialize a cache as a list (a dictionary # would work fine as well) of 0s with a length equal to the amount we're # looking to make change for. cache = [0] * (amount + 1) # Since we know there is one way to # make 0 cents in change, we'll initialize `cache[0] = 1` cache[0] = 1 # Now that we've initialized our cache, we'll start building it up. We have an # initial value in our cache, so we'll want to build up subsequent answers in # terms of this initial value. So, for a given coin, we can loop through all of # the higher amounts between our coin and the amount (i.e., `for higher_amount # in range(coin, amount + 1)`). If we take the difference between the higher # amount and the value of our coin, we can start building up the values in our # cache. # To go into a little more detail, let's walk through a small example. If we # imagine our coin is a penny, in the first loop iteration, `higher_amount` is # going to be 1 (since it will at first be the same value as our coin). If we # take the difference between `higher_amount` and our coin value, we get 0. We # already have a value for 0 in our cache; it's 1. So now we've just figured # out 1 way to 1 cent from a penny. Add that answer to our cache. # Next up, on the next iteration, `higher_amount` will now be 2. The difference # between `higher_amount` and our coin value now is 1. Well we just figured out # an answer for 1, so now we have an answer for 2. Add that to our cache. # Once this loop finishes, we'll have figured out all of the ways to make # different amounts using the current coin. At that point, all we have to do is # perform that loop for every single coin, and then return the answer in our # cache for the original amount! for coin in denominations: for higher_amount in range(coin, amount+1): coin_value = higher_amount - coin cache[higher_amount] += cache[coin_value] return cache[amount] # print(making_change(10, [1, 5, 10, 25, 50])) if __name__ == "__main__": # Test our your implementation from the command line # with `python making_change.py [amount]` with different amounts if len(sys.argv) > 1: denominations = [1, 5, 10, 25, 50] amount = int(sys.argv[1]) print("There are {ways} ways to make {amount} cents.".format(ways=making_change(amount, denominations), amount=amount)) else: print("Usage: making_change.py [amount]")
true
8bbdb6e9157642e89e718d51a76f674d5fa177be
ethirajmanoj/Python-14-6-exercise
/14-quiz.py
1,062
4.1875
4
# Create a question class # Read the file `data/quiz.csv` to create a list of questions # Randomly choose 10 question # For each question display it in the following format followed by a prompt for answer """ <Question text> 1. Option 1 2. Option 2 3. Option 3 4. Option 4 Answer :: """ import csv score = 0 score = int(score) f = open("quiz.csv",'r') d=csv.reader(f) next(f) #To Skip Header Row k = 0 adm = str(input("")) for row in d: if str(row[0])==adm: print("Que:= ", row[1]) print("01 = ", row[2]) print("02 = ", row[3]) print("03 = ", row[4]) print("04 = ", row[5]) #print("Key = ", row[6]) answer = input("Key: ") if answer ==str(row[6]): print("Correct!") score = score + 1 else: print("Incorrect, Correct Answer is " + str(row[6])) print("Your current score is " + str(score) + " out of 10") # Keep score for all right and wrong answer # Take an extra step and output the correct answer for all wrong answers at the end
true
b9c7eee17e69a1836d0cbf817509a874ebe5514f
nsvir/todo
/src/model/list_todo.py
1,158
4.125
4
class ListTodo: """ List Todo contains name Initialize an empty list lst = ListTodo() To get list >>> lst.list() [] To add element in list lst.add_list(TaskList()) To check if element is contained in list lst.contains_list(TaskList()) True """ def __init__(self): self.__lst = [] def list(self) : return self.__lst def contains_list(self, tasklist): for listt in self.__lst: if listt.name() == tasklist.name(): return True return False def contains_list_by_name(self, listname): for listt in self.__lst: if listt.name() == listname: return True return False def add_list(self, taskList): self.__lst.append(taskList) def get_list(self, namelist): for listt in self.__lst: if listt.name() == namelist: return listt return None def remove_list(self, namelist): newlst = [] for lst in self.__lst: if lst.name() != namelist: newlst.append(lst) self.__lst = newlst
true
d306f43d54d0a2713bc23a714a949af59714e9f4
Yosolita1978/Google-Basic-Python-Exercises
/basic/wordcount.py
2,898
4.34375
4
"""Wordcount exercise Google's Python class 1. For the --count flag, implement a print_words(filename) function that counts how often each word appears in the text and prints: word1 count1 word2 count2 ... Print the above list in order sorted by word (python will sort punctuation to come before letters -- that's fine). Store all the words as lowercase, so 'The' and 'the' count as the same word. 2. For the --topcount flag, implement a print_top(filename) which is similar to print_words() but which prints just the top 20 most common words sorted so the most common word is first, then the next most common, and so on. Use str.split() (no arguments) to split on all whitespace. Workflow: don't build the whole program at once. Get it to an intermediate milestone and print your data structure and sys.exit(0). When that's working, try for the next milestone. Optional: define a helper function to avoid code duplication inside print_words() and print_top(). """ def process_file(filename): with open(filename, "rU") as my_file: my_file_list = my_file.readlines() return my_file_list def count_words(file_list): words_count = {} for phrase in file_list: lower_phrase = phrase.lower().split() for word in lower_phrase: if word not in words_count: words_count[word] = 1 else: words_count[word] +=1 return words_count def print_sorted(dic): for key in sorted(dic.keys()): print key , ":" , dic[key] def top_count(dic): def count(key): return dic[key] top = sorted(dic, key=count, reverse= True) for key in top[:20]: print key, dic[key] def menu_gral(): menu = (""" Hello There! What file do you want to process: 1. Small 2. Alice 3. Exit """) option = raw_input(menu) return option def menu_file(): menu = (""" What do you want to do with this file: 1. Count words: 2. Count top words 3. Return gral menu """) option = raw_input(menu) return option def main(): user_choice = menu_gral() while True: if user_choice == "1": my_file_small = process_file("/Users/cristina/source/google-python-exercises/basic/small.txt") dictionary_small = count_words(my_file_small) question = menu_file() if question == "1": print_sorted(dictionary_small) elif question == "2": top_count(dictionary_small) else: user_choice = menu_gral() elif user_choice == "2": my_file_alice = process_file("/Users/cristina/source/google-python-exercises/basic/alice.txt") dictionary_alice = count_words(my_file_alice) question = menu_file() if question == "1": print_sorted(dictionary_alice) elif question == "2": top_count(dictionary_alice) else: user_choice = menu_gral() else: break if __name__ == '__main__': main()
true
9368e573f0bd816c214165e71571bccfed73076d
ThomasP1234/DofE
/Week 2/GlobalVariables.py
527
4.125
4
# Global Variables and Scope # ref: https://www.w3schools.com/python/ # Author: Thomas Preston x = "awesome" # When this is commented out there is an error because the final print doesn't know what x is def myfunc(): x = "fantastic" # Where as when this is commented out, the global x is printed print("Python is " + x) myfunc() print("Python is " + x) # You can add a variable to the global scope using the global keyword def func(): global y y = "super" print("Python is " + y) func() print ("Python is " + y)
true
95f146d5bd21e8f40343ea95c4f7e8f7ea0da0f8
ThomasP1234/DofE
/Week 5/WhileLoops.py
410
4.21875
4
# One of the primary loops in python # ref: https://www.w3schools.com/python/ # Author: Thomas Preston a = 1 while a < 10: print(a) a = a + 1 # Adds 1 to a each loop b = 1 while b < 6: print(b) if b == 3: break b += 1 c = 0 while c < 6: c += 1 if c == 3: continue print(c) # skips this step when c = 3 d = 1 while d < 10: print(d) d = d + 1 else: print('d is not long < 10')
true
9fba4c0eb7046f9b22e1f3a83e0752c961fedcd4
Yfaye/AlgorithmPractice
/python/InsertInterval.py
1,756
4.25
4
# Insert Interval # Description # Given a non-overlapping interval list which is sorted by start point. # Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary). # Example # Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]]. # Insert [3, 4] into [[1,2], [5,9]], we get [[1,2], [3,4], [5,9]]. # Tags # Basic Implementation LinkedIn Google # Related Problems # Easy Merge Intervals 20 % # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ intervals.append(newInterval) sortedIntervals = sorted(intervals, key = lambda x: (x.start, x.end)) i = 0 while i < len(sortedIntervals) - 1: # 总是忘记这里的range是 i < length - 1, 因为下面都要检查到i+1 if (sortedIntervals[i].end >= sortedIntervals[i+1].end): del sortedIntervals[i+1] elif (sortedIntervals[i].end < sortedIntervals[i+1].end and sortedIntervals[i].end >= sortedIntervals[i+1].start): sortedIntervals[i].end = sortedIntervals[i+1].end del sortedIntervals[i+1] else: i += 1 return sortedIntervals # 这题跟merge Intervals 是完全一样的一道题,就是多一个append操作。但是如果一开始出的是这一道题,就比merge 更难想到一些...... # 这两题自己都用的是排序好后删除的做法,下次要试一下用一个空数组然后生成的方法
true
bb711f3653e9dd1ae3f3a88d75a2fd038df612dc
vanctate/Computer-Science-Coursework
/CSCI-3800-Advanced-Programming/HW03/Problem1_Python/piece.py
1,365
4.1875
4
# Patrick Tate # CSCI 3800 HW03 | Problem 1 # class to represent a black or white piece to be inserted into an Othello gameboard # piece has a color(B/w), and a row and column in array notation, to be used with the Grid class class Piece: # subtract 1 from row and column for array notation def __init__(self, color, row, column): self.__color = color # char value 'B' or 'W' self.__row = row - 1 self.__column = column - 1 def setRow(self, row): self.__row = row def setColumn(self, column): self.__column = column def getRow(self): return self.__row def getColumn(self): return self.__column def getColor(self): return self.__color # used in the Grid class when a valid move flips the colors of the trapped pieces def getOppositeColor(self): if self.__color == 'B': return 'W' elif self.__color == 'W': return 'B' else: print("*** Error: Invalid color values ***") return 'E' # used in the Grid class when a valid move flips the colors of the trapped pieces def flipColor(self): if self.__color == 'B': self.__color = 'W' elif self.__color == 'W': self.__color = 'B' else: print("*** Error: Invalid color values ***")
true
89a568f79f10a3bf0370d01f195813475979832a
akeeton/leetcode-python
/0283-move-zeroes.py
1,676
4.1875
4
""" Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. """ class Solution: @staticmethod def bubble_sort_zeroes(nums): is_sorted = False while not is_sorted: is_sorted = True for left in range(len(nums) - 1): right = left + 1 if nums[left] == 0 and nums[right] != 0: nums[left], nums[right] = nums[right], nums[left] is_sorted = False @staticmethod def insertion_sort_zeroes(nums): index_first_sorted_zero = None for index_unsorted in range(len(nums)): if nums[index_unsorted] == 0: if index_first_sorted_zero is None: index_first_sorted_zero = index_unsorted continue if index_unsorted == 0 or index_first_sorted_zero is None: continue nums[index_first_sorted_zero] = nums[index_unsorted] nums[index_unsorted] = 0 index_first_sorted_zero += 1 def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ # Solution.bubble_sort_zeroes(nums) Solution.insertion_sort_zeroes(nums) def main(): sol = Solution() nums_a = [0, 1, 0, 3, 12] sol.moveZeroes(nums_a) print(nums_a) if __name__ == '__main__': main()
true
2319f0735e3516b43da4890f2682fc9d9055868f
harekrushnas/python_practice
/guess_the_number.py
1,513
4.21875
4
#The program will first randomly generate a number unknown to the user. The user needs to guess what that number is. # Reference link : https://knightlab.northwestern.edu/2014/06/05/five-mini-programming-projects-for-the-python-beginner/ import random #from colorama import* ran = random.randint(0,1000) #len1=len(str(abs(ran))) #print(ran,len1) below_ran=random.randint(ran-5,ran) above_ran=random.randint(ran,ran+5) #print(ran) print('Guess the number is in range of : ',below_ran,' and ',above_ran) print('Provied your number below line and you have 3 chances in your hand ') print('--------------------------------------------------------------------') for i in range(3): user_number = input(('PLEASE ENTER YOUR NUMBER :')) #print (i) if ran == int(user_number): print('Congrats....your guess is correct....NUMBER=', ran) break else: if i == 2: print('Ohh...U missed all the chances....','\n You Lose the game', '\n thanks for playing the game... ') chk_no=input('Do you want to see the Actual Number ? Y/N :') if chk_no=='Y' or chk_no=='y': print ('The actual no is : ',ran) else: print('Thank u...') else: #print('Ohhh....Your guess is incorrect.......don\'t worry you have ',Fore.RED + 2-i +Style.RESET_ALL , 'chance left') print('Ohhh....Your guess is incorrect.......don\'t worry you have ', 2 - i ,'chance left')
true
de3da113c7e0bbc9f73c2f2182539b2b0bb266c6
frankPairs/head-first-python-exercises
/chapter_4_functions_modules/vsearch_set.py
235
4.1875
4
def search_for_vowels(word: str) -> set: """Returns any vowels found in a supplied word""" vowels = set('aeiou') return vowels.intersection(set(word)) print(search_for_vowels("francisco")) print(search_for_vowels("sky"))
true
65268b86a2ed7ddfbf5f59db5e5b86577d3b9363
jeffkwiat/minesweeper
/app.py
2,961
4.125
4
import random class Minesweeper(object): """ Implementing a simple Minesweeper board. """ def __init__(self, width, height, number_of_mines): self.width = width self.height = height self.number_of_mines = number_of_mines self.board = self.generate_board() self.flag_cells() def get_coordinates(self): """ Get coordinates for this board. """ coordinates = [] for x in range(self.height): for y in range(self.width): coordinates.append((x, y)) return coordinates def generate_board(self): """ Build out the initial board. """ # Generate the initial board with 0s. board = [[0 for x in range(self.width)] for y in range(self.height)] # Set up the mines and surrounding counts. mines = random.sample(self.get_coordinates(), self.number_of_mines) for x, y in mines: board[x][y] = '*' return board def __repr__(self): """ Print the object representation to the screen. """ return "<Minesweeper width:%s height:%s number_of_mines:%s>" % \ (self.width, self.height, self.number_of_mines) def __str__(self): """ Print the board to the console. """ result = "" for row in self.board: result += ''.join([str(x) for x in row]) + '\n' return result def count_mines(self): """ Count the number of mines currently on the board. """ count = 0 for row in self.board: for cell in row: if cell == '*': count += 1 return count def _is_on_board(self, coordinate): """ Return True if the coordinate is on the board. Else, False. """ x, y = coordinate if (x >= 0 and x < len(self.board)) and (y >= 0 and y < len(self.board)): return True return False def get_surrounding_cells(self, coord): """ Return the surrounding (x, y) coords. """ surrounding = [] for x in range(coord[0] - 1, coord[0] + 2): for y in range(coord[1] - 1, coord[1] + 2): # Skip the current cell if (x, y) == coord: continue try: # If the surrounding coord is on the board, add it. if self._is_on_board((x, y)): surrounding.append((x, y)) except: print('trying to access: %s, %s' % (x, y)) print(self) return surrounding def flag_cells(self): """ Setup counts for all surrounding cells. """ for coordinate in self.get_coordinates(): for cell in self.get_surrounding_cells(coordinate): if self.board[cell[0]][cell[1]] == '*': continue self.board[cell[0]][cell[1]] += 1
true
53e9e59370cad6cfcf69c3219783070f35df4f81
GauravR31/Solutions
/Classes/Flower_shop.py
1,883
4.15625
4
class Flower(object): """docstring for ClassName""" def __init__(self, f_type, rate, quantity): self.type = f_type self.rate = rate self.quantity = quantity class Bouquet(object): """docstring for ClassName""" def __init__(self, name): self.name = name self.flowers = [] def add_flower(self): f_type = raw_input("Enter the flower type(Rose, Lily, Lotus, Daisy) ") if f_type == "Rose": f_quantity = input("Enter the flower quantity ") f = Flower(f_type, 10, f_quantity) elif f_type == "Lily": f_quantity = input("Enter the flower quantity ") f = Flower(f_type, 8, f_quantity) elif f_type == "Lotus": f_quantity = input("Enter the flower quantity ") f = Flower(f_type, 7, f_quantity) elif f_type == "Daisy": f_quantity = input("Enter the flower quantity ") f = Flower(f_type, 9, f_quantity) else: print("Invalid flower type") self.flowers.append(f) def update_flower(self): flag = 0 f_type = raw_input("Enter the flower type to remove ") for i in range(0, len(self.flowers)): if self.flowers[i].type == f_type: f_quantity = input("Enter the new quantity(0 for none) ") flag = 1 self.flowers[i].quantity = f_quantity if flag == 0: print("Flower not found") def bouquet_details(self): cost = 0 for f in self.flowers: print("Type : {}\nRate : {}\nQuantity : {}\n".format(f.type, f.rate, f.quantity)) cost += (f.rate * f.quantity) print("Total cost of the bouquet is {}".format(cost)) def main(): b = Bouquet("Bouquet1") while True: print("1. Add flower\n2. Update or remove flower\n3. Bouquet details\n4. Exit") ch = input("Enter your choice ") if ch == 1: b.add_flower() elif ch == 2: b.update_flower() elif ch == 3: b.bouquet_details() elif ch == 4: break else: print("Invalid choice.") if __name__ == '__main__': main()
true
ce97aff7408d5808d33756c8bb72e2910bbe77a4
ngrq123/learn-python-3-the-hard-way
/pythonhardway/ex30.py
732
4.34375
4
# Initialise people to 30 people = 30 # Initialise cars to 40 cars = 40 # Initialise buses to 15 buses = 15 # If there are more cars then people if cars > people: print("We should take the cars.") # Else if there are less cars then people elif cars < people: print("We should not take the cars.") else: print("We can't decide.") # If there are more buses than cars if buses > cars: print("That's too many buses.") # Else if there are less buses than cars elif buses < cars: print("Maybe we could take the buses.") else: print("We still can't decide.") # If there are more people than buses if people > buses: print("Alright, let's just take the buses.") else: print("Fine, let's stay home then.")
true
d61c6db3c3889e24794719d0d8e7c9a4c6a3732e
dkahuna/basicPython
/Projects/calcProgram.py
241
4.5
4
# Calculating the area of a circle radius = input('Enter the radius of your circle (m): ') area = 3.142 * int(radius)**2 # int() function is used to convert the user's input from string to integer print('The area of your circle is:', area)
true
5dbf3b63d6bb744d4a02aba9f41acd9ad64372c2
dkahuna/basicPython
/FCC/ex_09/ex_09.py
714
4.15625
4
fname = input('Enter file name: ') if len(fname) < 1 : fname = 'clown.txt' hand = open(fname) di = dict() #making an empty dictionary for line in hand : line = line.rstrip() #this line strips the white space on the right side per line of the file words = line.split() #this line splits the text file into an array # print(words) for wds in words: # idiom: retrieve/create/update counter di[wds] = di.get(wds,0) + 1 # print(di) #now to find the most common word largest = -1 theWord = None for k,v in di.items() : if v > largest : largest = v theWord = k #capture and remember the largest 'key' print('The most common word used is:', theWord, largest)
true
ecfe7da8cee6b57ab65108992a3c333f2e0dc283
RustingSword/adventofcode
/2020/01/sol2.py
315
4.125
4
#!/usr/bin/env python3 def find_triple(nums, target=2020): for first in nums: for second in nums: if (third := target - first - second) in nums: return first * second * third if __name__ == "__main__": nums = set(map(int, open("input"))) print(find_triple(nums))
true
7f5f33b40f1a8d3acc72c889bef1accf9432abb7
rubenvdham/Project-Euler
/euler009/__main__.py
833
4.4375
4
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ def find_triplet_with_sum_of(number): sum = number number = int(number/2) for a in range(1,number): for b in range (a,number): for c in range(b,number): if (a**2 +b**2) == c**2: if a+b+c == sum: return a,b,c def multiply(list): answer = 1 for i in range (0,len(list)): answer*=result[i] return answer if __name__ == '__main__': result = find_triplet_with_sum_of(1000) print("Triplet %s %s %s"%(result[0],result[1],result[2])) print("product:%s"%(multiply(result)))
true
156ce2abce7f089a563208dd1947eb0276c00a20
romeoalpharomeo/Python
/fundamentals/fundamentals/rock_paper_scissors.py
1,670
4.5
4
""" Build and application when both a user and computer can select either Rock, Paper or Scissors, determine the winner, and display the results For reference: Rock beats Scissors Scissors beats Paper Paper beats Rock Part I Compare user input agains computer choice and determine a winner Part II Compare user input agains computer choice and determine a winner. The winner will be the best 5 games, and end as soon at someone wins 3 games. """ player_win_count = 0 computer_win_count = 0 while player_win_count < 3 or computer_win_count < 3: import random computer_options = ['Rock', 'Paper', 'Scissors'] computer_choice = random.choice(computer_options) player_choice = input('Rock, paper, scissors, shoot!: ') if player_choice == computer_choice: print("TIE!") elif player_choice == "Rock": if computer_choice == "Scissors": print("Player wins!") player_win_count += 1 else: print("Player loses.") computer_win_count += 1 elif player_choice == "Paper": if computer_choice == "Rock": print("Player wins!") player_win_count += 1 else: print("Player loses.") computer_win_count += 1 elif player_choice == "Scissors": if computer_choice == "Paper": print("Player wins!") player_win_count += 1 else: print("Player loses.") computer_win_count += 1 if player_win_count > computer_win_count: print('Player won the game!') else: print('Computer won the game.')
true
0e792822cb1faeda92a0c0fec8bb86901c40aa09
anmolrajaroraa/CorePythonBatch
/largest-among-three.py
1,385
4.46875
4
# num1, num2, num3 = 12, 34, 45 # if (num1 > num2) and (num1 > num3): # print("The largest between {0}, {1}, {2} is {0}".format(num1, num2, num3)) # elif (num2 > num1) and (num2 > num3): # print("The largest between {0}, {1}, {2} is {1}".format(num1, num2, num3)) # else: # print("The largest between {1}, {2}, {0} is {0}".format(num3, num1, num2)) num1, num2, num3 = 12, 34, 45 if (num1 > num2) and (num1 > num3): largest = num1 elif (num2 > num1) and (num2 > num3): largest = num2 else: largest = num3 print("The largest between {}, {}, {} is {}".format(num1, num2, num3, largest)) # num1, num2, num3 = input("1st: "), input("2nd: "), input("3rd: ") # print(num1, num2, num3) # numbers = input("Enter three numbers separated by a blank space: ") # num1, num2, num3 = numbers.split() # print("num1 is {}, num2 is {}, num3 is {}".format(num1, num2, num3)) ''' 1. if-elif-else block 2. reduce repeating code as much as possible 3. 2 ways of printing strings using format() - stating variables in order print("The largest between {}, {}, {} is {}".format(num1, num2, num3, largest)) - stating indexes of variables between curly braces print("The largest between {1}, {2}, {0} is {0}".format(num3, num1, num2)) 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 nterms = 10 a = 0 b = 1 count = 2 while count < nterms: code 0 1 1 2 3 5 8 13 21 34 '''
true
5a38d95fe9db58447d65605ddfef48559e6ae689
angjerden/kattis
/pizza_crust/pizza_crust.py
845
4.1875
4
''' George has bought a pizza. George loves cheese. George thinks the pizza does not have enough cheese. George gets angry. George’s pizza is round, and has a radius of R cm. The outermost C cm is crust, and does not have cheese. What percent of George’s pizza has cheese? Input Each test case consists of a single line with two space separated integers, R and C . Output For each test case, output the percentage of the pizza that has cheese. Your answer must have an absolute or relative error of at most 10^6. . Limits 1≤C≤R≤100 ''' from sys import stdin import math line = stdin.readline() line = line.split(' ') r = int(line[0]) c = int(line[1]) r_cheese = r - c area = math.pi * math.pow(r, 2) area_cheese = math.pi * math.pow(r_cheese, 2) percent_not_cheese = (area_cheese / area) * 100 print(percent_not_cheese)
true
1e0e9f789c65d252092168bbf9d90f89092f0c17
maryade/Personal-Learning-Python
/Udemy Python Practice programming Module 3.py
918
4.46875
4
# # Addition # print(5+3) # # # Subtraction # print(11-4) # # # multiplication # print(22*5) # # # division # print(6/3) # # # modulo # print(9%5) # # # exponents # print(2^4) # print(6**2) # # # return integer instead of floating number # print(11//5) # print(451//5) # assignment operation x = 18 # print(x) # to increase by 2 use # x+=2 #x + 2 = 20 # print(x) # to decrease by 2 use # x-=2 #x - 2 = 16 # print(x) # to multiply by 2 use # x*=2 #x * 2 = 36 # print(x) # to divide by 2 use # x/=2 #x % 2 = 9 # print(x) # combining the operators # print( 3 + 4 -13 * (2+20) + 6 /2) # boolean # print(5==4) # print(10==10) # print(10!=4) # print(4!=4) # print(66>12) # print(78>=77) # print(True and True) # print(1==1 and 2==4) # print(1==1 or 2==3) # print(True and False) # print(True or False) # x=10 # y = 10 # print(x is y) # print(x is not y) y = [1,4,6,7] x = 1 print(x in y) print(x not in y)
true
d064c635389f767606f56ae246d695d7b1af6ecf
kevindsteeleii/HackerRank_InterviewPreparationKit
/00_WarmUpChallenges/jumpingOnClouds_2019_02_20.py
1,712
4.28125
4
""" Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game. For each game, Emma will get an array of clouds numbered 0 if they are safe or 1 if they must be avoided. For example, c = [0,1,0,0,0,1,0] indexed from 0...6. The number on each cloud is its index in the list so she must avoid the clouds at indexes 1 and 5. She could follow the following two paths: 0->2->4->6 or 0->2->3->4->6. he first path takes 3 jumps while the second takes 4. Function Description Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer. jumpingOnClouds has the following parameter(s): c: an array of binary integers Input Format The first line contains an integer (n),the total number of clouds. The second line contains (n) space-separated binary integers describing clouds ( c[i] ) where 0 <= i <= n. Constraints * 2 <= n <= 100 * c[i] /in {0,1} * c[0] = c[n-1] = 0 """ def jumpingOnClouds(c): i = 0 jumps = 0 while i < len(c)-1: # print(jumps) try: if c[i+2] == 0 or c[i+1] == 0: i = i + 2 if c[i+2] == 0 else i + 1 jumps += 1 except: jumps += 1 break return jumps if __name__ == '__main__': print(jumpingOnClouds([0,1,0,1,0]))
true
0915df88be07251462464e301bec6535ac91626d
tarjantamas/Virtual-Controller-CNN
/src/common/util.py
1,590
4.5625
5
def getArgumentParameterMap(argv): ''' Maps arguments to their list of parameters. :param argv: list of arguments from the command line :return: a map which maps argument names to their parameters. If the program is run in the following way: python main.py --capturedata param1 param2 param3 --othercommand param1 param2 the return value will be: { '--capturedata': ['param1', 'param2', 'param3'] '--othercomand': ['param1', 'param2'] } ''' argumentParameterMap = {} i = 0 while i < len(argv): arg = argv[i] j = i + 1 if '--' in arg: params = [] while j < len(argv) and '--' not in argv[j]: params.append(argv[j]) j += 1 argumentParameterMap[arg] = params i = j return argumentParameterMap def callWithParameters(function, params): function(*params) def isHigherThan(s1, s2): ''' If s1 and s2 are base N string representations of numbers then this function behaves as a comparator. :input s1: string to be compared :input s2: string to be compared :return: Returns True if s1's length is higher than s2's without scanning each character. Returns False if s1's length is lower than s2's without scanning each character. In other cases it compares the characters at each position of s1 and s2 until a position 'i' comes up where s1[i] > s2[i] at which point it returns True. Returns False if no such position comes up. ''' if len(s1) > len(s2): return True if len(s1) < len(s2): return False for i, j in zip(s1, s2): if i > j: return True return False
true
0cb1eb4245d4d82b15e885ab5b7374b0c419e6e0
epc0037/URI-CS
/CSC110/Python Lists/HW3/problem1.py
878
4.40625
4
# Evan Carnevale # CSC 110 - Survey of Computer Science # Professor Albluwi # Homework 3 - Problem 1 # This program will generate a list containing # all the odd numbers between 100 and 500 except 227 and 355. # create an empty number list & set the values we wish to remove from the list numList = [] a = 227 b = 355 # for loop that goes from 100 to 500 (501 because it doesn't include the last value) # if i in the range 100 to 500 has a remainder when divided by 2, i is added to the list # the last statements are nested if statements which remove the values 227 and 355 from our list for i in range(100,501): if i % 2 != 0: numList = numList + [i] if a in numList: numList.remove(a) if b in numList: numList.remove(b) # final output that prints the list to the user, except 227 and 355 print(numList)
true
2869a4a804531ff82b8957a250082d0eaecfdd07
epc0037/URI-CS
/CSC110/Python Functions/HW4/stocks.py
2,179
4.25
4
# Evan Carnevale # CSC 110 - Survey of Computer Science # Professor Albluwi # Homework 4 - Problem 1 # This program will get create two lists for stock names and prices, # which will be entered by the user using a loop. I will utilize 3 functions: # the main function, the searchStock function and the printStock function. def main(): # Create two empty lists for stock names and prices stockNames = [] stockPrices = [] # variable to control the loop end = "continue" while end != "done": #Get the stock name and prices name = str(input("Enter the stock name you wish to add to the list: ")) price = int(input("Enter the price of the stock you added to the list: ")) print("\n") # Append the name and prices to the lists stockNames.append(name) stockPrices.append(price) # Prompt the user to continue the loop print("If you wish to stop adding stocks, enter 'done' ") end = str(input("Type 'continue' to add more stocks: ")) print("\n") # Prompt the user to find a stock with its corresponding price in the list using functions s = str(input("Enter a stock name you wish to search for in order to see which stocks are higher: ")) p = searchStock(s, stockNames, stockPrices) printStock(p, stockNames, stockPrices) # Function that returns the price of the searched stock # I found an issue here at first in my code. I had an if-else statement # but I realized I did not need the else, rather to just pull out the return # and keep the indent even with the for loop. This seemed to solve my issue with # the loop because it would return -1 when I wanted it to return the price from # the stockPrices list. def searchStock(s, stockNames, stockPrices): for i in range(len(stockNames)): if stockNames[i] == s: return stockPrices[i] return -1 # Function that prints all the stocks above the value of the searched stock def printStock(p, stockNames, stockPrices): for i in range(len(stockPrices)): if stockPrices[i] > p: print(stockNames[i]) else: print() main()
true
1f97e7a5f66552f012f3c95e05152ac9f9747640
epc0037/URI-CS
/CSC110/Python Basics/HW2/problem3.py
404
4.375
4
#Evan Carnevale #CSC 110 - Survey of Computer Science #Professor Albluwi #Homework 2 - Problem 3 TOTAL_BUGS = 0 DAYS = 1 while DAYS <= 7: print("Day", DAYS, ": Did you collect a lot of bugs today?") today_bug = int(input("Enter the number of bugs collected today")) TOTAL_BUGS += today_bug DAYS +=1 print('\n') print("The total number of bugs collected in the week:", TOTAL_BUGS, "bugs.")
true
db0c5a43933e5f1a257eaca2e3003a3a3cd7a40d
Nathansbud/Wyzdom
/Students/Suraj/quiz.py
513
4.125
4
students = ["Jim", "John", "Jack", "Jacob", "Joseph"] grades = [] for student in students: passed = False while not passed: try: grade = float(input(f"Input a quiz grade for {student} (0-100): ")) if not 0 <= grade <= 100: raise ValueError() grades.append(grade) passed = True except ValueError: print("Grade must be a number between 0-100") print(f"Max: {max(grades)} - Min: {min(grades)} - Avg: {sum(grades) / len(grades)}")
true
49f9fe9f6f2e695223c8c73ed60d7dc01a41d0ff
rajdharmkar/Python2.7
/sortwordsinalbetorder1.py
527
4.53125
5
my_str = input("Enter a string: ") # breakdown the string into a list of words words = my_str.split()# here separator is a space between words print words # sort the list words.sort() # display the sorted words for word in words: print(word) my_str = input("Enter a string with words separated by semicolon: ") words = my_str.split(';')# here separator is a semicolon between words print words # sort the list words.sort() # display the sorted words for word in words: print(word)
true
17e86708d5b2a0476756c63ab8d0cd12a77eba92
rajdharmkar/Python2.7
/initmethd1.py
1,676
4.625
5
class Human: # def __init__(self): pass # init method initializing instance variables # # def __str__(): pass # ?? # # def __del__(self): pass # ??...these three def statements commented out using code>> comment with line comment..toggles def __init__(self, name, age, gender): # self means object in the init method inline comment example # type: (object, object, object) -> object self.name = name # creating and assigning new variable self.age = age self.gender = gender def speak_name(self): # a method defined here with a print statement to execute as well print "my name is %s" % self.name def speak(self, text): # def speak(text):; without self, we get nameerror...speaks take exactly one argument given two given; gave one arg but self is implied so two counted as given print text def perform_math(self, operation, *args): print "%s performed math and the result was %f" % (self.name, operation(*args)) def add(a, b):#this is an example of function not an object method and is callable everywhere return a + b rhea = Human('Rhea', 20, 'female') bill = Human('William', '24', 'male') # creating new object 'bill' which is an instance of class Human with variables assignment as well # getting saying bill is not defined print bill.name print bill.age print bill.gender bill.speak_name() bill.speak("Love") rhea.perform_math(add, 34,45) # method speak_name belongs to object 'bill' here; a method call? # method diff from function and it can be called only from the object and it bound to the class
true
53ebcd324577f722da9407c61ea2adf9dc66bed1
rajdharmkar/Python2.7
/math/fibo.py
1,296
4.28125
4
# Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, # comma in print statement acts like NOT newline , all numbers are printed in one line..a row of numbers # without comma or anything everytime there is a new line; we get a column of numbers a, b = b, a+ b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a + b return result # Executing modules as scripts # ---------------------------- # # When you run a Python module with :: # # python fibo.py <arguments> # # the code in the module will be executed, just as if you imported it, but with # the ``__name__`` set to ``"__main__"``. That means that by adding this code at # the end of your module:: if __name__ == "__main__": import sys fib ( int ( sys.argv[ 1 ] ) ) # you can make the file usable as a script as well as an importable module, # because the code that parses the command line only runs if the module is # executed as the "main" file:: # # $ python fibo.py 50 # 1 1 2 3 5 8 13 21 34 # If the module is imported, the code is not run:: # # >>> import fibo # >>>
true
16c0d9db5c7237b6f7dace39bdaf2b949d0b070e
rajdharmkar/Python2.7
/assertXpl2.py
2,214
4.40625
4
class B: # class declaration with keyword class, class object B created # class object; instance object; function object; method object x = 10 # this is a class attribute def __init__(self, name): # this is a __init__ method, also called a constructor that initializes default values of instance # attributes ; self refers to the instance object self.name = name '''B.x is a class attribute''' @property # using property decorator...property is a special kind of class attribute? def foo(self): # this is a declaration of instance method? """ B.x is a property This is the getter method """ print self.x #@bar.setter def bar(self, value): """ This is the setter method where we can check if it's not assigned a value < 0 """ if value < 0: raise ValueError("Must be >= 0") self.x = value b = B('harris')# creation or instantiation of class into a instance object with parentheses after classname like function call print b.name # accessing and printing an instance attribute print B.x # accessing and printing an class attribute print b.x # accessing a class attribute from instance? print B.__dict__ # prints dictionary of class attributes #print B.__dict() print b.__dict__# prints dictionary of instance attributes #print(b.foo()); foo not callable? print b.foo # no need for parentheses for b.foo prints self.x which is obj.x = 10 and None? #print b.bar(); parentheses cant be empty and unfilled; takes 1 arg print b.bar(100)# returning None yes and 100 assigned to self.x or obj.x or b.x so print b.x prints 100 print b.x #b.bar(-1)# raises valueError print b.bar(-1) # raises no valueError...print statement without parentheses print (b.bar(-1))# raises valueError #b.x = -1 # Traceback (most recent call last): # File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/assertXpl2.py", line 22, in <module> # b.x = -1 # File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/assertXpl2.py", line 19, in x # raise ValueError("Must be >= 0") # ValueError: Must be >= 0
true
b20e8e5fc85924d740d9c0ea38f22e43fecf3147
rajdharmkar/Python2.7
/continueeX.py
486
4.34375
4
for val in "string": if val == "i": continue print(val), print("The end") #The continue statement is used to skip the rest of the code inside a loop for #the current iteration only. Loop does not terminate but continues on with the #next iteration. #Syntax of Continue #continue #We continue with the loop, if the string is "i", not executing the rest of #the block. Hence, we see in our output that all the letters except "i" gets #printed.
true
13bcc351d18826e483b62b4a7eb9e94f85cdb0c6
rajdharmkar/Python2.7
/Exception handling/NameError3.py
684
4.5
4
s = raw_input('Enter a string:') # raw_input always returns a string whether 'foo'/foo/78/'78' # n =int(raw_input(prompt))); this converts the input to an integer n = input("Enter a number/'string':")# this takes only numbers and 'strings'; srings throw errors ..it also evaluates if any numeric expression is given p = input('Enter any numeric expression:')# if you enter for example 3+7*6 on prompt, input returns 45 print s print n print p print (type(s)) print (type(n)) print(type(n)) # getting NameError if in n we input a string without quotes / # wont get ValueError in this script which is getting type right but its value wrong for integer type if we input float
true
d3db4014449d6b02a3c6a99d7101ffc793e87048
rajdharmkar/Python2.7
/usinganyorendswith1.py
583
4.4375
4
#program to check if input string endswith ly, ed, ing or ers needle = raw_input('Enter a string: ') #if needle.endswith('ly') or needle.endswith('ed') or needle.endswith('ing') or needle.endswith('ers'): # print('Is valid') #else: # print('Invalid') if needle in ('ly', 'ed', 'ing', 'ers'):#improper code print('Is valid') else: print ('invalid') if 'ers' in needle:#doesnot mean endswith print('Is valid') else: print('Invalid') if any([needle.endswith(e) for e in ('ly', 'ed', 'ing', 'ers')]): print('Is valid') else: print('Invalid')
true