blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
8c8da9e1a61a6d6d78a2535e2b1bbda1a31b8b17
hhoangnguyen/mit_6.00.1x_python
/test.py
508
4.3125
4
def insertion_sort(items): # sort in increasing order for index_unsorted in range(1, len(items)): next = items[index_unsorted] # item that has to be inserted # in the right place # move all larger items to the right i = index_unsorted while i > 0 and items[i - 1] > next: items[i] = items[i - 1] i = i - 1 # insert the element items[i] = next return items result = insertion_sort([3, 4, 7, -1, 2]) print(result)
true
08b1c52901da46b2e7beb41246effc65ed9b4d3f
hhoangnguyen/mit_6.00.1x_python
/week_1/1_1.py
713
4.15625
4
""" Assume s is a string of lower case characters. Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print: 5 """ string = 'azcbobobegghakl' def is_valid_vowel(char): if char == 'a': return True if char == 'e': return True if char == 'i': return True if char == 'o': return True if char == 'u': return True return False def get_num_vowels(s): num_vowels = 0 for index in range(len(s)): if is_valid_vowel(s[index]): num_vowels += 1 print(num_vowels) get_num_vowels(string)
true
655a5b9cf59b58bde19148bbae7ad6650fe23374
advikchava/python
/learning/ms.py
484
4.21875
4
print("1.Seconds to minutes") print("2.Minutes to seconds") ch=int(input("Choose one option:")) if ch==1: num=int(input("Enter time in seconds:")) minutes=int(num/60) seconds=int(num%60) print("After the Seconds are converted to Minutes, the result is:",minutes,"Minutes", seconds,"Seconds") elif ch==2: num=float(input("Enter time in minutes:")) seconds=int(num*60) print("After the Minutes are converted to Seconds, the result is:", seconds,"Seconds")
true
156203c9c9a1c80101caf18ba558e1c89f682c42
JasmineOsti/pythonProject1
/Program.py
289
4.3125
4
#Write a program that takes three numbers and prints their sum. Every number is given on a separate line. A = int(input("Enter the first number: ")) B = int(input("Enter the second number: ")) C = int(input("Enter the third number: ")) sum = A+B+C print("the sum of three numbers is", sum)
true
df5270ff28213fc89bf0ee436b9855c73e026d9d
Sakshi011/Python_Basics
/set.py
1,190
4.21875
4
# set data type # unordered collection of data # INTRO ---------------------------------------------------------------------------------- s = {1,1.1,2.3,3,'string'} print(s) print("\n") # In set all elemets are unique that's why it is used to remove duplicate elements l = [1,2,4,2,3,6,3,7,6,6] s2 = list(set(l)) print(s2) print("\n") # ADD AND REMOVE ELEMENT ----------------------------------------------------------------- s3 = {1,2,3} s3.add(4) s3.add(5) print(s3) s3.remove(4) s3.discard(5) print(s3) print("\n") # FOR LOOP ------------------------------------------------------------------------------ for i in s: print(i) print("\n") # UNION --------------------------------------------------------------------------------- s1 = {1,2,3,4} s2 = {3,4,5,6} union_set = s1 | s2 print(union_set) print("\n") # INTERSECTION -------------------------------------------------------------------------- intersection_set = s1 & s2 print(intersection_set) print("\n") # SET COMPREHENSION --------------------------------------------------------------------- s = {i**2 for i in range(1,11)} print(s) print("\n") names = ['siya','tiya','nia'] first = {i[0] for i in names} print(first)
true
25401f5061ccabbded56366310f5e42e910eddd7
gourdcyberlab/pollen-testbed
/scapy-things/varint.py
1,438
4.375
4
#!/usr/bin/env python import itertools ''' Functions for converting between strings (formatted as varints) and integers. ''' class VarintError(ValueError): '''Invalid varint string.''' def __init__(self, message='', string=None): ValueError.__init__(self, message) self.string = string # Can't add methods to `int` or `str`, so we have these functions instead. def varint_str(x): '''Convert a number to its string varint representation.''' out = [] while x != (x & 0x7F): n, x = x & 0x7F, x >> 7 out += [chr(n | 0x80)] out += [chr(x)] return str.join('', out) def varint_with_remainder(s): '''Convert a string representation of a varint to an integer, with the remainder of the string. Returns (remainder, num).''' try: items = list(itertools.takewhile((lambda c: ord(c) & 0x80), s)) items.append(s[len(items)]) n = reduce((lambda x, (i, c): x+((ord(c) & 0x7F) << (i*7))), enumerate(items), 0) return s[len(items):], n except IndexError: raise VarintError('Not a valid varint', s) def varint_num(s): '''Convert a string representaion of a varint to an integer.''' return varint_with_remainder(s)[1] def varint_list(s): '''Convert a string of varints to integers. Assumes that there is no trailing string after final varint''' while s: s, n = varint_with_remainder(s) yield n
true
2c1699da529112c4820a06bdd0933ae4c6c11032
colinmcnicholl/automate_boring_tasks
/firstWordRegex.py
840
4.25
4
import re """How would you write a regex that matches a sentence where the first word is either Alice, Bob, or Carol; the second word is either eats, pets, or throws; the third word is apples, cats, or baseballs; and the sentence ends with a period? This regex should be case-insensitive.""" firstWordRegex = re.compile(r'^(Alice|Bob|Carol)\s+(eats|pets|throws)\s+(apples|cats|baseballs)\s*.$', re.IGNORECASE) print(firstWordRegex.search('Alice eats apples.')) print(firstWordRegex.search('Bob pets cats.')) print(firstWordRegex.search('Carol throws baseballs.')) print(firstWordRegex.search('Alice throws Apples.')) print(firstWordRegex.search('BOB EATS CATS.')) print(firstWordRegex.search('Robocop eats apples.')) print(firstWordRegex.search('ALICE THROWS FOOTBALLS.')) print(firstWordRegex.search('Carol eats 7 cats.'))
true
901cfcc418c14cbdc3dc6b67440c0bcd22c42a35
bryano13/holbertonschool-interview
/0x09-utf8_validation/0-validate_utf8.py
1,186
4.15625
4
#!/usr/bin/python3 """ This software defines rules to check if an integer combination is a valid UTF-8 Encoding A valid UTF-8 character can be 1 - 4 bytes long. For a 1-byte character, the first bit is a 0, followed by its unicode. For an n-bytes character, the first n-bits are all ones, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. """ def validUTF8(data): """ args: @data: Integer list with the information about the character Return: True if the integers are UTF 8 encodable False otherwise """ bytes_num = 0 for num in data: mask = 1 << 7 if bytes_num == 0: # If byte is not in chain dont ask for confirmation bytes while mask & num: bytes_num += 1 mask = mask >> 1 if bytes_num == 0: continue elif bytes_num == 1 or bytes_num > 4: return False else: # If byte doesnt start with 10 return false if not (num & 1 << 7 and not (num & 1 << 6)): return False bytes_num -= 1 if bytes_num == 0: return True return False
true
ad34250006ebd1305657f4ba94cd7982895f6ddb
sofiarani02/Assigments
/Assignment-1.2.py
2,825
4.5
4
print("***Python code for List operation***\n") # declaring a list of integers myList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # List slicing operations # printing the complete list print('myList: ',myList) # printing first element print('first element: ',myList[0]) # printing fourth element print('fourth element: ',myList[3]) # printing list elements from 0th index to 4th index print('myList elements from 0 to 4 index:',myList[0: 5]) # printing list -7th or 3rd element from the list print('3rd or -7th element:',myList[-7]) # appending an element to the list myList.append(111) print('myList after append():',myList) # finding index of a specified element print('index of \'80\': ',myList.index(80)) # sorting the elements of iLIst myList.sort() print('after sorting: ', myList); # popping an element print('Popped elements is: ',myList.pop()) print('after pop(): ', myList); # removing specified element myList.remove(80) print('after removing \'80\': ',myList) # inserting an element at specified index # inserting 100 at 2nd index myList.insert(2, 100) print('after insert: ', myList) # counting occurances of a specified element print('number of occurences of \'100\': ', myList.count(100)) # extending elements i.e. inserting a list to the list myList.extend([11, 22, 33]) print('after extending:', myList) #reversing the list myList.reverse() print('after reversing:', myList) #clearing the list myList.clear() print('after clearing:', myList) print("\n*********************************************\n") print("***Python code for String operation***\n") s = "Strings are awesome!" # Length should be 20 print("Length of s = %d" % len(s)) # First occurrence of "a" should be at index 8 print("The first occurrence of the letter a = %d" % s.index("a")) # Number of a's should be 2 print("a occurs %d times" % s.count("a")) # Slicing the string into bits print("The first five characters are '%s'" % s[:5]) # Start to 5 print("The next five characters are '%s'" % s[5:10]) # 5 to 10 print("The thirteenth character is '%s'" % s[12]) # Just number 12 print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing) print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end # Convert everything to uppercase print("String in uppercase: %s" % s.upper()) # Convert everything to lowercase print("String in lowercase: %s" % s.lower()) # Check how a string starts if s.startswith("Str"): print("String starts with 'Str'. Good!") # Check how a string ends if s.endswith("ome!"): print("String ends with 'ome!'. Good!") # Split the string into three separate strings, # each containing only a word print("Split the words of the string: %s" % s.split(" "))
true
56cc4deeb8d82fe0a032ea4b0f84feff308315ab
baroquebloke/project_euler
/python/4.py
541
4.125
4
# A palindromic number reads the same both ways. The largest palindrome made # from the product of two 2-digit numbers is 9009 = 91 x 99. # Find the largest palindrome made from the product of two 3-digit numbers. # result: 906609 # time: 0.433s # # *edit: optimized* def palind_num(): is_pal = 0 for x in range(999, 99, -1): for y in range(x, 99, -1): num = x * y if str(num) == str(num)[::-1]: if is_pal < num: is_pal = num return is_pal print palind_num()
true
054eaa44d1652eb87ed365839643ee4e76d4bbe7
codejoncode/Sorting
/project/iterative_sorting.py
2,418
4.5
4
# Complete the selection_sort() function below in class with your instructor def selection_sort(arr): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for j in range(i, len(arr)): if arr[j] < arr[smallest_index]: smallest_index = j # TO-DO: swap arr[cur_index], arr[smallest_index] = arr[smallest_index], arr[cur_index] return arr # TO-DO: implement the Insertion Sort function below def insertion_sort(arr): i = 1 while i < len(arr): x = arr[i] j = i - 1 while j >= 0 and arr[j] > x: arr[j+1] = arr[j] j = j - 1 # end of nested while arr[j+1] = x i = i + 1 # end of parent while loop return arr # STRETCH: implement the Bubble Sort function below def bubble_sort(arr): """ O(n^2) time complexity should be used with smaller lists can be used with semi sorted lists. arr must be an iterable perferably an array type. Will sort in ascending order. """ for element in arr: for index in range(len(arr) - 1): if arr[index] > arr[index + 1]: arr[index], arr[index+1] = arr[index+1], arr[index] return arr # STRETCH: implement the Count Sort function below def count_sort(arr, maximum=-1): """ algorithm for sorting a collection of objects according to keys that are small integers; that is an integer sorting algorithm It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each value in the output sequence. Time complexity O(n log n) """ if len(arr) == 0: return [] k = max(arr) count = [0 for x in range(k+1)] output = [0 for x in range(len(arr))] for i in range(0, len(arr)): if arr[i] < 0: return "Error, negative numbers not allowed in Count Sort" else: count[arr[i]] = count[arr[i]] + 1 # end of for loop for i in range(2, len(arr)): count[i] = count[i] + count[i-1] # end of for loop i = len(arr) - 1 for i in range(len(arr) - 1, -1, -1): output[count[arr[i]]] = arr[i] # end of for loop return output
true
1ced62858071d7ea1ee50ff2bf50760f9ff7b65c
ElenaMBaudrit/OOP_assignments
/Person.py
1,108
4.25
4
#Todd's March 21st 2018 #example of a class. class Person(object): #Always put "object" inside the parentheses of the class def __init__(self, name, age, location): #double underscores in Python: something that is written somewhere else. "Dunder"= double underscores. #constructor: name of the function/method. There will be the attributes for the specific class. #the "name, age, location" are the parameters that "person" instance will have. "Self" help us create the linkage between the class and the instances. It is similar to "this", from JQuery. self.name = name self.age = age self.location = location def say_hello(self): print "Hello, my name is {}".format(self.name) #Instance: think of it as a variable, defining the class it belongs to. p1 = Person("Javier", 23, "San Jose") print p1.name print p1.age print p1.location #If there are more individuals, it goes like this: p2 = Person ("Rodolfo", 23, "San Jose") p3 = Person("Elena", 21, "San Jose") p4 = Person ("Manzura", 21, "Tempe") p3.say_hello()
true
d07f8d3ae500f5aefc1e03accc48d230ce4b4edd
adibhatnagar/my-github
/NIE Python/Third Code/Further Lists.py
1,629
4.3125
4
list_1=['Apple','Dell','HP','LG','Samsung','Acer','MSI','Asus','Razer'] #declares list containing names of laptop makers as strings list_2=[1,2,3,3,3,4,5,5,6,7,8,8,8,8,9] #declares list containing integers #Remember list elements have index starting from 0 so for list_1 the element 'Apple' has index 0 #If you store an element of a list using inverted commas then it is stored as a string #For example, list_temporary=['1','2','3'] contains the first three integers as strings #for the following code uncomment each line to see what it does #after observing comment that line re-run code after saving this code #print(list_2.count(8)) #print(list_2.count(3)) #print(list_1.count('Apple')) #print(list_2.index(3)) #print(list_2.index(5)) #print(list_2.index(8)) #print(list_2.pop(0)) #print(list_2.pop(5)) #print(list_2.remove(3)) #print(list_1.reverse()) #print(list_1.sort()) #follow the next 4 lines by uncommenting and recommenting two lines at once #list_1.insert(0,'Lenovo') #print(list_1) #print(list_1.remove('Lenovo')) #print(list_1) #this code prints the list_1 by accessing index through list_2 # to compare values of strings, integers, etc we use comparators #for example '!=' is comparator for 'not-equal-to' # '==' is comporator for 'equal' # '>' and '<' are 'less/greater than' comparators #follow the next six lines one after other or else you will get an error message #for i in range(0, (len(list_2)-1)): # if list_2[i]<list_2[i+1]: # print(list_2[i], list_1[list_2[i]-1]) # if i+1==len(list_2)-1: # if list_2[i] != list_2[i+1]: # print(list_2[i+1], list_1[list_2[i]])
true
e5e227509210a211bbbd4c9c4a7e3fcc9dd23a96
gagande90/Data-Structures-Python
/Comprehensions/comprehension_list.py
562
4.25
4
# list with loop loop_numbers = [] # create an empty list for number in range(1, 101): # use for loop loop_numbers.append(number) # append 100 numbers to list print(loop_numbers) # list comprehension comp_numbers = [ number for number in range(1, 101) ] # create a new list print("-"*25) print(comp_numbers) # list comprehension with added condition comp_numbers_three = [ number for number in range(1, 101) if number % 3 == 0 ] # multiples of three print("&"*25) print(comp_numbers_three)
true
bbd9d9f89619a93c37c79c269f244d899b047394
rebecabramos/Course_Exercises
/Week 6/search_and_replace_per_gone_in_list.py
1,123
4.375
4
# The program create a list containing the integers from (1 to 10) in increasing order, and outputs the list. # Then prompt the user to enter a number between 1 and 10, replace this number by the str object (gone) and output the list. # If the user enters a string that does not represent an integer between 1 and 10, instead output the appropriate message sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(sequence) number_for_verification = input('Enter an integer between 1 and 10 >') for x in sequence: if number_for_verification.isnumeric() == True: if int(number_for_verification) >= sequence[0] and int(number_for_verification) <= sequence[-1]: if x == int(number_for_verification): # knowing that the list in python starts with index zero, # so the third element corresponds to position two of the list sequence[x-1] = 'gone' print(sequence) break else: print(number_for_verification, 'is not between 1 and 10') break else: print(number_for_verification, 'is not a positive integer') break
true
23aed0b18c33addf4ed34a8a25f206b826239b9c
rebecabramos/Course_Exercises
/Week 6/split_str_space-separated_and_convert_upper.py
308
4.46875
4
# The program performs space-separated string conversion in a list # and then cycles through each index of the list # and displays the result in capital and capital letters string = input('Enter some words >') list_string = string.split() print(list_string) for x in list_string: print(x, x.upper())
true
0f8cc167c0447ed209bb00b04ebdb2cb3053b2fb
hm06063/OSP_repo
/py_lab/aver_num.py
282
4.28125
4
#!/usr/bin/python3 if __name__ == '__main__': n = int(input("How many numbers do you wanna input?")) sum = 0 for i in range(0,n): num = int(input("number to input: ")) sum += num mean = sum/n print("the mean of numbers is {}".format(mean))
true
86b2340e9602b2aa3eab5c4fd4fd3dc1b9b9cf9a
zatserkl/learn
/python/numpy_matrix_solve.py
1,756
4.28125
4
################################################# # See the final solution in the numpy_matrix.py # ################################################# import numpy as np """ Solve equation A*x = b where b is represented by ndarray or matrix NB: use matmul for the multiplication of matrices (or arrays). """ def solve_matrix_matrix(): A = np.mat("1 -2 1;0 2 -8;-4 5 9") print("A:\n", A) # define b as matrix: b should be a column vector b = np.matrix([0, 8, -9]).T print("b is a numpy matrix:\n", b) x = np.linalg.solve(A, b) print("Solution of the equation A*x = b:\n", x, "\ntype(x) =", type(x)) # check the solution # b1 = A.dot(x) # b1 = np.dot(A, x) b1 = np.matmul(A, x) print('b1 = np.matmul(A, x):\n', b1) def solve_matrix_array(): A = np.mat("1 -2 1;0 2 -8;-4 5 9") print("A:\n", A) # define b as ndarray: b should be a row vector b = np.array([0, 8, -9]) # b = np.matrix([0, 8, -9]).T # if b is matrix, it should be column print("b is a numpy array, row vector:\n", b) x = np.linalg.solve(A, b) # if b is column matrix, x will be column matrix print("Solution of the equation A*x = b:\n", x, "\ntype(x) =", type(x)) # check the solution # b1 = A.dot(x) # if b is column matrix, x will be column matrix b1 = np.dot(A, x.T) # if b is array, x will be array: transpose it print('b1 = A.dot(x.T):\n', b1) b1 = np.matmul(A, x.T) # b1 = A.dot(x.T) # if b is array, x will be array: transpose it print('b1 = np.matmul(A, x.T):\n', b1) print("\nSolve equation A*x = b") print("where we use dot-product A.dot(x)") print("\ndefine b as a np.matrix") solve_matrix_matrix() print("\ndefine b as a np.array") solve_matrix_array()
true
cf44c9820ab6c0e5c8ae0c270c5f097cd6c79550
zatserkl/learn
/python/class_set.py
1,286
4.15625
4
class Set: """Implementation of set using list """ def __init__(self, list_init=None): """constructor""" self.list = [] if list_init is not None: for element in list_init: self.list.append(element) """From http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python So, my advice: focus on making __str__ reasonably human-readable, and __repr__ as unambiguous as you possibly can, even if that interferes with the fuzzy unattainable goal of making __repr__'s returned value acceptable as input to __eval__! """ def __repr__(self): """string representation of the Set object It will be printed in IPython if you type object name followed by <CR> """ return str(self.list) def __str__(self): """string representation of the Set object It will be printed in IPython if you type object name followed by <CR> """ return 'list: ' + str(self.list) def contains(self, element): return element in self.list def add(self, element): if element not in self.list: self.list.append(element) def remove(self, element): if element in self.list: self.list.remove(element)
true
62cbd1bb70a63056c31bf7eb173481b151060d0b
zatserkl/learn
/python/plot.py
849
4.1875
4
"""See Python and Matplotlib Essentials for Scientists and Engineers.pdf """ import matplotlib.pyplot as plt x = range(5) y = [xi**2 for xi in x] plt.figure() # fig = plt.figure() # create a figure pointed by fig # fig.number # get number of the figure pointed by fig # plt.gcf().number # get number of the curent figure # plt.figure(1) # make figure No. 1 current # plt.clf() # clear current figure plt.plot(x, y, marker='o', color='black', label='square', linestyle='None') plt.title('y vs x') plt.xlabel('x') plt.ylabel('y') # plt.legend(loc=1, numpoints=1) # defaults: loc=1, numpoints=2 in the legend plt.legend(loc=2, numpoints=1) # loc=2 is the top left corner plt.grid(True) # turn on gridlines # plt.gcf().set_size_inches(6.5, 5) # gcf: get current figure plt.show()
true
821e0a1793c5fb08e85102dfe2f73d3744f24589
zatserkl/learn
/python/generator_comprehension.py
481
4.3125
4
# modified example from https://wiki.python.org/moin/Generators nmax = 5 # Generator expression: like list comprehension doubles = (2*n for n in range(nmax)) # parenthesis () instead of brackets [] # print("list of doubles:", list(doubles)) while True: try: number = next(doubles) # raises StopIteration if no default value except StopIteration: print("caught StopIteration") # StopIteration e returns empty string break print(number)
true
2e449b4aeae7d9409d28e6ff4ae686b58ab315b5
zatserkl/learn
/python/numpy_matrix.py
1,614
4.375
4
################################################################### # This is the final solution: use array for the matrix operations # ################################################################### """ See https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html NumPy matrix operations: use arrays and dot(A, B) for multiplication. NB: for ndarray all operations (*, /, +, - etc.) are elementwise The vector is considered as a row or a column depending on context. dot(A,v) treats v as a column vector, while dot(v,A) treats v as a row vector. NB: attribute Transpose does not change the ndarray vector. To use convenient interface like mat("1 -2 1;0 2 -8;-4 5 9") use casting A = np.array(np.mat("1 -2 1;0 2 -8;-4 5 9")) Solve equation A*x = b where all variables are represented by ndarray. """ import numpy as np def solve_matrix_array(): A = np.array(np.mat("1 -2 1;0 2 -8;-4 5 9")) # convenient mat interface print("A:\n", A) print("type(A) =", type(A)) b = np.array([0, 8, -9]) print("b is a numpy array:\n", b) print("type(b) =", type(b)) x = np.linalg.solve(A, b) # b will be treated as a column vector print("Solution of the equation A*x = b:\n", x, "\ntype(x) =", type(x)) # check the solution b1 = np.dot(A, x) # x will be treated as a column vector print('b1 = np.dot(A, x):\n', b1) print("type(b1) =", type(b1)) print("\nSolve equation A*x = b") print("where we use dot-product np.dot(A, x)") print("\ndefine b as a ndarray: it will be treated row- or column-wise " "depending on context") solve_matrix_array()
true
b02955a662cd3093d93d4783334982e507492132
liyangwill/python_repository
/plot.py
1,395
4.15625
4
# Print the last item from year and pop print(year[-1]) print(pop[-1]) # Import matplotlib.pyplot as plt import matplotlib.pyplot as plt # Make a line plot: year on the x-axis, pop on the y-axis plt.plot(year,pop) plt.show() # Print the last item of gdp_cap and life_exp print(gdp_cap[-1]) print(life_exp[-1]) # Make a line plot, gdp_cap on the x-axis, life_exp on the y-axis plt.plot(gdp_cap,life_exp) # Display the plot plt.show() # Change the line plot below to a scatter plot plt.scatter(gdp_cap, life_exp) # Put the x-axis on a logarithmic scale plt.xscale('log') # Show plot plt.show() # Import package import matplotlib.pyplot as plt # Build Scatter plot plt.scatter(pop, life_exp) # Show plot plt.show() # Create histogram of life_exp data plt.hist(life_exp) # Display histogram plt.show() # Build histogram with 5 bins plt.hist(life_exp, bins=5) # Show and clean up plot plt.show() plt.clf() # Build histogram with 20 bins plt.hist(life_exp, bins=20) # Show and clean up again plt.show() plt.clf() # Specify c and alpha inside plt.scatter() plt.scatter(x = gdp_cap, y = life_exp, s = np.array(pop) * 2, c=col, alpha=0.8) # Previous customizations plt.xscale('log') plt.xlabel('GDP per Capita [in USD]') plt.ylabel('Life Expectancy [in years]') plt.title('World Development in 2007') plt.xticks([1000,10000,100000], ['1k','10k','100k']) # Show the plot plt.show()
true
f236b8b9866ac9eae15b53802cc2c01854c248f9
MainakRepositor/Advanced-Programming-Practice
/Week 3/Q.1.py
543
4.4375
4
'''1.Develop an Python code to display the following output using class and object (only one class and two objects)''' class Birdie: species = "bird" def __init__(self, name, age): self.name = name self.age = age blu = Birdie("Blu", 10) woo = Birdie("Woo", 15) print("Blu is a {}".format(blu.__class__.species)) print("Woo is also a {}".format(woo.__class__.species)) # access the instance attributes print("{} is {} years old".format( blu.name, blu.age)) print("{} is {} years old".format( woo.name, woo.age))
true
12b16dbd277eb214c3ccc2dc47d64dccfceb0d36
hari-bhandari/pythonAlgoExpert
/QuickAndBubbleSort.py
684
4.15625
4
def quickSort(array): length=len(array) if length<=1: return array else: pivot=array.pop() itemsGreater=[] itemsLower=[] for item in array: if(item>pivot): itemsGreater.append(item) else: itemsLower.append(item) return quickSort(itemsLower)+[pivot]+quickSort(itemsGreater) print(quickSort([1,5,2,3,4,12,32,11,2122,1,23,23])) def bubbleSort(array): for i in range(len(array)-1): for j in range(0,len(array)-1-i): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return array print(bubbleSort([1,5,2,3,4,12,32,11,2122,1,23,23]))
true
357fbd822fa1d9e68afd1b880fc4c2f76988b384
jjen6894/PythonIntroduction
/Challenge/IfChallenge.py
593
4.21875
4
# Write a small program to ask for a name and an age. # When both values have been entered, check if the person # is the right age to gon on an 18-30 holiday must be over 18 # under 31 # if they are welcome them to the holiday otherwise print a polite message # refusing them entry name = input("What's your name? ") age = int(input("Also, what's your age {0}? ".format(name))) if 18 <= age < 31: print("Welcome {0}! You are entitled to go on this amazing lad or ladette holiday".format(name)) else: print("Sorry {0}, you aren't eligible to part-take in this holiday!".format(name))
true
49a053c483508ebe7a6bed95bafbe294b56239c1
gabmwendwa/PythonLearning
/3. Conditions/2-while.py
396
4.34375
4
# With the while loop we can execute a set of statements as long as a condition is true. i = 1 while i <= 10: print(i) i += 1 print("---------") # Break while loop i = 1 while i <= 10: print(i) if i == 5: break i += 1 print("---------") # With the continue statement we can stop the current iteration, and continue with the next: i = 0 while i < 10: i += 1 if i == 5: continue print(i)
true
b5ab9138384b9079b73d6a64e922a307d500fe42
gabmwendwa/PythonLearning
/4. Functions/1-functions.py
2,308
4.71875
5
# In Python a function is defined using the def keyword: def myfunction(): print("Hello from function") # Call function myfunction() print("-------") # Information can be passed to functions as parameter. def namefunc(fname): print(fname + " Mutisya") namefunc("Mutua") namefunc("Kalui") namefunc("Mwendwa") print("-------") # The following example shows how to use a default parameter value. # If we call the function without parameter, it uses the default value: def mycountry(country = "Kenya"): print("I am from " + country) mycountry("Tanzania") mycountry("Rwanda") mycountry() mycountry("Uganda") print("-------") #You can send any data types of parameter to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. #E.g. if you send a List as a parameter, it will still be a List when it reaches the function: def myfunc(food): for x in food: print(x) fruits = ["apple", "mango", "cherry"] myfunc(fruits) print("-------") # To let a function return a value, use the return statement: def myfunc(x): return 5 * x print(myfunc(3)) print(myfunc(4)) print(myfunc(5)) print("-------") # Python also accepts function recursion, which means a defined function can call itself. # Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result. # The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming. #In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0). #To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it. def tri_recursion(k): if(k>0): result = k+tri_recursion(k-1) print(result) else: result = 0 return result print("\n\nRecursion Example Results") tri_recursion(6)
true
71b8b67c39bb8c55568ba0c8dcdbb0e3565c1972
gabmwendwa/PythonLearning
/2. Collections/4-dictionary.py
2,577
4.34375
4
# Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. mdic = { "brand" : "Ford", "model" : "Mustang", "year" : 1969 } print(mdic) # Get the value of the "model" key: print(mdic["model"]) # There is also a method called get() that will give you the same result: print(mdic.get("model")) # You can change the value of a specific item by referring to its key name: mdic["year"] = 2019 print(mdic) # Print all key names in the dictionary, one by one: for x in mdic: print(x) # Print all values in the dictionary, one by one: for x in mdic: print(mdic[x]) # You can also use the values() function to return values of a dictionary: for x in mdic.values(): print(x) # Loop through both keys and values, by using the items() function: for x, y in mdic.items(): print(x, y) # To determine if a specified key is present in a dictionary use the in keyword: if "model" in mdic: print("Yes, \"model\" exists") else: print("None exists") # To determine how many items (key-value pairs) a dictionary has, use the len() method. print(len(mdic)) # Adding an item to the dictionary is done by using a new index key and assigning a value to it: mdic["color"] = "red" print(mdic) # There are several methods to remove items from a dictionary: # The pop() method removes the item with the specified key name: mdic.pop("model") print(mdic) # The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead): mdic.popitem() print(mdic) # The del keyword removes the item with the specified key name: mdic = { "brand" : "Ford", "model" : "Mustang", "year" : 1969 } del mdic["model"] print(mdic) # The del keyword can also delete the dictionary completely: del mdic #print(mdic) # The clear() keyword empties the dictionary: mdic = { "brand" : "Ford", "model" : "Mustang", "year" : 1969 } mdic.clear() print(mdic) # Make a copy of a dictionary with the copy() method: mdic = { "brand" : "Ford", "model" : "Mustang", "year" : 1969 } ndic = mdic.copy() print(ndic) # Another way to make a copy is to use the built-in method dict(). odic = dict(mdic) print(odic) # It is also possible to use the dict() constructor to make a new dictionary: vdic = dict(Brand="Ford", Model="Mustang", Year=1969) # note that keywords are not string literals # note the use of equals rather than colon for the assignment print(vdic)
true
252d6fb9fb6b77cfd70c38325fedc0b50e1d530d
alantanlc/what-is-torch-nn-really
/functions-as-objects-in-python.py
1,897
4.71875
5
# Functions can be passed as arguments # We define an 'apply' function which will take as input a list, _L_ and a function, _f_ and apply the function to each element of the list. def apply(L, f): """ Applies function given by f to each element in L Parameters ---------- L : list containing the operands f : the function Returns -------- result: resulting list """ result = [] for i in L: result.append(f(i)) return result L = [1, -2, -5, 6.2] a = apply(L, abs) print(a) # [1, 2, 5, 6.2] # abs is applied on elements passed in L a = apply(L, int) print(a) # [1, -2, -5, 6] # We can also pass a self-defined function. For example: def sqr(num): return num ** 2 a = apply(L, sqr) print(a) # [1, 4, 25, 38.440000000000005] # The ability to perform the same operation on a list of elements is also provided by a higher-order python function called __map__. # In its simplest form, it takes in a 'unary' function and a collection of suitable arguments and returns an 'iterable' which we must walk down. for i in map(abs, L): print(i) # Functions as elements of a list # Functions can be stored as elements of a list or any other data structure in Python. For example, if we wish to perform multiple operations to a particular number, we define `apply_func(L, x)` that takes a list of functions, L and an operand, x and applies each function in L on x. from math import exp def apply_func(L,x): result = [] for f in L: result.append(f(x)) return result function_list = [abs, exp, int] print(apply_func(function_list, -2.3)) print(apply_func(function_list, -4)) # Side Note: In both the above examples, we could have used list comprehensions, which provide an elegant way of creating lists based on another list or iterator. output = [f(-2.3) for f in function_list] print(f'output: {output}')
true
78c1296a009f6ff19884a46f48e67f6795e312f4
mariarozanska/python_exercises
/zad9.py
768
4.34375
4
'''Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. Extras: Keep the game going until the user types “exit” Keep track of how many guesses the user has taken, and when the game ends, print this out.''' import random number = random.randint(1, 9) tries = 1 while True: guess = int(input('Guess the number (1-9): ')) if number == guess: print('Yes, it\'s {}. It took you {} tries.'.format(number, tries)) break if number > guess: print('Too low...') else: print('Too high...') game = input('Do you want to try again? (y/exit) ') if game == 'exit': break tries += 1
true
4b610d707b407ef845cc19fde9da3eefc6115065
BlakeBeyond/python-onsite
/week_02/08_dictionaries/09_03_count_cases.py
1,065
4.5
4
''' Write a script that takes a sentence from the user and returns: - the number of lower case letters - the number of uppercase letters - the number of punctuations characters (count) - the total number of characters (len) Use a dictionary to store the count of each of the above. Note: ignore all spaces. Example input: I love to work with dictionaries! Example output: Upper case: 1 Lower case: 26 Punctuation: 1 ''' message = input("Type word: ") message.replace(" ", "") up = "Upper Case: " + str(sum(1 for c in message if c.isupper())) low = "Lower Case: " + str(sum(1 for c in message if c.islower())) punctuation = [".", "?", "!", ","] punct = "Punctuation: "+ str(sum(1 for c in message if c in punctuation)) char = "Characters: " + str(len(message)) print(up) print(low) print(punct) print(char) dict_count = {"Upper Case": sum(1 for c in message if c.isupper()), "Lower Case": sum(1 for c in message if c.islower()), "Punctuation": sum(1 for c in message if c in punctuation), "Characters": len(message)} print(dict_count)
true
d7af1592985a4677bc8929c35905f045b25ca842
BlakeBeyond/python-onsite
/week_02/06_tuples/02_word_frequencies.py
628
4.40625
4
''' Write a function called most_frequent that takes a string and prints the letters in decreasing order of frequency. For example, the follow string should produce the following result. string_ = 'hello' Output: l, h, e, o For letters that are the same frequency, the order does not matter. ''' my_dict = {} sorted_list = [] def most_frequent(fstring_): for ch in fstring_: if ch not in my_dict: my_dict[ch] = fstring_.count(ch) for key, value in sorted(my_dict.items(), key=lambda v: v): sorted_list.append(key) print(sorted_list) function_output = most_frequent("kanapka")
true
e8f1c5cd3e440886e0fa8f594d1092fb58fb509a
cp105/dynamic_programming_101
/dp101/knapsack01.py
1,896
4.4375
4
""" The knapsack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items. The problem often arises in resource allocation where the decision makers have to choose from a set of non-divisible projects or tasks under a fixed budget or time constraint, respectively. https://en.wikipedia.org/wiki/Knapsack_problem function "knapsack(item_names, value, weight, capacity)" takes the items' names, values, weights, and maximum weight that the backpack can carry as arguments. Returned tuple containing array of names of selected items, total value of selected items and total weight. """ def knapsack01(item_names, value, weight, capacity): if (len(value) != len(weight)) or (len(value) != len(item_names)): raise RuntimeError('value, weight and item_names must be of same size.') for i in range(len(value)): if weight[i] < 0: raise RuntimeError('weights must be positive numbers.') return knapsack01_(item_names, value, weight, capacity) def knapsack01_(item_names, value, weight, capacity): if (not item_names) or (capacity <= 0): return [], 0, 0 names0, v0, w0 = knapsack01_(item_names[1:], value[1:], weight[1:], capacity) if capacity >= weight[0]: names0, v0, w0 = knapsack01_(item_names[1:], value[1:], weight[1:], capacity) names1, v1, w1 = knapsack01_(item_names[1:], value[1:], weight[1:], capacity - weight[0]) if (v1 + value[0]) > v0: return [item_names[0]] + names1, v1 + value[0], w1 + weight[0] return names0, v0, w0
true
e441e0e4fa599fefe6f3f49f32477c68dd46e29a
jtannas/intermediate_python
/caching.py
1,368
4.65625
5
""" 24. Function caching Function caching allows us to cache the return values of a function depending on the arguments. It can save time when an I/O bound function is periodically called with the same arguments. Before Python 3.2 we had to write a custom implementation. In Python 3.2+ there is an lru_cache decorator which allows us to quickly cache and uncache the return values of a function. Let’s see how we can use it in Python 3.2+ and the versions before it. """ ### PYTHON 3.2+ ############################################################### from functools import lru_cache @lru_cache(maxsize=32) def fib(n): if n < 2: return n return fib(n - 1) + fib(n - 2) [n for n in range(16)] #: The maxsize argument tells lru_cache about how many recent return #: values to cache. # It can be inspected via: fib.cache_info() # It can be cleared via: fib.cache_clear() ### PYTHON 2+ ################################################################# from functools import wraps def memoize(function): memo = {} @wraps(function) def wrapper(*args): if args in memo: return memo[args] else: rv = function(*args) memo[args] = rv return rv return wrapper @memoize def fibonacci(n): if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2)
true
ebd261d238b7e9fe9a2167c9333de3046439771b
jtannas/intermediate_python
/ternary.py
574
4.25
4
""" 6. Ternary Operators Ternary operators are more commonly known as conditional expressions in Python. These operators evaluate something based on a condition being true or not. They became a part of Python in version 2.4 """ # Modern Python Way. def positive_test(num): return 'positive' if num > 0 else 'not positive' print(f"1 is {positive_test(1)}") print(f"-1 is {positive_test(-1)}") # Pre Python 2.4 way - do not use - it evaluates all possibities. num = 3 print(('not positive', 'positve')[num > 0]) print(':-)' if True else 1/0) print((1/0, ':D')[True])
true
9b381446f85c86c9b92fb0749fe97301418828ff
Anjustdoit/Python-Basics-for-Data-Science
/string_try1.py
546
4.25
4
name = "hello" print(type(name)) message = 'john said to me "I\'ll see you later"' print(message) paragraph = ''' Hi , I'm writing a book. I will certainly do''' print(paragraph) hello = "Hello World!" print(hello) name = input('What is your name ? --> ') print(name) # What is your age age = input('What is your age ? --> ') print(age) string = "you name is {} and you age is {}" output = string.format(name,age) print(output) A = "part" B=1 #print(A+str(B)) AF = "{} - {}".format(A,B) print(AF)
true
d50626ac217a242938030eb2621bc6263893c191
martinak1/diceman
/diceman/roll.py
2,993
4.25
4
import random def roll( num: int = 1, sides: int = 6) -> list: ''' Produces a list of results from rolling a dice a number of times Paramaters ---------- num: int The number of times the dice will be rolled (Default is 1) sides: int The number of sides the dice has (Default is 6) ''' results: list = [] [results.append(random.randint(1, sides)) for _ in range(1, sides)] return results # end roll def filter_eq(results: list, qualifier: int) -> list: ''' Filters the results from a dice roll that are equal to a certain value Parameters ---------- results: list, required The results of a dice roll, usually generated by the roll function qualifier: int The value the rolls are compaired against ''' filtered_results: list = [] [filtered_results.append(i) for i in results if qualifier == i] return filtered_results # end filter_eq def filter_gt(results: list, qualifier: int) -> list: ''' Filters the results from a dice roll that are greater a certain value Parameters ---------- results: list, required The results of a dice roll, usually generated by the roll function qualifier: int The value the rolls are compaired against ''' filtered_results: list = [] [filtered_results.append(i) for i in results if qualifier < i] return filtered_results # end filter_gt def filter_gt_or_eq( results: list, qualifier: int ) -> list: ''' filters the results from a dice roll that are greater than or equal to a certain value parameters ---------- results: list, required the results of a dice roll, usually generated by the roll function qualifier: int the value the rolls are compaired against ''' filtered_results: list = [] [filtered_results.append(i) for i in results if qualifier <= i] return filtered_results # end filter_gt_or_eq def filter_lt(results: list, qualifier: int) -> list: ''' Filters the results from a dice roll that are less than a certain value Parameters ---------- results: list, required The results of a dice roll, usually generated by the roll function qualifier: int The value the rolls are compaired against ''' filtered_results: list = [] [filtered_results.append(i) for i in results if i < qualifier] return filtered_results # end filter_lt def filter_lt_or_eq( results: list, qualifier: int ) -> list: ''' Filters the results from a dice roll that are less than or equal to a certain value Parameters ---------- results: list, required The results of a dice roll, usually generated by the roll function qualifier: int The value the rolls are compaired against ''' filtered_results: list = [] [filtered_results.append(i) for i in results if i <= qualifier] return filtered_results # end filter_lt_or_eq
true
36028b8aae863b3c6de5d5e1e76f32c6037c7d7f
Cakarena/CS-2
/numprint.py
235
4.15625
4
##Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. ## Note : Use 'continue' statement. Name the code. Expected Output : 0 1 2 4 5 for i in range(0,7): if i==3 or i==6: continue print(i,end='')
true
097b292ea5a0d040181ec80c9beb3965f1cacb93
JohnKlaus-254/python
/Python basics/String Operations.py
1,105
4.28125
4
#CONCACTINATION using a plus #CONCACTINATION using a format first_name= "John" last_name = "Klaus" full_name = first_name +' '+ last_name print(full_name) #a better way to do this is; full_name = "{} {}".format(first_name, last_name) print(full_name) print("this man is called {} from the family of {} ".format(first_name, last_name)) #format names ="John Klaus" name2 = "jake williams" name3 = "DENNIS WAWERU" print(name2.title()) #count - counts the number of time something has been repeated #python is case sensitive sen="Man is to error because man did not create Man" print(sen.lower().count("a")) #String slicing #left of the colon signify the starting element #right of the coon signify the ending position but that element in that position is excluded. so to include it, add up to the next element. print(sen[0:15]) jina = "muyani" print(jina[1:-2]) print(jina[2::-2]) print(sen.split()) sente ="learning more string funtions" print(sente.join()) print(sente.replace()) print(sente.index()) print(sente.find()) print(sente.center()) print(sente.isalpha())
true
7dd6519daded48e31f9c24276fee8f1c51a19623
GuptaNaman1998/DeepThought
/Python-Tasks/Rock-Paper-Scissors/Code.py
999
4.21875
4
""" 0-Rock 1-Paper 2-Scissor """ import random import os def cls(): os.system('cls' if os.name=='nt' else 'clear') Options={0:"Rock",1:"Paper",2:"Scissor"} # Created Dictionary of available choices poss={(0, 1):1,(0, 2):0,(1, 2):2} # Dictionary of possibilities and the winner value # print("Hi User!") player=int(input("Please enter your choice: 0-Rock | 1-Paper | 2-Scissor : ")) # User input while player not in Options.keys(): cls() player=int(input("Please enter your choice: 0-Rock | 1-Paper | 2-Scissor : ")) print("you choose "+Options[player] ) computer=random.randrange(0,3) # Comuters random choice print("computer choose "+Options[computer] ) res=[player,computer] res.sort() res=tuple(res) # Below is the if else loop to decide winner if player==computer: print(" It is a tie !!...") elif poss[res]==computer: print("Computer won the game by choosing "+Options[computer] ) elif poss[res]==player: print("You won the game by choosing "+Options[player] )
true
ce4fe060c3a35b03a49650e8aa385dc68d42715d
alexhohorst/MyExercises
/ex3.py
844
4.28125
4
print "I will now count my chickens:" print "Hens", 25 + 30 / 6 #adds 25 and 30 and divides this by 6 print "Roosters", 100 - 25 * 3 % 4 #substracts 25 from 100, multiplies with 3 and divides by 4, returning the remainder print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 #adds 3 and 2 and 1, substracts 5, adds 4, divides this by 2, returning the remainder, substracts 1, divides by 4 and adds 6 print "Is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 7 print "What is 3 + 2?", 3 + 2 #adds 3 plus 2 print "What is 5 - 7?", 5 - 7 #substracts 5 and 7 print "Oh, that's why it's false." print "How about some more." print "Is it greater?", 5 > -2 #any statement that is true print "Is it greater or equal?", 5 >= -2 #any statement that is true print "Is it less or equal?", 5 <= -2 #any statement that is false
true
f494f59caa548f497bd1d3825fd5448ac3cff339
MReeds/Classes-Practices
/pizzaPractice/classes.py
1,021
4.4375
4
#Add a method for interacting with a pizza's toppings, # called add_topping. #Add a method for outputting a description of the #pizza (sample output below). #Make two different instances of a pizza. #If you have properly defined the class, #you should be able to do something like the #following code with your Pizza type. class Pizza: def __init__(self): self.size = "" self.crust_type = "" self.toppings = list() def add_topping(self, item): self.toppings.append(item) def print_order(self): print(f"I would like a {self.size}-inch, {self.crust_type} pizza with {' and '.join(self.toppings)}.") my_pizza = Pizza() my_pizza.size = 16 my_pizza.crust_type = "thin crust" my_pizza.add_topping("mushrooms") my_pizza.add_topping("bell peppers") my_pizza.print_order() his_pizza = Pizza() his_pizza.size = 12 his_pizza.crust_type = "Deep dish" his_pizza.add_topping("sausage") his_pizza.add_topping("onions") his_pizza.print_order()
true
bf49ad63a8611cdbcfc34e384f940d47e9eed772
SethMiller1000/Portfolio
/Foundations of Computer Science/Lab 11- String Contents.py
1,202
4.28125
4
# The String Contents Problem- Lab 11: CIS 1033 # Seth Miller and Kaitlin Coker # Explains purpose of program to user print("Hello! This program takes a string that you enter in and tells you what the string contains.") # Ask user for string userString = input("Please enter a string ---> ") # Tests if it contains only letters if userString.isalpha(): print("This string contains only letters.") # Tests if it contains only uppercase letters if userString.isupper(): print("This string contains only uppercase letters.") # Tests if it contains only lowercase letters if userString.islower(): print("This string contains only lowercase letters.") # Tests if it contains only digits if userString.isdigit(): print("This string contains only digits.") # Tests if it contains only letters and digits if userString.isalnum(): print("This string contains only letters and digits.") # Tests if it starts with an uppercase letter firstCharacter = userString[0] if firstCharacter.isupper(): print("This string starts with an uppercase letter.") # Tests if it ends with a period if userString.endswith("."): print("This string ends with a period.")
true
74a25f4969bc732424c26c88dc80441e2f4f499d
SethMiller1000/Portfolio
/Foundations of Computer Science/Lab 17- Training Heart Rate.py
1,034
4.21875
4
# The Training Heart Rate Problem # Lab 17: CIS 1033 # Author: Seth Miller # function that calculates training heart rate # based on age and resting heart rate def trainingHeartRate( age, restingHeartRate ) : maxHeartRate = 220 - age result = maxHeartRate - restingHeartRate result2 = result * 0.60 trainingHeartRate = result2 + restingHeartRate return trainingHeartRate # MAIN METHOD # # Explain purpose of program to user print(" Hello! This program calculates your training heart rate") print(" based on your age and resting heart rate.") print( "" ) # Ask user for age and resting heart rate ageInput = int(input("Please enter your age: ")) restingRateInput = int(input("Please enter your heart rate when resting: ")) print( "" ) # Call function to calculate training heart rate userTrainingRate = trainingHeartRate( ageInput, restingRateInput ) # Display training heart rate of user print("Your training heart rate is " + str(userTrainingRate) + ".")
true
bd4bf3185496a137ef716b6188082d27b9f084e8
SethMiller1000/Portfolio
/Foundations of Computer Science/Lab 9- Electric Bill.py
1,048
4.25
4
# The Electric Bill Problem- Lab 9 CIS 1033 # Author: Seth Miller # Input: receives the meter reading for the previous # and current month from the user prevMonthMeterReading = int(input("Meter reading for previous month: ")) currentMonthMeterReading = int(input("Meter reading for current month: ")) # Input: assigns values to flat monthly fee # and charge per extra kilowatt hour variable FLAT_MONTHLY_FEE = 20 CHARGE_PER_EXTRA_KILOWATT_HOUR = 0.03 # Process: calculates usage for the month in kilowatt hours usageForMonth = currentMonthMeterReading - prevMonthMeterReading # Process: tests if there is an added fee and calculates total bill if (usageForMonth > 300): addedFee = CHARGE_PER_EXTRA_KILOWATT_HOUR * (usageForMonth - 300) totalBill = FLAT_MONTHLY_FEE + addedFee else: totalBill = FLAT_MONTHLY_FEE # Output: displays the usage and the total bill for the month print("Usage for the month is " + str(usageForMonth) + " kilowatt hours.") print("Total bill for the month is $" + str(totalBill) + ".")
true
c3050341b766f637b39ba112c5967a9b43d74dfe
MortalKommit/Coffee-Machine
/coffee_machine.py
2,630
4.1875
4
class CoffeeMachine: def __init__(self, capacity, menu): self.capacity = {} contents = ("water", "milk", "coffee beans", "disposable cups", "money") for content, cap in zip(contents, capacity): self.capacity[content] = cap self.menu = menu def get_user_input(self): action = '' while action != 'exit': print("Write action (buy, fill, take, remaining, exit):") action = input() self.process_action(action) def process_action(self, action): if action == "buy": print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:") order = input() if order == 'back': return for key in self.capacity.keys(): if key != "money": if self.capacity[key] - self.menu[order][key] < 0: print(f"Sorry, not enough {key}!") break else: print("I have enough resources, making you a coffee!") # Add money self.capacity["money"] += self.menu[order]["money"] # Subtract the rest for key in self.capacity.keys(): if key != "money": self.capacity[key] -= self.menu[order][key] elif action == "fill": print("Write how many ml of water do you want to add:") self.capacity["water"] += int(input()) print("Write how many ml of milk do you want to add:") self.capacity["milk"] += int(input()) print("Write how many grams of coffee beans do you want to add:") self.capacity["coffee beans"] += int(input()) print("Write how many disposable cups do you want to add:") self.capacity["disposable cups"] += int(input()) elif action == "take": print(f"I gave you ${self.capacity['money']}") self.capacity["money"] = 0 elif action == "remaining": print("The coffee machine has:") for key, value in self.capacity.items(): print(value, f"of {key}") cafe_menu = {'1': {"water": 250, "milk": 0, "coffee beans": 16, "disposable cups": 1, "money": 4}, '2': {"water": 350, "milk": 75, "coffee beans": 20, "disposable cups": 1, "money": 7}, '3': {"water": 200, "milk": 100, "coffee beans": 12, "disposable cups": 1, "money": 6} } caffe = CoffeeMachine((400, 540, 120, 9, 550), cafe_menu) caffe.get_user_input()
true
1702acae637148eee91612d432b6e8fa4d594205
toddljones/advent_of_code
/2019/1/a.py
1,013
4.4375
4
""" Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. For example: - For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2. - For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2. - For a mass of 1969, the fuel required is 654. - For a mass of 100756, the fuel required is 33583. The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values. What is the sum of the fuel requirements for all of the modules on your spacecraft? """ from math import floor modules = [] for modmass in [int(x.strip()) for x in open("input.a").readlines()]: print(f"modmass={modmass}") modules.append(floor(modmass / 3) - 2) ttl_fuel = sum(modules) print(f"ttl_fuel={ttl_fuel}")
true
694ac91eec52f84fdac4581f1cd3be42554925d4
CertifiedErickBaps/Python36
/Listas/Practica 7/positives.py
1,028
4.125
4
# Authors: # A013979896 Erick Bautista Perez # #Write a program called positives.py. Define in this program a function called #positives(x) that takes a list of numbers x as its argument, and returns a new #list that only contains the positive numbers of x. # # October 28, 2016. def positives(x): a = [] for c in x: if c >= 0: a += [c] return a def main(): print(positives([-21, -31])) print(positives([-48, -2, 0, -47, 45])) print(positives([-9, -38, 49, -49, 32, 6, 4, 26, -8, 45])) print(positives([-27, 48, 13, 5, 27, 5, -48, -42, -35, 49, -41, -24, 11, 29, 33, -8, 45, -44, 12, 46])) print(positives([-2, 0, 27, 47, -13, -23, 8, -28, 23, 7, -29, -24, -30, -6, -21, -17, -35, -8, -30, -7, -48, -18, -2, 1, -1, 18, 35, -32, -42, -5, 46, 8, 0, -31, -23, -47, -4, 37, -5, -45, -17, -5, -29, -35, -2, 40, 9, 25, -11, -32])) main()
true
df7911328fd4b62321d98a88f8399978c053c5d0
CertifiedErickBaps/Python36
/Manipulacion de textos/Practica 6/username.py
2,277
4.3125
4
# Authors: # A01379896 Erick Bautista Pérez #Write a program called username.py. Define in this program a function called username(first, middle, last) #that takes the first name, middle name, and last name of a person and generates her user name given the above #rules. You may assume that every first name has at least one letter and every middle name has at least one #consonant. Use string.lower() to convert string into lower case letters. # # October 14, 2016. #def first(name): # for c in name: # if name != "": # return str.lower(name[:1]) #def middle(name1): # for a in name1: # if a not in "AEIOUaeiou": # return str.lower(a) #def last(name2): # if name2 < name2[0:6]: # return str.lower(last) # else: # return str.lower(name2[0:6]) #def main(): # print(first('Scarlett'), middle('Ingrid'), last('Johansson'), sep ="") # print(first('Donald'), middle('Ervin'), last('Knuth'), sep ="") # print(first('Alan'), middle('Mathison'), last('Turing'), sep ="") # print(first('Martin'), middle('Luther'), last('King'), sep ="") # print(first('Stephen'), middle('William'), last('Hawking'), sep ="") # print(first('Alejandro'), middle('Gonzalez'), last('Inarritu'), sep ="") #main() def primera_consonante(cadena): for c in cadena.lower(): # .lower() es para regresar el valor en minusculas if c in "bcdfghjklmnpqrtsvwxyz": return c #en este return acaba inmediatamente y regresa la consonante def username(first, middle, last): resultado = first[0] resultado += primera_consonante(middle) resultado += last if len(resultado) > 8: #El len() me regresa el numero de caracteres resultado = resultado[:8] resultado = resultado.lower() #Este resultado esta fuera del if por que es una condicion a llamar con el tamaño return resultado def main(): print(username('Scarlett', 'Ingrid', 'Johansson')) print(username('Donald', 'Ervin', 'Knuth')) print(username('Alan', 'Mathison', 'Turing')) print(username('Martin', 'Luther', 'King')) print(username('Stephen', 'William', 'Hawking')) print(username('Alejandro', 'Gonzalez', 'Inarritu')) main()
true
5af607504652e3240c32ecfb8a764987e5e58786
Exclusive1410/practise3
/pr3-4.py
231
4.34375
4
#Write Python program to find and print factorial of a number import math def fact(n): return (math.factorial(n)) num = int(input('Enter the number:')) factorial = fact(num) print('Factorial of', num, 'is', factorial)
true
f14a298f9b623616b2e81fe80aa2d1860e707bf4
StephenJonker/python-sample-code
/sort-list/sort-list-of-integer-list-pairs.py
1,780
4.25
4
# uses python3 # # Written by: Stephen Jonker # Written on: Tuesday 19 Sept 2017 # Copyright (c) 2017 Stephen Jonker - www.stephenjonker.com # # Purpose: # - basic python program to show sorting a list of number pairs # # - Given a list of integer number pairs that will come from STDIN # - first read in n, the number of lines of input containing input pairs # - then for 1 to n, read in each integer number pair into a list like structure # with each number pair also in a list # - this will create a list whose elements are lists, that contains integer number pairs # E.g.: [ [1,10], [7,70], [2,20], [4, 40] ] # - Once read, sort the list based on the first or second list-pair elelment # # E.g. input # 3 # 1 10 # 7 70 # 2 20 # 4 40 # # Output: # - the sorted list of list pairs # E.g. [['1', '10'], ['2', '20'], ['4', '40'], ['7', '70']] # # Constraints: # - the program does not do input validation if __name__ == "__main__": debug = False # get the number of lines to input from STDIN n = int(input()) if debug: print("Input n: " + str(n) + " Type: " + str(type(n)) ) numberPair = [] theList = [] # Get the lines of input and store in a list of number pairs # E.g.: [ [1,10], [7,70], [2,20], [4, 40] ] for i in range(0,n): numberPair = input().split() theList.append(numberPair) if debug: print("The pair list: " + str(theList) + " Type: " + str(type(theList)) ) if debug: print("Length of the list: " + str(len(theList))) # Function to return the first element of the integer list pair # Needed to make the "sorted" function work with more complex list elements def sortKey(item): return item[0] newSortedList = sorted(theList, key=sortKey) if debug: print("newSortedList: " + str(newSortedList)) print(str(newSortedList)) # # End of file. #
true
e6b38846ceed488f1334a77279b1220c31a4d21d
jeansabety/learning_python
/frame.py
608
4.25
4
#!/usr/bin/env python3 # Write a program that prints out the position, frame, and letter of the DNA # Try coding this with a single loop # Try coding this with nested loops dna = 'ATGGCCTTT' for i in range(len(dna)) : print(i, i%3 , dna[i]) #i%3 -> divide i (which is a number!) by i, and print the remainder for i in range(0, len(dna), 3) : #i = 0, 3, 6, 9 for j in range(3) : # j = 0,1,2 print(i+j, j, dna[i+j]) #i+j -> number of characters in dna (0+0, 0+1, 0+2, 3+0...) // j -> "frame" // dna[i+j] -> dna[1..9] """ python3 frame.py 0 0 A 1 1 T 2 2 G 3 0 G 4 1 C 5 2 C 6 0 T 7 1 T 8 2 T """
true
632a36b7c686db27cfee436935eecfc9ba74be30
jeansabety/learning_python
/xcoverage.py
1,902
4.15625
4
#!/usr/bin/env python3 # Write a program that simulates random read coverage over a chromosome # Report min, max, and average coverage # Make variables for genome size, read number, read length # Input values from the command line # Note that you will not sample the ends of a chromosome very well # So don't count the first and last parts of a chromsome #I do not understand what this assignment is asking #have a genome, fill it up with reads, does some region have 2x as much #1 sequencing read that cover x amount of base pairs #repeat and then see how many nt were read more than once #how much sequencing do you need to do to cover the entire genome #genome is 100 bp long, read= 10, 1x coverage = 10 reads (enough to go over the genome once) but does this actually happen? import sys import random gen_size = int(sys.argv[1]) rnum = int(sys.argv[2]) rlen = int(sys.argv[3]) #1. empty set of zeros for the genome genome = [0] * gen_size #print(genome) #for every read, pick a random starting point, and then read for i in range(rnum) : #do this for the number of reads #print(i) x = random.randint(0, len(genome) - rlen) #choose a random value in the genome, do not want to sampel anything that "falls off" - last reads last value should be the last value of the list for j in range(rlen) : #print(x +j) genome[x+j] += 1 #j will be every value as long as the read length, will add one to the next value everytime we run through the loop #print(genome) #minimum, max, avg: min = genome[rlen] #don't want to sample ends because they get sampled less max=genome[rlen] total = 0 for n in genome[rlen:-rlen]: #-1 = last values, once again you don't want to sample ends if n<min : min = n if n>max : max = n total += n #n will be the number of times the nt was counted print(min, max, total/(gen_size - 2*rlen)) """ python3 xcoverage.py 1000 100 100 5 20 10.82375 """
true
7efe190f957eec5b5c7a62adb1e45b520066f33f
bensenberner/ctci
/peaksAndValleys.py
638
4.40625
4
''' in an array of ints, a peak is an element which is greater than or equal to the adjacent integers. the opposite for a valley. Given an array of ints, sort it into an alternating sequence of peaks and valleys. ''' def peakSort(arr): for i in range(1, len(arr), 2): # make sure indices don't go out of bounds if arr[i] < arr[i-1] or arr[i] < arr[i+1]: if arr[i-1] > arr[i+1]: arr[i], arr[i-1] = arr[i-1], arr[i] else: arr[i], arr[i+1] = arr[i+1], arr[i] if __name__ == "__main__": arr = [5, 3, 1, 2, 3, 4] print(arr) peakSort(arr) print(arr)
true
1a5541ac2b3af545ec206ad68986eaf8d6232512
dheerajps/pythonPractice
/algorithms/unsortedArrayHighestProduct.py
1,344
4.21875
4
# same as highestProduct.py # but find the maximum product possible by three numbers in an array without sorting it #so O(N) must be time requirements def getMaxProductOfThreeNumbers(array): import sys #Max product can be 3 maximum numbers or 2 minimum numbers and 1 max firstMax = -sys.maxsize-1 secondMax = -sys.maxsize-1 thirdMax = -sys.maxsize-1 firstMin = sys.maxsize secondMin = sys.maxsize i=0 #loop throught the array and keep updating the values while i < len(array): if(array[i]>firstMax): thirdMax = secondMax secondMax = firstMax firstMax = array[i] elif(array[i]>secondMax): thirdMax = secondMax secondMax = array[i] elif(array[i]>thirdMax): thirdMax = array[i] if(array[i]<firstMin): secondMin = firstMin firstMin = array[i] elif(array[i] < secondMin): secondMin = array[i] i+=1 #find the maximum possible product and return it return max(firstMin*secondMin*firstMax , firstMax*secondMax*thirdMax) inputArray = [-1,-7,-8,3,-1,-5,2,3,8,9] print " The input array is ",inputArray maxProduct = getMaxProductOfThreeNumbers(inputArray) print " The max product from 3 numbers(using O(n) time) is ",maxProduct
true
32e8588930e8821ae35ef762dc37c3fa5368fd97
lyndsiWilliams/cs-module-project-algorithms
/sliding_window_max/sliding_window_max.py
1,063
4.5
4
''' Input: a List of integers as well as an integer `k` representing the size of the sliding window Returns: a List of integers ''' def sliding_window_max(nums, k): # Your code here # Check if numbers array exists if nums: # Set an empty list for the max numbers to live max_numbers = [] # Loop through the list of numbers for i in range(len(nums)): # If k is <= the length of the numbers list if k <= len(nums): # Set the window to start at the current index and # end 'k' elements over window = nums[i:k] # Move the window up one position k += 1 # Append the max number to the max_numbers array max_numbers.append(max(window)) return max_numbers if __name__ == '__main__': # Use the main function here to test out your implementation arr = [1, 3, -1, -3, 5, 3, 6, 7] k = 3 print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
true
a2b4f9b45b1888a518e7db8a687c3bf452aca122
manu4xever/leet-code-solved
/reverse_single_linked_list.py
506
4.1875
4
Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ temp=None while head: head.next,head,temp=temp,head.next,head return temp
true
0d4b6e26e09ea7d90e4d45941f07a4d9046ba1b4
Hety06/caesar_cipher
/caesar_cipher.py
878
4.1875
4
def shift(letter, shift_amount): unicode_value = ord(letter) + shift_amount if unicode_value > 126: new_letter = chr(unicode_value - 95) else: new_letter = chr(unicode_value) return new_letter def encrypt(message, shift_amount): result = "" for letter in message: result += shift(letter, shift_amount) return result def decrypt(message, shift_amount): result = "" for letter in message: result += shift(letter, -shift_amount + 95) return result unencrypted_message = "Apples can taste sour \ sweet, but Timmy says that some apples are both sour and sweet! What do you think?" encrypted_message = encrypt(unencrypted_message, 10) decrypted_message = decrypt(encrypted_message, 10) print(unencrypted_message) print(encrypted_message) print(decrypted_message)
true
1eb92fd964d785db16d04628b9734810a5460374
anterra/area-calculator
/area_calculator.py
1,016
4.15625
4
import math class Rectangle: def __init__(self, length1, length2): self.length1 = length1 self.length2 = length2 def area(self): area = self.length1 * self.length2 return area class Circle: def __init__(self, radius): self.radius = radius def area(self): area = math.pi * self.radius ** 2 return area while True: shape = input("Area Calculator. Is your shape a rectangle, circle, or triangle? ") if shape == "rectangle" or "triangle": length1 = int(input("What is the width/base? ")) length2 = int(input("What is the height? ")) my_shape = Rectangle(length1, length2) if shape == "rectangle": print(my_shape.area()) elif shape == "triangle": print(my_shape.area()/2) break elif shape == "circle": radius = int(input("What is the radius? ")) my_shape = Circle(radius) print(my_shape.area()) break else: break
true
f8cb2d4ff4976169893c680ba37018de7e936e34
dileep208/dileepltecommerce
/test/one.py
341
4.25
4
# This is for printing print('This is a test') # This is for finding the length of a string s = 'Amazing' print(len(s)) # This for finding the length of hippopotomus s='hippopotomous' print(len(s)) # This is for finding the length of string print('Practice makes man perfect') # finding the length of your name s = 'dileep' print(len(s)) it
true
a7a5cbedf25dc380bfcf6c152cfa4848d32f0c55
vinaykumar7686/Algorithms
/Data Structures/Binary-Tree/Binary Search Tree/[BST] Validate Binary Search Tree.py
2,161
4.375
4
# Validate Binary Search Tree ''' Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [2,1,3] Output: true Example 2: Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4. Constraints: The number of nodes in the tree is in the range [1, 104]. -231 <= Node.val <= 231 - 1 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def __init__(self): self.ans = True def isValidBST(self, root: TreeNode) -> bool: def func(root, l, r): if root: if root.val<=l or root.val>=r: self.ans = False return func(root.left, l, root.val) func(root.right, root.val, r) func(root, float("-inf"), float("inf")) return self.ans # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution1: def __init__(self): self.nums = [] def isValidBST(self, root: TreeNode) -> bool: def inorder(root): if not root: return inorder(root.left) self.nums.append(root.val) inorder(root.right) inorder(root) # print(self.nums, sorted(self.nums)) return self.nums == sorted(self.nums) and len(self.nums) == len(set(self.nums))
true
867ffc604bc02ee32ef1798070530ef9861ef0a1
vinaykumar7686/Algorithms
/Algorithms/Dynamic_Programming/Nth_Fibonacci_No/fibonacci _basic _sol.py
1,022
4.40625
4
def fibo_i(n): ''' Accepts integer type value as argument and returns respective number in fibonacci series. Uses traditional iterative technique Arguments: n is an integer type number whose respective fibonacci nyumber is to be found. Returns: nth number in fiboacci series ''' # Simply returning the value if the value of n is 0 or 1 if n in [0,1]: return n else: a = 0 b = 1 c = a+b while n-2>0: n-=1 a=b b=c c = a+b return c def fibo_r(n): ''' Accepts integer type value as argument and returns respective number in fibonacci series. Uses traditional recursive technique Arguments: n is an integer type number whose respective fibonacci nyumber is to be found. Returns: nth number in fiboacci series ''' if n in [0,1]: return n else: return fibo_r(n-1)+fibo_r(n-2) n = int(input('Enter the number : ')) print(fibo_r(n))
true
f04e1c9e1d991242d1dcce33de00c651125572a7
ziolkowskid06/Python_Crash_Course
/ch10 - Files and Exceptions/10-03. Guest.py
222
4.4375
4
""" Write a program that prompts the user for their name. """ name = input("What's your name? ") filename = 'guest.txt' # Save the variable into the .txt file with open(filename, 'w') as f: f.write(name)
true
daddc2badb17111c59d9406fdeb09dd7871b620e
ziolkowskid06/Python_Crash_Course
/ch05 - IF Statements/5-02. More Conditional Tests.py
673
4.125
4
""" Write more conditional tests. """ # Equality and iequality with strings. motorcycle = 'Ducati' print("Is motorcycle != 'Ducati'? I predict False.") print(motorcycle == 'ducati') print("\nIs motorycle == 'Ducati'? I predict True.") print(motorcycle == 'Ducati') # Test using lower() method. pc = 'DELL' print("\n\nIs pc == 'dell'? I predict True.") print(pc.lower() == 'dell') # Check if item is in a list or not. names = ['Anna', 'Julia', 'Rachel', 'Elizabeth'] print("\n\nCheck, if 'Samantha' is not in the list. I predict True.") print('Samantha' not in names) print("\nCheck, if 'Julia' is in the list. I preduct True.") print('Julia' in names)
true
58ca8613f51031792f48d896a3f5c3d6a4cfc565
ziolkowskid06/Python_Crash_Course
/ch05 - IF Statements/5-08. Hello Admin.py
473
4.4375
4
""" Make a list of five or more usernames, including the name'admin'. Imagine you are writing code that will print a greeting to each user after they log in to a website and the question for admin. """ names = ['anna', 'elizabeth', 'julia', 'kim', 'admin', 'rachel'] for name in names: if name == 'admin': print('Hello admin, would you like to see a status report?') else: print(f"Hello {name.title()}, thank you for logging in again.")
true
d90c7e345eb4fe782187b003523f9caa1909447c
ziolkowskid06/Python_Crash_Course
/ch07 - User Input and WHILE Loops/7-10. Dream Vacation.py
494
4.15625
4
""" Write a program that polls users about their dream vacation. """ poll = {} while True: name = input("What's your name? ") vacation = input("If you could visit one place in the world, " "where would you go? ") poll[name] = vacation quit = input("Stop asking? (yes/no) ") if quit == 'yes': break print("\n---- Poll Result ----") for name, vacation in poll.items(): print(f"{name.title()} would go to {vacation.title()}.")
true
b9014e87d1d5167c8cdcd0f0837609b7d61e240e
ziolkowskid06/Python_Crash_Course
/ch03 - Introducing Lists/3-09. Dinner Guests.py
319
4.21875
4
""" Working with one of the programs from Exercises 3-4 through 3-7 (page 42), use len() to print a message indicating the number of people you are inviting to dinner. """ # Print a number of elements guest_list = ['mary jane', 'elizabeth hurtley', 'salma hayek'] print(f" There are {len(guest_list)} people invited to dinner.")
true
30176a4c40a0682963e4d0d9de8d27004b191ff1
ziolkowskid06/Python_Crash_Course
/ch07 - User Input and WHILE Loops/7-02. Restaurant Seating.py
277
4.21875
4
""" Write a program that asks the user how many people are in their dinner group. """ seating = input('How many people are in your dinner group?\n') seating = int(seating) if seating > 8: print("You need to wait for a table.") else: print("Table is ready!")
true
c41f4dcd82e4b041185764f8646f5de6dc5b1ab6
Alex-Angelico/math-series
/math_series/series.py
1,337
4.3125
4
def fibonacci(num): """ Arguments: num - user-selected sequence value from the Fibonacci sequence to be calculated by the funciton Returns: Calculated value from the sequence """ if num <= 0: print('Value too small.') elif num == 1: return 0 elif num == 2: return 1 else: return fibonacci(num-1) + fibonacci(num-2) def lucas(num): """ Arguments: num - user-selected sequence value from the Lucas sequence to be calculated by the funciton Returns: Calculated value from the sequence """ if num == 0: return 2 if num == 1: return 1 return lucas(num-1) + lucas(num-2) def sum_series(num, x=0, y=1): """ Arguments: num - user-selected sequence value from the special number sequence (e.g. Fibonacci, Lucas) to be calculated by the funciton x - the lower bound number calculating the progression of the special number sequence y - the upper bound number calculating the progression of the special number sequence Returns: Calculated value from the sequence """ if x == 0 and y == 1: if num - 1 == 0: return x if num - 1 == 1: return y return sum_series(num - 1, x, y) + sum_series(num - 2, x, y) else: if num == 1: return x if num == 2: return y return sum_series(num - 1, x, y) + sum_series(num - 2, x, y)
true
cddc10f2fb3571e8d55ac0bc8393f5fe1aabd2cb
Priyojeet/man_at_work
/python_100/string_manipulation1.py
322
4.34375
4
# Write a Python program to remove the nth index character from a nonempty string. def remove_char(str, n): slice1 = str[:n] slice2 = str[n + 1:] #print(slice1) #print(slice2) return slice1 + slice2 l = str(input("enter a string:-")) no = int(input("enter a number:-")) print(remove_char(l, no))
true
97a822a515d3434b42b402aebbcb5513b01334f4
Priyojeet/man_at_work
/python_100/decision_making_nested_if_else.py
562
4.125
4
# check prime number with nested loop number = eval(input("enter the number you want:-")) if(isinstance(number,str)): print(" please enter an integer value") elif(type(number) == float): print("you enter a float number") else: if (number <= 0): print("enter an integer grater then 0") elif (number == 1): print("you have enter 1") else: for i in range(2, number): if ((number % i) == 0): print("number is not prime") break else: print("number is prime")
true
0862a345a5b5422d0e062f977015a95ef4ad3f3b
dipsuji/coding_pyhton
/coding/flatten_tree.py
1,266
4.1875
4
class Node: """ create node with lest and right attribute """ def __init__(self, key): self.left = None self.right = None self.val = key def print_pre_order(root): """ this is pre order traversal """ if root: # First print the data of root print(root.val), # Recursion function call left tree print_pre_order(root.left) # Recursion function call right tree print_pre_order(root.right) def find(root, item): """ search the given element in tree """ if root: # check the element if it is in root if root.val == item: print("Tree " + str(root.val)) if root.left is not None: print(" Left " + str(root.left.val)) if root.right is not None: print(" Right " + str(root.right.val)) return # Recursion function call left tree find(root.left, item) # Recursion function call right tree find(root.right, item) tree_root = Node(1) tree_root.left = Node(13) tree_root.right = Node(10) tree_root.left.left = Node(8) tree_root.right.left = Node(1) print("Pre order traversal:") print_pre_order(tree_root) find(tree_root, 1)
true
44e6ef8dd8212448ed8684262c52fcc71da35d4e
dipsuji/coding_pyhton
/udemy_leetcode/Hash Map Facebook Interview Questions solutions/majority_element.py
846
4.1875
4
""" - https://leetcode.com/problems/majority-element/ Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1: Input: nums = [3,2,3] Output: 3 Example 2: Input: nums = [2,2,1,1,1,2,2] Output: 2 """ from typing import List class Solution: def majorityElement(self, nums: List[int]) -> int: m = {} for num in nums: m[num] = m.get(num, 0)+1 for num in nums: if(m[num]>len(nums)//2): return num num1 = [2, 11, 11, 7, 11] # list length = 5, half = 2.5, ans - element have more than 2 times. # num1 = [2, 11, 7, 15] s = Solution() answer = s.majorityElement(num1) print(answer)
true
0045f7f9c3c0e13656f0b5f5c815f7cb17ac13bc
dipsuji/coding_pyhton
/udemy_leetcode/Microsoft Interview Questions solutions/missing_number.py
1,121
4.15625
4
from typing import List """ 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. Example 1: 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. Example 2: 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. Example 3: Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8 Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. """ class Solution: def missing_number(self, nums: List[int]) -> int: currentSum = sum(nums) n = len(nums) intendedSum = n * (n + 1) / 2 return int(intendedSum - currentSum) s = Solution() answer = s.missing_number([9, 6, 4, 2, 3, 5, 7, 0, 1]) print(answer)
true
77e3b9062540fd72f2a1deb8f3ccf652d982ad0d
lehmanwics/programming-interview-questions
/src/general/Python/4_fibonachi_numbers.py
1,402
4.28125
4
""" 4. Write fibonacci iteratively and recursively (bonus: use dynamic programming) """ # Fibonachi recursively (function calls itself) def fib(nth_number): if nth_number == 0: return 0 elif nth_number == 1: return 1 else: return fib(nth_number-1) + fib(nth_number - 2) # Fibonachi iteratively (use a loop) def fib_iter(nth_number): if nth_number == 0: return 0 if nth_number == 1: return 1 else: """ we have to keep track of the previous 2 numbers (assuming we are in the 2nd fibonacci number) """ prev_previous = 0 prev = 1 result = 0 for x in range(2, nth_number+1): # range stop parameter is non-inclusive result = prev_previous + prev # update the previous 2 numbers prev_previous = prev prev = result return result if __name__ == '__main__': """ create a list of the first 10 fibonacci numbers and store them in a list""" print("Generating the first 10 fibonacci numbers iteratively and recursively") fib_numbers = [fib(x) for x in range(1, 11)] fib_iter_numbers = [fib_iter(x) for x in range(1,11)] print("Recursive list of fibonacci numbers: "+str(fib_numbers)) print("Iterative list of fibonacci numbers: "+str(fib_iter_numbers))
true
935726112481fa8173f8e4bc7a817225d123d126
sarma5233/pythonpract
/python/operators.py
2,108
4.40625
4
a = 10 b = 8 print("ARITHMETIC operators") print('1.Addition') print(a+b) print() print('2.subtraction') print(a-b) print('3.Multiplication') print(a*b) print('4.Division') print(a/b) print('5.Modulus') print(a%b) print('6.Exponentiation') print(a**b) print('7.floor Division') print(a//b) print("Comparision Operators") print('1.Equal') print(a == b) print('2.Not Equal') print(a != b) print('3.Greater than') print(a > b) print('4.Lessthan') print(a < b) print('5.Greaterthan or Equal to') print(a >= b) print('6.Lessthan or Equal to') print(a <= b) print("Logical Operators") print('1.AND...,Returns True if both statements are true') print(a > 5 and a < 20) print('2.OR...,Returns True if one of the statements is true') print(a < 20 or a > 15) print('3.NOT...,Reverse the result, returns False if the result is true') print(not(a < 20 or a > 15)) print("ASSIGNMENT Operators") import math x = 10 print('1.=') print(x) print('2.+=') x += 5 print(x) print('3.-=') x -= 5 print(x) print('4.*=') x *= 5 print(x) print('5./=') x /= 5 print(x) print('6.%=') x %= 5 print(x) print('7.//=') x //= 5 print(x) print('8.**=') x **= 5 print(x) '''print('9.&=') x &= 5 print(x) print('10.|=') x |= 5 print(x) print('11.^=') x ^= 5 print(x) print('12.>>=') x >>= 3 print(x) print('13.<<=') x <<= 5 print(x)''' print("IDENTITY Operators") M=10 N=10.35 print(id(M)) print(id(N)) print('1.IS') print(type(M) is int) print('2.IS NOT') print(type(M) is not float) print('1.IS') print(type(N) is int) print('2.IS NOT') print(type(N) is float) print("MEMBERSHIP Operators") print('1.IN') vowels = ['a', 'e', 'i', 'o', 'u','A', 'E', 'I', 'O', 'U'] ch = input('Please Enter a Letter:\n') if ch in vowels: print('You entered a vowel character') else: print('You entered a consonants character') print('2.NOT IN') primes=(2,3,5,7,11) print(1 not in primes) print(3 not in primes) print("UNARY MINUS OPERATOR(-)") s=-50 print(s) print(-s) print() print("Ternary Operator") i, j = 10, 20 # Copy value of i in min if i < j else copy j min = i if i > j else j print(min)
true
8fb2558f6f9bed68720ee257727e9be5840cbe0d
sarma5233/pythonpract
/flow_controls/while.py
210
4.15625
4
n = int(input("enter a number:")) sum = 0 total_numbers = 1 while total_numbers <= n: sum += total_numbers total_numbers += 1 print("sum =", sum) average = sum/n print("Average = ", average)
true
c8ff41d4b83e1b1285f1acde17504d2236b453c6
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/04-regular_expression_in_python/e32_flying_home.py
1,297
4.15625
4
""" Flying home The variable flight containing one email subject was loaded in your session. You can use print() to view it in the IPython Shell. Import the re module. Complete the regular expression to match and capture all the flight information required. Only the first parenthesis were placed for you. Find all the matches corresponding to each piece of information about the flight. Assign it to flight_matches. Complete the format method with the elements contained in flight_matches. In the first line print the airline,and the flight number. In the second line, the departure and destination. In the third line, the date. """ # Import re import re flight = "Subject: You are now ready to fly. Here you have your boarding pass IB3723 AMS-MAD 06OCT" # Write regex to capture information of the flight regex = r"([A-Z]{2})(\d{4})\s([A-Z]{3})-([A-Z]{3})\s(\d{2}[A-Z]{3})" #print(re.findall(regex,flight)) # Find all matches of the flight information flight_matches = re.findall(regex,flight) print(flight_matches) print(flight_matches[0][0]) #Print the matches print("Airline: {} Flight number: {}".format(flight_matches[0][0], flight_matches[0][1])) print("Departure: {} Destination: {}".format(flight_matches[0][2], flight_matches[0][3])) print("Date: {}".format(flight_matches[0][4]))
true
fa7afe7b83e2d11110183c186ed9019e7043d306
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/05-Working_with_Dates_and_Times/e22_how_many_hours_elapsed_around_daylight_saving.py
1,348
4.5625
5
""" How many hours elapsed around daylight saving? Let's look at March 12, 2017, in the Eastern United States, when Daylight Saving kicked in at 2 AM. If you create a datetime for midnight that night, and add 6 hours to it, how much time will have elapsed? You already have a datetime called start, set for March 12, 2017 at midnight, set to the timezone 'America/New_York'. Add six hours to start and assign it to end. Look at the UTC offset for the two results. You added 6 hours, and got 6 AM, despite the fact that the clocks springing forward means only 5 hours would have actually elapsed! Calculate the time between start and end. How much time does Python think has elapsed? Move your datetime objects into UTC and calculate the elapsed time again. Once you're in UTC, what result do you get? """ # Import datetime, timedelta, tz, timezone from datetime import datetime, timedelta, timezone from dateutil import tz # Start on March 12, 2017, midnight, then add 6 hours start = datetime(2017, 3, 12, tzinfo=tz.gettz('America/New_York')) end = start + timedelta(hours=6) print(start.isoformat() + " to " + end.isoformat()) # How many hours have elapsed? print((end - start).total_seconds() / (60 * 60)) # What if we move to UTC? print((end.astimezone(timezone.utc) - start.astimezone(timezone.utc)) \ .total_seconds() / (60 * 60))
true
afb5a251bfa0ba326669aa7ae14f0004c54d914e
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/12-Introduction_to_Deep_Learning_in_Python/e1_coding_the_forward_propagation_algorithm.py
1,574
4.375
4
""" Coding the forward propagation algorithm The input data has been pre-loaded as input_data, and the weights are available in a dictionary called weights. The array of weights for the first node in the hidden layer are in weights['node_0'], and the array of weights for the second node in the hidden layer are in weights['node_1']. The weights feeding into the output node are available in weights['output']. NumPy will be pre-imported for you as np in all exercises. Instructions 100 XP Calculate the value in node 0 by multiplying input_data by its weights weights['node_0'] and computing their sum. This is the 1st node in the hidden layer. Calculate the value in node 1 using input_data and weights['node_1']. This is the 2nd node in the hidden layer. Put the hidden layer values into an array. This has been done for you. Generate the prediction by multiplying hidden_layer_outputs by weights['output'] and computing their sum. Hit 'Submit Answer' to print the output! """ import numpy as np input_data = np.array([3, 5]) weights = {'node_0': np.array([2, 4]), 'node_1': np.array([4, -5]), 'output': np.array([2, 7])} # Calculate node 0 value: node_0_value node_0_value = (input_data * weights['node_0']).sum() # Calculate node 1 value: node_1_value node_1_value = (input_data * weights['node_1']).sum() # Put node values into array: hidden_layer_outputs hidden_layer_outputs = np.array([node_0_value, node_1_value]) # Calculate output: output output = (hidden_layer_outputs * weights['output']).sum() # Print output print(output)
true
a5437c79e37d03fd36f379c41ee2f84ea191bb79
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/02-python-data-science-toolbox-part-2/e33_writing_an_iterator_to_load_data_in_chunks3.py
1,534
4.15625
4
""" Writing an iterator to load data in chunks (3) The packages pandas and matplotlib.pyplot have been imported as pd and plt respectively for your use. Instructions 100 XP Write a list comprehension to generate a list of values from pops_list for the new column 'Total Urban Population'. The output expression should be the product of the first and second element in each tuple in pops_list. Because the 2nd element is a percentage, you also need to either multiply the result by 0.01 or divide it by 100. In addition, note that the column 'Total Urban Population' should only be able to take on integer values. To ensure this, make sure you cast the output expression to an integer with int(). Create a scatter plot where the x-axis are values from the 'Year' column and the y-axis are values from the 'Total Urban Population' column. """ import pandas as pd import matplotlib.pyplot as plt # Code from previous exercise urb_pop_reader = pd.read_csv('ind_pop_data.csv', chunksize=1000) df_urb_pop = next(urb_pop_reader) df_pop_ceb = df_urb_pop[df_urb_pop['CountryCode'] == 'CEB'] pops = zip(df_pop_ceb['Total Population'], df_pop_ceb['Urban population (% of total)']) pops_list = list(pops) print(pops_list) # Use list comprehension to create new DataFrame column 'Total Urban Population' df_pop_ceb['Total Urban Population'] = [int(tup[0] * tup[1] * 0.01) for tup in pops_list] # Plot urban population data df_pop_ceb.plot(kind='scatter', x='Year', y='Total Urban Population') plt.show()
true
c1a72827d922ed8468dd66d50a7c0d2d4c897ce8
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/02-python-data-science-toolbox-part-2/e18_list_comprehensions_vs_generators.py
1,679
4.5
4
""" List comprehensions vs generators generators does not store data in memnory like list if there a very large list then use generators. There is no point in using large list instead use generators In this exercise, you will recall the difference between list comprehensions and generators. To help with that task, the following code has been pre-loaded in the environment: # List of strings fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli'] # List comprehension fellow1 = [member for member in fellowship if len(member) >= 7] # Generator expression fellow2 = (member for member in fellowship if len(member) >= 7) Try to play around with fellow1 and fellow2 by figuring out their types and printing out their values. Based on your observations and what you can recall from the video, select from the options below the best description for the difference between list comprehensions and generators. Instructions Possible Answers 1.List comprehensions and generators are not different at all; they are just different ways of writing the same thing. 2.A list comprehension produces a list as output, a generator produces a generator object. 3.A list comprehension produces a list as output that can be iterated over, a generator produces a generator object that can't be iterated over. Answer : 2 """ # List of strings fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli'] # List comprehension fellow1 = [member for member in fellowship if len(member) >= 7] # Generator expression fellow2 = (member for member in fellowship if len(member) >= 7) print(fellow1) print(fellow2)
true
7278153d5148595cd0bc4cfb92ccef72cd4706c7
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/10-Supervised_Learning_with_scikit-learn/e28_centering_and_scaling_your_data.py
1,912
4.28125
4
""" Centering and scaling your data You will now explore scaling for yourself on a new dataset - White Wine Quality! Hugo used the Red Wine Quality dataset in the video. We have used the 'quality' feature of the wine to create a binary target variable: If 'quality' is less than 5, the target variable is 1, and otherwise, it is 0. The DataFrame has been pre-loaded as df, along with the feature and target variable arrays X and y. Explore it in the IPython Shell. Notice how some features seem to have different units of measurement. 'density', for instance, takes values between 0.98 and 1.04, while 'total sulfur dioxide' ranges from 9 to 440. As a result, it may be worth scaling the features here. Your job in this exercise is to scale the features and compute the mean and standard deviation of the unscaled features compared to the scaled features. Instructions Import scale from sklearn.preprocessing. Scale the features X using scale(). Print the mean and standard deviation of the unscaled features X, and then the scaled features X_scaled. Use the numpy functions np.mean() and np.std() to compute the mean and standard deviations. """ import pandas as pd import numpy as np # Import scale from sklearn.preprocessing import scale df = pd.read_csv('white-wine.csv') X = df.drop('quality', axis=1).values # if quality less than 5 then True else False y = df['quality'].apply(lambda x: 'True' if x < 5 else 'False').to_numpy() # Scale the features: X_scaled X_scaled = scale(X) # Print the mean and standard deviation of the unscaled features print("Mean of Unscaled Features: {}".format(np.mean(X))) print("Standard Deviation of Unscaled Features: {}".format(np.std(X))) # Print the mean and standard deviation of the scaled features print("Mean of Scaled Features: {}".format(np.mean(X_scaled))) print("Standard Deviation of Scaled Features: {}".format(np.std(X_scaled)))
true
246c365f2c3f7f10c249933ead07532244770291
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/03-cleaning_data_in_python/e36_pairs_of_restaurants.py
1,325
4.125
4
""" in this exercise, you will perform the first step in record linkage and generate possible pairs of rows between restaurants and restaurants_new. Both DataFrames, pandas and recordlinkage are in your environment. Instructions Instantiate an indexing object by using the Index() function from recordlinkage. Block your pairing on cuisine_type by using indexer's' .block() method. Generate pairs by indexing restaurants and restaurants_new in that order. Now that you've generated your pairs, you've achieved the first step of record linkage. What are the steps remaining to link both restaurants DataFrames, and in what order? """ import pandas as pd import recordlinkage restaurants = pd.read_csv('restaurant.csv') restaurants_new = pd.read_csv('restaurant_new.csv') # Create an indexer and object and find possible pairs indexer = recordlinkage.Index() # Block pairing on cuisine_type indexer.block('cuisine_type') # Generate pairs pairs = indexer.index(restaurants, restaurants_new) print(pairs) """ Possible Answers A.Compare between columns, score the comparison, then link the DataFrames. B.Clean the data, compare between columns, link the DataFrames, then score the comparison. C.Clean the data, compare between columns, score the comparison, then link the DataFrames. Answer A """
true
5b718cdb7f238284afaa3e3a5080213062c4bf15
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/04-regular_expression_in_python/e3_palindromes.py
782
4.28125
4
""" The text of a movie review for one example has been already saved in the variable movie. You can use print(movie) to view the variable in the IPython Shell. Instructions 100 XP Extract the substring from the 12th to the 30th character from the variable movie which corresponds to the movie title. Store it in the variable movie_title. Get the palindrome by reversing the string contained in movie_title. Complete the code to print out the movie_title if it is a palindrome. """ movie = "oh my God! desserts I stressed was an ugly movie" # Get the word movie_title = movie[11:30] print(movie_title) # Obtain the palindrome palindrome = movie_title[::-1] print(palindrome) # Print the word if it's a palindrome if movie_title == palindrome: print(movie_title)
true
d4cf7f2383afe7107d2218d684df69e3f9e4c9e8
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/05-Working_with_Dates_and_Times/e16_the_long_and_the_short_of_why_time_is_hard.py
1,779
4.46875
4
""" The long and the short of why time is hard As before, data has been loaded as onebike_durations. Calculate shortest_trip from onebike_durations. Calculate longest_trip from onebike_durations. Print the results, turning shortest_trip and longest_trip into strings so they can print. """ from datetime import datetime, timedelta onebike_datetimes = [ {'start': datetime(2017, 10, 1, 15, 23, 25), 'end': datetime(2017, 10, 1, 15, 26, 26)}, {'start': datetime(2017, 10, 1, 15, 42, 57), 'end': datetime(2017, 10, 1, 17, 49, 59)}, {'start': datetime(2017, 10, 2, 6, 37, 10), 'end': datetime(2017, 10, 2, 6, 42, 53)}, {'start': datetime(2017, 10, 2, 8, 56, 45), 'end': datetime(2017, 10, 2, 9, 18, 3)}] # Initialize a list for all the trip durations onebike_durations = [] for trip in onebike_datetimes: #print(trip) # Create a timedelta object corresponding to the length of the trip trip_duration = trip['end'] - trip['start'] print(trip_duration) # Get the total elapsed seconds in trip_duration trip_length_seconds = trip_duration.total_seconds() # Append the results to our list onebike_durations.append(trip_length_seconds) # What was the total duration of all trips? total_elapsed_time = sum(onebike_durations) print(total_elapsed_time) # What was the total number of trips? number_of_trips = len(onebike_durations) print(number_of_trips) # Divide the total duration by the number of trips print(total_elapsed_time / number_of_trips) # Calculate shortest and longest trips shortest_trip = min(onebike_durations) longest_trip = max(onebike_durations) # Print out the results print("The shortest trip was " + str(shortest_trip) + " seconds") print("The longest trip was " + str(longest_trip) + " seconds")
true
9aa4a68742400f5dff59647d53bfb1e0e7d91a14
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/07-Exploratory_Data_Analysis_in_Python/e32_making_predictions.py
1,169
4.21875
4
""" Making predictions At this point, we have a model that predicts income using age, education, and sex. Let's see what it predicts for different levels of education, holding age constant. Using np.linspace(), add a variable named 'educ' to df with a range of values from 0 to 20. Add a variable named 'age' with the constant value 30. Use df to generate predicted income as a function of education. """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy import stats from empiricaldist import Pmf from scipy.stats import norm from scipy.stats import linregress import seaborn as sns import statsmodels.formula.api as smf gss = pd.read_hdf('gss.hdf5', 'gss') # Add a new column with educ squared gss['educ2'] = gss['educ'] ** 2 gss['age2'] = gss['age'] ** 2 # Run a regression model with educ, educ2, age, and age2 results = smf.ols('realinc ~ educ + educ2 + age + age2', data=gss).fit() # Make the DataFrame df = pd.DataFrame() df['educ'] = np.linspace(0, 20) df['age'] = 30 df['educ2'] = df['educ'] ** 2 df['age2'] = df['age'] ** 2 # Generate and plot the predictions pred = results.predict(df) print(pred.head())
true
7e486404b32bb6b34085ee5fc263fbb2437cd3b6
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/09-Statistical_Thinking_in_Python_Part2/e7_linear_regression_on_appropriate_anscombe_data.py
1,403
4.125
4
""" Linear regression on appropriate Anscombe data Compute the parameters for the slope and intercept using np.polyfit(). The Anscombe data are stored in the arrays x and y. Print the slope a and intercept b. Generate theoretical and data from the linear regression. Your array, which you can create with np.array(), should consist of 3 and 15. To generate the data, multiply the slope by x_theor and add the intercept. Plot the Anscombe data as a scatter plot and then plot the theoretical line. Remember to include the marker='.' and linestyle='none' keyword arguments in addition to x and y when to plot the Anscombe data as a scatter plot. You do not need these arguments when plotting the theoretical line. Hit 'Submit Answer' to see the plot! """ import numpy as np import matplotlib.pyplot as plt # Perform linear regression: a, b x = np.array([10., 8., 13., 9., 11., 14., 6., 4., 12., 7., 5.]) y = np.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]) a, b = np.polyfit(x, y, 1) # Print the slope and intercept print(a, b) # Generate theoretical x and y data: x_theor, y_theor x_theor = np.array([3, 15]) y_theor = a * x_theor + b # Plot the Anscombe data and theoretical line _ = plt.plot(x, y, marker='.', linestyle='none') _ = plt.plot(x_theor, y_theor, marker='.', linestyle='none') # Label the axes plt.xlabel('x') plt.ylabel('y') # Show the plot plt.show()
true
dab0d9344df34e3f0730c2b87683c050d701e011
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/04-regular_expression_in_python/e2_artificial_reviews.py
1,271
4.15625
4
""" The text of two movie reviews has been already saved in the variables movie1 and movie2. You can use the print() function to view the variables in the IPython Shell. Remember: The 1st character of a string has index 0. Instructions Select the first 32 characters of the variable movie1 and assign it to the variable first_part. Select the substring going from the 43rd character to the end of movie1. Assign it to the variable last_part. Select the substring going from the 33rd to the 42nd character of movie2. Assign it to the variable middle_part. Print the concatenation of the variables first_part, middle_part and last_part in that order. Print the variable movie2 and compare them. """ movie1 = "the most significant tension of _election_ is the potential relationship between a teacher and his student ." movie2 = "the most significant tension of _rushmore_ is the potential relationship between a teacher and his student ." first_part = movie1[:32] print(first_part) # Select from 43rd character to the end of movie1 last_part = movie1[42:] print(last_part) # Select from 33rd to the 42nd character of movie2 middle_part = movie2[32:42] print(middle_part) # Print concatenation and movie2 variable print(first_part+middle_part+last_part) print(movie2)
true
b6eb4dde3b6ef947df4922a52e971102397f01e9
sarmabhamidipati/UCD
/Specialist Certificate in Data Analytics Essentials/DataCamp/07-Exploratory_Data_Analysis_in_Python/e7_compute_birth_weight.py
818
4.3125
4
""" Compute birth weight Make a Boolean Series called full_term that is true for babies with 'prglngth' greater than or equal to 37 weeks. Use full_term and birth_weight to select birth weight in pounds for full-term babies. Store the result in full_term_weight. Compute the mean weight of full-term babies. """ import pandas as pd import numpy as np import matplotlib.pyplot as plt pd.options.display.max_columns = None nsfg = pd.read_hdf('nsfg.hdf5', 'nsfg') agecon = nsfg["agecon"]/100 # Plot the histogram plt.hist(agecon, bins=20, histtype='step') # Create a Boolean Series for full-term babies full_term = nsfg['prglngth'] >= 37 # Select the weights of full-term babies full_term_weight = birth_weight[full_term] # Compute the mean weight of full-term babies print(full_term_weight.mean())
true
fef3d8a8eb810bfeebd65a7951b14f2f55c514c8
DiniH1/python_concatenation_task
/python_concactination_task.py
507
4.21875
4
# Task 1 name = "" name = input("What is your name? ") name_capitalize = name.capitalize() print(name_capitalize + " Welcome to this task!") # Task 2 full_name = "" full_name = input('What is your full name? ') first_name = (full_name.split()[0]) first_name_capitalize = first_name.capitalize() last_name = (full_name.split()[1]) last_name_capitalize = last_name.capitalize() full_name_capitalize = first_name_capitalize + " " + last_name_capitalize print(full_name_capitalize + " Welcome to this task!")
true
2ae3f62714952207aaf401db24a148f92a9871d1
AtxTom/Election_Analysis
/PyPoll.py
1,017
4.125
4
# The data we need to retrieve. # 1. The total number of votes cast # 2. A complete list of candidates who received votes # 3. The percentage of votes each candidate won # 4. The total number of votes each candidate won # 5. The winner of the election based on popular vote. # Add our dependencies. import csv import os # Add a variable to load a file from a path. file_to_load = os.path.join("Resources/election_results.csv") # Add a variable to save the file to a path. file_to_save = os.path.join("analysis", "election_analysis.txt") # 1. Initialize a total vote counter. total_votes = 0 # Open the election results and read the file with open(file_to_load) as election_data: print(election_data) # file_reader = csv.reader(election_data) # # Read the header row. # headers = (next(file_reader)) # # Print each row in the CSV file. # for row in election_data: # # 2. Add to the total vote count. # total_votes += 1 # # 3. Print the total votes. # print(total_votes)
true
fceebe8dfa503b1bfe1925f59e1a06c7f14a3851
lengfc09/Financial_Models
/NLP/Codes/code-sklearn-k-means-clustering.py
792
4.3125
4
# This script illustrates how to use k-means clustering in # SciKit-Learn. from sklearn.cluster import KMeans import numpy as np # We create a numpy array with some data. Each row corresponds to an # observation. X = \ np.array( [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]) # Perform k-means clustering of the data into two clusters. kmeans = KMeans(n_clusters=2, random_state=0).fit(X) # Show the labels, i.e. for each observation indicate the group # membership. kmeans.labels_ # Ifyou have two new observations (i.e. previously unseen by the # algorithm), to which group would they be assigned? kmeans.predict( [[0, 0], [12, 3]]) # Show the centers of the clusters as determined by k-means. kmeans.cluster_centers_
true
302334f9a7cd8ac3ae4ff61777bc7926899baca4
sanraj99/practice_python
/prime_number.py
509
4.15625
4
# A Prime number can only divided by 1 and itself def is_prime(num): for i in range(2, num): if (num % i) == 0: return False return True def getPrimes(max_number): list_of_primes = [] for num1 in range(2, max_number): if is_prime(num1): list_of_primes.append(num1) return list_of_primes max_num_to_check = int(input("Search for Primes up to : ")) list_of_prime = getPrimes(max_num_to_check) for prime in list_of_prime: print(prime)
true
4f97b96ca9683d7dea5defd2201e10d4408b169b
sourav-gomes/Python
/Part - I/Chapter 3 - Strings/03_string_functions.py
854
4.28125
4
story = "once upon a time there was a boy named Joseph who was good but very lazy fellow and never completed any job" # String Functions # print(len(story)) # gives length of the string # print(story.endswith("job")) # returns True or false. In this case True. # print(story.count("a")) # returns how many times a character 'a' has occurred # print(story.count("was")) # returns how many times a string 'was' has occurred, in this case 2 # print(story.capitalize()) # Capitalizes first word of the string print(story.find("was")) # Finds the first occurrence of the word in the string (only first) and returns their position # print(story.replace("was", "WOULD BE")) # Finds & replaces old word with new in the string (all occurrences) year = '1700' print(int(year[:2])+1) print(year[2:]) print(int(float('1.07')))
true
b79a137c9f02c076e43d751bbaec2b0ede6f6603
sourav-gomes/Python
/Part - I/Chapter 5 - Dictionary & Sets/03_Sets_in_python_and methods.py
1,726
4.375
4
''' a = (1, 2, 3) # () means --> tuple print(type(a)) # prints type --> <class 'tuple'> a = [1, 2, 3] # [] means --> list print(type(a)) # prints type --> <class 'list'> a = {1, 2, 3} # {x, y,....} means --> set print(type(a)) # prints type --> <class 'set'> a = {1:3} # {x:y} means --> dictionary print(type(a)) # prints type --> <class 'dict'> a = {} print(type(a)) # Important this syntax will create an empty dictionary, NOT an empty set # To create an empty set you use the following command b = set() print(type(b)) # Methods in Sets b.add(4) # add() to add value to the set b.add(10) # An object is hashable if it has a hash value that DOES NOT change during its entire lifetime # b.add([1,3,6]) # cannot add a list to a set since a list is not hashable # b.add((1,3,6)) # But you can add a tuple to a set # b.add({5:8}) # cannot add a list to a set since a dictionar is not hashable # Only HASHABLE datatypes can exist inside a set print(b) s = {1,4,4,1,6,1,6} print(s) # will print only {1, 4, 6} since a set can have only unique values print(len(s)) # prints length of set, in this case 3 s.remove(6) # removes 6 from the above set of {1, 4, 6} # s.remove(5) # Throws error as 5 is not an element of the set above set of {1, 4, 6} print(s) print(s.pop()) # Randomly removed a value from the set and returns the remaining print(s.clear()) # Clears/Empties the set and returns None ''' set1 = {2, 5, 6, 8} set2 = {6, 3, 0, 1} print(set1.union(set2)) # Eg. of set1 & set2 union print(set1.intersection(set2)) # Eg. of set1 & set2 intersection (only 6 is common)
true
22f684c1ea3a1f78b58f9b8db35238d5041091ce
suneeshms96/python-password-validator
/python-password-validator.py
795
4.28125
4
digit_count = 0 alpha_count = 0 char_count = 0 lower_count = 0 #we can change password strength requirement here..! required_digit_count = 5 required_alpha_count = 2 required_char_count = 4 required_lower_count = 2 uname = input('Enter your username: ') word = input('Enter a password : ') for w in str(word): if w.isdigit(): digit_count = digit_count + 1 elif w.isalpha(): alpha_count = alpha_count + 1 if w.islower(): lower_count = lower_count + 1 else: char_count = char_count + 1 if digit_count >= required_digit_count and alpha_count >= required_alpha_count and char_count >= required_char_count and lower_count >= required_lower_count : print ('The password is successfully added for',uname) else: print('The password is not valid')
true
321abe804a7ce7b47ee132886559168e3b52d640
wojlas/Guess-the-number
/guess_the_number.py
909
4.1875
4
import random def guess_the_number(): try: """function checks if the given number is equal to the drawn number and displays an appropriate message""" user_number = int(input("Guess the number: ")) index = 0 while user_number != random_number: if user_number < random_number: print("Too small!") user_number = int(input("Guess the number: ")) index += 1 else: print("Too big!") user_number = int(input("Guess the number: ")) index += 1 print(f"You win in {index + 1} steps") except ValueError: """when given value is not a number function print message "It's not a number" """ print("It's not a number!") if __name__ == '__main__': random_number = random.randint(1, 100) print(guess_the_number())
true
29ab376394ff53ed3542e6f22877b23d5d115e72
dchtexas1/pythonFiles
/division.py
233
4.4375
4
"""Gives quotient and remainder of two numbers.""" a = input("Enter the first number: ") b = input("Enter the second number: ") print("The quotient of {} divided by {} is {} with a remainder of {}.".format( a, b, a / b, a % b))
true