blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d6846c5fdeaf0b2680e0ab99ab31480a1bf093aa
manchenkoff/geekbrains-python-homework
/lesson01/task04.py
634
4.1875
4
""" Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции. """ user_input = input("Введите число >>> ") if not user_input.isdigit(): print("Неверный формат числа") exit() number = int(user_input) max_num = 0 while number and max_num != 9: print(number) current = number % 10 number = number // 10 max_num = current if current > max_num else max_num print(max_num)
false
de7f58a8084ee33e834c6487c65ef0cf13a19913
Md-Hiccup/Problem-Solving
/HackerRank/Rank/easy/symmetric_difference.py
2,623
4.125
4
""" a new data type: sets. Concept: If the inputs are given on one line separated by a space character, use split() to get the separate values in the form of a list: >> a = raw_input() 5 4 3 2 >> lis = a.split() >> print (lis) ['5', '4', '3', '2'] If the list values are all integer types, use the map() method to convert all the strings to integers. >> newlis = list(map(int, lis)) >> print (newlis) [5, 4, 3, 2] Sets are an unordered bag of unique values. A single set contains values of any immutable data type. CREATING SETS >> myset = {1, 2} # Directly assigning values to a set >> myset = set() # Initializing a set >> myset = set(['a', 'b']) # Creating a set from a list >> myset {'a', 'b'} MODIFYING SETS Using the add() function: >> myset.add('c') >> myset {'a', 'c', 'b'} >> myset.add('a') # As 'a' already exists in the set, nothing happens >> myset.add((5, 4)) >> myset {'a', 'c', 'b', (5, 4)} Using the update() function: >> myset.update([1, 2, 3, 4]) # update() only works for iterable objects >> myset {'a', 1, 'c', 'b', 4, 2, (5, 4), 3} >> myset.update({1, 7, 8}) >> myset {'a', 1, 'c', 'b', 4, 7, 8, 2, (5, 4), 3} >> myset.update({1, 6}, [5, 13]) >> myset {'a', 1, 'c', 'b', 4, 5, 6, 7, 8, 2, (5, 4), 13, 3} REMOVING ITEMS Both the discard() and remove() functions take a single value as an argument and removes that value from the set. If that value is not present, discard() does nothing, but remove() will raise a KeyError exception. >> myset.discard(10) >> myset {'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 13, 11, 3} >> myset.remove(13) >> myset {'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 11, 3} COMMON SET OPERATIONS Using union(), intersection() and difference() functions. >> a = {2, 4, 5, 9} >> b = {2, 4, 11, 12} >> a.union(b) # Values which exist in a or b {2, 4, 5, 9, 11, 12} >> a.intersection(b) # Values which exist in a and b {2, 4} >> a.difference(b) # Values which exist in a but not in b {9, 5} The union() and intersection() functions are symmetric methods: >> a.union(b) == b.union(a) True >> a.intersection(b) == b.intersection(a) True >> a.difference(b) == b.difference(a) False These other built-in data structures in Python are also useful. Output Format Output the symmetric difference integers in ascending order, one per line. Sample Input 4 2 4 5 9 4 2 4 11 12 Sample Output 5 9 11 12 """ # m = int(input()) # lm = list(map(int, input().split())) # n = int(input()) # ln = list(map(int, input().split())) m = 4 lm = set([2, 4, 5, 9]) n = 4 ln = set([2, 4, 11, 12]) data = sorted(lm.difference(ln).union(ln.difference(lm))) print(*data, sep='\n')
true
acfbd6ce55de265ead5aa37b15d13d6ad78c6060
Md-Hiccup/Problem-Solving
/HackerRank/Rank/easy/any_or_all.py
719
4.125
4
""" any(): This expression returns True if any element of the iterable is true. If the iterable is empty, it will return False. all(): This expression returns True if all of the elements of the iterable are true. If the iterable is empty, it will return True. Prob: Print True if all the conditions of the problem statement are satisfied. Otherwise, print False Sample Input 5 12 9 61 5 14 Sample Output True """ # Enter your code here. Read input from STDIN. Print output to STDOUT n, numb = int(input()), list(map(int, input().split())) chk_any = all(list(map(lambda x: x > 0, numb))) pallindromic_any = any(list(map(lambda x: list(str(x)) == list(reversed(str(x))), numb))) print(chk_any and pallindromic_any)
true
1ef078d6c92399bc43e5737112cf6d41105963de
Md-Hiccup/Problem-Solving
/HackerRank/Rank/easy/collection_namedtuple.py
924
4.4375
4
""" collections.namedtuple() Basically, namedtuples are easy to create, lightweight object types. They turn tuples into convenient containers for simple tasks. With namedtuples, you don’t have to use integer indices for accessing members of a tuple. Example: >>> from collections import namedtuple >>> Point = namedtuple('Point','x,y') >>> pt1 = Point(1,2) >>> pt2 = Point(3,4) >>> dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y ) >>> print dot_product 11 Problem: Sample Input: 5 ID MARKS NAME CLASS 1 97 Raymond 7 2 50 Steven 4 3 91 Adrian 9 4 72 Stewart 5 5 80 Peter 6 Sample Output: 81.00 # Average = (97+50+91+72+80)/5 """ from collections import namedtuple n = int(input()) Student = namedtuple('Student', 'ID, Marks, Name, Class')
true
c2c0745b71a66464daf21d104a2831c38de9d9bb
ErenBtrk/Python-Fundamentals
/Numpy/NumpyStrings/Exercise16.py
313
4.125
4
''' 16. Write a NumPy program to count the lowest index of "P" in a given array, element-wise. ''' import numpy as np np_array = np.array(['Python' ,'PHP' ,'JS' ,'examples' ,'html']) print("\nOriginal Array:") print(np_array) print("count the lowest index of ‘P’:") r = np.char.find(np_array, "P") print(r)
true
339a24e71cbd4b32a815332c1ad9426a1d99c335
ErenBtrk/Python-Fundamentals
/Python Operators/4-ComparisonOperatorsExercises.py
1,368
4.34375
4
#1 - Prompt user to enter two numbers and print larger one number1 = int(input("Please enter a number : ")) number2 = int(input("Please enter a number : ")) result = number1 > number2 print(f"number1 : {number1} is greater than number2 : {number2} => {result}") #2 - Prompt user to enter 2 exam notes and calculate average.If >50 print Passed ,if no print Try Again exam1 = float(input("Please enter your exam note : ")) exam2 = float(input("Please enter your exam note : ")) average = (exam1+exam2)/2 result = average >= 50 print(f"Average is : {average} , You Passed the class : {result}") #3 - Prompt user to enter a number.Print if its odd or even number3 = int(input("Please enter a number : ")) result = (number3 % 2 != 0) print(f"The number : {number3} is an odd number : {result}") #4 - Prompt user to enter a number.Print if its negative or positive number3 = int(input("Please enter a number : ")) result = (number3 > 0) print(f"The number : {number3} ,is positive : {result}") #5 - Prompt user to enter email and password.Check if its true # ( email = email@gmail.com password = abcd123) email = "email@gmail.com" password = "abcd123" inputUserEmail = input("Please enter your email : ") inputUserPassword = input("Please enter your password : ") result = (email == inputUserEmail.strip()) & (password == inputUserPassword.strip()) print(f"Logged in : {result}")
true
b9d440a9aafd661b1d1ed641cc8921e5e24ebd02
ErenBtrk/Python-Fundamentals
/Numpy/NumpyLinearAlgebra/Exercise14.py
256
4.1875
4
''' 14. Write a NumPy program to compute the condition number of a given matrix. ''' import numpy as np m = np.array([[1,2],[3,4]]) print("Original matrix:") print(m) result = np.linalg.cond(m) print("Condition number of the said matrix:") print(result)
true
b99c2578051bef4298f3c7110ac76b9b3c0c9063
ErenBtrk/Python-Fundamentals
/Numpy/NumpyLinearAlgebra/Exercise10.py
270
4.125
4
''' 10. Write a NumPy program to find a matrix or vector norm. ''' import numpy as np v = np.arange(7) result = np.linalg.norm(v) print("Vector norm:") print(result) m = np.matrix('1, 2; 3, 4') print(m) result1 = np.linalg.norm(m) print("Matrix norm:") print(result1)
true
d888cf76ca3c466760c7c6397a7c056aa44f9368
ErenBtrk/Python-Fundamentals
/Python Conditional Statements/4-IfElseExercises2.py
2,940
4.46875
4
#1- Prompt the user to enter a number and check if its between 0-100 number1 = int(input("Please enter a number : ")) if(number1>0) and (number1<100): print(f"{number1} is between 0-100") else: print(f"{number1} is NOT between 0-100") #2- Prompt the user to enter a number and check if its positive even number number2 = int(input("Please enter a number : ")) if(number2 > 0): if(number2 % 2 == 0): print(f"{number2} is positive even number") else: print(f"{number2} is not an even number") else: print(f"{number2} is not a positive number") #3- Prompt the user to enter password and email and check if info is right email = "email@gmail.com" password = "123456" inputEmail = input("Email : ") inputPassword = input("Password : ") if (email == inputEmail.strip()): if(password == inputPassword.strip()): print("Logged in.") else: print("Password is wrong.") else: print("Email is wrong.") #4- Prompt the user to enter 3 numbers and compare them number3 = int(input("Please enter a number : ")) number4 = int(input("Please enter a number : ")) number5 = int(input("Please enter a number : ")) if(number3 > number4) and (number3 > number5): print(f"{number3} is the greatest") if(number4 > number3) and (number4 > number5): print(f"{number4} is the greatest") if(number5 > number3) and (number5 > number4): print(f"{number5} is the greatest") #5- Prompt the user to enter 2 exam notes (%60) and 1 final note.And calculate average. # if average is equal or larger than 50 print passed # a-)Even though average is 50 final note has to be at least 50 # b-)If final note is equal or larger than 70 student can pass exam1 = int(input("Please enter your first exam note : ")) exam2 = int(input("Please enter your second exam note : ")) final = int(input("Please enter your final exam note : ")) average = (((exam1+exam2) / 2)*0.6 + final*0.4) print(f"Your average is {average}") if(average >= 50): print("You passed the class.") else: if(final >= 70): print("You passed the class.Cause you got at least 70 in final exam.") else: print("You could not pass the class.") #6- Prompt the user to enter name,weight,height and calculate body mass index # Formula : (weight / height**2) # Whats user BMI according to table below # 0-18.4 => thin # 18.5-24.9 => Normal # 25.0-29.9 => Overweight # 30.0-34.9 => Obese name = input("Please enter your name : ") weight = float(input("Please enter your weight : ")) height = float(input("Please enter your height in meters : ")) bmi = weight / (height**2) print(f"Your body mass index is {bmi}") if (bmi >= 0) and (bmi <=18.4): print(f"{name} has thin bmi") elif (bmi >= 18.5) and (bmi <=24.9): print(f"{name} has normal bmi") elif (bmi >= 25.0) and (bmi <=29.9): print(f"{name} has overweight bmi") elif (bmi >= 30.0): print(f"{name} is obese")
true
31e0a2c1b41f587b63bb213ebda6c68d96d83d36
ErenBtrk/Python-Fundamentals
/Pandas/PandasDataSeries/Exercise13.py
289
4.15625
4
''' 13. Write a Pandas program to create a subset of a given series based on value and condition. ''' import pandas as pd pd_series = pd.Series([1,2,3,4,5]) print(pd_series) relationalVar = pd_series > 3 new_series = pd_series[relationalVar] new_series.index = [0,1] print(new_series)
true
66c7b75d33b882e78fc35a61720bd25ded68c7cf
ErenBtrk/Python-Fundamentals
/Numpy/NumpyStatistics/Exercise13.py
515
4.4375
4
''' 13. Write a Python program to count number of occurrences of each value in a given array of non-negative integers. Note: bincount() function count number of occurrences of each value in an array of non-negative integers in the range of the array between the minimum and maximum values including the values that did not occur. ''' import numpy as np array1 = [0, 1, 6, 1, 4, 1, 2, 2, 7] print("Original array:") print(array1) print("Number of occurrences of each value in array: ") print(np.bincount(array1))
true
a8f9a363b9710a8f7c3941e34a99ef9c9da89bd8
ErenBtrk/Python-Fundamentals
/Pandas/PandasDataframe/Exercise21.py
362
4.34375
4
''' 21. Write a Pandas program to iterate over rows in a DataFrame. ''' import pandas as pd import numpy as np import pandas as pd import numpy as np exam_data = [{'name':'Anastasia', 'score':12.5}, {'name':'Dima','score':9}, {'name':'Katherine','score':16.5}] df = pd.DataFrame(exam_data) for index, row in df.iterrows(): print(row['name'], row['score'])
false
dd07c492b76d1079edc9f2e76dbd71de44c55f9e
ErenBtrk/Python-Fundamentals
/Pandas/PandasDataframe/Exercise61.py
453
4.3125
4
''' 61-Write a Pandas program to get topmost n records within each group of a DataFrame. ''' import pandas as pd d = {'col1': [1, 2, 3, 4, 7, 11], 'col2': [4, 5, 6, 9, 5, 0], 'col3': [7, 5, 8, 12, 1,11]} df = pd.DataFrame(data=d) print("Original DataFrame") print(df) print("\ntopmost n records within each group of a DataFrame:") df1 = df.nlargest(3, 'col1') print(df1) df2 = df.nlargest(3, 'col2') print(df2) df3 = df.nlargest(3, 'col3') print(df3)
false
2461f2c598528a6a45b35da2708517717532fd3a
ErenBtrk/Python-Fundamentals
/Pandas/PandasDataframe/Exercise53.py
425
4.5
4
''' 53. Write a Pandas program to insert a given column at a specific column index in a DataFrame. ''' import pandas as pd d = {'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]} df = pd.DataFrame(data=d) print("Original DataFrame") print(df) new_col = [1, 2, 3, 4, 7] # insert the said column at the beginning in the DataFrame idx = 0 df.insert(loc=idx, column='col1', value=new_col) print("\nNew DataFrame") print(df)
true
789d52f7c4e9b6fd3a91586d188bd06fec4da709
ErenBtrk/Python-Fundamentals
/Numpy/NumpyRandom/Exercise13.py
288
4.4375
4
''' 13. Write a NumPy program to find the most frequent value in an array. ''' import numpy as np x = np.random.randint(0, 10, 40) print("Original array:") print(x) print("Most frequent value in the above array:") print(np.unique(x)) print(np.bincount(x)) print(np.bincount(x).argmax())
true
dcecd4f5f65e24e8bcf2bb130d180b590c3aae74
ErenBtrk/Python-Fundamentals
/Pandas/PandasDataSeries/Exercise24.py
311
4.25
4
''' 24. Write a Pandas program convert the first and last character of each word to upper case in each word of a given series. ''' import pandas as pd import numpy as np pd_series = pd.Series(["kevin","lebron","kobe","michael"]) print(pd_series.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper() ))
true
5feffbf991ad5558f23181cdce21396930a98fb5
ErenBtrk/Python-Fundamentals
/Python Object-Oriented Programming/3-ClassMethods.py
1,428
4.1875
4
#class class Person: #pass #keyword for classes without attributes or methods #class attributes adress = "No information" #constructor def __init__(self,name,year): #object attributes self.name = name self.year = year print("init method is working.") #instance methods def intro(self): print(f"Hello World from {self.name}") def calculateAge(self): return 2021 - self.year #object (instance) p1 = Person("Bat",1993) print(p1) p1.name = "Ahmet" #Updating print(f"name : {p1.name} , year : {p1.year} , adress : {p1.adress}") #accessing object attributes p2 = Person(name = "Eagle",year = 1990) print(p2) print(f"name : {p2.name} , year : {p2.year} , adress : {p2.adress}") #accessing object attributes print(type(p1)) print(type(p2)) print(p1==p2) p1.intro() p2.intro() print(p1.calculateAge()) print(p2.calculateAge()) class Circle: #Class object attribute pi = 3.14 def __init__(self,radius = 1): self.radius = radius #Methods def calculatePerimeter(self): return 2 * self.pi * self.radius def calculateArea(self): return self.pi * (self.radius ** 2) c1 = Circle() # radius = 1 c2 = Circle(5) print(f"c1 : area = {c1.calculateArea()} , c1 : perimeter = {c1.calculatePerimeter()} ") print(f"c2 : area = {c2.calculateArea()} , c2 : perimeter = {c2.calculatePerimeter()} ")
false
68131c94887ff1da6069d0a22c3a07352769ea24
ErenBtrk/Python-Fundamentals
/Numpy/NumpyLinearAlgebra/Exercise1.py
304
4.40625
4
''' 1. Write a NumPy program to compute the multiplication of two given matrixes. ''' import numpy as np np_matrix1 = np.arange(0,15).reshape(5,3) print(np_matrix1) np_matrix2 = (np.ones(9,int)*2).reshape(3,3) print(np_matrix2) print(f"Multiplication of matrixes :\n{np.dot(np_matrix1,np_matrix2)}")
true
5802078b29d8753c500cf7d3793bc5e9cf76742b
ErenBtrk/Python-Fundamentals
/Python Object-Oriented Programming/4-Inheritance.py
1,295
4.1875
4
# Inheritance : # Person => name , lastname , age , eat() , run() , drink() # Student(Person),Teacher(Person) #Animal => Dog(Animal),Cat(Animal) class Person(): def __init__(self,firstName,lastName): self.firstName = firstName self.lastName = lastName print("Person created") def who_am_i(self): print("I am a person.") def eat(self): print("I am eating.") class Student(Person): def __init__(self,firstName,lastName,number): Person.__init__(self,firstName,lastName) self.studentNumber = number print("Student created") def who_am_i(self): #override print("I am a student") def sayHello(self): print("Hello from a student.") class Teacher(Person): def __init__(self,firstName,lastName,branch): super().__init__(firstName,lastName) self.branch = branch def who_am_i(self): #override print(f"I am a {self.branch} teacher") p1 = Person("Ali","Yilmaz") s1 = Student("Isa","Musa",1256) t1 = Teacher("Ayse","Fatma","Math") print(p1.firstName + " " +p1.lastName) print(s1.firstName + " " +s1.lastName + " "+ str(s1.studentNumber)) p1.who_am_i() s1.who_am_i() p1.eat() s1.eat() s1.sayHello() print(t1.firstName + " " +p1.lastName) t1.who_am_i()
false
a82bd7fba196142b95745e0fef2c83054557c2cb
ErenBtrk/Python-Fundamentals
/Numpy/NumpySortingAndSearching/Exercise1.py
407
4.5
4
''' 1. Write a NumPy program to sort a given array of shape 2 along the first axis, last axis and on flattened array. ''' import numpy as np a = np.array([[10,40],[30,20]]) print("Original array:") print(a) print("Sort the array along the first axis:") print(np.sort(a, axis=0)) print("Sort the array along the last axis:") print(np.sort(a)) print("Sort the flattened array:") print(np.sort(a, axis=None))
true
58663499fffaf60cef97fe20896338a49cf40112
ErenBtrk/Python-Fundamentals
/Pandas/PandasDataSeries/Exercise8.py
468
4.3125
4
''' 8. Write a Pandas program to convert the first column of a DataFrame as a Series. ''' import pandas as pd dict1 = { "First Name" : ["Kevin","Lebron","Kobe","Michael"], "Last Name" : ["Durant","James","Bryant","Jordan"], "Team" : ["Brooklyn Nets","Los Angeles Lakers","Los Angeles Lakers","Chicago Bulls"] } df = pd.DataFrame(data=dict1) print(df) print(type(df)) pd_series = df.iloc[:,0] print(pd_series) print(type(pd_series))
false
924527cad45d7f7c910fc4658a0b60b50517dbc3
anshu9/LeetCodeSolutions
/easy/add_digits.py
796
4.21875
4
""" Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime? """ def add_digits_simple(num): num_total = 0 while (len(str(num)) > 1): num_string = str(num) for i in range(len(num_string)): num_total = num_total + int(num_string[i]) num = num_total num_total = 0 return num def add_digits_digital_root(num): """ This method comes solving the digital root for the number given. The formula for solving the digital root is: dr = 1 + ((n-1) % 9) """ return 1 + ((num - 1) % 9)
true
d8601e88783790f690dfa9dd73aee6bc2f7d4527
damiangene/Practice-assignments
/2. Control, For, If, While/Firstday.py
900
4.125
4
year1= int(input("What is the first year?")) year2= int(input("What is the second year?")) for year in range(year1,year2+1): #day = R(1 + 5R(Year − 1, 4) + 4R(Year − 1, 100) + 6R(Year − 1, 400), 7) day6 = 6*((year - 1)%400) #print (day6) day4 = 4*((year - 1)%100) #print (day4) day5 = 5*((year - 1)%4) #print (day5) day = (day5 + day6 + day4 +1)%7 if day == 0: print ("%s starts on a Sunday" % (year)) if day == 1: print ("%s starts on a Monday" % (year)) if day == 2: print ("%s starts on a Tuesday" % (year)) if day == 3: print ("%s starts on a Wednesday" % (year)) if day == 4: print ("%s starts on a Thursday" % (year)) if day == 5: print ("%s starts on a Friday" % (year)) if day == 6: print ("%s starts on a Saturday" % (year))
false
67334c8d4146f1c8ba8580a5c95039a163e4bec2
juliancomcast/100DaysPython
/Module1/Day09/day09_indexing.py
1,121
4.5
4
#specific items can be retrieved from a list by using its indicies quotes = ["Pitter patter, let's get ar 'er", "Hard no!", "H'are ya now?", "Good-n-you", "Not so bad.", "Is that what you appreciates about me?"] print(quotes[0]) print(f"{quotes[2]}\n\t {quotes[3]}\n {quotes[4]}") #slicing uses the format [start:stop:step], start is inclusive but stop is exclusive print(quotes[2:5]) #the step can be used to identify how manuy items to skip between returned values print(quotes[::2]) #the step can also be used to reverse the order of the returned values print(quotes[::-1]) print("break") #slicing can be combined with indices to return a sequence from a specific item print(quotes[0][::2]) print(quotes[0][::-1]) #slicing doesn't only need to applied to lists wayne = "Toughest Guy in Letterkenny" print(wayne[::-1]) print("break") #retrieval by index and slicing can also be applied to a string print("That's a Texas sized 10-4."[0:9:2]) print("0123456789_acbdef"[0:9:2]) #neither the start, nor the stop values are required when slicing print(quotes[:]) print(quotes[3:]) print(quotes[:3]) print(quotes[::3])
true
4fe297d8354295929f95c9f78e80dd4c90e131d1
juliancomcast/100DaysPython
/Module1/Day11/day11_augAssign.py
811
4.59375
5
#An augmented assignment improves efficiency because python can iterate a single variable instead of using a temporary one. #There are several types of augmented assignment operators: # += : Addition # -= : Subtraction # *= : Multiplication # /= : Division # //= : Floor Division # %= : Remainder/Modulus # **= : Exponent # <<= : Left Shift # >>= : Right Shift # &= : And # ^= : Exclusive Or (XOR) # |= : Inclusive Or (OR) x = 42 x += 3 print(x) x = 42 x -= 3 print(x) x = 42 x *= 3 print(x) x = 42 x /= 3 print(x) x = 42 x //= 3 print(x) x = 42 x %= 3 print(x) x = 42 x **= 3 print(x) x = 1 x <<= 2 print(x) x = 4 x >>= 1 print(x) x = True y = False x &= y print(x) x = True y = False x ^= y print(x) x = True y = False x |= y print(x) x = "Ten Million" y = "Dollars" x *= 3 x += y print(x)
true
dc853f47647cfa8185eeded8b7b4abd458463413
jpike/PythonProgrammingForKids
/BasicConcepts/Functions/FirstFunction.py
828
4.4375
4
# This is the "definition" of our first function. # Notice the "def" keyword, the function's name ("PrintGreeting"), # the parentheses "()", and the colon ":". def PrintGreeting(): # Here is the body of our function, which contains the block # or lines of code that will be executed when our function is # called. A function body can contain any code just like # our previous Python programs. # Note how the body of the function is indented once more # from the first line of the function definition above. print("Hello!") # Here is where we're calling our function. Without the line below, # the code in our function would not execute, and our program would # do nothing. # Notice how we call the function - the function's name ("PrintGreeting"), # followed by parentheses "()". PrintGreeting()
true
5a63befb4bb2b1b00552c54b2416ad8c1da0b99e
jpike/PythonProgrammingForKids
/BasicConcepts/SyntaxErrors/Volume1_Chapter3_SyntaxErrors.py
689
4.125
4
# String variable statements with syntax errors. string variable = 'This line should have a string variable.' 1string_variable_2 = "This line should have another string variable." another_string_variable = 'This line has another string variable." yet_another_string_variable = "This line has yet another string variable.' first_string_variable_to_print = This string variable should be printed on the next line print(first_strng_variable_to_print) print("Here is the string variable's value again: " + first_strng_variable_to_print) combined_strings = "Here's a case where multiple strings " + string_variable + first_string_variable_to_print " are being combined" print(combined_strings)
true
4cf02d87043e701ed04156a935e710a10f54e7a0
techacker/Hackerank
/commandlistchallenge.py
1,279
4.21875
4
print('The program performs the given function on a list in a recursive manner.') print('First enter an "Integer" to tell how many functions you would like to do.') print('Then enter the command with appropriate values.') print() print('Enter an integer.') N = int(input()) z = [] def operation(inst, item, ind): if inst == 'append': z.append(item) return z elif inst == 'insert': z.insert(ind, item) return z elif inst == 'remove': if item in z: z.remove(item) return z elif inst == 'sort': z.sort() return z elif inst == 'pop': z.pop(-1) return z elif inst == 'reverse': z.reverse() return z elif inst == 'print': print(z) #continue print("Now enter a command in format: 'list_operation number number'") for i in range(N): commands = input().split(sep=" ") if len(commands) == 1: inst = commands[0] ind = None item = None elif len(commands) == 2: inst = commands[0] ind = None item = int(commands[1]) elif len(commands) == 3: inst = commands[0] ind = int(commands[1]) item = int(commands[2]) operation(inst, item, ind)
true
68571bcf57eaa90a749cfbeaa39e613e6aeaa7f6
techacker/Hackerank
/calendarModule.py
392
4.125
4
# Task # You are given a date. Your task is to find what the day is on that date. # Input Format # A single line of input containing the space separated month, day and year, respectively, in MM DD YYYY format. import calendar s = input().split() m = int(s[0]) d = int(s[1]) y = int(s[2]) day = calendar.weekday(y,m,d) weekday = calendar.day_name.__getitem__(day) print(weekday.upper())
true
3215b0ada68e50621452d257cac18e767d0239e6
techacker/Hackerank
/alphabetRangoli.py
811
4.25
4
# You are given an integer, N. # Your task is to print an alphabet rangoli of size N. # (Rangoli is a form of Indian folk art based on creation of patterns.) # # Example : size 5 # # --------e-------- # ------e-d-e------ # ----e-d-c-d-e---- # --e-d-c-b-c-d-e-- # e-d-c-b-a-b-c-d-e # --e-d-c-b-c-d-e-- # ----e-d-c-d-e---- # ------e-d-e------ # --------e-------- import string # To be able to quickly create a list of alphabets. # Function that actually creates the design. def print_rangoli(size): alpha = string.ascii_lowercase printList = [] for i in range(size): tmp = '-'.join(alpha[i:size]) printList.append((tmp[::-1] + tmp[1:]).center(4*size - 3, '-')) print('\n'.join(printList[:0:-1] + printList)) n = int(input()) print_rangoli(n)
true
0b0dcbc0b619f5ce51dd55a65a7ede07dfbb5695
Joeshiett/beginner-python-projects
/classes_example.py
633
4.125
4
class Person: # Instantiate class person as blueprint to create john and esther object def __init__(self, name, age): self.name = name self.age = age def walking(self): #defining of behaviour inside of class indentation print(self.name +' ' + 'is walking...') def speaking(self): print(self.name + ' is ' + str(self.age) + ' Years old!') john = Person('John', 22) # Instantiate object and define exact properties name and age Esther = Person('Esther', 23) john.walking() #invoking walking behaviour Esther.walking() john.speaking() #invoking speaking behaviour Esther.speaking()
true
7d890451efc7b5a59dbf4e0a774223033e2f8aec
Rosa-Palaci/computational-thinking-for-engineering
/semana-3/class-11/mayores-prueba1.py
1,103
4.125
4
#INSTRUCCIONES: # Define una función que recibe tres números # enteros y regresa los número ordenados de # menor a mayor. # Haz la prueba con dos tercias de números def orden_asc(a, b, c): if a > b and a > c: mayor = a if b > c: medio = b menor = c else: #Significa que c > b medio = c menor = b elif b > a and b > c: mayor = b if a > c: medio = a menor = c else: medio = c menor = a else: #Significa que 'c' es el mayor mayor = c if a > b: medio = a menor = b else: medio = b menor = a return menor, medio, mayor for veces in range(2): a = int(input('Introduce el número 1: ')) b = int(input('Introduce el número 2: ')) c = int(input('Introduce el número 3: ')) menor, medio, mayor = orden_asc(a, b, c) #print(f'Los números sin ordenar son: {a}, {b} y {c}\n') print(f'Los números en orden ascendente son: {menor}, {medio}, {mayor}')
false
3f8cd4a99aeffc1420bf4dd4c9af2f1b487914f7
Jonie23/python-calculator
/calculator.py
2,095
4.375
4
#welcome user def welcome(): print(''' Welcome to Jones's calculator built with python ''') welcome() # calculator() #define a function to run program many times def calculator(): #ask what operation user will want to run operation = input(''' Please type in the calculator operation you will want to run + for addition - for subtraction * for multiplication / for division ** for exponent % for modulus ''') #prompt user for inputs #And convert input to float data type to take floats(decimals) first_number = float(input('Enter the first number: ')) second_number = float(input('Enter the second number: ')) #Addition Operators if operation == '+' : print(' {} + {} = '.format(first_number, second_number)) #use string format to provide more feedback print(first_number + second_number) #Subtraction Operator elif operation == '-' : print(' {} - {} = '.format(first_number, second_number)) print(first_number - second_number) #Multiplication Operator elif operation == '*' : print(' {} * {} = '.format(first_number, second_number)) print(first_number * second_number) #Division elif operation == '/' : print(' {} / {} = '.format(first_number, second_number)) print(first_number / second_number) elif operation == '**': print(' {} / {} = '.format(first_number, second_number)) print(first_number ** second_number) elif operation == '%': print(' {} / {} ='.format(first_number, second_number)) print(first_number % second_number) else: print('Please type a valid operator and run again.') repeat() #function to repeat calculator def repeat(): repeat_calc = input(''' Do you want to calculate again? Please type Y for YES or N for NO. ''') if repeat_calc.upper() == 'Y': calculator() elif repeat_calc.upper() == 'N': print('Alright. Hope to see you another time') else: repeat() #Call calculator calculator()
true
4d7a1ccf22595544dfedd57e7cc2181d18013d5c
milan-crypto/PRACTICE_PYTHON
/Divisors.py
503
4.3125
4
# Create a program that asks the user for a number and then prints out a list of all the divisors of that number. # (If you don’t know what a divisor is, it is a number that divides evenly into another number. # For example, 13 is a divisor of 26 because 26 / 13 has no remainder.) number = int(input("Please choose a number to divide: ")) list_range = list(range(1, number+1)) divisorlist = [] for num in list_range: if number % num == 0: divisorlist.append(num) print(divisorlist)
true
68247317c0145405a949c82d10f08dd4d535bd52
dhirajMaheswari/findPhoneAndEmails
/findPhonesAndEmails.py
1,853
4.4375
4
'''this code makes use of the command line to find emails and/or phones from supplied text file or text using regular expressions. ''' import argparse, re def extractEmailAddressesOrPhones(text, kKhojne = "email"): ''' this function uses the regular expressions to extract emails from the supplied text import re ''' if kKhojne.lower() == "email": Pattern = re.compile(r'[a-zA-Z0-9_.]+@[a-zA-Z0-9.]+[a-zA-Z]+') # pattern for email elif kKhojne.lower() == "phone": Pattern = re.compile(r'(\d{3}-\d{3}-\d{4})|(\d{10})|(\d{3}\.\d{3}\.\d{4})') # pattern for phone emailPhoneLists = Pattern.findall(text) return emailPhoneLists ap = argparse.ArgumentParser() ap.add_argument("-p", "--filePath",required = True, help = "path to file.") ap.add_argument("-f", "--find", required = True, help = "What to find? options are phone and email.") args = vars(ap.parse_args()) n = len(args) filep = args["filePath"] findwhat = args["find"] sourceText = [] fp = open(filep, 'r') for l in fp: sourceText.append(l) fp.close() sourceText = ' '.join(sourceText) if findwhat.lower() == "email": tt = extractEmailAddressesOrPhones(sourceText) print("I found {} email addresses in the file {}" .format(len(tt), args["filePath"])) print("**************") for w in range(len(tt)): print("Email address {}: {}".format(w+1, tt[w])) elif findwhat.lower() == "phone": tt = extractEmailAddressesOrPhones(sourceText, kKhojne = "phone") print("I found {} phone numbers in the file {}" .format(len(tt), args["filePath"])) print("**************") for w in range(len(tt)): print("Phone number {}: {}".format(w+1, tt[w])) else: print("Invalid request made.") print("Correct Usage: findPhonesAndEmails.py --filePath fileName --find phone/email.")
true
04f9b9e623652aff89ff6261069df137c4e48c25
ManishVerma16/Data_Structures_Learning
/python/recursion/nested_recursion.py
226
4.125
4
# Recursive program to implement the nested recursion def nestedFun(n): if (n>100): return n-10 else: return nestedFun(nestedFun(n+11)) number=int(input("Enter any number: ")) print(nestedFun(number))
true
88db8f87b369d7626c0f2e0466e60cc73b1d11cc
BrettMcGregor/coderbyte
/time_convert.py
499
4.21875
4
# Challenge # Using the Python language, have the function TimeConvert(num) # take the num parameter being passed and return the number of # hours and minutes the parameter converts to (ie. if num = 63 # then the output should be 1:3). Separate the number of hours # and minutes with a colon. # Sample Test Cases # # Input:126 # # Output:"2:6" # # Input:45 # # Output:"0:45" def time_convert(num): return str(num // 60) + ":" + str(num % 60) print(time_convert(126)) print(time_convert(45))
true
6eb3619bec8465aab552c5ad9043447217d81334
BrettMcGregor/coderbyte
/check_nums.py
578
4.1875
4
# Challenge # Using the Python language, have the function CheckNums(num1,num2) # take both parameters being passed and return the string true if num2 # is greater than num1, otherwise return the string false. If the # parameter values are equal to each other then return the string -1. # Sample Test Cases # # Input:3 & num2 = 122 # # Output:"true" # # Input:67 & num2 = 67 # # Output:"-1" def check_nums(num1, num2): if num2 > num1: return 'true' elif num2 == num1: return '-1' return 'false' print(check_nums(3, 122)) print(check_nums(67, 67))
true
1645c0e1b348decce12680b6e3980b659f87c82a
RahulBantode/Pandas_python
/Dataframe/application-14.py
702
4.40625
4
''' Write a program to delete the dataframe columns by name and index ''' import pandas as pd import numpy as np def main(): data1 = [10,20,30,40] data2 = ["a","b","c","d"] data3 = ["jalgaon","pune","mumbai","banglore"] df = pd.DataFrame({"Int":data1,"Alpha":data2,"city":data3}) print(df) #To delete the dataframe entity pandas provide drop function print("\n Drop Column by Name \n") print(df.drop("Alpha",axis=1)) print("\n Drop columns by index \n") print(df.drop(df.columns[:-1],axis=1)) print("\n Drop the row by name/id \n") #we know that by default id will be start from 0 print(df.drop([0,1],axis=0)) if __name__ == '__main__': main()
true
717593f18f04b22e4a10c90c6ae6328ab3bd42df
RahulBantode/Pandas_python
/Dataframe/application-7.py
732
4.15625
4
#Write a program to create a dataframe using pandas series. import pandas as pd import matplotlib.pyplot as plt def main(): Author = ["Rahul","Nitin","Kunal","Mohit"] b_price = [900,450,740,100] Article = ["C-lang","Java-lang","Flutter","Native-core"] auth_series = pd.Series(Author) book_series = pd.Series(b_price) articl_series = pd.Series(Article) frame = {"Author" : auth_series, "Book-price": book_series , "Article" : articl_series} df = pd.DataFrame(frame) #Now add series externally into the dataframe age = [78,25,82,39] df["Age"] = pd.Series(age) #hyane ek new series externally add hote. print(df) df.plot.bar() plt.show() if __name__ == '__main__': main()
false
141abe7dfe844acd5ce5f999880197ce266a2865
ziyadedher/birdynet
/src/game/strategy.py
2,091
4.1875
4
"""This module contains strategies used to play the game.""" import random import pygame from game import config class Strategy: """Defines an abstract strategy that can be built on.""" def __init__(self) -> None: """Initialize this abstract strategy. Do not initialize an abstract strategy. """ pass def get_move(self) -> bool: """Return whether or not to move the player.""" raise NotImplementedError class IdleStrategy(Strategy): """Defines a strategy to do nothing at all.""" def __init__(self) -> None: """Initialize this idle strategy.""" super().__init__() def get_move(self) -> bool: """Return whether or not to move the player.""" return False class InputStrategy(Strategy): """Defines a strategy to move when the user hits space.""" _key_down_this_frame: bool = False def __init__(self) -> None: """Initialize this input strategy.""" super().__init__() @classmethod def key_down(cls, val: bool): """Flag that the input key has or has not been pressed this frame.""" cls._key_down_this_frame = val def get_move(self) -> bool: """Return whether or not to move the player.""" return self._key_down_this_frame class WordStrategy(Strategy): """Defines a strategy to move depending on word.""" _current_word: str def __init__(self) -> None: """Initialize this word strategy.""" super().__init__() self._current_word = "" self.new_word() def new_word(self) -> None: """Assign a new word for the strategy.""" self._current_word = random.choice(config.WORDS).lower() print(self._current_word) def get_move(self) -> bool: """Return whether or not to move the player.""" if pygame.key.get_pressed()[ord(self._current_word[0])]: self._current_word = self._current_word[1:] if not self._current_word: self.new_word() return True return False
true
28287d94a090ac3b9643a8d652896bd534211c0d
k501903/pythonstudy
/C01_dict.py
771
4.125
4
# -*- coding: utf-8 -*- # 字典dict grades = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print(grades['Tracy']) # 添加 grades['Adam'] = 67 print(grades['Adam']) # 修改 grades['Adam'] = 66 print(grades['Adam']) # 删除 grades.pop('Adam') print(grades) # 判断是否存在 if 'Thomas' in grades: print(grades['Thomas']) else: grades['Thomas'] = 90 print(grades.get('Thomas')) # key值是不可变变量(list是可变对象,tuple是不可变对象) # grades[[1, 2]] = 78 grades[(1, 2)] = 78 print(grades) # 集合set grades = set([1, 2, 3]) print(grades) grades = set((4, 5, 6)) print(grades) grades.add(10) print(grades) grades.remove(10) print(grades) grades.add(4) print(grades) a = {1, 2, 3, 4} b = {2, 4, 6, 8} s = a & b print(s) p = a | b print(p)
false
c65710674d3194cd7a5453a490660d898118f7b8
k501903/pythonstudy
/C03_Iteration.py
832
4.25
4
# -*- coding: utf-8 -*- # 迭代器 # 迭代对象Iterable from collections import Iterable print('[]是Iterable吗? ', isinstance([], Iterable)) print('{}是Iterable吗? ', isinstance({}, Iterable)) print('abc是Iterable吗? ', isinstance('abc', Iterable)) print('(x for x in range(10))是Iterable吗? ', isinstance((x for x in range(10)), Iterable)) print('100是Iterable吗? ', isinstance(100, Iterable)) # 迭代器Iterator from collections import Iterator print('[]是Iterator吗? ', isinstance([], Iterator)) print('{}是Iterator吗? ', isinstance({}, Iterator)) print('abc是Iterator吗? ', isinstance('abc', Iterator)) print('(x for x in range(10)是Iterator吗? ', isinstance((x for x in range(10)), Iterator)) # 迭代器转化 print('iter([])是Iterator吗? ', isinstance(iter([]), Iterator))
false
dadaab812f4ce7ee2e0a5a95436088f109a0a63d
saadhasanuit/Lab-04
/question 11.py
487
4.125
4
print("Muhammad Saad Hasan 18B-117-CS Section:-A") print("LAB-04 -9-NOV-2018") print("QUESTION-11") # Program which calculates the vowels from the given string. print("This program will count total number of vowels from user defined sentence") string=input("Enter your string:") vowels=0 for i in string: if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'): vowels=vowels+1 print("Number of vowels are:") print(vowels)
true
877a89267774f79b7b4516e112c8f73a1ebad162
MariyaAnsi/Python-Assignments
/Assignment_5.py
363
4.34375
4
#Write a program that prompts for a file name, then opens that file and reads through the file, #and print the contents of the file in upper case. fname = input("Enter file name: ") fh = open(fname) print("fh___", fh) book = fh.read() print("book___", book) bookCAPITAL = book.upper() bookCAPITALrstrip = bookCAPITAL.rstrip() print(bookCAPITALrstrip)
true
e23db0c2b2df63611d1066b76cf1606fd40852ba
TewariUtkarsh/Python-Programming
/Tuple.py
553
4.1875
4
myCars = ("Toyota","Mercedes","BMW","Audi","BMW") #Tuple declared print("\nTuple: ",myCars) # Tuple has only 2 built in functions: # 1.count()- To count the number of Element ,that is passed as the Parameter, in the Tuple print("\nNumber of times BMW is present in the Tuple: ",myCars.count("BMW")) print("Number of times Audi is present in the Tuple: ",myCars.count('Audi')) # 2.index()- Returns the Index of the Element that is passed as an Arguement print("\nToyota is present at index ",myCars.index("Toyota")) print(f"\nTuple: {myCars}")
true
6717306792716cbc062e400eeb7c6d434f28544a
gorkememir/PythonProjects
/Basics/pigTranslator.py
1,160
4.21875
4
# Take a sentence from user original = input("Please enter a sentence: ").strip().lower() # Split it into words splitted = original.split() # Define a new list for storing the final sentence new_words = [] # Start a for loop to scan all the splitted words one by one for currentWord in splitted: # If the first letter of the word in the current loop is a vowel, add "Yay" at the end, # and store this as the new_word if currentWord[0] in "aieou": new_word = currentWord + "Yay" # If the first letter is not a vowel, scan through the word until you find a vowel, # mark the vowel position, split the word as consonants up to that vowel and the rest. # set new_word as such: cons + theRest + "Ay" else: vowelPos = 0 for letter in currentWord: if letter not in "aieou": vowelPos = vowelPos + 1 else: break new_word = currentWord[vowelPos:] + currentWord[:vowelPos] + "Ay" # Append the new_word to the new_words list new_words.append(new_word) # Turn the list into a sentence, and print it. output = " ".join(new_words) print(output)
true
a23034a6ada538ad5c35ec45b514900a68183d1f
GospodinJovan/raipython
/Triangle.py
1,234
4.5625
5
""""" You are given the lengths for each side on a triangle. You need to find all three angles for this triangle. If the given side lengths cannot form a triangle (or form a degenerated triangle), then you must return all angles as 0 (zero). The angles should be represented as a list of integers in ascending order. Each angle is measured in degrees and rounded to the nearest integer number (Standard mathematical rounding). triangle-angles Input: The lengths of the sides of a triangle as integers. Output: Angles of a triangle in degrees as sorted list of integers. Example: checkio(4, 4, 4) == [60, 60, 60] checkio(3, 4, 5) == [37, 53, 90] checkio(2, 2, 5) == [0, 0, 0] 1 2 3 How it is used: This is a classical geometric task. The ideas can be useful in topography and architecture. With this concept you can measure an angle without the need for a protractor. Precondition: 0 < a,b,c ≤ 1000 """ from math import acos, degrees get_angle = lambda a, b, c: round(degrees(acos((b*b+c*c-a*a)/(float(2*b*c))))) def checkio(a, b, c): if a + b <= c or b + c <= a or c + a <= b: return [0, 0, 0] return sorted([get_angle(a, b, c), get_angle(b, c, a), get_angle(c, a, b)]) a=2 b=4 c=5 print (checkio(a,b,c))
true
6681c74eed15a86ce699efb6e28cbf1e98630cfb
bipuldev/US_Bike_Share_Data_Analysis
/Bike_Share_Analysis_Q4a.py
2,117
4.4375
4
## import all necessary packages and functions. import csv # read and write csv files from datetime import datetime # operations to parse dates from pprint import pprint # use to print data structures like dictionaries in # a nicer way than the base print function. def number_of_trips(filename): """ This function reads in a file with trip data and reports the number of trips made by subscribers, customers, and total overall. """ with open(filename, 'r') as f_in: # set up csv reader object trip_reader = csv.DictReader(f_in) # initialize count variables n_subscribers = 0 n_customers = 0 # tally up ride types for row in trip_reader: if row['user_type'] == 'Subscriber': n_subscribers += 1 else: n_customers += 1 # compute total number of rides n_total = n_subscribers + n_customers # return tallies as a tuple return(n_subscribers, n_customers, n_total) ## Modify this and the previous cell to answer Question 4a. Remember to run ## ## the function on the cleaned data files you created from Question 3. ## #data_file = './data/NYC-2016-Summary.csv' city_info = {'Washington':'./data/Washington-2016-Summary.csv', 'Chicago': './data/Chicago-2016-Summary.csv', 'NYC': './data/NYC-2016-Summary.csv'} for city, data_file in city_info.items(): n_subscribers, n_customers, n_total = number_of_trips(data_file) n_proportion_subscribers = round(n_subscribers/n_total, 4) n_proportion_customers = round(n_customers/n_total,4) print ("City: {0} ".format(city)) print ("Subscribers: {0}".format(n_subscribers)) print ("Customers: {0}".format(n_customers)) print ("Total Trips: {0}".format(n_total)) print ("Subscriber proportion: {0}".format(n_proportion_subscribers)) print ("Customer proportion: {0}".format(n_proportion_customers)) print ()
true
d59a3a58b3cc73976c685c0e634fea373283868c
ShiJingChao/Python-
/PythonStart/0722Python/0805Python/day05/集合/demo01_集合的定义.py
1,731
4.4375
4
""" 集合: set python的基础数据类型之一; 定义: 用于存储一组无序的不重复的数据; 特点: 1. 集合是无序的; 2. 集合中的元素是不重复的, 唯一的; 3. 集合中存储的数据必须是不可变的数据类型; 4. 集合是可变的数据类型; 语法: set1 = {1, 2, 3} # int --> 不可变 增加: add() update() 参数: 可迭代对象(容器) 将可迭代对象中和集合中不重复的元素添加到集合中 删除: pop() 随机删除某个元素 remove() 删除指定的元素 clear() 清空集合 del 集合名 删除整个集合 集合的遍历: for in """ set1 = {1, 2, 3} print(set1) print(type(set1)) # <class 'set'> # set2 = {} # print(type(set2)) # <class 'dict'> # 创建一个空集合变量 set2 = set({}) print(set2) print(type(set2)) # <class 'set'> list1 = [1, 2, 2, 3, 1] # 给这个列表去除重复 set3 = set(list1) print(set3) # {1, 2, 3} # 集合中存储的是不可变的数据类型 # set4 = {"abc", 0.2, [1, 2, 3]} # print(set4) # TypeError: unhashable type: 'list' # 添加操作 add set5 = {1, 2, 3} set5.add(4) print(set5) # {1, 2, 3, 4} # update() set5.update({5, 6, 7, 8}) print(set5) # {1, 2, 3, 4, 5, 6, 7, 8} set5.update({1, 2, 3, 100}) print(set5) # {1, 2, 3, 4, 5, 6, 7, 8, 100} set5.pop() # 随机删除一个数据 print(set5) set5.remove(100) # 删除指定元素 print(set5) # {2, 3, 4, 5, 6, 7, 8} set5.clear() print(set5) # set() del set5 # print(set5) # NameError: name 'set5' is not defined
false
d5cb46d19ae0577089f571658d80240e5237ca21
ShiJingChao/Python-
/PythonStart/0722Python/0805Python/day05/集合/demo02_集合中的数学运算.py
917
4.25
4
""" 集合中的数学运算 交集: 取的公共部分 & intersection 并集: 取的是所有部分,不包括重复数据 | union 差集: 第一个集合有的,第二个集合没有的 - difference 反交集: 跟交集反着 取的非公共部分 ^ symmetric_difference 子集: 判断某个集合是不是另一个集合的子集 set1 < set2 issubset 超集: """ set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} print(set1 & set2) # {3, 4} print(set1.intersection(set2)) print(set1 | set2) # {1, 2, 3, 4, 5, 6} print(set1.union(set2)) print(set1 - set2) # {1, 2} print(set1.difference(set2)) print(set1 ^ set2) # {1, 2, 5, 6} print(set1.symmetric_difference(set2)) print(set1 < set2) # False print(set1.issubset(set2)) print({1, 2} < {1, 2, 3, 4}) # True print(set2 > set1) # False print(set2.issuperset(set1)) print({3, 4, 5, 6} > {3, 6}) # True
false
22b535c891b0c5a719870142dc9a765417f963f5
ShiJingChao/Python-
/PythonStart/0722Python/0805Python/day09/demo07_类属性练习.py
1,108
4.21875
4
""" 1. 写一个类, 这个可以记录产生对象的个数 2. 写个游戏类: 1. 记录历史最高分 2. 传入当前玩家姓名, 随机玩家分数 3. 获取历史最高分 """ import random class Person: count = 0 # 不可变数据类型的类属性, 记录产生对象的个数 def __init__(self): Person.count += 1 p1 = Person() p2 = Person() p3 = Person() print(p2.count) class Game: history_score = 0 def play_game(self, name): score = random.randint(1, 100) print("尊敬的%s, 得分为%d!!!" % (name, score)) if score > Game.history_score: # 如果此次游戏所得分数>历史最高分 Game.history_score = score # 更新历史最高分 def get_history_score(self): print("历史最高分为:%d" % self.history_score) g = Game() g.play_game("永登高峰") # 尊敬的永登高峰, 得分为92!!! g.play_game("永登高峰") g.play_game("永登高峰") g.play_game("永登高峰") g.play_game("永登高峰") g.play_game("永登高峰") g.get_history_score()
false
c4cc79727967ed588676506a3a865445f06682cb
ShiJingChao/Python-
/PythonStart/0722Python/0805Python/day09/demo03_init方法初始化实例变量.py
1,135
4.46875
4
""" 1. 创建对象的过程:p1 = Person() 1. 开辟内存,存储对象 2. 自动调用了init方法 2. 实例变量: 初始化实例变量, 初始化对象的属性; 实例变量: 对象的变量 --> 对象属性; 实例变量 归对象所有, 每个对象都有一份, 对象之间互不影响; self.变量名 --> 表示实例变量(实例属性) 3. init 默认情况下啥事也没干; 一般情况下,会在init方法中初始化实例变量(对象的属性); """ class Person: # 姓名, 年龄, 性别 def __init__(self, name, age, sex): # name=高科 age=100 sex=女 # print("啦啦啦啦 高科啥时候来呀 啦啦啦啦") self.name = name # name属性的值 = 高科 self.age = age self.sex = sex # 创建对象, 1,开辟内存; 2,自动调用init方法 p1 = Person("高科", 100, "女") p2 = Person("吴钰铂", 38, "女") print(p1.age, p1.name, p1.sex) print(p2.age, p2.name, p2.sex) p1.name = "高蝌蚪" print(p1.name) p2.age = 251 print(p2.age)
false
266ad53bb1950c25ff582bfe6bb710290947c8f8
ShiJingChao/Python-
/PythonStart/0722Python/0805Python/day10/demo08_多层继承.py
743
4.15625
4
""" 多继承: 子类具有多个父类的情况; 子类可以继承多个父类的功能; python: (继承的传递) 多层继承: 子类 --> 父类 --> 爷爷类 --> 祖先类 ---> object类 """ class A: def func1(self): print("我是A中func1中的方法...") class B(A): def func2(self): print("我是B中的func2的方法...") # def func1(self): # print("我是B中的func1的方法...") class C(B): def func3(self): print("我是C中的func3的方法...") # b = B() # b.func1() c = C() # C --> B --> A --> object c.func3() # 我是C中的func3的方法... c.func2() # 我是B中的func2的方法... c.func1() # 我是A中func1中的方法...
false
67a7ca9faf0d06210928aa7da6ed28a3e47dc8f6
ShiJingChao/Python-
/PythonStart/0722Python/0805Python/day04/demo03_字符串的切片.py
1,710
4.34375
4
""" 1. 字符串的拼接 + : "abc" + "def" ---> "abcdef" * : "李现" * 3 ---> "李现李现李现" 2. 字符串的长度 容器: 字符元素 python的内置函数len(): 获取变量的长度; 3. 切片:slice 通过切片操作获取字符串中的一部分数据; 格式: 字符串[start : stop : step] start: 起始值, 索引值 stop: 结束值, 索引值 step: 步长, 整数 * 注意: 1. 切片中的::必须写 2. step默认为1 3. start默认是从头开始切; 4. stop默认是切到最后一个字符 """ s = '人生苦短 我用python' print(len(s)) # 13 s1 = 'i love python' # step 步长为正数 print(s1[2:6:1]) # love print(s1[2:6:]) # love print(s1[0::2]) # 从第一个字符开始到最后一个字符,每两个字符取一个 print(s1[::2]) # start默认是从头开始切; stop默认是切到最后一个字符 s2 = '0123456789' # 1. 截取下标(索引)是从2-5的字符串 print(s2[2:6:]) # 2. 截取下标从2开始到末尾的字符串 print(s2[2::]) # 3. 截取字符串开始到5的位置, 不包含5 print(s2[0:5:]) print(s2[:5:]) # 4. 截取完整的字符串 print(s2[::]) # 5. 从开始位置, 每隔一个字符截取 print(s2[::2]) # 6. 从索引1开始, 每隔一个字符截取 print(s2[1::2]) # 7. 截取从2到末尾的前一个字符串 print(s2[2:9:]) print(s2[2:len(s2)-1:]) print(s2[2:-1:]) # 8. 截取末尾2个字符串 print(s2[8::]) print(s2[-2::]) # step 步长为负数 # 9. 反转字符串 print(s2[::-1]) print(s2[9::-1]) # 10. 截取出'97531'这个字符串 print(s2[::-2])
false
006d4318ecc5f77efd912464de98ef2cf852dd42
NataliaBeckstead/cs-module-project-recursive-sorting
/src/searching/searching.py
1,278
4.40625
4
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): if start > end: return -1 mid = (start + end) // 2 if arr[mid] == target: return mid elif target < arr[mid]: return binary_search(arr, target, start, mid-1) else: return binary_search(arr, target, mid+1, end) # STRETCH: implement an order-agnostic binary search # This version of binary search should correctly find # the target regardless of whether the input array is # sorted in ascending order or in descending order # You can implement this function either recursively # or iteratively def agnostic_binary_search(arr, target): left = 0 right = len(arr)-1 ascending_order = arr[0] < arr[right] while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid if ascending_order: if target < arr[mid]: right = mid - 1 else: left = mid + 1 else: if target > arr[mid]: right = mid - 1 else: left = mid + 1 return -1 print(agnostic_binary_search([1, 2, 3, 4, 5], 4)) print(agnostic_binary_search([5, 4, 3, 2, 1], 4))
true
70dcd1ee1a606f67646d7e8f7f3862908e3a0c76
JannickStaes/LearningPython
/TablePrinter.py
1,061
4.21875
4
#! python3 # prints a table of a list of string lists tableDataExample = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def determineMaxColumnWidths(tableData): columnWidths = [] #a list to store the max length of each string row, to be used as the max column width for stringList in tableData: maxLength = 0 for word in stringList: if len(word) > maxLength: maxLength = len(word) columnWidths.append(maxLength) return columnWidths def printTable(tableData): columnWidths = determineMaxColumnWidths(tableDataExample) rows = len(tableData[0]) #all lists are equal length so we can just take the first one columns = len(tableData) for row in range(rows): printRow = [] for column in range(columns): printRow.append( tableData[column][row].rjust(columnWidths[column])) line = ' '.join( printRow ) print(line) printTable(tableDataExample)
true
af175e0913b72d5c984cd90490f8405d8843d258
Hubert51/pyLemma
/Database_sqlite/SecondPart_create class/Test_simplify_function/class2.py
1,440
4.125
4
import sqlite3 class DatabaseIO: l12 = [1, 2, 3] d_table = {} def __init__(self, name): """ In my opinion, this is an initial part. If I have to use variable from other class, I can call in this part and then call to the following part. Some variable must be renamed again. """ self.con = sqlite3.connect(name) self.cur = self.con.cursor() d_table = {} def create_table1(self): table_name = raw_input("Please entre the table name ==> ") i = 0 l = [] # This list stores the info which is used to create table l2 = [] # This list stores the table info which will be useful when we need to know the columns of table d_table = dict() check = True while check: column = raw_input('''Please entre column with this data tpye such as INTEGER or TXT (if finish, type: end) ==> ''') if column != "end": l.append(column) l2.append(column) else: break d_table[table_name] = l2 key = raw_input("Please enter the key ==> ") command = "CREATE TABLE {:} (".format(table_name) for i in l: command += "{:} NOT NULL,".format(i) command += "PRIMARY KEY ({:}))".format(key) self.cur.execute(command) self.con.commit()
true
5a2dd5cb914cdbd397847ab8d77521e0612580e0
shubhranshushivam/DSPLab_22-10-2020
/ques8.py
605
4.1875
4
# 8. Find the Union and Intersection of the two sorted arrays def union(arr1,arr2): res=arr1+arr2 res=set(res) return list(res) def intersection(arr1, arr2): res=[] for i in arr1: if i in arr2: res.append(i) return res n1=int(input("Enter size of 1st array=")) arr1, arr2=[],[] for i in range(n1): arr1.append(int(input("ENter element="))) n2=int(input("Enter size of 2nd array=")) for i in range(n2): arr2.append(int(input("ENter element="))) print("UNION=",union(arr1, arr2)) print("INTERSECTION=",intersection(arr1, arr2))
true
fd8b7a3eb61438223ca6563de920c9e7f8eab7a4
jadenpadua/Data-Structures-and-Algorithms
/efficient/validParenthesis/validParenthesis.py
1,772
4.125
4
#Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. #imports functions from our stack data structure file from stack import Stack #helper method checks if our open one and closed are the same def is_match(p1, p2): if p1 == "(" and p2 == ")": return True elif p1 == "{" and p2 == "}": return True elif p1 == "[" and p2 == "]": return True else: return False #can be called to check if paren are balanced def is_paren_balanced(paren_string): #creates new stack object, sets balanced flag to true and starts an index that will iterate through string s = Stack() is_balanced = True i = 0 #while string is still balanced it will loop through string while i < len(paren_string) and is_balanced: #current parenthesis pointer is on paren = paren_string[i] #pushes element to stack if in those value ranges case where open paren if paren in "([{": s.push(paren) #case where closing paren else: #returns false if only one closing paren in stack if s.is_empty(): is_balanced = False #pops our open paren, calls helper else: #pops our open paren top = s.pop() #checks if the open paren and closed one are equal if not is_match(top, paren): is_balanced = False i += 1 #if stack is empty and balanced by default return true if s.is_empty() and is_balanced: return True else: return False print(is_paren_balanced("(((({}))))")) print(is_paren_balanced("[][]]]")) print(is_paren_balanced("[][]"))
true
3b98b69d8a5182fca01f3ceea90444eff427a5a6
jadenpadua/Data-Structures-and-Algorithms
/bruteforce/largest_swap.py
370
4.21875
4
Write a function that takes a two-digit number and determines if it's the largest of two possible digit swaps. To illustrate: largest_swap(27) ➞ False largest_swap(43) ➞ True def largest_swap(num): original = num d = 0 rev = 0 while num > 0: d = num % 10 num = int(num/10) rev = rev*10 + d if rev > original: return False else: return True
true
d6404fac5d7e72741972ade1038e83de849ac709
jadenpadua/Data-Structures-and-Algorithms
/bruteforce/needleInHaystack.py
564
4.25
4
# Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. def strStr(haystack,needle): for i in range(len(haystack) - len(needle) + 1): if haystack[i:i+len(needle)] == needle: return i return - 1 haystack = "Will you be able to find the needle in this long haystack sentence?" needle = "te" print("Haystack: Will you be able to find the needle in this long haystack sentence?") print("Needle: te") print("The index of the needle in the haystack is: ") print(strStr(haystack,needle))
true
3702a2e59ec372033ed9f0f3cb2aa2af7bc4653b
jadenpadua/Data-Structures-and-Algorithms
/bruteforce/alternating_one_zero.py
626
4.46875
4
Write a function that returns True if the binary string can be rearranged to form a string of alternating 0s and 1s. Examples can_alternate("0001111") ➞ True # Can make: "1010101" can_alternate("01001") ➞ True # Can make: "01010" can_alternate("010001") ➞ False can_alternate("1111") ➞ False def can_alternate(s): if '1' not in s or '0' not in s: return False else: zero_count = 0 one_count = 0 for i in range(len(s)): if s[i] == '0': zero_count += 1 else: one_count += 1 if abs(zero_count - one_count) == 1 or abs(zero_count - one_count) == 0: return True else: return False
true
0ccbe214b5bc91d4c53e4f16218b0835b1b9d513
jadenpadua/Data-Structures-and-Algorithms
/bruteforce/digits_in_list.py
689
4.3125
4
#Create a function that filters out a list to include numbers who only have a certain number of digits. #Examples #filter_digit_length([88, 232, 4, 9721, 555], 3) ➞ [232, 555] # Include only numbers with 3 digits. #filter_digit_length([2, 7, 8, 9, 1012], 1) ➞ [2, 7, 8, 9] # Include only numbers with 1 digit. #filter_digit_length([32, 88, 74, 91, 300, 4050], 1) ➞ [] # No numbers with only 1 digit exist => return empty list. #filter_digit_length([5, 6, 8, 9], 1) ➞ [5, 6, 8, 9] # All numbers in the list have 1 digit only => return original list. def filter_digit_length(lst, num): temp = [] for item in lst: if len(str(item)) == num: temp.append(item) return temp
true
84d5fef5a0c4f7de4606fcfb9ed1ee4909d00420
ankitniranjan/The-Complete-Data-Structure-and-Algorithms-Course-in-Python-Udemy
/1.Recursion/fibonacci.py
239
4.1875
4
#!/usr/bin/env python3 def fibonacci(n): assert n >= 0 and int(n) == n, "Input should be of integer type" if n in [0, 1]: return n else: return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(4)) #Output 3
false
80b15569f8adf836485424359c93bfaf7f87cfd3
giovic16/Python
/solo9.py
256
4.1875
4
#Faça um Programa que peça a temperatura em graus Farenheit, transforme e mostre a temperatura em graus Celsius. fahrenheit = int(input('Entre com a temperatura:')) celsius = (fahrenheit-32)//1.8 print('A temperatura transofrmada é {}' .format(celsius))
false
67c62395c49f7327da7f66d2ab1d04b96886b53a
UnicodeSnowman/programming-practice
/simulate_5_sided_die/main.py
565
4.1875
4
# https://www.interviewcake.com/question/simulate-5-sided-die?utm_source=weekly_email # You have a function rand7() that generates a random integer from 1 to 7. # Use it to write a function rand5() that generates a random integer from 1 to 5. # rand7() returns each integer with equal probability. rand5() must also return each integer with equal probability. from random import random from math import floor def rand_7(): return floor(random() * 7) + 1 def rand_5(): rando = rand_7() while rando > 5: rando = rand_7() return rando print(rand_5())
true
7443a894f9ca0f6e6276d36e49a12f27dbd76b80
JITHINPAUL01/Python-Assignments
/Day_5_Assignment.py
1,654
4.25
4
""" Make a generator to perform the same functionality of the iterator """ def infinite_sequence(): # to use for printing numbers infinitely num = 0 while True: yield num num += 1 for i in infinite_sequence(): print(i, end=" ") """ Try overwriting some default dunder methods and manipulate their default behavior """ class distance: def __init__(self, ft=0,inch=0): self.ft=ft self.inch=inch def __add__(self,x): temp=distance() temp.ft=self.ft+x.ft temp.inch=self.inch+x.inch if temp.inch>=12: temp.ft+=1 temp.inch-=12 return temp def __str__(self): return 'ft:'+str(self.ft)+' in: '+str(self.inch) d1=distance(3,10) d2=distance(4,4) print(f"d1= {d1} d2={d2}") d3=d1+d2 # overridden the + operator __add__ print(d3) """ Write a decorator that times a function call using timeit start a timer before func call end the timer after func call print the time diff """ import timeit def time_function(inner_fun): def time(*args, **kwargs): t_start=timeit.default_timer() print(f"satrt time : {t_start}") inner_fun(*args, **kwargs) t_end=timeit.default_timer() print(f"end time : {t_end}") run_time=t_end-t_start print(f"execution time : {run_time}") return time @time_function def my_loop_method(i): total=0 print(f'I am a loop method to sum numbers in entered range having decorator to track time of execution!') for i in range(0,i): total +=i my_loop_method(10000) # takes more execution time my_loop_method(10)
true
b461bf0edc931efe39b3f6a00dcf5f86e3dd2cf8
lijianzwm/leetcode
/101.py
1,021
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 18/11/9 14:05 # @Author : lijian # @Desc : https://leetcode.com/problems/symmetric-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool 镜像二叉树 <==> 左子树的镜像=右子树 """ def isMirror(r1, r2): if r1 is None and r2 is None: return True if r1 and r2 and r1.val == r2.val: return (isMirror(r1.left, r2.right) and isMirror(r1.right, r2.left)) return False return isMirror(root, root) if __name__ == "__main__": class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None root = TreeNode(1) print(Solution().isSymmetric(root))
false
36a3aa0df6425f0876442c374eca48c0c709d592
shahasifbashir/LearnPython
/ListOver/ListOverlap.py
591
4.28125
4
import random #This Examples gives the union of two Lists A = [1,2,3,4,5,6,7,8,5,4,3,3,6,7,8] B=[6,7,8,9,4,3,5,6,78,97,2,3,4,5,5,6,7,7,8] # we will use the set becouse a set contains unique elemets only ann then use an and operator print(list(set(A)&set(B))) # The same example using Random Lists A= range(1,random.randint(1,30)) B= range(1,random.randint(1,40)) print("_____________________________") print(list(set(A)&set(B))) myList=[] # Ths same example using a for loop for item in A: if item in B: if item not in myList: myList.append(item) print(myList)
true
57992d8e576a9c5df264083e74d67b6d29ae00c9
susanbruce707/Virtual-Rabbit-Farm
/csv_mod.py
1,205
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 13 00:27:26 2020 @author: susan Module to read CSV file into nested dictionary and write nested dictionar to CSV file rd_csv requires 1 argument file, as file name for reading wrt_csv requires 2 arguments file name and dictionary name to write CSV file. """ import csv def wrt_csv(file, dictionary): with open(file, 'w',newline='') as f: dic = dictionary[0] header = list(dic.keys()) writer = csv.DictWriter(f, fieldnames=header) writer.writeheader() for dic in dictionary: writer.writerow(dictionary[dic]) def rd_csv(file): dictionary = {} with open(file) as csv_file: csv_reader = csv.DictReader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: dictionary[line_count] = row line_count += 1 return dictionary #rabbits = rd_csv('rabbits.csv') # example use read # wrt_csv('rabbits1.csv', rabbits) # example use write #k = len(list(rabbits.keys())) #lrk = [] #for num in range(k): # print(num) # rk = list(rabbits[num].values()) # lrk.append(rk) #print(lrk)
true
29e7fdf995e4f6245899f4a61aac03ac1cac6426
fadhilmulyono/cp1404practicals
/prac_09/sort_files_1.py
910
4.25
4
""" CP1404/CP5632 Practical Sort Files 1.0 """ import os def main(): """Sort files to folders based on extension""" # Specify directory os.chdir('FilesToSort') for filenames in os.listdir('.'): # Check if there are any files in directory if os.path.isdir(filenames): continue # Split the filename between the file name and extension extension = filenames.split('.')[-1] # If folder does not exist in directory, create the folder try: os.mkdir(extension) except FileExistsError: pass # Move the files to the folders that were just created os.rename(filenames, "{}/{}".format(extension, filenames)) print() for directory_name, subdirectories, filenames in os.walk('.'): print("Directory:", directory_name) print("\tcontains files:", filenames) main()
true
6e6569c90097c6ae65b39aa6736e234fbf6f4bdf
BruderOrun/PY111-april
/Tasks/a0_my_stack.py
798
4.1875
4
""" My little Stack """ stak = [] def push(elem) -> None: """ Operation that add element to stack :param elem: element to be pushed :return: Nothing """ stak.append(elem) def pop(): """ Pop element from the top of the stack :return: popped element """ if stak == []: return None else: return stak.pop() def peek(ind: int = 0): """ Allow you to see at the element in the stack without popping it :param ind: index of element (count from the top) :return: peeked element """ try: s = stak[ind - 1] except IndexError: return None else: return s def clear() -> None: """ Clear my stack :return: None """ stak.clear() return None
true
7f72b1120e1a02c17ccc9113866e32cab1164830
tjgiannhs/Milisteros
/GreekBot/greek_preprocessors.py
1,609
4.15625
4
""" Statement pre-processors. """ def seperate_sentences(statement): ''' Adds a space after commas and dots to seperate sentences If this results in more than one spaces after them another pre-processor will clean them up later :param statement: the input statement, has values such as text :return: the statement with the modified text ''' statement.text = statement.text.replace(",",", ") statement.text = statement.text.replace(".",". ") return statement def capitalize(statement): ''' Makes the first letter after dots capital Adds a dot at the end if no other punctuation exists already :param statement: the input statement, has values such as text :return: the statement with the modified text ''' text = "" for protash in statement.text.split('.'): text = text + protash.strip().capitalize() +"." if text[-2]=="." or text[-2]=="!" or text[-2]=="?" or text[-2]==";": statement.text = text[:-1] else: statement.text = text return statement def clean_apostrophes(statement): ''' Removes apostrophes, both single and double Uses a different way to remove the double because replace wouldn't work correctly with them :param statement: the input statement, has values such as text :return: the statement with the modified text ''' text = "" statement.text = statement.text.replace("'","") for protash in statement.text.split('"'): text = text+protash statement.text = text return statement
true
24409c8cc7b6c497409449e8327e5f16a2162020
qufeichen/Python
/asciiUni.py
352
4.15625
4
# program that prints out a table with integers from decimal 0 to 255, it's hex number, and the character corresponding to the unicode with UTF-8 encoding # using a loop for x in range(0, 256): print('{0:d} {0:#04x} {0:c}'.format(x)) # using list comprehension ll = [('{0:d} {0:#04x} {0:c}'.format(x)) for x in range(0, 256)] print( "\n".join(ll) )
true
859c35f9a9bcdcfbe3da843f8296b00f23c37f95
ZhuXingWuChang/CollegePython
/pythonCrashCourse/chapter3/cars.py
602
4.34375
4
# 给sort()方法传入reverse=True参数,会使列表本身被修改(可变对象) cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort(reverse=True) print(cars) cars.sort() print(cars) # 使用sorted(ListName)方法,会返回一个新的排序后的列表(不可变对象) cars = ['bmw', 'audi', 'toyota', 'subaru'] print("\nHere is the original list: ") print(cars) print("\nHere is the sorted list: ") print(sorted(cars)) print("\nHere is the original list agian: ") print(cars) # ListName.reverse()会修改列表,使其倒序 print() print(cars) cars.reverse() print(cars) print(len(cars))
false
f2a34668c27bc15c17545666e077ad857937c554
PravinSelva5/LeetCode_Grind
/Dynamic Programming/BestTimetoBuyandSellaStock.py
1,006
4.125
4
''' Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. ------- RESULTS ------- Time Complexity: O(N) Space Complexity: O(1) Runtime: 64 ms, faster than 52.70% of Python3 online submissions for Best Time to Buy and Sell Stock. Memory Usage: 15 MB, less than 70.66% of Python3 online submissions for Best Time to Buy and Sell Stock. ''' class Solution: def maxProfit(self, prices: List[int]) -> int: buyPrice = 10000 profit = 0 for price in prices: if buyPrice > price: buyPrice = price else: profit = max(profit, price - buyPrice) return profit
true
e238362a9fe70015b725ea93b7d4ea60663dfcab
PravinSelva5/LeetCode_Grind
/RemoveVowelsFromAString.py
1,081
4.21875
4
''' Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string. Example 1: Input: "leetcodeisacommunityforcoders" Output: "ltcdscmmntyfrcdrs" Example 2: Input: "aeiou" Output: "" Runtime: 28 ms, faster than 75.93% of Python3 online submissions for Remove Vowels from a String. Memory Usage: 14.3 MB, less than 99.95% of Python3 online submissions for Remove Vowels from a String ''' class Solution: def removeVowels(self, S: str) -> str: """ - Create a vowel_list that contains the possible vowels - Iterate through the given string - If current letter IN vowel_list - pop the letter out - ELSE CONTINUE WITH the loop """ vowel_list = ['a', 'e', 'i', 'o', 'u'] output = "" for letter in S: if letter not in vowel_list: output += letter else: continue return output
true
1f5c2a31e43d65a1bb470666f432c53b1e0bd8c9
PravinSelva5/LeetCode_Grind
/SlidingWindowTechnique.py
1,204
4.125
4
# It is an optimization technique. # Given an array of integers of size N, find maximum sum of K consecutive elements ''' USEFUL FOR: - Things we iterate over sequentially - Look for words such as contiguous, fixed sized - Strings, arrays, linked-lists - Minimum, maximum, longest, shortest, contained with a specific set - maybe we need to calculate something ''' def maxSum(arr, WindowSize): arraySize = len(arr) if( arraySize <= WindowSize): print("Invalid operation") return -1 window_sum = sum( [arr[i] for i in range(WindowSize)]) max_sum = window_sum # To compute the new sum, we remove (subtract) the first element in the previous window AND add the second element in the NEW WINDOW for i in range(arraySize-WindowSize): window_sum = window_sum - arr[i] + arr[i + WindowSize] # This is where you subtract the first element from the previous window and ADD the second element of the NEW WINDOW max_sum = max(window_sum, max_sum) return max_sum arr = [80, -50, 90, 100] k = 2 # window size answer = maxSum(arr, k) # Final answer should be 190 print(answer)
true
41fa5b705be4a2f44f143a811186796fa94f9e01
PravinSelva5/LeetCode_Grind
/Trees and Graphs/symmetricTree.py
1,008
4.28125
4
''' Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). ------------------- Results ------------------- Time Complexity: O(N) Space Complexity: O(N) Runtime: 28 ms, faster than 93.85% of Python3 online submissions for Symmetric Tree. Memory Usage: 14.4 MB, less than 52.06% of Python3 online submissions for Symmetric Tree. ''' # 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 isMirror(self,node1, node2): if node1 == None and node2 == None: return True if node1 == None or node2 == None: return False return (node1.val == node2.val) and (self.isMirror(node1.left, node2.right)) and (self.isMirror(node1.right, node2.left)) def isSymmetric(self, root: TreeNode) -> bool: return self.isMirror(root, root)
true
7cabf6be4d6c2b465dcdcdfb75e83441fb8c1fd5
PravinSelva5/LeetCode_Grind
/Linked_Lists/RemoveNthNodeFromEndOfList.py
1,247
4.1875
4
''' Given the head of a linked list, remove the nth node from the end of the list and return its head. BECASUE THE GIVEN LIST IS SINGLY-LINKED, THE HARDEST PART OF THIS QUESTION, IS FIGURING OUT WHICH NODE IS THE Nth ONE THAT NEEDS TO BE REMOVED -------- RESULTS -------- Time Complexity: O(N) Space Complexity: O(1) Runtime: 36 ms, faster than 41.26% of Python3 online submissions for Remove Nth Node From End of List. Memory Usage: 14.3 MB, less than 18.59% of Python3 online submissions for Remove Nth Node From End of List. ''' # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: behind_ptr = ListNode(0) answer = behind_ptr ahead_ptr = head behind_ptr.next = head for i in range(1, n+1): ahead_ptr = ahead_ptr.next while ahead_ptr != None: behind_ptr = behind_ptr.next ahead_ptr = ahead_ptr.next behind_ptr.next = behind_ptr.next.next return answer.next
true
9ee562a0c867c164558a362629732cd514632ca5
PravinSelva5/LeetCode_Grind
/Array_101/MergeSortedArray.py
1,051
4.21875
4
''' Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Notes The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. Unfortunately had to reference the solutions for this question ''' class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ #Pointers for nums1 & nums2 p1 = m - 1 p2 = n - 1 #Pointer for nums1 p = m + n - 1 while p1 >= 0 and p2 >= 0: if nums2[p2] > nums1[p1]: nums1[p] = nums2[p2] p2 -= 1 else: nums1[p] = nums1[p1] p1 -= 1 p -= 1 # If there are still nums1[:p2 + 1] = nums2[:p2 + 1]
true
4d8c4cd3b1005c20887c69c87e0b127c1b0189d5
PravinSelva5/LeetCode_Grind
/Linked_Lists/MergeTwoSortedLists.py
1,762
4.25
4
''' Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Runtime: 40 ms, faster than 39.21% of Python3 online submissions for Merge Two Sorted Lists. Memory Usage: 14.3 MB, less than 8.31% of Python3 online submissions for Merge Two Sorted Lists. ----------------------- COMPLEXITY ----------------------- Time Complexity: O(N) Space Complexity: O(1) ''' # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # Utilize the fact that the lists are sorted current = ListNode(0) answer = current # points to the beginning of our list while l1 and l2: if l1.val > l2.val: current.next = l2 l2 = l2.next else: current.next = l1 l1 = l1.next current = current.next # If one list still needs to be added while l1: current.next = l1 l1 = l1.next current = current.next while l2: current.next = l2 l2 = l2.next current = current.next return answer.next s = Solution() l1_1 = ListNode(1) l1_2 = ListNode(2) l1_4 = ListNode(4) l1_1.next = l1_2 l1_2.next = l1_4 l2_1 = ListNode(1) l2_3 = ListNode(3) l2_4 = ListNode(4) l2_1.next =l2_3 l2_3.next = l2_4 answer = s.mergeTwoLists(l1_1, l2_1) while answer is not None: print(answer.val) answer = answer.next
true
480fbd431ed529d6cc8b30ed2e902d271cea3d84
dwkeis/self-learning
/day3_strategy_pattern/fries.py
869
4.15625
4
"""is a test for factory model""" class Fries(): """define fries""" def describe(self): pass class NoSalt(Fries): """define fries without salt""" def __init__(self,flavor): self.__name = flavor def describe(self): print("i am " + self.__name + " fries") class Default(Fries): """ it's the default flavor of fries""" def __init__(self,flavor): self.__name = flavor def describe(self): print("i am " + self.__name + " fries") class Factory: """where to make fries""" def produce_fries(self, flavor): if flavor == 'nosalt': return NoSalt("no salt") if flavor == 'original': return Default("default") if __name__ == '__main__': factory = Factory() factory.produce_fries('nosalt').describe() factory.produce_fries('original').describe()
true
146b1098deab1d4334990e51bfde7e2d75c8419c
IyvonneBett/Data-Science
/Lesson 3.py
520
4.25
4
# Looping...repeating a task n times eg playing music, generating payslip n times # two types of while/ for loop x = 1 while x <= 10: # n times print('Increment..',x) # 1 to 10 x = x + 1 # Loop works with this update #int(input('Enter some money')) # another to print 10 to 1 y = 10 while y >= 1: print('Decrement.. ', y) y = y-1 # loop from -1...-10 z = -1 while z >= -10: print(z) z = z - 1 # for loop 3fln2 # print 1..10 # print 1950..2020 for/while loop # training@modcom.co.ke
false
bff349b3cf94bd9cf6fd561259023d81318d9773
R0YLUO/Algorithms-and-Data-Structures
/data_structures/queue.py
1,384
4.1875
4
"""Implementation of a queue using a python list""" from typing import Generic, TypeVar T = TypeVar('T') class Queue(Generic[T]): def __init__(self) -> None: """Instantiates an empty list""" self.length = 0 self.list = [] def __len__(self) -> int: """Length of our queue""" return self.length def is_empty(self) -> bool: return len(self) == 0 def append(self, item: T) -> None: """Add item to rear of queue""" self.list.append(item) self.length += 1 def serve(self) -> T: """Remove item at front of queue and return it""" if not self.is_empty(): self.length -= 1 return self.list.pop(0) else: raise Exception("Queue is empty") def peek(self) -> T: """Look at item at front of queue removing""" if not self.is_empty(): return self.list[0] else: raise Exception("Queue is empty") def __str__(self) -> str: """Prints contents in Queue from front to rear.""" n = len(self) output = "" if n == 0: return output else: output += '[' output += str(self.list[0]) for i in range(1, n): output += ", " + str(self.list[i]) output += ']' return output
true
36131e269728e7573a366ecde5bb68178834c161
pranaymate/100Plus_Python_Exercises
/21.py
1,152
4.25
4
#~ 21. A website requires the users to input username and password to register. Write a program to check the validity of password input by users. #~ Following are the criteria for checking the password: #~ 1. At least 1 letter between [a-z] #~ 2. At least 1 number between [0-9] #~ 1. At least 1 letter between [A-Z] #~ 3. At least 1 character from [$#@] #~ 4. Minimum length of transaction password: 6 #~ 5. Maximum length of transaction password: 12 #~ Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. #~ If the following passwords are given as input to the program: #~ ABd1234@1, aF1#, 2w3E*, 2We3345 #~ Then, the output of the program should be: #~ ABd1234@1 #~ Hints: In case of input data being supplied to the question, it should be assumed to be a console input. import re def main(): passwords = input().split(",") result = [] for password in passwords: if len(password) >= 6 and len(password) <= 12: if re.search("([a-zA-Z0-9])+([@#$])+",password): result.append(password) print(",".join(result)) if __name__=="__main__": main()
true
cb085973dc8a164bcdb82b3beb80310303f0ceee
pranaymate/100Plus_Python_Exercises
/04.py
569
4.40625
4
#~ 04. Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. #~ Suppose the following input is supplied to the program: #~ 34,67,55,33,12,98 #~ Then, the output should be: #~ ['34', '67', '55', '33', '12', '98'] #~ ('34', '67', '55', '33', '12', '98') def Main(): numberSequence = input("Enter the comma-separated sequence: ") numberList = numberSequence.split(',') numberTuple = tuple(numberList) print(numberList) print(numberTuple) if __name__ == '__main__': Main()
true
3a6da2770d72955dd5330363f7a126a033e49d0e
pranaymate/100Plus_Python_Exercises
/12.py
632
4.4375
4
#~ 12. Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. #~ Suppose the following input is supplied to the program: #~ Hello world #~ Practice makes perfect #~ Then, the output should be: #~ HELLO WORLD #~ PRACTICE MAKES PERFECT #~ Hints: In case of input data being supplied to the question, it should be assumed to be a console input. def main(): lines = eval(input("Enter number of lines: ")) seq_lines = [] for i in range(lines): seq_lines.append(input().upper()) for i in seq_lines: print(i) if __name__=='__main__': main()
true
f67dc2f0ab519d287974c0c6ddc403eed51a59fe
Nmeece/MIT_OpenCourseware_Python
/MIT_OCW/MIT_OCW_PSets/PS3_Scrabble/Test_Files/is_word_vaild_wildcard.py
1,979
4.15625
4
''' Safe space to try writing the is_word_valid function. Modified to accomodate for wildcards. '*' is the wildcard character. should a word be entered with a wildcard, the wildcard shall be replaced by a vowel until a word found in the wordlist is created OR no good word is found. Nygel M. 29DEC2020 ''' VOWELS = 'aeiou' word = "h*ney" hand = {'n': 1, 'h': 1, '*': 1, 'y': 1, 'd': 1, 'w': 1, 'e': 2} word_list = ["hello", 'apple', 'honey', 'evil', 'rapture', 'honey'] def is_word_valid(word, hand, word_list): low_word = str.lower(word) hand_copy = hand.copy() vowels_list = list(VOWELS) wild_guess_list = [] wild_guess_counter = 0 while '*' in low_word: while len(vowels_list) >= 1 and ''.join(wild_guess_list) not in word_list: wild_guess_list = [] for n in low_word: if n != str("*"): wild_guess_list.append(n) else: wild_guess_list.append(vowels_list[0]) del vowels_list[0] wild_guess_counter += 1 wild_guess = ''.join(wild_guess_list) if wild_guess in word_list: for letter in low_word: if letter in hand_copy and hand_copy[letter] >= 1: hand_copy[letter] -= 1 if hand_copy[letter] <= 0: del(hand_copy[letter]) else: return print('False') return print('True') else: return print('False') while low_word in word_list: for letter in low_word: if letter in hand_copy and hand_copy[letter] >= 1: hand_copy[letter] -= 1 if hand_copy[letter] <= 0: del (hand_copy[letter]) continue else: return print('False') return print('True') return print('False') is_word_valid(word, hand, word_list)
true
691af67d856274a7c8e1027e27e48eceae5e8181
wilcer1/War-assignment
/cardhand.py
1,352
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Class for cards in hand.""" import random class Cardhand: """cardhand class.""" def __init__(self): """Initialize class.""" self.hand = [] def cards_remaining(self): """Check how many cards remain in hand.""" return len(self.hand) def recieve_cards(self, cards): """Add recieved cards to hand.""" for card in cards: self.hand.append(card) def war(self): """Return cards for war.""" face_down = [] for _num in range(3): index = random.randint(0, len(self.hand) - 1) face_down.append(self.hand.pop(index)) face_up = self.hand.pop(random.randint(0, len(self.hand) - 1)) return face_down, face_up def last_war(self): """Get the last few cards of player, return face up and down.""" face_down = [] if self.cards_remaining() > 1: face_up = self.hand.pop(random.randint(0, len(self.hand) - 1)) index = self.cards_remaining() - 1 while index >= 0: face_down.append(self.hand.pop(index)) index -= 1 elif self.cards_remaining() == 1: face_up = self.hand.pop() else: return face_down, None return face_down, face_up
false
082b03fc887f3cf806c335df90a15c8b4252d491
heikoschmidt1187/DailyCodingChallenges
/day05.py
1,095
4.53125
5
#!/bin/python3 """ cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: def cons(a, b): def pair(f): return f(a, b) return pair Implement car and cdr. """ # cons is a closure that constructs a pair using a given function def cons(a, b): # inner function pair builds the pair based on a given function f # f therefore defines >how< the pair is created def pair(f): return f(a, b) return pair # get the first element of the pair def car(c): # we need a function to forward to the pair function in cons # that is used to return the first value def first(a, b): return a # put the function to the closure and return the result return c(first) # get the second element of the pair - same principle as car def cdr(c): def second(a, b): return b return c(second) if __name__ == '__main__': print(car(cons(3, 4))) print(cdr(cons(3, 4)))
true
0d2eb22e96d280be6ebb47a615a4802696fe8fed
Peter-John88/ConquerPython
/009dict_and_set.py
1,371
4.15625
4
# -*- coding:utf-8 -*- ####dict d={'Michael':95, 'Bob':75, 'Tracy':85} print d print d['Michael'] d['Adam']=67 print d['Adam'] d['Jack']=90 print d['Jack'] d['Jack']=88 print d['Jack'] print d #d['Thomas'] KeyError print 'Thomas' in d print d.get('Thomas') print d.get('Thomas',-1) print d d.pop('Bob') print d # #和list比较,dict有以下几个特点:查找和插入的速度极快,不会随着key的增加而增加;需要占用大量的内存,内存浪费多。 # #dict的key必须是不可变对象。 #key=[1,2,3] #d[key]='a list' #TypeError: unhashable type: 'list' ####set s=set([1,2,3]) print s s=set([1,1,2,2,3,3]) print s s.add(4) print s s.add(4) print s s.remove(4) print s s1=set([1,2,3]) s2=set([2,3,4]) print s1&s2 print s1|s2 # #set的原理和dict一样,所以,同样不可以放入可变对象,因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”。 # # s=set([1,2,[1,2,3],3]) #TypeError: unhashable type: 'list' ####unhashable object a=['c','b','a'] #unhashable a.sort() print a a='abc' #hashable b=a.replace('a','A') #new object print b print a t={(1, 2, 3):95, 'Adam':98} #(1, 2, 3) is hashable, can work as key in dict print t t={(1, [2, 3]):95, 'Adam':98} #TypeError: unhashable type: 'list'
false
3666c2e7decfaa73e0a10daa76cdd23a1aa89379
Achew-glitch/python_homework
/hw01_normal_02.py
817
4.40625
4
# Задача-2: Исходные значения двух переменных запросить у пользователя. # Поменять значения переменных местами. Вывести новые значения на экран. # Решите задачу, используя только две переменные. # Подсказки: # * постарайтесь сделать решение через действия над числами; # * при желании и понимании воспользуйтесь синтаксисом кортежей Python. a = int(input('Введите число а: ')) print('a = ', a) b = int(input('Введите число b: ')) print('b = ', b) print('\n') a += b b = a - b a = a - b print('a = ', a) print('b = ', b)
false
c401e5a8cde94a8accd7480f97d201b8a7e01f8c
Mahler7/udemy-python-bootcamp
/errors-and-exceptions/errors-and-exceptions-test.py
965
4.1875
4
###Problem 1 Handle the exception thrown by the code below by using try and except blocks. try: for i in ['a','b','c']: print(i**2) except TypeError: print('The data type is not correct.') ###Problem 2 Handle the exception thrown by the code below by using **try** and **except** blocks. Then use a **finally** block to print 'All Done.' x = 5 y = 0 try: z = x/y except ZeroDivisionError: print('There is a zero division error here') finally: print('All done') ###Problem 3 Write a function that asks for an integer and prints the square of it. Use a while loop with a try,except, else block to account for incorrect inputs. def ask(): while True: try: squared = int(input('Please enter a number to be squared: ')) print(squared ** 2) except: print('You must enter an integer') continue else: print('Integer entered') break ask()
true
5acbcdc262bf5e6a07f4b938dc4cb17599c45df4
Michael37/Programming1-2
/Lesson 9/Exercises/9.3.1.py
683
4.34375
4
# Michael McCullough # Period 4 # 12/7/15 # 9.3.1 # Grade calculator; gets input of grade in numbers and converts info to a letter value grade = float(input("what is a grade in one of your classes? ")) if grade > 0.0 and grade < 0.76: print ("You have an F") elif grade > 0.75 and grade < 1.51: print ("You have a D") elif grade > 1.50 and grade < 2.01: print ("You have a C") elif grade > 2.0 and grade < 2.51: print ("You have a B-") elif grade > 2.50 and grade < 3.01: print ("You have a B") elif grade > 3.0 and grade < 3.51: print ("You have an A-") elif grade > 3.50 or grade <= 4.0: print ("You have a solid A!") else: print ("Grade value not found.")
true
d15526a594a6593a328f8200607616c128eb4296
bozy15/mongodb-test
/test.py
1,245
4.21875
4
def welcome_function(): """ This function is the welcome function, it is called first in the main_program_call function. The function prints a welcome message and instructions to the user. """ print("WELCOME TO LEARNPULSE") print( "Through this program you can submit and search for \n" "staff training information" ) print("\n") print("What would you like to do?") print("Please enter one of the following options to progress:") print('- Enter "input" to add trainee data to the database') print('- Enter "search" to search for trainee data') while True: user_branch_choice = input("Please input your command: ") if user_branch_choice == "input": return user_branch_choice elif user_branch_choice == "search": return user_branch_choice else: print("Sorry, that command was invalid please try again") print("\n") # def program_branch(): def main_program_call(): """ This function is the main function in the program through which all other functions are called. """ branching_variable = welcome_function() print(branching_variable) main_program_call()
true
3e628ae24afa40165546a5ece7ed0078b620a2e3
mattjhann/Powershell
/001 Multiples of 3 and 5.py
342
4.21875
4
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. numbers = [] for i in range(1000): if i % 3 == 0 or i % 5 == 0: numbers.append(i) j = 0 for i in numbers: j += i print(j)
true
e2b2c9b2c24413046ea0a66011ac651c68736a7e
EmilyJRoj/emoji27
/anothernewproj/anothernewproj.py
607
4.1875
4
# starting off print(22 / 7) print(355 / 113) import math print(9801 / (2206 * math.sqrt(2))) def archimedes(numsides, numSides): innerAngleB = 360.0 / numSides halfAngleA = innerAngleB / 2 oneHalfSides = math.sin(math.radians(halfAngleA)) sideS = oneHalfSideS * 2 polygoncircumference = numSides * side5 pi = polygonCircumference / 2 return pi print(archimedes(16)) for sides in range(8, 100, 8): print(sides, archimedes(sides)) # Experiment with the loop above alongside the actual value of pi. How many # sides does it take to make the two close? # 102 sides.
true
acdb0ee0f25254591fac1875be103230231f2acd
starxfighter/Python
/pythonoop/animalOOP.py
1,594
4.34375
4
# Set definition of the parent animal class class Animal(): def __init__(self, name, health): self.name = name self.health = health def walk(self): self.health -= 1 return self def run(self): self.health -= 5 return self def display_health(self): print("The health for ", self.name, " is now", self.health) # Set definition for a child class of animal call Dog class Dog(Animal): def __init__(self, name, health): super().__init__(name, health) self.health = 150 def pet(self): self.health += 5 return self # set definition for a child class of animal called Dragon class Dragon(Animal): def __init__(self, name, health): super().__init__(name, health) self.health = 170 def fly(self): self.health -= 10 return self def display_health(self): super().display_health() print("I am a Dragon") # Create animal, walk three times, run twice and then display health anAnimal = Animal("Bear", 100) anAnimal.walk().walk().walk() anAnimal.run().run() anAnimal.display_health() # Create a dog, walk three times,run twice, pet and then display health poodle = Dog("Fluffy", 100) poodle.display_health() poodle.walk().walk().walk() poodle.run().run() poodle.pet() poodle.display_health() # Create a dragon, walk three times, run twice, fly and then display health oldDragon = Dragon("Drago", 100) oldDragon.display_health() oldDragon.walk().walk().walk() oldDragon.run().run() oldDragon.fly() oldDragon.display_health()
false