blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
acdda0fa4bceeaf72b4b94836f606591b7141a6c
joook1710-cmis/joook1710-cmis-cs2
/assignment1.py
2,319
4.3125
4
#Created a variable and defined my name. myName = "Joo Ok Kim" print myName #Created a variable and defined my age. myAge = 16.4 print myAge #Created a variable and defined my height. myHeight = 1.65 print myHeight #Created a variable and defined the length of a sqaure. lengthOfSquare = 4 print lengthOfSquare #Created a variable and defined the length of a rectangle. lengthOfRectangle = 8 print lengthOfRectangle #Created a variable and defined the height of the rectangle. heightOfRectangle = 16 print heightOfRectangle #Created a variable and defined my age in months. monthInYears = 12 myAgeInMonths = monthInYears * myAge print myAgeInMonths #Created a variable and defined the years I would live. yearsToCome = 80 yearsToLive = myAge + yearsToCome print yearsToLive #Created a variable and defined my height in feet. myHeightInFeet = 5.4 print myHeightInFeet #Created a variable and defined the average height of a Korean. koreanFemaleHeight = 1.62 differenceInHeight = myHeight - koreanFemaleHeight print differenceInHeight #Created a variable and defined the area of the square. areaOfSquare = 4 *4 print areaOfSquare #Created a variable and defined half of the cube. halfOfCube = 0.5 * 16 * 4 print halfOfCube #Created a variable and defined the area of the rectangle. areaOfRectangle = lengthOfRectangle * heightOfRectangle print areaOfRectangle #Created a variable and defined one ninth of the area of the rectangle. ninthAreaOfRectangle = 0.11 * areaOfRectangle print ninthAreaOfRectangle #Created a message. print "Hello, it's me, " + myName + "." + " I am " + str(myAge) + " years old. " + " I am " + str(myHeightInFeet) + " feet tall. " + " I am " + str(myHeight) + " tall in meters. " + " Staticstically speaking, I can live up to " + str(yearsToLive) + " years. " #Created another message. print " My age in months is " , str(myAgeInMonths),"." , " Korean female's average height is " , str(koreanFemaleHeight) , " in meters." , " I like squares. The length of the square I created is " , str(lengthOfSquare), "." , " I like rectangles too. The length of the rectangle I created is " , str(lengthOfRectangle),"." , " The area of my rectangle is " , str(areaOfRectangle), "." #Created a varirable and printed the smiley faces. smileyFace = ";)" print smileyFace * int(10000)
true
95e1b9576d1227e9bbe48ad5045c65f55605fb8e
indykiss/DataStructures-Algos
/Leetcode/Python Easies/Anagram_mappings.py
878
4.15625
4
# Find Anagram Mappings # You are given two integer arrays nums1 and nums2 where nums2 is # an anagram of nums1. Both arrays may contain duplicates. # Return an index mapping array mapping from nums1 to nums2 where # mapping[i] = j means the ith element in nums1 appears in nums2 at index j. # If there are multiple answers, return any of them. # An array a is an anagram of an array b means b is made by # randomizing the order of the elements in a. # Input: nums1 = [84,46], nums2 = [84,46] # Output: [0,1] class Solution: def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]: arr = [] dict2 = {} for j in range(len(nums2)): dict2[nums2[j]] = j for i in range(len(nums1)): idx = dict2[nums1[i]] arr.append(idx) return arr
true
efaabae63cbd556d6e1a3d52a1bb39d61a163fab
Zahidsqldba07/codingbat-programming-problems-python
/Solutions/string-2/end_other.py
579
4.1875
4
# Given two strings, return True if either of the strings appears at # the very end of the other string, ignoring upper/lower case differences # (in other words, the computation should not be "case sensitive"). # Note: s.lower() returns the lowercase version of a string. # end_other('Hiabc', 'abc') → True # end_other('AbC', 'HiaBc') → True # end_other('abc', 'abXabc') → True def end_other(a, b): shorter = a.lower() longer = b.lower() if len(a) > len(b): shorter = b.lower() longer = a.lower() return longer[-len(shorter):] == shorter
true
55ea429df48b2ae917a8239f40e1a12acad1179d
yasu094/learning-python
/10-calendars.py
1,139
4.15625
4
import calendar # print a text calendar (week start day is Sunday) c = calendar.TextCalendar(calendar.SUNDAY) str = c.formatmonth(2020, 1, 0, 0) print (str) # create an HTML formatted calendar hc = calendar.HTMLCalendar(calendar.SUNDAY) str = hc.formatmonth(2020, 1) print (str) # loop over the days of a month # zeroes mean that the day of the week is in an overlapping month for i in c.itermonthdays(2020, 2): print (i) # The Calendar module provides useful utilities for the given locale, # such as the names of days and months in both full and abbreviated forms for name in calendar.month_name: print (name) for day in calendar.day_name: print (day) # first Wednesday of every month print ("First Wednesday of the month:") for m in range(1,13): cal = calendar.monthcalendar(2020, m) weekone = cal[0] weektwo = cal[1] if weekone[calendar.WEDNESDAY] != 0: firstwednesday = weekone[calendar.WEDNESDAY] else: # if the first wednesday isn't in the first week, it must be in the second firstwednesday = weektwo[calendar.WEDNESDAY] print ("%10s %2d" % (calendar.month_name[m], firstwednesday))
true
fc74fe344919966935cef5b6eb206e92564af881
nseetim/Hackerrank_challenges
/String_Validators.py
2,562
4.34375
4
''' Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc. str.isalnum() This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9). >>> print 'ab123'.isalnum() True >>> print 'ab123#'.isalnum() False str.isalpha() This method checks if all the characters of a string are alphabetical (a-z and A-Z). >>> print 'abcD'.isalpha() True >>> print 'abcd1'.isalpha() False str.isdigit() This method checks if all the characters of a string are digits (0-9). >>> print '1234'.isdigit() True >>> print '123edsd'.isdigit() False str.islower() This method checks if all the characters of a string are lowercase characters (a-z). >>> print 'abcd123#'.islower() True >>> print 'Abcd123#'.islower() False str.isupper() This method checks if all the characters of a string are uppercase characters (A-Z). >>> print 'ABCD123#'.isupper() True >>> print 'Abcd123#'.isupper() False Task You are given a string . Your task is to find out if the string contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters. Input Format A single line containing a string . Constraints 0 < len(string) < 1000 Output Format In the first line, print True if has any alphanumeric characters. Otherwise, print False. In the second line, print True if has any alphabetical characters. Otherwise, print False. In the third line, print True if has any digits. Otherwise, print False. In the fourth line, print True if has any lowercase characters. Otherwise, print False. In the fifth line, print True if has any uppercase characters. Otherwise, print False. Sample Input qA2 Sample Output True True True True True ''' def get_datatype(user_input_string): print(any(each_character.isalnum() for each_character in user_input_string)) print(any(each_character.isalpha() for each_character in user_input_string)) print(any(each_character.isdigit() for each_character in user_input_string)) print(any(each_character.islower() for each_character in user_input_string)) print(any(each_character.isupper() for each_character in user_input_string)) user_input_string=str(input()) get_datatype(user_input_string) '''For those who who would love a shorter cut, you could use the "eval" method''' user_input=str(input()) For each_test in ("isalnum","isalpha","isdigit","islower", "isupper"): print(any(eval("i."+each_test+"()") for i in user_input))
true
819f06ff47d9843a78fb41d30b6960ab7c77c710
PapaGateau/Python_practicals
/089-Safe_list_get/safe_list_get.py
629
4.15625
4
def recuperer_item(liste, index): """function to get and element form a list using its index incorrect indexes are protected and will return an error string Args: liste ([list]): [list searched] index ([int]): [index of searched element] Returns: [str]: [list element or error string] """ if index > len(liste) - 1 or index < -len(liste): return "Index {} hors de la liste".format(index) else: return liste[index] # liste = ["Julien", "Marie", "Pierre"] # print(recuperer_item(liste, 0)) # print(recuperer_item(liste, 5)) # print(recuperer_item(liste, -13))
true
dcf82c1d994f980388094411e11da0c36af8b939
BhagyashreeKarale/function
/output2.py
1,629
4.28125
4
# def primeorNot(num): # if num > 1:#it will only take numbers more then 1,not even 1 # for i in range(2,num):#all the numbers from 2 to the given number.i.e in this case 406 # if (num % i) == 0: # print(num,"is not a prime number") # print(i,"times",num//i,"is",num) # break#break can be ysed only within a loop # else:#else block is at wrong place # print(num,"is a prime number") # else:#for 1 or less than 1 # print(num,"is not a prime number") # primeorNot(407) # this program will give result based on the respective i # for example: # consider number 9 # we are starting the loop from num 2 # therefore as 9 is not divisible by two, it will print 9 is a prime number,which is False # next i value is 3 # 9 is divisible by 3 # therefore now it will print 9 is not a prime number and we have applied break statement under this block # therefore now the loop will stop # this ain't the correct code def primeorNot(num): if num > 1:#it will only take numbers more then 1,not even 1 406 for i in range (2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") else:#for 1 or less than 1 print(num,"is neither a prime number nor a composite number") primeorNot(407) #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<output>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>># # 407 is not a prime number # 11 times 37 is 407
true
ab111b6810f7652e3f3b52e2eb1934971f8484c9
BhagyashreeKarale/function
/palindrome.py
622
4.375
4
# Write a Python function that checks whether a passed string is palindrome or not. def palindromecheck(string): rlist=(string[::-1]) if rlist == string: print("It is a palidrome") else: print("It isn't a palidrome") # another one for palidrome: def palidromecheck2(string): left_pos = 0 right_pos = len(string) - 1 while right_pos <= left_pos: if string[right_pos] != string[left_pos]: print("It isn't a palidrome") return False left_pos = left_pos + 1 right_pos = right_pos - 1 print("It is a palidrome") return True
true
72871b67dd71410aedb185651c2764a1397aa5f0
DorotaNowak/machine-learning
/simple-linear-regression/simple_linear_regression.py
1,057
4.15625
4
# Simple linear regression import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv('Salary_Data.csv') # print(dataset.head()) X = dataset.iloc[:,:-1].values y = dataset.iloc[:,1].values from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=0) # Fitting Simple Linear Regression to the training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the test set results y_pred = regressor.predict(X_test) # Plots plt.scatter(X_train, y_train, color='red') plt.plot(X_train, regressor.predict(X_train)) plt.title('Salary vs Experience (Training set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show() plt.scatter(X_test, y_test, color='red') plt.plot(X_train, regressor.predict(X_train)) plt.title('Salary vs Experience (Test set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show()
true
b10395a36be87b043ed18ad3973f2ae4eeb955ca
tdominic1186/ATBS
/Chapter 2/question13while.py
214
4.28125
4
""" 13. Write a short program that prints the numbers 1 to 10 using a for loop. Then write an equivalent program that prints the numbers 1 to 10 using a while loop. """ i = 1 while i < 11: print(i) i += 1
true
e168e246982a5e6861163b33e13510592705ae44
adivis/PythonProg
/prob_5.py
1,233
4.1875
4
""" Problem Statement:- You are given few sentences as a list (Python list of sentences). Take a query string as an input from the user. You have to pull out the sentences matching this query inputted by the user in decreasing order of relevance after converting every word in the query and the sentence to lowercase. Most relevant sentence is the one with the maximum number of matching words with the query. Sentences = [“Python is cool”, “python is good”, “python is not python snake”] Input: Please input your query string “Python is” Output: 3 results found: python is not python snake python is good Python is cool """ print("Enter the length of list of sentences") n = int(input()) lst_sen = [] for i in range(n): print("enter the sentence in list") lst_sen.append(input().lower()) print(lst_sen) search = input("Please enter your query\n").lower() print(search) search_lst = search.split(' ') print(search_lst) lst_occ = [] for i in lst_sen: count = 0 for j in search_lst: if i.count(j)>0: count = count + i.count(j) lst_occ.append(count) for i in range(0,len(lst_sen)): print(lst_sen[lst_occ.index(max(lst_occ))]) lst_occ[lst_occ.index(max(lst_occ))] = -2
true
764a3d777da00681901ef7251ac5c2925d57576c
kazamari/Stepik
/course_568/2.245_repetition coding.py
687
4.375
4
''' Encoding of repeats is carried as the following: s = 'aaaabbсaa' is converted into 'a4b2с1a2', that is, the groups of the same characters of the input string are replaced by the symbol and the number of its repetitions in this string. Write a program that reads a line from the file corresponding to the string, compressed using the repetition coding, and performs the reverse operation, obtaining the source string. Output the obtained string into a file and attach it as a solution to this problem. The original string does not contain any numbers; it means that the code is definitely interpretable. Sample Input: a3b4c2e10b1 Sample Output: aaabbbbcceeeeeeeeeeb '''
true
16b4c66261f6057635577382f87f38df85f3c289
kazamari/Stepik
/course_568/2.316_re-occurrence-of-a-symbol.py
2,386
4.625
5
''' In this problem, we will look how to implement re-occurrence of a symbol using regular expressions. We may use the three various constructions to implement the repeat: 1. Wildcards { }, inside which we can place the minimum/maximum number of repeats that we are satisfied with, or the exact number of repeats that we are looking for. For example, the pattern "A{3, 5}" will fit all substrings, consisting of consecutive characters А, with length from 3 to 5, and the pattern "T{4}" will fit only those substrings, which contain 4 T in a row. 2. Wildcard *. This wildcard means any number of occurrences of a character (or a group of characters): from zero to any number you want. Thus, the pattern "A*" fits all sequences, consisting of any number of consecutive А, and fits an empty string (as zero also fits). 3. Wildcard +. This wildcard means any positive number of occurrences of a character (or a group of characters): from zero to any number you want. This way, the pattern "A+" fits all sequences, consisting of any number of consecutive А. Unlike "А*", the empty string will not fit. All repeat meta characters are applied to a character after which they occur (or group of characters). Examples of usage: import re results = re.findall("A+", "AAATATAGCGC") print(results) results = re.findall("TA{2}", "AATATAGCGTATA") print(results) Given the list of phone numbers (each line contains one phone number). Your task is to check whether these phone numbers are "cool": a phone number is called "cool", if it contains 3 or more same digits in a row. For example, number 19992034050 is a "cool" one, but 19500237492 is not. Your task is to leave only the cool numbers: the standard output should contain "cool" numbers, each number on a separate line. Sample Input: 89273777416 89273777167 89273776902 89273778915 89273778982 89273774216 89273771708 89273772982 89273775302 89273775244 89273777007 89273778140 89273778817 89273770487 89273772728 89273773272 89273777273 89273779341 89273779862 89273772225 Sample Output: 89273777416 89273777167 89273777007 89273777273 89273772225 ''' # Posted from PyCharm Edu import re, sys results = [line.strip() for line in sys.stdin if re.match(r'.*(\d)\1{2}.*', line)] print('\n'.join(results))
true
6afb4c76020ade8c19294dbd36574926ed37223f
kazamari/Stepik
/course_568/2.325_message-encoding.py
578
4.46875
4
''' We will be dealing with a trivial example of message encoding, where the mapping of original symbols to the "code" is simply taking the ASCII value of the symbol. For example, the "code" version of the letter 'A' would be 65. You will be given as input a string of any length consisting of any possible ASCII characters. You must print out the numerical ASCII value of each character of the string, separated by spaces. Sample Input: Hello, World! Sample Output: 72 101 108 108 111 44 32 87 111 114 108 100 33 ''' print(' '.join([str(ord(i)) for i in input()]))
true
7a09b5c4a6616f296b64ef2f9797799193fdc167
ZacharyLasky/Algorithms
/recipe_batches/recipe_batches.py
956
4.125
4
#!/usr/bin/python import math def recipe_batches(recipe, ingredients): min_batch = None for ingredient in recipe: if ingredient in ingredients: batches = ingredients[ingredient] // recipe[ingredient] if min_batch is None: min_batch = batches else: min_batch = min(batches, min_batch) else: return 0 return min_batch recipe_batches( {'milk': 2, 'sugar': 40, 'butter': 20}, {'milk': 5, 'sugar': 120, 'butter': 500} ) 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
29a00d5c563dc100b8e3e07fd813b23838961cff
Nyajur/python-pill
/18 exponent_again.py
572
4.125
4
base = float(input("Please enter a number: ")) exponential = float(input("Pleae enter a power to raise to: ")) def raiser(): return base**exponential print(raiser()) def raiser(): base = float(input("Please enter a number: ")) exponential = float(input("Pleae enter a power to raise to: ")) return base**exponential print(raiser()) def raiser(base,exponential): return base**exponential print(raiser(2,4)) def raiser(base,exponential): result = 1 for i in range(exponential): result =result*base return result print(raiser(2,4))
true
eaa3e22cabb29391f6aaf4531f8b76e7d465c321
xlaw-ash/VSLearn-Python
/PythonBasics/comprehensions.py
1,624
4.90625
5
# for loops have some special uses with List Comprehensions # Make a list of letters in greeting string. greeting = 'Hello World!' letters = [] for letter in greeting: letters.append(letter) print(letters) letters = [] # Above 3 statements can be combined in a single line. letters = [letter for letter in greeting] # letter is added to list. It is same as append. print(letters) # Note that list comprehension is same as append method with loop. It is just a short way to create list. # List comprehensions can be used with arithmetic operations # Make a list of multiples of 5 from 1 to 50, i.e. Table of 5. table_of_5 = [x * 5 for x in range(1,11)] print(table_of_5) # Make list of even numbers from 1 to 20 evens = [x for x in range(1,11) if x % 2 == 0] print(evens) # Nested List comprehensions # Make a list of even multiples of 5 evens_5 = [x for x in [x * 5 for x in range(1,11)] if x % 2 == 0] print(evens_5) # Above nested statement looks a bit confusing, but it is quite simple. Inner list is created and then outer list is created from inner list. # [x * 5 for x in range(1,11)] creates a list of multiples of 5 from 5 to 50. # Outer list comprehension takes input from list of multiples of 5 and creates new list of even numbers in list of multiples of 5. # Creating one list and then creating next list using first list is same as nested list comprehension. # Note that above example is just to show nested list compreshension. # More efficient way to make a list of even multiples of 5 by creating only one list. evens_5 = [] evens_5 = [x * 5 for x in range(1,11) if (x * 5) % 2 == 0] print(evens_5)
true
8aac407392e79b9f910e117562de31c5dd678d7a
xlaw-ash/VSLearn-Python
/PythonBasics/booleans.py
2,490
4.625
5
# Booleans have only two values. Either True or False. # Booleans are used for conditions. yes = True no = False print(yes) print(type(yes)) # Booleans are mostly used with logical operators. There are three main logical operators. # 'and' operator between two conditions returns True only when both conditions are True, else it returns False. print("'and' operator matrix") print('and\tTrue\tFalse') print(f'True\t{True and True}\t{True and False}') print(f'False\t{False and True}\t{False and False}') # 'or' operator between two conditions returns True when either condition is True. print("'or' operator matrix") print('or\tTrue\tFalse') print(f'True\t{True or True}\t{True or False}') print(f'False\t{False or True}\t{False or False}') # 'not' operator is applied to a condition to reverse it's result. In other words, True becomes False and False becomes True print(f'not false: {not False}') print(f'not True: {not True}') # There are various comparison operators which are used to get boolean result. [Left Value operator Right Value] # '>' : Greater than operator. Returns True when Left Value is greater than Right Value. print(3>2) # Prints True since 3 is greater than 2. print(2>5) # Prints False # '<' : Less than operator. Returns True when Left Value is less than Right Value. print(3<2) # Prints False since 3 is greater than 2 print(2<5) # Prints True # '==' : Equality operator. Returns True when both values are equal. print(3==3) # Returns True since 3 is equal to 3. print(3.0==3) # Returns True even though 3.0 is float and 3 is int because the values are same. # Note that to check equality, two equal signs are used because single equal sign is used as assignment operator. a = 3 assigns 3 to a. a == 3 will check if a is equal to 3. # '!=' : 'Not equal to operator'. This operator is used to check if the two values are unqual. # Check if num is odd. num = 15 print(num % 2 != 0) # Odd numbers are divisible by 2. So, the remainder of num divided by 2 should not be 0. This prints True. # Check if num is even. num = 20 print(num % 2 == 0) # Even numbers are divisible by 2. So, the remainder of num divided by 2 should be 0. This prints True # '>=' : Returns True when Left Value is greater than or equal to Right value # '<=' : Returns True when Left Value is less than or equal to Right value # Print True if num is between 10 and 20 inclusive num = 15 print(num >= 10 and num <= 20) # Prints True num = 25 print(num >= 10 and num <= 20) # Prints False
true
d4701afadc306985d744bdc1b613fd1a5330fd4b
kehillah-coding-2020/ppic04-ForresterAlex
/set_d.py
1,748
4.5625
5
#!/usr/bin/env python3 # # pp. 148, 151 # """ 4.36 Modify the frequency chart function to draw wide bars instead of lines. """ """ 4.37* Modify the frequency chart function so that the range of the x axis is not tightly bound to the number of data items in the list but rather uses some minimum and maximum values. """ """ 4.38* Another way to compute the frequency table is to obtain a list of key-value pairs using the `items` method. This list of tuples can be sorted and printed without returning to the original dictionary. Reqrite the frequency table function using this idea. """ """ 4.39* A good programming practice is to take a step back and look at your code and to factor out the parts that you have reused into separate functions. This is the case with our `frequencyTable()` function. Modify `frequencyTable()` so that it returns the dictionary of frequency counts it creates. """ """ 4.40* Now write a separate function to print the frequency table using the dictionary created by the `frequencyTable()` function in the previous problem. """ """ 4.41* Modify `frequencyChart()` from listing 4.10 to use the new `frequencyTable()` function. """ """ 4.42 Modify the frequency chart function to include a graphical representation of the mean. """ """ 4.43 Modify the frequency chart function to draw a line representing plus or minus 1 standard deviation from the mean. """ """ 4.44 Using `random.uniform`, generate a list of 1,000 numbers in the range 0-50. Graph the frequency distribution along with the mean and standard deviation. """ """ 4.45 Using the `random.gauss`, generate a list of 1,000 numbers in the range 0-50. Graph the frequency distribution along with the mean and standard deviation. """
true
679e5e6734b9f3fa577e914c7b6ca3655dfc3884
StefanoskiZoran/Python-Learning
/Practise provided by Ben/Clock Calculator by Me.py
1,210
4.125
4
""" Request the amount of seconds via keyboard, turn the seconds into months/days/years/decades etc. """ def main(): seconds_request = int(input(f'Please input your desired seconds: ')) minute_result = 0 hour_result = 0 day_result = 0 month_result = 0 year_result = 0 decade_result = 0 century_result = 0 millennia_result = 0 seconds = seconds_request % 60 minute_result = seconds_request / 60 minute = minute_result % 60 hour_result = minute_result / 60 hour = hour_result % 60 day_result = hour_result / 24 day = day_result % 60 week_result = day_result / 7 week = week_result % 7 month_result = day_result / 30 month = month_result % 30 year_result = month_result / 12 year = year_result % 12 decade_result = year_result / 10 decade = decade_result % 10 century_result = decade_result / 10 century = century_result % 10 millennia_result = century_result / 10 millennia = millennia_result % 10 print(f'{millennia:02.0f}:{century:02.0f}:{decade:02.0f}:{year:02.0f}:{month:02.0f}:{week:02.0f}:{day:02.0f}:{hour:02.0f}:{minute:02.0f}:{seconds:02.0f}') if __name__ == '__main__': main()
true
254aa0ded80bba9f1cefcf1bee130276579604a6
KitsuneNoctus/makeschool
/site/public/courses/CS-1.2/src/PlaylistLinkedList-StarterCode/main.py
1,584
4.5
4
from Playlist import Playlist playlist = Playlist() while True: # Prints welcome message and options menu print(''' Welcome to Playlist Maker 🎶 ===================================== Options: 1: View playlist 2: To add a new song to playlist 3: To remove a song from playlist 4: To search for song in playlist 5: Return the length of the playlist ===================================== ''') # Prints welcome message and options menu user_selection = int(input('Enter one of the 5 options: ')) # Option 1: View playlist if user_selection == 1: playlist.print_songs() # Option 2: To add a new song to playlist elif user_selection == 2: song_title = input('What song do you want to add? ') playlist.add_song(song_title) # Option 3: To remove a song from playlist elif user_selection == 3: song_title = input('What song do you want to remove? ') playlist.remove_song(song_title) # Option 4: To search for song in playlist elif user_selection == 4: song_title = input('Which song do you want to find? ') index = playlist.find_song(song_title) if index == -1: print(f"The song {song_title} is not in the set list.") else: print(f"The song {song_title} is song number {index+1}") # Option 5: Return the length of the playlist elif user_selection == 5: print(f"This set list has {playlist.length()} songs.") # Message for invalid input else: print('That is not a valid option. Try again.\n')
true
f3c543fb60d13114cd3e3b1b80176cae8c1f4d6b
KitsuneNoctus/makeschool
/site/public/courses/CS-2.2/Challenges/Solutions/challenge_1/src/vertex.py
1,155
4.25
4
class Vertex(object): """ Vertex Class A helper class for the Graph class that defines vertices and vertex neighbors. """ def __init__(self, vertex_id): """Initialize a vertex and its neighbors. neighbors: set of vertices adjacent to self, stored in a dictionary with key = vertex, value = weight of edge between self and neighbor. """ self.id = vertex_id self.neighbors = {} def add_neighbor(self, vertex, weight=1): """Add a neighbor along a weighted edge.""" if vertex not in self.neighbors: self.neighbors[vertex] = weight def __str__(self): """Output the list of neighbors of this vertex.""" return f"{self.id} adjacent to {[x.id for x in self.neighbors]}" def get_neighbors(self): """Return the neighbors of this vertex.""" return self.neighbors.keys() def get_id(self): """Return the id of this vertex.""" return self.id def get_edge_weight(self, vertex): """Return the weight of this edge.""" return self.neighbors[vertex]
true
54433cda9ab97c3b60023dd046cc7aafc1f06908
KitsuneNoctus/makeschool
/site/public/courses/CS-2.1/Code/prefixtreenode.py
2,797
4.40625
4
#!python3 class PrefixTreeNode: """PrefixTreeNode: A node for use in a prefix tree that stores a single character from a string and a structure of children nodes below it, which associates the next character in a string to the next node along its path from the tree's root node to a terminal node that marks the end of the string.""" # Choose an appropriate type of data structure to store children nodes in # Hint: Choosing list or dict affects implementation of all child methods CHILDREN_TYPE = list # or dict def __init__(self, character=None): """Initialize this prefix tree node with the given character value, an empty structure of children nodes, and a boolean terminal property.""" # Character that this node represents self.character = character # Data structure to associate character keys to children node values self.children = PrefixTreeNode.CHILDREN_TYPE() # Marks if this node terminates a string in the prefix tree self.terminal = False def is_terminal(self): """Return True if this prefix tree node terminates a string.""" # TODO: Determine if this node is terminal def num_children(self): """Return the number of children nodes this prefix tree node has.""" # TODO: Determine how many children this node has def has_child(self, character): """Return True if this prefix tree node has a child node that represents the given character amongst its children.""" # TODO: Check if given character is amongst this node's children def get_child(self, character): """Return this prefix tree node's child node that represents the given character if it is amongst its children, or raise ValueError if not.""" if self.has_child(character): # TODO: Find child node for given character in this node's children ... else: raise ValueError(f'No child exists for character {character!r}') def add_child(self, character, child_node): """Add the given character and child node as a child of this node, or raise ValueError if given character is amongst this node's children.""" if not self.has_child(character): # TODO: Add given character and child node to this node's children ... else: raise ValueError(f'Child exists for character {character!r}') def __repr__(self): """Return a code representation of this prefix tree node.""" return f'PrefixTreeNode({self.character!r})' def __str__(self): """Return a string view of this prefix tree node.""" return f'({self.character})'
true
6e332a122b6c6a83a49e2bdcc66aaba3bfb8a191
MayankMaheshwar/DS-and-Algo-solving
/hypersonic2.py
585
4.125
4
""" 1) Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. Input: nums = [0,1] Output: 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. """ ans = 0 for i in range(arr): ans ^= arr[i] print(ans)
true
a1fcaf556a09f43581122e608c1995ec37bbc260
nrkavya/python-training
/1.py
308
4.375
4
#Create a program to compare three numbers and find the bigger numbers no1 = int(input("Enter no1")) no2= int(input ("Enter no2")) no3 = int(input("enter no3")) if(no1>no2 and no1>no3): print("no1 is greatest") elif(no2>no1 and no2>no3): print("no2 is greatest") else: print("no3 is greatest")
true
60308a1f2aa94fa65c89ca7461b1ec664a7beba5
riceh3/210CT-CW
/binary_search.py
1,358
4.15625
4
def binary_search(entry): # Divide and Conquer """ Search through input for values within the given high & low parameters """ length = len(entry) middle = length/2 # Find the middle value in the list middle = int(middle) if entry[middle] == low or entry[middle] == high: print("TRUE") elif middle < 1: # Value not in range print("FALSE") else: if entry[middle] > low and entry[middle] < high: print("TRUE") elif low < entry[middle]: entry = entry[:middle] # Disregard first half of list binary_search(entry) return entry elif high > entry[middle]: entry = entry[middle:] # Disregard second half of list binary_search(entry) return entry else: print("FALSE") try: # Check for input errors entry = [2,3,5,7,9,13] low = 10 high = 14 if low < high: binary_search(entry) else: print("Low parameter must be less than High parameter") except NameError: print("Input must be all integers")
true
cf981cdb74758f85e6e9801b94a2394911268a0a
LizzieDeng/kalman_fliter_analysis
/docs/cornell CS class/lesson 21. Object-Oriented Design/demos/point.py
1,932
4.21875
4
""" A module with a simple Point3 class. This module has a simpler version of the Point class. The primary purpose of this module is to show off the built-in methods __str__ and __repr___ Author: Walker White (wmw2) Date: October 20, 2019 """ import math class Point3(object): """ A class to represent a point in 3D space Attribute x: The x-coordinate Invariant: x is a float Attribute y: The y-coordinate Invariant: y is a float Attribute z: The y-coordinate Invariant: z is a float """ # INITIALIZER def __init__(self,x=0.0,y=0.0,z=0.0): """ Initializes a new Point3 Parameter x: the x-coordinate (default is 0.0) Precondition: x is a float (or optional) Parameter y: the y-coordinate (default is 0.0) Precondition: y is a float (or optional) Parameter z: the z-coordinate (default is 0.0) Precondition: z is a float (or optional) """ self.x = x # x is parameter, self.x is field self.y = y # y is parameter, self.y is field self.z = z # z is parameter, self.z is field def __str__(self): """ Returns: this Point as a string '(x, y, z)' """ return '('+str(self.x)+', '+str(self.y)+', '+str(self.z)+')' def __repr__(self): """ Returns: unambiguous representation of Point3 """ return str(self.__class__)+str(self) def distance(self,other): """ Returns: Distance from self to other Parameter other: the point to measure to Precondition: other is a Point3 """ assert type(other) == Point3, repr(other)+' is not a Point3' dx = (self.x-other.x)*(self.x-other.x) dy = (self.y-other.y)*(self.y-other.y) dz = (self.z-other.z)*(self.z-other.z) return math.sqrt(dx+dy+dz)
true
d52820228570073946ec653e69322c7d30a2d315
LizzieDeng/kalman_fliter_analysis
/docs/cornell CS class/Lesson 28. Generators/demos/filterer.py
1,139
4.1875
4
""" Module to demonstrate the idea behind filter This module implements the filter function. It also has several support functions to show how you can leverage it to process data. You may want to run this one in the Python Tutor for full effect. Author: Walker M. White (wmw2) Date: May 24, 2019 """ def filter(f,data): """ Returns a copy of data, removing anything for which f is false Parameter f: The function to apply Precondition: f is a BOOLEAN function taking exactly one argument Parameter data: The data to process Precondition: data an iterable, each element satisfying precond of f """ accum = [] for item in data: if f(item): accum.append(item) return accum def iseven(x): """ Returns True if x is even Parameter x: The number to add to Precondition: x is an int """ return x % 2 == 0 def ispos(x): """ Returns True if x > 0 Parameter x: The number to add to Precondition: x is an int or float """ return x > 0 # Add this if using the Python Tutor #a = [-2,1,4] #b = filter(iseven, a) #c = filter(ispos, a)
true
c1478e4316bf8c3c4c764d4192dcb54b7d1140fa
LizzieDeng/kalman_fliter_analysis
/docs/cornell CS class/lesson 17. Recursion/demos/com.py
1,950
4.53125
5
""" A recursive function adding commas to integers. These functions show the why the choice of division at the recursive step matters. Author: Walker M. White (wmw2) Date: October 10, 2018 """ import sys # Allow us to go really deep #sys.setrecursionlimit(999999999) # COMMAFY FUNCTIONS def commafy(s): """ Returns a copy of s, with commas every 3 digits. Example: commafy('5341267') = '5,341,267' Parameter s: string representing an integer Precondition: s a string with only digits, not starting with 0 """ # You can't always check everything with an assert # However, check what you can assert type(s) == str, repr(s) + ' is not a string' # Work on small data (BASE CASE) if len(s) <= 3: return s # Break up into halves (RECURSIVE CASE) left = commafy(s[0:-3]) right = s[-3:] # Combine the answer return left + ',' + right def commafy_int(n): """ Returns n as a string, with commas every 3 digits. Example: commafy('5341267') = '5,341,267' Parameter n: number to convert Precondition: n is an int with n >= 0 """ assert type(n) == int, repr(n)+' is not an int' # get in the habit assert n >= 0, repr(n)+' is negative' # get in the habit # Use helpers return commafy(str(n)) # Work on small data (BASE CASE) #if n < 1000: # return str(n) # Break up into halves (RECURSIVE CASE) #left = commafy(n//1000) #right = to3(n % 1000) # Combine the answer #return left + ',' + right def to3(p): """ Returns a string representation of p with at least 3 chars Adds leading 0's if necessary Parameter n: number to pad Precondition: p is an int """ assert type(p) == int, repr(p)+' is not an int' # get in the habit if p < 10: return '00' + str(p) elif p < 100: return '0' + str(p) return str(p)
true
0ff7c36732279dd198f5034931b84041c0ac45d4
LizzieDeng/kalman_fliter_analysis
/docs/cornell CS class/lesson 16. For-Loops/demos/mut.py
906
4.40625
4
""" Module to demonstrate how to modify a list in a for-loop. This function does not use the accumulator pattern, because we are not trying to make a new list. Instead, we wish to modify the original list. Note that you should never modify the list you are looping over (this is bad practice). So we loop over the range of positions instead. You may want to run this one in the Python Tutor for full effect. Author: Walker M. White (wmw2) Date: May 24, 2019 """ def add_one(lst): """ (Procedure) Adds 1 to every element in the list Example: If a = [1,2,3], add_one(a) changes a to [2,3,4] Parameter lst: The list to modify Precondition: lst is a list of all numbers (either floats or ints), or an empty list """ size = len(lst) for k in range(size): lst[k] = lst[k]+1 # procedure; no return # Add this if using the Python Tutor #a = [3,2,1] #add_one(a)
true
e633be9b864b2ae81f2275718708f73f9aff44e6
LizzieDeng/kalman_fliter_analysis
/docs/cornell CS class/lesson 26. While-Loops/demos/newton.py
1,256
4.40625
4
""" A module to show while-loops and numerical computations. This is one of the most powerful uses of a while loop: using it to run a computation until it converges. There are a lot of algorithms from Calculus and Numerical Analysis that work this way. Author: Walker M. White Date: April 15, 2019 """ def sqrt(c,err=1e-6): """ Returns: the square root of c to with the given margin of error. We use Newton's Method to find the root of the polynomial f(x) = x^2-c Newton's Method produces a sequence where x_(n+1) = x_n - f(x_n)/f'(x_n) = x_n - (x_n*x_n-c)/(2x_n) which we simplify to x_(n+1) = x_n/2 + c/2 x_n We can stop this process and use x_n as an approximation of the square root of c. The error when we do this is less than |x_n*x_n - c|. So we loop until this error is less than err. Parameter c: The number to compute square root Precondition: c >= 0 is a number Parameter err: The margin of error (OPTIONAL: default is e-6) Precondition: err > 0 is a number """ # Start with a rough guess x = c/2.0 while abs(x*x-c) > err: # Compute next in Newton's Method sequence x = x/2.0+c/(2.0*x) return x
true
cb35550231866abfbadca029a1c91a125a2e9e2f
gunishj/python_async_multiprocessing
/AsyncIO/implementing_asyncio.py
1,157
4.5625
5
import asyncio import time def sync_f(): print('one', end=' ') time.sleep(1) # I'm simulating an expensive task like working with an external resource. I want it to wait for 1 sec print('two', end=' ') # ASYNCHRONOUS async def async_f(): print('one', end=' ') await asyncio.sleep(1) print('two', end=' ') async def main(): # Note that there are 3 awaitable objects: coroutines, tasks and futures. tasks = [async_f() for _ in range(3)] # we schedule the coroutines to run asap by gathering the tasks like this: await asyncio.gather(*tasks) s = time.time() # The entrance point of any asyncio program is asyncio.run(main()), where main() is a top-level coroutine. # asyncio.run() was introduced in Python 3.7, and calling it creates an event loop # and runs a coroutine on it for you. run() creates the event loop. asyncio.run(main()) # prints out: one one one two two two and takes 1 second print(f'Execution time (ASYNC):{time.time()-s}') print('\n') s = time.time() for _ in range(3): sync_f() # prints out: one two one two one two and takes 3 seconds print(f'Execution time (SYNC):{time.time()-s}')
true
0fcd16dcfa157c95f8ff55b16fb8e8f687a96e62
Regenyi/python
/Thonny_continue.py
729
4.15625
4
menu = """-- Calculator Menu -- 0. Quit 1. Add two numbers 2. Subtract two numbers 3. Multiply two numbers 4. Divide two numbers""" selection = None while selection != 0: print(menu) selection = int(input("Select an option: ")) if selection not in range(5): print("Invalid option: %d" % selection) continue if selection == 0: continue a = float(input("Please enter the first number: ")) b = float(input("Please enter the second number: ")) if selection == 1: result = a + b elif selection == 2: result = a - b elif selection == 3: result = a * b elif selection == 4: result = a / b print("The result is %g." % result)
true
fa669ab56fb32241a23d3f9d00857001571cb2b2
Regenyi/python
/sorting.py
1,608
4.1875
4
#Sorting algo - RA CC Python SI1 A3 import re #getting the number from the user: input_numbers = [] input_numbers = input("\nTell me positive integers that you want to sort, by separting them with a coma (so for example: 10,2,45):\n\n") #exception handler for wrong format: while True: if (len(input_numbers)<6 or len(input_numbers)>100): input_numbers = input("Wrong format!\nTell me the numbers that you want to sort, by separting them with a coma (so for example: 10,2,45)\n: ") elif re.search("[a-z]",input_numbers): input_numbers = input("Wrong format!\nTell me the numbers that you want to sort, by separting them with a coma (so for example: 10,2,45)\n: ") elif not re.search("[,]",input_numbers): input_numbers = input("Wrong format!\nTell me the numbers that you want to sort, by separting them with a coma (so for example: 10,2,45)\n: ") else: break input_numbers = input_numbers.split(",") print("\nYou gave these numbers:\n") print(*input_numbers, sep=',') input_numbers = list(map(int, input_numbers)) #the actual sorting starts here: def sorting(): iteration = 1 N = len(input_numbers) while iteration < N: j = 0 while j <= N-2: if input_numbers[j] > input_numbers [j+1]: temp = input_numbers[j+1] input_numbers[j+1] = input_numbers[j] input_numbers[j] = temp else: j += 1 else: iteration += 1 sorting() print("\nSorted numbers:\n") print(*input_numbers, sep=',') print("")
true
a3c4170dbc8d48142cf7f8319ba45775e1956886
Tij99/compsci-jmss-2016
/triangleXs.py
384
4.28125
4
# Write a program to print out an isosceles triangle of Xs # rewrite the program to work for an arbitrary number of rows (ie the user can # enter the required number of rows) def triangle(height): for i in range(height): spaces = height - i - 1 xs = 2 * i + 1 print("-" * spaces + "|" * xs + "-" * spaces) h = int(input("how many lines?")) triangle(h)
true
f8ac9454b1333d1fce5f4f43c2d3b54731b979b7
ArthurkaX/W3SCHOOL-learning
/Python basic P1/Ex_3.py
286
4.40625
4
# Write a Python program to display the current date and time import datetime print('first variant:') print('current date & time is:') print(datetime.datetime.now()) now = datetime.datetime.now print('second variant:') print('{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
true
d5fac45dfae4e162546dd53c4a2b3bd154bcc4a3
ArthurkaX/W3SCHOOL-learning
/Python basic P1/Ex_1.py
514
4.25
4
# Write a Python program to print the following string in a specific format some_txt = 'Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are' x = 0 for a in some_txt: if a.isupper() == True and a != 'I': print() if a == 'H': x = 1 if a== 'U' or a== 'L': x = 2 for tab in range(x): print('\t' , end = '') x = 0 print(a, end = '')
true
50426db78b533ce033a059f1157c9f0d44123146
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_9_Classes/Dog.py
800
4.21875
4
class Dog(object): """A simple attempt to model a dog.""" def __init__(self,name,age): """Initialize name and age attribute""" 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!") my_dog=Dog('willie',6) print("My dog's name is "+my_dog.name.title()+".") print("My dog is " + str(my_dog.age) + " years old.") my_dog.sit() my_dog.roll_over() your_dog=Dog('lucy',3) print("\nYour dog's name is "+your_dog.name.title() + ".") print("Your dog's age is " + str(your_dog.age)) your_dog.sit() your_dog.roll_over()
true
91b3c0eace34899e1e0f2c1e40853ace87382362
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_3_Intoducing_Lists/bicyclesIntroToLists.py
1,152
4.625
5
#In Python, square brackets indicate a list, and individual elements in the list are separated by commas. bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles) #Because this isnt the output you want your users to see, lets learn how to access the individual items in a list. #To access an ele- ment in a list, write the name of the list followed by the index of the item enclosed in square brackets. print bicycles[0] #When we ask for a single item from a list, Python returns just that element without square brackets or quotation marks: print bicycles[0].title() #prints the 1st element of the list #index positions star at 0,not 1--> #subtract 1 from actual position to get index position. #To check from the right side of a list or the lasr element #of the list--> start with -1 index position-->will return last element print bicycles[-1] print bicycles[-2]#second last and so on .. #Now , How to use individual values of a list for a message? Simple: message="My first bicycle was a "+bicycles[0].title()+"." print message #At 17, we build a sentence using the value at bicycles[0] and store it in the variable message.
true
0ba59210ae47c36fd6abeab0670ead59fef062f7
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_3_Intoducing_Lists/untitled folder/3-3.py
462
4.46875
4
# 3-3. Your Own List: Think of your favorite mode of # transportation, such as a motorcycle or a car, and # make a list that stores several examples. Use your # list to print a series of statements about these items, # such as “I would like to own a Honda motorcycle.” cars = ['audi' , 'bmw' , 'mercedes'] print("I would like own an " + cars[0].title()) print("I would like to own a " + cars[1].upper()) print("I would like to own a " + cars[2].title())
true
d88e288cffdaf538374ae33bc2f91b3410b3b143
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_9_Classes/electric_car.py
2,219
4.46875
4
class Car(object): """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 self.odometer_reading=0 def get_descriptive_name(self): """Return a neatly formatted descriptive name""" long_name=str(self.year) + " " + self.make + " " + self.model return long_name.title() def read_odometer(self): """Print a statement showing the car's mileage""" print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """Set the odometer reading to given value. Reject the change if anyone tries to roll the odometer back.""" if self.odometer_reading <= mileage: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self , increment_mileage): self.odometer_reading += increment_mileage def fill_gas_tank(self): check = self.odometer_reading % 50 if check == 0: print("It's time to fill the gas tank.") else: print("Fill gas after " + str(50 - check) + " miles.") my_car=Car('audi','a4',2016) print(my_car.odometer_reading) my_car.update_odometer(60) my_car.read_odometer() my_car.fill_gas_tank() class ElecticCar(Car): """Represents aspects of a car, specific to electric vehicles""" def __init__(self, make, model, year): """Initialize attributes of the parent class. Then initalize attributes specific to an electic car.""" super().__init__(make, model, year) self.battery_size = 70 def describe_battery(self): """Prints a statement describing the battery size.""" print("This car has " + str(self.battery_size) + "-kWh battery.") def fill_gas_tank(self): """Electric cars don't have gas tanks.""" print("This car doesn't have a gas tank.") my_tesla = ElecticCar('tesla','model s',2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery() my_tesla.fill_gas_tank()
true
d11e007939ad611f6f34dbf43ef9949442310658
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_7_User_Input_And_While_Loop/Practice2/4.rollercoaster.py
209
4.15625
4
height = raw_input("How tall are you , in inches? ") height = int(height) if height >= 36: print("\nYou're tall enought to ride!") else: print("You will be able to ride when you're a little older.")
true
68b3d1a63e3df0f1f75e4fc83af3a3dd2b29f093
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_3_Intoducing_Lists/untitled folder/3-2Greetings.py
477
4.25
4
# 3-2. Greetings: Start with the list you used in Exercise 3-1, but instead of just printing each persons name, # print a message to them. The text of each message should be the same, but each message should be personalized # with the persons name. friend_list=['manan','samarth','rohan','rishi'] print ("Hello, "+friend_list[0].title()+"!") print ("Hello, "+friend_list[1].title()+"!") print ("Hello, "+friend_list[2].title()+"!") print ("Hello, "+friend_list[3].title()+"!")
true
3389a5cd1051d2edcf6125b7adb4452d591f0726
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_9_Classes/practice2/9-6.IceCreamStand.py
1,332
4.21875
4
class Restaurant(): """An attempt to model a restaurant""" def __init__(self,restaurant_name,cuisine_type): """Initializing name and age attributes""" self.name = restaurant_name self.cuisine = cuisine_type def describe_restaurant(self): # Describes the restaurant name and cuisine print(self.name.title() + " serves " + self.cuisine + " food.") def open_restaurant(self): # Opens the restaurant and welcomes customers. print(self.name.title() + " is now Open. \nCome. \nHave some delicious " + self.cuisine + " food.") restaurant1 = Restaurant("big chill","italian") class IceCreamStand(Restaurant): """An attempt to model a restaurant , specific to InceCreamStand""" def __init__(self,restaurant_name,cuisine_type): """Initializing attributes of parent class , Restaurant""" super().__init__(restaurant_name,cuisine_type) self.flavors = ['vanilla','chocolate','mint','blueberry','strawberry'] # def display_flavors(self): print("Here is the list of flavors: ") for flavor in self.flavors: print(flavor) IceCreamStand1 = IceCreamStand('mother dairy','ice cream') IceCreamStand1.describe_restaurant() IceCreamStand1.open_restaurant() IceCreamStand1.display_flavors()
true
9a707f3c487622e2c8caa16d2d8ca8c4d7507911
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_8_Functions/practice2/16.profile.py
989
4.53125
5
# Sometimes you'll want to accept an arbitary number of # argument but you won't know ahead of time # what kind of information will be passed to the # function. # Write a function that accepts as many key-value pairs as the # calling statement provides. # Example : Building user profiles. # You're sure that you'll get information about the user but # you're not sure that what kind of information will be # given to you. # The function build_profile() taken in the first and the last # name but also takes in an arbitrary number of keyword # arguments. def build_profile(first,last, **user_info): """Build a dictionary containing everything we know about a user""" profile = {} profile['First name' ] = first profile['Last name'] = last print(user_info) for key,value in user_info.items(): profile[key] = value return profile user_profile = build_profile('albert','einstein', location = 'princeton', field = 'physics') print(user_profile)
true
c9349dd22148f7f878bb1be59820cc8e1b6ddcd5
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_10_File_And_Exceptions/10-6.Addition.py
1,950
4.15625
4
while True: try: first_number = raw_input("Give me two numbers and i will add them." + "\nEnter 'quit' to quit program anytime."+ "\nFirst Number: ") if first_number == 'quit': break else: first_number = int(first_number) second_number = raw_input("Second Number: ") if second_number == 'quit': break else: second_number = int(second_number) except ValueError: print("You wrote in a word. Type in a number next time.") continue else: print(first_number + second_number) '''What the try block does:''' # First it tells the user what the program will do. # Next, it tell the use that he/she can quit at anytime. # Next, It asks for the first number. # Now if the user enters: 'quit' # The program will exit/break. # Till here , if the user has entered a non-integer value except 'quit'.. # The program will go to the first else block(first_number = int(first_number) # Here, it will catch the error (ValueError) , if there is any. # Similarly: The process is same for second_number. # Anytime a ValueError comes due to entering non-integer value(except 'quit'): # The program shift to the except block. '''What the except block does''' # Anytime a ValueError comes due to entering non-integer value(except 'quit'): # The program shift to the except block. # 1.the except block displays a friendly message telling the user to enter a number instead # of a word next time. # 2. continue: Goes back to the starting of the loop and prompts for first number again. # Starts the whole program again. '''What the else block does:''' # If no error occurs, it prints the sun of the 2 numbers. # if first_number != 'quit': # second_number = raw_input("Second Number: ") # if second_number != 'quit': # second_number = int(second_number) # print(first_number + second_number)
true
f2d74a5bea40e74454c884bfefb8ec99d9b9d276
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_5_If_Statements/banned_users_CheckWhetherAValueIsInAList.py
986
4.125
4
print "Checking whether a value is not in a list " # Other times, its important to know if a value does not appear in a list. # You can use the keyword not in this situation. For example, consider a # list of users who are banned from commenting in a forum. You can check whether # a user has been banned before allowing that person to submit a comment. banned_users=['andrew','carolina','david'] user='marie' if user not in banned_users: print(user.title()+", you can post a comment if you wish.") print "What are Boolean Expressions?" print " Boolean expression=Conditional tests-->It is either True or False" # Boolean values are often used to keep track of certain conditions, such as whether # a game is running or whether a user can edit certain content on a website: # game_active = True # can_edit = False # Boolean values provide an efficient way to track the state of a program or a # particular condition that is important in your program.
true
7d900b9d8a49c9f3b4753b7c8effd72764ddbbf6
sweenejp/learning-and-practice
/treehouse/python-beginner/monty_python_tickets.py
1,349
4.15625
4
SERVICE_CHARGE = 2 TICKET_PRICE = 10 tickets_remaining = 100 def calculate_price(number_of_tickets): # $2 service charge per transaction return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE while tickets_remaining > 0: print("There are only {} tickets remaining!\nBuy now to secure your spot for the show!".format(tickets_remaining)) name = input("Hi there! What's your name? ") order = input("Okay, {}, how many tickets would you like? ".format(name)) try: order = int(order) if order > tickets_remaining: raise ValueError("There are only {} tickets remaining".format(tickets_remaining)) except ValueError as err: # Include the error text in the output print("Oh no, we ran into an issue.") print("{} Please try again".format(err)) else: amount_due = calculate_price(order) print("Great, {}! You ordered {} tickets. Your amount due is ${}".format(name, order, amount_due)) intent_to_purchase = input('Do you want to proceed with your purchasing order?\nPlease enter "yes" or "no" ') if intent_to_purchase.lower() == 'yes': print('SOLD!') tickets_remaining -= order else: print('Thank you for stopping by, {}.'.format(name)) print('We are so sorry! This event is sold out. :(')
true
8b69c22357ef25ddca9167989f2337674fe78784
sweenejp/learning-and-practice
/practicepythondotorg/exercise_14.py
692
4.1875
4
# Write a program (function!) that takes a list and returns a new list that contains all the # elements of the first list minus all the duplicates. # # Extras: # # Write two different functions to do this - one using a loop and constructing a list, # and another using sets. Go back and do Exercise 5 using sets, and write the solution for that # in a different function. def remove_duplicates(x): return list(set(x)) def other_remove_duplicates(x): a_list = [] for item in x: if item not in a_list: a_list.append(item) return a_list print(remove_duplicates([1, 1, 3, 5, 6, 7, 7, 7, 10])) print(other_remove_duplicates([1, 1, 3, 5, 6, 7, 7, 7, 10]))
true
cb066d54e563da61e1c97f7621ac4ac43c42e3e1
sweenejp/learning-and-practice
/treehouse/python-beginner/team.py
1,286
4.21875
4
# TODO Create an empty list to maintain the player names player_names = [] # TODO Ask the user if they'd like to add players to the list. wants_to_add = input("Would you like to add a player to the team?\nYes/no: ") # If the user answers "Yes", let them type in a name and add it to the list. while wants_to_add.lower() == "yes": new_player = input("Enter the name of the player: ") player_names.append(new_player) wants_to_add = input("Would you like to add a player to the team?\nYes/no: ") # If the user answers "No", print out the team 'roster' # TODO print the number of players on the team print("\nThere are {} players on your team.".format(len(player_names))) # TODO Print the player number and the player name # The player number should start at the number one player_number = 1 for player in player_names: print("Player {}: {}".format(player_number, player)) player_number += 1 # TODO Select a goalkeeper from the above roster keeper = input("Please select the goalkeeper by entering that person's player number. (1-{}): ".format(len(player_names))) keeper = int(keeper) print("Great!!! The goalkeeper for the game will be {}.".format(player_names[keeper - 1])) # TODO Print the goal keeper's name # Remember that lists use a zero based index
true
28301a007b829871cd518834994588e9f088b53b
Kinosa777/Lits-Python
/convert_n_to_m.py
1,377
4.21875
4
def convert_n_to_m(x, n, m): """Converts a number in n-based system into a number in m-based system.""" def convert_n_to_dec(x): """Converts a n-based number into decimal. No int(num, base) function for number conversion is used.""" if n == 10: return x elif n == 1: return len(x) else: dec = 0 for i in range(0, len(x)): dec += (chars.index(x[i]) * (n ** (len(x) - i - 1))) return dec def convert_dec_to_m(dec, result=''): """Converts a decimal number into a m-based number. Recursion is used.""" dec = int(dec) if m == 10: return str(dec) elif m == 1: return '0'*dec else: if dec < m: return str(dec) + result else: result = str(chars[dec % m]) + result return convert_dec_to_m(dec // m, result) x = str(x) chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' for ch in x: if ch not in chars[:n]: return False return convert_dec_to_m(convert_n_to_dec(x)) print(convert_n_to_m([123], 4, 3)) print(convert_n_to_m("0123", 5, 6)) print(convert_n_to_m("123", 3, 5)) print(convert_n_to_m(123, 4, 1)) print(convert_n_to_m(-1230, 11, 16)) print(convert_n_to_m("A1Z", 36, 16))
true
3aecd3afc0558b00aa683aeb245b1e2876f78706
hazim/Treehouse---Python-Basic
/check_please.py
519
4.21875
4
import math def split_check(total, number_of_people): # we want to round up the number in order to make sure that the person paying is not paying the extra out of their own pocket return math.ceil(total_due / split_among) try: total_due = float(input("What is the total? \n")) split_among = int(input("How many people are we spliting it among? \n")) except ValueError: print('Oh No! Enter a number please. ') else: amount_due = split_check(total_due, split_among) print(f'Each person owes ${amount_due}')
true
7f4dd8521d12aa3d208fa4c51d507d84b304de6b
mtaziz/python_projects
/Basic Rock Paper Scissors Game (CLI).py
1,945
4.25
4
import random # Welcome text print("ROCK PAPER SCISSORS") # Game variables ties = 0 wins = 0 losses = 0 # Gameloop while True: # Displaying game data. print("%s Wins, %s Loses, %s Ties" % (wins, losses, ties)) # Loop for player choice. while True: print("Enter any one: (r)ock (p)aper (s)cissor or (q)uit") player_move = input('- ').lower() if player_move == 'q': exit() elif player_move == 'r' or player_move == 'p' or player_move == 's': break print("Type one of: r, p, s or q") # Printing text according to choice. if player_move == 'r': print("ROCK versus...") elif player_move == 'p': print("PAPER versus...") elif player_move == 's': print("SCISSORS versus...") # Generating random number num = random.randint(1, 3) # Blank variable for computer move. computer_move = '' # Assigning values to computerMove accordingly. if num == 1: computer_move = 'r' print("ROCK") elif num == 2: computer_move = 'p' print("PAPER") elif num == 3: computer_move = 's' print("SCISSORS") # Condition for tie if player_move == computer_move: print("IT'S A TIE!") ties += 1 # Conditions for wins elif player_move == 'r' and computer_move == 's': print("YOU WIN!") wins += 1 elif player_move == 'p' and computer_move == 'r': print("YOU WIN!") wins += 1 elif player_move == 's' and computer_move == 'p': print("YOU WIN!") wins += 1 # Conditions for losses elif computer_move == 'r' and player_move == 's': print("YOU LOSE!") losses += 1 elif computer_move == 'p' and player_move == 'r': print("YOU LOSE!") losses += 1 elif computer_move == 's' and player_move == 'p': print("YOU LOSE!") losses += 1
true
5af7a4ac6b300fee0b1e86a4eb14378eb9243279
cgscreamer/UdemyProjects
/Python/dictionaries.py
671
4.1875
4
fruit = {"orange": "a sweet, orange, citrus fruit", "apple": "good for making cider", "lemon": "a sour, yellow citrus fruit", "grape": "a small, sweet fruit growing in bunches", "lime": "a sour, green citrus fruit"} #To add to a dictionary fruit["pear"] = "an odd shaped apple" #To delete a dictionary entry #del fruit["lime"] for f in sorted(fruit.keys()): print(f + " - " + fruit[f]) while True: dict_key = raw_input("Please enter a fruit: ") if dict_key == "quit": break description = fruit.get(dict_key, "We don't have a " + dict_key) print(description) #To clear/empty the dictionary #fruit.clear
true
fa82962cae016363dee794c962553a62b8a4fdc8
andyhou2000/exercises
/chapter-6/ex_6_5.py
1,129
4.125
4
# Programming Exercise 6-5 # # Program to total the value of numbers in a text file. # The program takes no user input, but requires a text file with numbers, one per line, # which it opens, reads line by line, and totals the numbers in a variable, # then displays the total on the screen. # Define the main function. # Declare a local string variable for line and two floats for total and current number # Open numbers.txt file for reading # iterate over the lines in the file # get a number from the current line # add it to total # Close file # Display the total of the numbers in the file # Call the main function to start the program. def main(): file = open("numbers.txt","r") total = int(0) count = int(0) a = str("bob") while a != "": a = file.readline() if a == "": pass else: a = int(a) total = total + a count = count + 1 print("Total: ",total) print("Count: ",count) file.close() main()
true
5bd4a64c40de41eb21d95ec08c4ce5ba06d351b8
andyhou2000/exercises
/chapter-4/ex-4-5.py
2,173
4.46875
4
# Programming Exercise 4-5 # # Program to compute total and average monthly rainfall over a span of years. # This program gets a number of years from a user, # then uses nested loops to prompt for rainfall for each month in each year # and calculate the total and the average monthly rainfall, # then displays the number of months, total rainfall and average monthly rainfall # Create float variables for total rainfall, monthly rainfall, average monthly rainfall # Create int variables for number of years and number of months. # Get number of years from the user # Nested loop logic to loop through the years and their months # # Outer for loop for the number of years # Print the current year message # Inner loop for 12 months # Get monthly rainfall for current month from the user # add monthly rainfall to total rainfall # increment number of months # Calculate the average rainfall using total rainfall and number of months # print the results on the screen, including details for total months, total rainfall, # and average monthly rainfall, formatting any floats to 2 decimal places. startYear = input("Input starting year: ") startYear = int(startYear) years = input("Input amount of years: ") years = int(years) totalRain = 0 totalRain = float(totalRain) yearRain = 0 yearRain = float(yearRain) x = 0 x = int(x) y = 1 y = int(y) for x in range(0,years): currentYear = startYear + x print("Input rainfall data for year",currentYear) for y in range(1,13): print("Input inches of rain in month", y,": ", end="") rain = input() rain = float(rain) yearRain = yearRain + rain y = y + 1 averageRain = yearRain / 12.0 print("Rain in year ",currentYear,": ",format(yearRain,'.2f')," inches.") print("Average rain per month in year ",currentYear,": ",format(averageRain,'.2f')," inches") totalRain = totalRain + yearRain yearRain = 0 x = x + 1 y = 1 averageTotalRain = totalRain / (12.0 * x) print("Total rain in period: ",format(totalRain,'.2f')," inches") print("Average rain per month in period:",format(averageTotalRain,'.2f')," inches")
true
80c8bb6fa0068c40e7417af66c9230ec5945fcfc
andyhou2000/exercises
/chapter-2/ex-2-5.py
797
4.59375
5
# Programming Exercise 2-5 # # Program to calculate distances traveled over time at a speed. # This program uses no input. # It will calculate the distance traveled for 6, 10 and 15 hours at a constant speed, # then display all the results on the screen. # Variables to hold the three distances. # be sure to initialize these as floats. # Constant for the speed. # Calculate the distance the car will travel in # 6, 10, and 15 hours. # Print the results for all calculations. speed = 40 speed = float(speed) distSix = speed * 6 distTen = speed * 10 distFifteen = speed * 15 print("Distance after six hours: %.2f"%distSix, "miles") print("Distance after ten hours: %.2f"%distTen, "miles") print("Distance after fifteen hours: %.2f"%distFifteen, "miles")
true
ddc8b5c1c688595eb24cdebc4d594fa50faa04c6
impradeeparya/python-getting-started
/tree/SymetricTree.py
2,042
4.21875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def is_child_symmetric(self, children): is_symmetric = True left_index = 0 right_index = len(children) - 1 while left_index < right_index: if children[left_index] is None and children[right_index] is None: is_symmetric = True elif (children[left_index] is None and children[right_index] is not None) or ( children[left_index] is not None and children[right_index] is None) or ( children[left_index].val != children[right_index].val): is_symmetric = False break left_index += 1 right_index -= 1 if is_symmetric: children_nodes = [] is_leaf_level = True for index in range(len(children)): children_nodes.append(children[index].left if children[index] is not None else None) children_nodes.append(children[index].right if children[index] is not None else None) if children[index] is not None: is_leaf_level = False if not is_leaf_level: is_symmetric = self.is_child_symmetric(children_nodes) return is_symmetric def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ is_symmetric = True if root is not None: if root.left is not None and root.right is not None and root.left.val == root.right.val: is_symmetric = self.is_child_symmetric([root.left, root.right]) elif root.left != root.right: is_symmetric = False return is_symmetric left = TreeNode(2, None, TreeNode(3)) right = TreeNode(2, None, TreeNode(3)) root = TreeNode(1, left, right) print(Solution().isSymmetric(root))
true
a145bda0848c345599343ef6abee82d44a11ba41
chanchalkumawat/Learn-Python-Hardway
/ex4of46.py
351
4.15625
4
#Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise. def check(c): if c=='a'or c=='A' or c=='e' or c=='E' or c=='i' or c=='I' or c=='o' or c=='O' or c=='u' or c=='U': return True else: return False z=raw_input("Enter the character :") print check(z)
true
7278e5b16a928c6764dde79d296d30e063352e93
taylorperkins/foobar
/test/test_solar_doomsday.py
1,916
4.125
4
import unittest from utils import print_time from logic.solar_doomsday import answer class TestSolarDoomsday(unittest.TestCase): """Challenge 1 Solar Doomsday ============== Who would've guessed? Doomsday devices take a LOT of power. Commander Lambda wants to supplement the LAMBCHOP's quantum antimatter reactor core with solar arrays, and she's tasked you with setting up the solar panels. Due to the nature of the space station's outer paneling, all of its solar panels must be squares. Fortunately, you have one very large and flat area of solar material, a pair of industrial-strength scissors, and enough MegaCorp Solar Tape(TM) to piece together any excess panel material into more squares. For example, if you had a total area of 12 square yards of solar material, you would be able to make one 3x3 square panel (with a total area of 9). That would leave 3 square yards, so you can turn those into three 1x1 square solar panels. Write a function answer(area) that takes as its input a single unit of measure representing the total area of solar panels you have (between 1 and 1000000 inclusive) and returns a list of the areas of the largest squares you could make out of those panels, starting with the largest squares first. So, following the example above, answer(12) would return [9, 1, 1, 1]. Test Cases ========== Inputs: (int) area = 12 Output: (int list) [9, 1, 1, 1] Inputs: (int) area = 15324 Output: (int list) [15129, 169, 25, 1] """ def setUp(self): pass def tearDown(self): pass @print_time def test_example_one(self): response = answer(12) self.assertEqual(response, [9, 1, 1, 1]) @print_time def test_example_two(self): response = answer(15324) self.assertEqual(response, [15129, 169, 25, 1])
true
719d9d0e1b3548a2b791779d09693228e0824ab7
prof-paradox/project-euler
/7.py
520
4.125
4
''' Calculates the 10001st prime number ''' import math def isPrime(num): if num % 2 == 0: return False for i in range(3, round(math.sqrt(num)) + 1, 2): if num % i == 0: return False return True natural_no = 3 prime_count = 1 # initial count for 2 max_prime = 2 while prime_count <= 10000: if(isPrime(natural_no)): prime_count += 1 max_prime = natural_no natural_no += 2 # since 2 is the only even prime number print(max_prime)
true
db37990f15e0b9eaeab5dacf38b1adf87735b416
rawsashimi1604/Qns_Leetcode
/leetcode_py/valid-parentheses.py
834
4.125
4
class Solution: def isValid(self, s: str) -> bool: stack = [] lookup = { "}": "{", ")": "(", "]": "[" } for p in s: if p in lookup.values(): stack.append(p) # Must make sure that stack exists, so that there will not be any index errors. # Example input : "]" ... # p will not be in lookup values, but cannot call stack[-1] elif stack and lookup[p] == stack[-1]: stack.pop() # Remove from top of stack # If p not in lookup values, means not valid. # And if the p did not exist in stack, means it is invalid else: return False return stack == [] test = Solution() output = test.isValid(']') print(output)
true
df38b1d404b01498a368916adb754a496f354c1e
callumr1/Programming_1_Pracs
/Prac 4/number_list.py
681
4.15625
4
def main(): numbers = [] print("Please input 5 numbers") for count in range(1, 6): num = int(input("Enter number {}: ".format(count))) numbers.append(num) average = calc_average(numbers) print_numbers(numbers, average) def calc_average(numbers): average = sum(numbers) / len(numbers) return average def print_numbers(numbers, average): print("The first number is {}".format(numbers[0])) print("The last number is {}".format(numbers[-1])) print("The smallest number is {}".format(min(numbers))) print("The largest number is {}".format(max(numbers))) print("The average of the number is {}".format(average)) main()
true
c543270a6ffa5c251551c3cc3eb2082e013a2e0e
CRUZEAAKASH/PyCharmProjects
/section3_StringsAndPrint/String Methods.py
1,469
4.5
4
""" len() and str() practice: 1.create a variable and assign it the string "Python" 2.create another variable and assign it the length of the string assigned to the variable in step 1 3.create a variable and use string slicing and len() to assign it the length of the slice "yth" from the string assigned to the variable from step 1 4.create a variable and assign it the float 1.32 5.create a variable and assign it the string "2" from the float assigned to the variable from the last problem (use the str() string method for this) """ # type your code for "len() and str() practice" below this single line comment and above the one below it -------------- # ---------------------------------------------------------------------------------------------------------------------- var1 = "Python" var2 = len(var1) var3 = len(var1[1:4]) var4 = 1.32 #var5 = 1.3(str(2)) print(var1) print(var2) print(var3) print(var4) #print(var5) """ .upper() and .lower() practice: 1.create a variable and assign it the string "upper" changed to "UPPER" using .upper() 2.create a variable and assign it the string "owe" from "LOWER" using string slicing and .lower() """ # type your code for ".upper() and .lower() practice" below this single line comment and above the one below it -------- # ---------------------------------------------------------------------------------------------------------------------- var6= "upper".upper() var7 = "LOWER".lower() print(var6) print(var7)
true
15d758afcd551443056c912accd5a639b0d150c2
CRUZEAAKASH/PyCharmProjects
/section4_ConditionalsAndFlowControl/BooleanOperatorProblems.py
1,605
4.625
5
""" and, or, and not: 1.create a variable and set it equal to True using a statement containing an "and" Boolean operator 2.create a variable and set it equal to False using a statement containing an "and" Boolean operator 3.create a variable and set it equal to True using a statement containing an "or" Boolean operator 4.create a variable and set it equal to False using a statement containing an "or" Boolean operator 5.create a variable and set it equal to True using a statement containing an "not" Boolean operator 6.create a variable and set it equal to False using a statement containing an "not" Boolean operator """ # type your code for "and, or, and not" below this comment and above the one below it.--------------------------------- # ---------------------------------------------------------------------------------------------------------------------- print(True and True) print(True and False) print(True or True) print(False or False) print (not False) print (not True) """ order of operations for Boolean operators: 1.make var1 evaluate to False by changing or removing a single Boolean operator 2.make var2 evaluate to True by changing or removing a single Boolean operator """ # type your code for "order of operations for Boolean operators" below this comment and above the one\below it. -------- var1 = not 3 > 1 and 5 != 2 or 6 == 6 var2 = 4 * 2 != 6 and not 7 % 6 == 1 # ---------------------------------------------------------------------------------------------------------------------- print(not 3 > 1 and 5 != 2 and 6 == 6) print(4 * 2 != 6 and 7 % 6 == 1) print("hello")
true
cafc90b922a9c73f77e2ff2d3020c8563e93d60b
CRUZEAAKASH/PyCharmProjects
/section14_RegularExpressions/findAll.py
215
4.15625
4
import re pattern = r"eggs" String = "We have eggs in our string. eggs just eggstoeggs count the presence of eggs in the string" print(re.findall(pattern, String)) print(re.findall(pattern, String).__len__())
true
f5b2f41977280c6920d18c3736071647b38f0786
CRUZEAAKASH/PyCharmProjects
/section5_Functions/FunctionsProblems.py
2,525
4.875
5
""" Single parameter and zero parameter functions: 1.define a function that takes no parameters and prints a string 2.create a variable and assign it the value 5 3.create a function that takes a single parameter and prints it 4.call the function you created in step 1 5.call the function you created in step 3 with the variable you made in step 2 as its input """ # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- def function1(): print("printing Method 1") var1 = 5 def function2(a): print(a) function1() function2(var1) """ multiple parameter functions: 1.create 3 variables and assign integer values to them 2.define a function that prints the difference of 2 parameters 3.define a function that prints the product of the 3 variables 4.call the function you made in step 2 using 2 of the variables you made for step 1 5.call the function you made in step 3 using the 3 variables you created for step 1 """ # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- var1 = 10 var2 = 20 var3 = 30 def function3(a,b): print(abs(a-b)) def function4(a,b,c): print(a * b * c) function3(var1,var2) function4(var1,var2,var3) """ Calling previously defined functions within functions: 1.create 3 variables and assign float values to them 2.create a function that returns the quotient of 2 parameters 3.create a function that returns the quotient of what is returned by the function from the second step and a third parameter 4.call the function you made in step 2 using 2 of the variables you created in step 1. Assign this to a variable. 5.print the variable you made in step 4 6.print a call of the function you made in step 3 using the 3 variables you created in step 1 """ # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- flt1 = 10.0 flt2 = 20.0 flt3 = 30.0 def function5(a,b): return a/b def function6(a,b,c): return((function5(a,b))/c) flat4 = function5(flt1,flt2) print(flat4) print(function6(flt2,flt1,flt3))
true
1a07035dcb4f3909b26f5b0aa1d1b4af20192866
CRUZEAAKASH/PyCharmProjects
/section15_Tkinter/TkinterMessageBox.py
340
4.125
4
from tkinter import Tk from tkinter import messagebox window = Tk() messagebox.showinfo("title", "You are seeing message box") response = messagebox.askquestion("Question 1", "Do you love Coffee?") if (response == 'yes'): print("Here are your coffee loverrr!!!!!!!!!!!!!!!!!") else: print("What do you love???") window.mainloop()
true
ef26690eccdd553f9a81cd1b9daa6f5c9e02cb93
chithracmenon/AutomateBoringStuff
/ch7_date_detection.py
1,743
4.71875
5
"""Date Detection Write a regular expression that can detect dates in the DD/MM/YYYY format. Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero. The regular expression doesn’t have to detect correct days for each month or for leap years; it will accept nonexistent dates like 31/02/2020 or 31/04/2021. Then store these strings into variables named month, day, and year, and write additional code that can detect if it is a valid date. April, June, September, and November have 30 days, February has 28 days, and the rest of the months have 31 days. February has 29 days in leap years. Leap years are every year evenly divisible by 4, except for years evenly divisible by 100, unless the year is also evenly divisible by 400. Note how this calculation makes it impossible to make a reasonably sized regular expression that can detect a valid date.""" #!python3 # Date Detection import regex as re import sys regexobject = re.compile(r'([0-2]?[0-9]|31|30)/([0]?[0-9]|[1][0-2])/([1-2][0-9][0-9][0-9])') date = '29/2/2020' mo = regexobject.findall(date) if len(mo): date = int(mo[0][0]) month = int(mo[0][1]) year = int(mo[0][2]) else: print("Not valid date") sys.exit() def leap_year(year): return (~(year % 4) and (year % 100) or ~(year % 400))) months_with30 = [4, 6, 9, 11] if (month in months_with30) and (date <= 30): print("Valid date1") elif (month == 2) and ((date <= 28) or ((date <= 29) and (leap_year(year)))): print("valid date2") elif (month not in (months_with30 + [2])) and (date <= 31): print("valid date4") else: print("invalid date") print(date, month, year)
true
4a891d4030805ca7bab9a9b2538d3c2084cd3114
JaneNjeri/python_crash_course
/factorial.py
235
4.3125
4
def factorial(num): if num == 0: return 1 else: return num * factorial(num - 1) print("Please enter a number to recieve its factorial.") num = int(input() ) print (factorial(num)) # good recursion practice
true
ac74ba0fde939786aca05fff2648c368f46db4ef
miaha15/Programming-coursework
/Week 5 Question 1.py
974
4.34375
4
''' Premade list is given to the function A for loop is used to step through the list As it steps through each value of the list, it appends the list called TempList If the current element is GREATER than the next element of the list then it will check if everything stored in the TempList upto current element is longer than the sequence stored in LongestSequence If it is then it will be overwritten, else it will ignore. ''' import sys def SubSequence(List): TempList = [] LongestSequence = ("") for element in range(0, len(List)-1): TempList.append(List[element]) if List[element] > List[element+1]: if len(TempList) > len(LongestSequence): LongestSequence = [] LongestSequence = TempList TempList = [] return LongestSequence print('The Longest Sub-Sequence is:', SubSequence([1,2,3,4,1,2,3,4,5,0])) sys.exit()
true
9067db5d36f43f7d225c98628272ab067ac8dbd9
yerol89/100_Days_Of_Coding_With_Python
/1. Day_1_Working With Variables to Manage Data/Day1.py
861
4.1875
4
print("Day 1 - String Manipulation") print("String Concatenation is done with the '+' sign.") print("New lines can be created with a backslash.") print("Hello" + " " + "Everyone") print("Hello Python\nHello 100 Days of Coding") print("Hello" + " " + input("What is your name?\n")) name = input("What is your name? ") print("Length of your name is " + str(len(name))) #Swapping variables with each other a = input("a: ") b = input("b: ") print("BEFORE SWAP") print("a is equal to " + a) print("b is equal to " + b) c = a a = b b = c print("AFTER SWAP") print("a is equal to " + a) print("b is equal to " + b) # DAY1 PROJECT : BAND NAME GENERATOR print("Welcome to Band Name Generator") city = input("What is the name of city that you borned?\n") pet = input("What is the name of your first pet?\n") print("The name of the band is " + city +"_" + pet + " BAND")
true
5e5d664cba8f82e045f025a763a3825d5342b0dd
msausville/ToolBox-Pickling
/counter.py
2,030
4.40625
4
""" A program that stores and updates a counter using a Python pickle file""" from os.path import exists import sys from pickle import dump, load def update_counter(file_name, reset=False): """ Updates a counter stored in the file 'file_name' A new counter will be created and initialized to 1 if none exists or if the reset flag is True. If the counter already exists and reset is False, the counter's value will be incremented. file_name: the file that stores the counter to be incremented. If the file doesn't exist, a counter is created and initialized to 1. reset: True if the counter in the file should be rest. returns: the new counter value >>> update_counter('blah.txt',True) 1 >>> update_counter('blah.txt') 2 >>> update_counter('blah2.txt',True) 1 >>> update_counter('blah.txt') 3 >>> update_counter('blah2.txt') 2 """ # Note: Looked at classmates' code to help make this. if exists(file_name) and not reset: # The file has already been made and the reset button hasn't been pressed. file = open(file_name, 'rb+') # Open the file in reading mode counter = load(file) counter += 1 # Tell the counter to add one because the file was opened again. file.close return counter # Close the file and tell us the number on the counter. else: file = open(file_name, 'wb') # The file hasn't been declared or has been reset, rewrite it or make a new one. counter = 1 # The file has been opened once so the count is one. dump(counter, file) # dumping it is what saves the pickle. file.close return counter # pickle.load # check if file exists # if doesn't, create file # initialize counter variable if __name__ == '__main__': if len(sys.argv) < 2: import doctest doctest.testmod() else: print("new value is " + str(update_counter(sys.argv[1])))
true
2b47b550001583c7a0f60d8b2022051796d39ad5
utkpython/utkpython.github.io
/session3/simulation.py
733
4.3125
4
# modeling the idea that "students getting ahead in life" # some start off in a higher spot # some have more skill, some less from random import randint import matplotlib.pyplot as plt def rand_walk(numSteps, position, skill): '''Returns a random walk list of size numSteps + 1. position is the starting position. skill is a measure of how far forward you are able to walk per turn.''' walk = [position] numSteps = numSteps for i in xrange(numSteps): if randint(0,1): step = 1 * skill #take a step forward else: step = -1 #take a step backward position = position + step walk.append(position) return walk
true
1ae5d1eb7c5408cedc29486dbe1ee36a2a0df77c
joyvai/Python-
/stopwatch.py
1,615
4.28125
4
# stopwatch.py - A simple stopwatch program. # The stopwatch program will need to use the current time, so you will want to # import the time module. Your program should also print some brief instruc- # tions to the user before calling input() , so the timer can begin after the user # presses enter . Then the code will start tracking lap times. import time # Display the program's instructions. print ('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch.Press Ctrl-C to quit.') raw_input() # press ENTER to begin print 'Started.' startTime = time.time() # get the first lap's start time. lastTime = startTime lapNum = 1 # TODO: Start tracking the lap times. # Step 2: Track and Print Lap Times try: while True: raw_input() lapTime = round(time.time() - lastTime,2) totalTime = round(time.time() - startTime, 2) print 'Lap #%s: %s (%s)' % (lapNum, totalTime, lastTime) lapNum += 1 lastTime = time.time() # reset the last lap time except KeyboardInterrupt: print '\nDone.' # we use except because of KeyboardInterrupt error messages. # It works when Ctrl-C press. # Here while loop is a infinite loop. # it calls the raw_input() and waits for enter # to end a lap.when user press enter that means lap finished. # when a lap ends we calculate the laptime. # we subtract the start time of the lap from current time using time.time() # We calculate the total time elapsed by subtracting # the overall start time of the stopwatch, startTime ,from the current time # setting lastTime to the current time, which # is the start time of the next lap.
true
7412acf2022c4a9509ddd22859ba8f85422abf57
fobbytommy/Algorithm-Practice
/10_week_2/nth_largest.py
386
4.34375
4
# Given an array, return the Nth-largest element from python_modules import bubble_sort def nth_largest(arr, n): list_length = len(arr) if n <= 0 or list_length < n: return None sorted_arr = arr bubble_sort.bubble_sort(sorted_arr) return sorted_arr[list_length - n] arr = [23, 32, -2 , 6 ,2 ,7, 10, 3, 10, 22, 3, -1, 19, 24, 33] result = nth_largest(arr, 3) print(result)
true
8f4667338e761fca8b77a813d4f5ee957e0cbaa0
Akansha0211/Basics-of-try-except-revision
/Basics of try-except.py
1,461
4.1875
4
'''num1=input("Enter the first number \n") num2=input("Enter the second number \n") try: print("the sum of twoi numbers is", int(num1) + int(num2)) except Exception as e: print(e) print("This line is very important")''' #Will never come in except block '''a=[1,2,3] try: print("second element",a[1]) except Exception as e: print("Fourth element") print(" An Error occured") ''' '''a=[1,2,3] try: print("Second element is",a[1]) print("Fourth element is",a[3]) except Exception as e: print(e)''' '''a=[1,2,3] try: print("Second element",a[1]) print("Fourth element is",a[3]) except IndexError: print("An Error occured")''' '''try: a=3 if a<4: b=a/(a-3) print(b) except Exception as e: print(e)''' '''try: a=eval(input("Enter anumber between 3 and 4,inclusive")) if a<4: b=a/(a-3) print("Value of b:",b) print("Value of b",b) except (ZeroDivisionError): print("ZeroDivsionError occured") except (NameError): print("NameError occured")''' '''def func(a,b): try: c=(a+b)/(a-b) except (ZeroDivisionError): print("Result is 0") else: print(c) func(3,2) func(2,2)''' #Raise statement #force a specific exception to occur. # try: # raise NameError("Hi there") #raise # except NameError: # print("An exception") # raise
true
8c4d57da1267b058b76250618f25893a4114949f
jonesy212/Sorting
/src/iterative_sorting/iterative_sorting.py
1,277
4.15625
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): def selection_sort(arr): for i in range(0, len(arr)-1): cur__index = i smallest_index = cur_index #find the next smallest element q for x in range(cur_index, len(arr)): if arr[x] < arr[smallest_index]: #found new smallest thing! smalles_index = x # loop through everything but the last element return arr # Always pick first element as pivot. # Always pick last element as pivot (implemented below) # Pick a random element as pivot. # Pick median as pivot. # *compare first and last number # *if second number is bigger than the # one to the left, swap # # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): swap = True while swap: swap = False for i range(0, len(arr)-1): current_index = i next_index = i + 1 if arr[i] > arr[next_index]: arr[i], arr[next_index] = arr[next_index], arr[i] swap = True return arr # print(arr.sort()) # # STRETCH: implement the Count Sort function below # def count_sort( arr, maximum=-1 ): # return arr
true
be344fd136945a81eb038d99bbda7372fdba3c0b
anihakobyan98/group-2
/Exceptions/task4.py
274
4.5
4
''' Number that type is integer and it can be divided to 3 ''' try: a = int(input("Enter a number: ")) except ValueError: print("Entered value must be an integer type") else: if a % 3 != 0: raise TypeError("Number must be divisible to 3") else: print("Excellent")
true
b1119e6cb30d4b4a20dcc6a0f7065150fc080b32
ayushthesmarty/Simple-python-car-game
/main.py
1,336
4.25
4
help_ = """ The are the commands of the game help - show the commands start - start the car stop - stop the car exit - exit the game """ print(help_) running = True car_run = False while running: command = input("Your command: ").lower() if command == "help": print(help_) elif command == "start": if not car_run: car_run = True print("Starting car!!\n") print("The car is started!!") else: print("Starting car!!\n") print("The car is already started!!") elif command == "stop": if car_run: car_run = False print("Stopping car!!\n") print("The car is stopped!!") else: print("Stopping car!!\n") print("The car is already stopped!!") elif command == "exit": exit_run = True while exit_run: input_ = input("Do you want to exit the game? (y or n) ").lower() if input_ == "y": print("Bye, Bye!") exit() elif input_ == "n": break else: print("I don't recognize this command!!!") else: print("I don't recognize this command!!!")
true
1ff020d024ad2dd9d2e238125f6ec7402acac880
chanzer/leetcode
/575_distributeCandies.py
1,205
4.625
5
""" Distribute Candies 题目描述: Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain. Example 1: Input: candies = [1,1,2,2,3,3] Output: 3 Explanation: There are three different kinds of candies (1, 2 and 3), and two candies for each kind.Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. The sister has three different kinds of candies. Example 2: Input: candies = [1,1,2,3] Output: 2 Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies. Note: 1.The length of the given array is in range [2, 10,000], and will be even. 2.The number in given array is in range [-100,000, 100,000]. """ class Solution: def distributeCandies(self,candies): """ :type candies:List[int] :rtype : int """ return min(len(candies)//2,len(set(candies)))
true
25b3275a82d546d5f17f9232ec4c363e2e85c402
chanzer/leetcode
/867_transpose.py
862
4.21875
4
""" Transpose Matrix 题目描述: Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. Example 1: Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2: Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]] Note: 1. 1 <= A.length <= 1000 2. 1 <= A[0].length <= 1000 """ # 方法一: class Solution: def transpose(self, A): return list(zip(*A)) # 方法二: class Solution: def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ R,C = len(A),len(A[0]) ans = [[None]*R for _ in range(C)] for r,row in enumerate(A): for c,val in enumerate(row): ans[c][r] = val return ans
true
6d801ce1b4951d9b4b7fa1c7e39aa2d1dd69a1b4
chanzer/leetcode
/697_findShortestSubArray.py
1,269
4.21875
4
""" Degree of an Array 题目描述: Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. Example 1: Input: [1, 2, 2, 3, 1] Output: 2 Explanation:The input array has a degree of 2 because both elements 1 and 2 appear twice.Of the subarrays that have the same degree:[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2. Example 2: Input: [1,2,2,3,1,4,2] Output: 6 Note: nums.length will be between 1 and 50,000. nums[i] will be an integer between 0 and 49,999. """ from collections import Counter class Solution: def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ c = Counter(nums) deg = max(c.values()) if deg == 1: return 1 candidates = [k for k in c if c[k] == deg] n = len(nums) minlen = 50000 for i in candidates: l = nums.index(i) r = n - nums[::-1].index(i) - 1 minlen = min(minlen, r - l + 1) return minlen
true
4eef3b2411dd7eaa18cd6ceb5224098379d4672c
chanzer/leetcode
/628_maximumProduct.py
669
4.5
4
""" Maximum Product of Three Numbers 题目描述: Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output:6 Example 2: Input: [1,2,3,4] Output:24 Note: 1.The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. 2.Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. """ class Solution: def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return max(nums[0]*nums[1]*nums[-1],nums[-1]*nums[-2]*nums[-3])
true
0f8c88f4a60a4c9f26553c9903e7d6d111ca8ed1
chanzer/leetcode
/453_minMoves.py
842
4.15625
4
""" Minimum Moves to Equal Array Elements 题目描述: Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. Example: Input:[1,2,3] Output:3 Explanation:Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] """ # 方法一 class Solution: def minMoves(self, nums): """ :type nums: List[int] :rtype: int """ return sum(nums) - len(nums) * min(nums) # 方法二 class Solution(object): def minMoves(self, nums): """ :type nums: List[int] :rtype: int """ minimum = min(nums) res = 0 for n in nums: res += n - minimum return res
true
6947cc6a019c3b232b432788a8ce9ed5729e8551
MichelGeorgesNajarian/randomscripts
/Python/recursive_rename.py
907
4.28125
4
# Python3 code to rename multiple # files in a directory or folder #give root directory as argument when executing program and all the file in root directory and subsequent folders will be renamed #renaming parameter are to remove any '[xyz123]', '(xyz123)' and to replace '_' by ' ' # importing os module import os import re import sys # Function to rename multiple files def main(): pathToDir = str(sys.argv[1]) for root, dirs, files in os.walk(pathToDir): for filename in files: newFile = re.sub(r'(\s)*\[(.*?)\](\s)*|(\s)*\((.*?)\)(\s)*', '', filename) #regex to match all patterns that are of the form striong inside square or normal brackets newFile = re.sub(r'_', ' ', newFile) #replace _ by whitespace if (newFile != filename): os.rename(root + "\\" + filename, root + "\\" + newFile) # Driver Code if __name__ == '__main__': # Calling main() function main()
true
0d1564abb38b41d58ce025ee1353e90e62d084be
wrgsRay/playground
/amz_label.py
2,181
4.21875
4
""" Python 3.6 @Author: wrgsRay """ import time class Shipment: def __init__(self, last_page, total_pallet, pallet_list=[], current_pallet): self.last_page = last_page self.total_pallet = total_pallet self.pallet_list = pallet_list self.current_pallet = current_pallet def get_pallet_input(self): while True: pallet_input = input(f'Please enter carton number for Pallet {self.current_pallet}, enter nothing to stop ') if pallet_input == '': break else: pallet_input = int(pallet_input) self.pallet_list.append(pallet_input) print(f'Pallet {self.current_pallet}: {pallet_input}') self.current_pallet += 1 def amz(): shipment = Shipment(1, 10, [], 1) shipment.get_pallet_input() def main(): last_page = int(input('Please enter the last page number(eg. 1064) ')) pallet_total = int(input('Please enter the total number of pallets(eg. 24) ')) pallet_list = list() current_pallet = 1 while True: pallet_input = input(f'Please enter carton number for Pallet {current_pallet}, enter nothing to stop ') if pallet_input == '': break else: pallet_input = int(pallet_input) pallet_list.append(pallet_input) print(f'Pallet {current_pallet}: {pallet_input}') current_pallet += 1 if len(pallet_list) != pallet_total: print(f'Pallet Total mismatch: expected {pallet_total} pallets got {len(pallet_list)} pallets') elif sum(pallet_list) != last_page: print(f'Carton Total Mismatch expected {last_page} cartons got {sum(pallet_list)} cartons') # pallet_list = [49, 49, 36, 36, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 48, 44, 30, 15, 35, 48, 56, 30] else: current = 1 print(len(pallet_list)) print(sum(pallet_list)) for pallet in pallet_list: print(f'{current}-{current + pallet - 1}') current += pallet print('Window is closing in 30 seconds...') time.sleep(30) if __name__ == '__main__': amz()
true
d603602255347b138dfb7b6685222b2b03501986
SaraKenig/codewars-solutions
/python/7kyu/Unique string characters.py
598
4.34375
4
# In this Kata, you will be given two strings a and b and your task will be to return the characters that are not common in the two strings. # For example: # solve("xyab","xzca") = "ybzc" # --The first string has 'yb' which is not in the second string. # --The second string has 'zc' which is not in the first string. # Notice also that you return the characters from the first string concatenated with those from the second string. # More examples in the tests cases. # Good luck! def solve(a,b): return f'{"".join([r for r in a if r not in b])}{"".join([r for r in b if r not in a])}'
true
acbf417955c0e14618b09ab10a0952fc6e63d79a
SaraKenig/codewars-solutions
/python/7kyu/sort array by last character.py
539
4.34375
4
# Sort array by last character # Write a function sortMe or sort_me to sort a given array or list by last character of elements. # Element can be an integer or a string. # Example: # sortMe(['acvd','bcc']) => ['bcc','acvd'] # The last characters of the strings are d and c. As c comes before d, sorting by last character will give ['bcc', 'acvd']. # If two elements don't differ in the last character, then they should be sorted by the order they come in the array. def sort_me(arr): return sorted(arr, key=lambda x: str(x)[-1])
true
77637b2eaef358ad308de773a915caddab871f12
begogineni/cs-guided-project-python-basics
/src/demonstration_03.py
566
4.40625
4
""" Challenge #3: Create a function that takes a string and returns it as an integer. Examples: - string_int("6") ➞ 6 - string_int("1000") ➞ 1000 - string_int("12") ➞ 12 """ import re def string_int(txt): ''' input: str output: int ''' # Your code here #what to do if there is a letter in the given string - remove all but numbers - check other assignments # only_nums = re.sub('[^a-zA-Z ]', '', txt) #replace # return int(only_nums) return int(txt) # check print(string_int("65")) # print(string_int("65 tigers"))
true
2bea7f84ca43f1bfde89b3590f7212edf469a5d9
tarushsinha/WireframePrograms
/3fizz5buzz.py
452
4.125
4
## program that returns multiples of 3 as fizz, multiples of 5 as buzz, and multiples of both as fizzbuzz within a range def fizzBuzz(rng): retList = [] for i in range(rng): if i % 3 == 0 and i % 5 == 0: retList.append("fizzbuzz") elif i%3 == 0: retList.append("fizz") elif i%5 == 0: retList.append("buzz") else: retList.append(i) print(retList) fizzBuzz(100)
true
52f36317552e8eb0e533b61c0f4947b653e7d52d
saikirandulla/HW06
/HW06_ex09_04.py
1,337
4.40625
4
#!/usr/bin/env python # HW06_ex09_04.py # (1) # Write a function named uses_only that takes a word and a string of letters, # and that returns True if the word contains only letters in the list. # - write uses_only # (2) # Can you make a sentence using only the letters acefhlo? Other than "Hoe # alfalfa?" # - write function to assist you # - type favorite sentence(s) here: # 1: Hello half leech face # 2: cool cafe coffee # 3: coach fell off hellhole ############################################################################## # Imports # Body def uses_only(word, s): flag = True for letter in word: if letter not in s: return False return True # if word.find(s[i]) == -1: # flag = False # else: # flag = True # return True # return False def word_maker(): fin = open('words.txt') words_file_list = [] for line in fin: words_file_list.append(line.strip('\r\n')) return words_file_list def sentence_maker(words_file_list): count = 0 for letter in words_file_list: if uses_only(letter, 'acefhlo'): count +=1 print letter print count ############################################################################## def main(): words_file_list = word_maker() sentence_maker(words_file_list) # print uses_only("Hello", "abcd") if __name__ == '__main__': main()
true
31f3c7d5da418e3abbf4c44fced349ab7aac1fab
yotroz/white-blue-belt-modules
/17-exceptions/blue_belt.py
488
4.53125
5
#%% #Create a function that reads through a file #and prints all the lines in uppercase. # # # #be sure to control exceptions that may occur here, #such as the file not existing def print_file_uppercase(filename): try: file = open(filename) for line in file: print(line.upper().strip()) except Exception: print("file doesnt exist") print_file_uppercase("data.txt") print_file_uppercase("other_file.txt")
true
147ebca997008e894bd6b5f6f74d63c658643188
Umesh8Joshi/My-Python-Programs
/numbers/PItoNth.py
274
4.21875
4
''' Enter a number to find the value of PI till that digit ''' def nthPI(num): ''' function to return nth digit value of PU :param num: number provided by user :return : PI value till that digit ''' num = input('Enter the digit') return "%.{num}f"(22/7).format(num)
true
d05ea438611f9a1af279a4935c1c966047ae41d5
Chener-Zhang/HighSchoolProject
/Assembly/hw6pr5.py
2,447
4.15625
4
# hw6 problem 5 # # date: # # Hmmm... # # # For cs5gold, this is the Ex. Cr. recursive "Power" (Problem4) # and recursive Fibonacci" (Problem5) program # Here is the starter for gold's Problem4 (recursive power): # This is the recursive factorial from class, to be changed to a recursive _power_ program: Problem4 = """ 00 read r1 # read input and put into r1. 01 setn r15 42 # 42 is the beginning of the stack, put that address in r15. 02 call r14 5 # begin function at line 5, but first put next address (03) into r14. 03 jumpn 21 # Let's defer final output to line 21... 04 nop # no operation -- but useful for squeezing in an extra input... 05 jnez r1 8 # BEGINNING OF FACTORIAL FUNCTION! Check if r1 is non-zero. If it is go to line 8 and do the real recursion! 06 setn r13 1 # otherwise, we are at the base case: load 1 into r13 and... 07 jumpr r14 # ... return to where we were called from (address is in r14) 08 storer r1 r15 # place r1 onto the stack 09 addn r15 1 # increment stack pointer 10 storer r14 r15 # place r14 onto the stack 11 addn r15 1 # increment stack pointer 12 addn r1 -1 # change r1 to r1-1 in preparation for recursive call 13 call r14 5 # recursive call to factorial, which begins at line 5 - but first store next memory address in r14 14 addn r15 -1 # we're back from the recursive call! Restore goods off the stack. 15 loadr r14 r15 # restoring r14 (return address) from stack 16 addn r15 -1 # decrement stack pointer 17 loadr r1 r15 # restoring r1 from stack 18 mul r13 r13 r1 # now for the multiplication 19 jumpr r14 # and return! 20 nop # nothing 21 write r13 # write the final output 22 halt """ # # for the other extra credit, here's a placeholder... (named Problem5) # # This is a placeholder by that name whose code you'll replace: Problem5 = """ 00 read r1 # get # from user to r1 01 read r2 # ditto, for r2 02 mul r3 r1 r2 # r3 = r1 * r2 03 write r3 # print what's in r3 04 halt # stop. """ # This function runs the Hmmm program specified # def run(): """ runs a Hmmm program... """ import hmmmAssembler ; reload(hmmmAssembler) # import helpers hmmmAssembler.main(Problem4) # this runs the code! # change this name ^^^^^^^^ to run a different function!
true
f8c33c98dc671fd597a5b40848d72e42f504fbc5
tsakallioglu/Random-Python-Challenges
/Weak_numbers.py
1,324
4.25
4
#We define the weakness of number x as the number of positive integers smaller than x that have more divisors than x. #It follows that the weaker the number, the greater overall weakness it has. For the given integer n, you need to answer two questions: #what is the weakness of the weakest numbers in the range [1, n]? #how many numbers in the range [1, n] have this weakness? #Return the answer as an array of two elements, where the first element is the answer to the first question, #and the second element is the answer to the second question. #Function that calculates the number of divisors for a given number def num_of_div(n): div=[] result=1 if n!=1: while (n!=1): for i in range(2,n+1): if n%i==0: div.append(i) n /= i break for x in set(div): result *= div.count(x)+1 return result #Main Function def weakNumbers(n): divisors=[] weaknesses=[] for i in range(1,n+1): curr_div=num_of_div(i) divisors.append(curr_div) weakness=0 for j in range (1,i): if divisors[j]>curr_div: weakness += 1 weaknesses.append(weakness) return [max(weaknesses),weaknesses.count(max(weaknesses))]
true
71417cb49cb8704d54aa0f6f923e92bd37da5bd9
Niteshyadav0331/Zip-File-Extractor
/main.py
248
4.15625
4
from zipfile import ZipFile file_name = input("Enter the name of file you want to file in .zip: ") with ZipFile(file_name, 'r') as zip: zip.printdir() print('Extracting all the files...') zip.extractall() print("Done!")
true
74d174d8878c2604daf720d755e6b156a6ec4881
netor27/codefights-solutions
/arcade/python/arcade-theCore/07_BookMarket/053_IsTandemRepeat.py
643
4.3125
4
def isTandemRepeat(inputString): ''' Determine whether the given string can be obtained by one concatenation of some string to itself. Example For inputString = "tandemtandem", the output should be isTandemRepeat(inputString) = true; For inputString = "qqq", the output should be isTandemRepeat(inputString) = false; For inputString = "2w2ww", the output should be isTandemRepeat(inputString) = false. ''' middle = len(inputString) // 2 return inputString[:middle] == inputString[middle:] print(isTandemRepeat("tandemtandem")) print(isTandemRepeat("qqq"))
true
e082ba713c0a0001a3c47dfb5b1e31719534600d
netor27/codefights-solutions
/arcade/python/arcade-theCore/07_BookMarket/054_IsCaseInsensitivePalindrome.py
339
4.1875
4
def isCaseInsensitivePalindrome(inputString): ''' Given a string, check if it can become a palindrome through a case change of some (possibly, none) letters. ''' lowerCase = inputString.lower() return lowerCase == lowerCase[::-1] print(isCaseInsensitivePalindrome("AaBaa")) print(isCaseInsensitivePalindrome("aabbc"))
true
c32f3501b32a4141e575abe2f57b9b8eb712b6e1
netor27/codefights-solutions
/arcade/python/arcade-intro/02_Edge of the Ocean/004_adjacentElementsProduct.py
522
4.15625
4
def adjacentElementsProduct(inputArray): '''Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. ''' n = len(inputArray) if n < 2: raise "inputArray must have at least 2 elements" maxValue = inputArray[0] * inputArray[1] for i in range(n - 1): aux = inputArray[i] * inputArray[i + 1] if aux > maxValue: maxValue = aux return maxValue print(adjacentElementsProduct([3, 6, -2, -5, 7, 3]))
true