blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ea84d83db6a672ef7a015ef0fec2f0af48368284
sukhvir786/Python-DAY-4
/fun12.py
525
4.25
4
""" Problem: Heron's formula a,b,c are length of sides of a triangle s = semi circumference s = (a+b+c)/2 area = sqroot(s(s-a)(s-b)(s-c)) """ # %% def FUN(): """ computes area of triangle using Heron's formula. """ a = float(input("Enter length of side one: ")) b = float(input("Enter length of side two: ")) c = float(input("Enter length of side three: ")) s = (a + b + c)/2 AR = s*((s-a)*(s-b)*(s-c)) print("Area of a triangle with sides",AR**0.5 ) # %%
false
c097917a104b8d1fbb1614c90c7af19d0a2ce64b
TrinityChristiana/py-functions
/cash-to-coins.py
938
4.125
4
# **************************** Challenge: Cash to Coins **************************** """ Author: Trinity Terry pyrun: python cash-to-coins.py """ import math # Now do the reverse. Convert the dollar amount into the coins that make up that dollar amount. The final result is an object with the correct number of quarters, dimes, nickels, and pennies. def calc_coins(cash): piggyBank = { "quarters": 0, "dimes": 0, "nickels": 0, "pennies": 0 } cents = cash * 100 piggyBank["quarters"] = math.floor(cents // 25) cents -= piggyBank["quarters"] * 25 piggyBank["dimes"] = math.floor(cents // 10) cents -= piggyBank["dimes"] * 10 piggyBank["nickels"] = math.floor(cents // 5) cents -= piggyBank["nickels"] * 5 piggyBank["pennies"] = math.floor(cents) print("real: ", piggyBank) print("test: ", { 'quarters': 34, 'dimes': 1, 'nickels': 1, 'pennies': 4 }) calc_coins(8.69)
false
6d63f96591f210049407b3930d131435727b2dfa
nicodlv99/100-days-of-code
/basics/sequence-types.py
1,657
4.59375
5
#Creating a string s = "Hello World, how are you doing!" #Creating a string to print print(s) s1 = """This is a line of code with multiple ines""" print(s1) #defining a string that contains multiple lines print(s[0]) #indexing to find the first letter in a word using dictionaries #first number in a dictionary is 0 print(s*2) #will print it three times print(len(s1)) #used to find the length of a string print(len(s)) #Slicing print(s[0:5]) #Slicing - using to find index within a string print(s[0:]) #not closing off the index means it will splice the whole string print(s[0:8]) print(s[-3:-1]) #splicing using negative numbers means it indexes from the back to front print(s[0:9:2]) #returns by skipping on variable at a time print(s[15:: -1]) #will come from the end all the way to the beginning in reverse print(s[::-1]) #will return the string but reversed #Stripping print(s.strip()) #will strip out the spaces in a string print(s.lstrip()) #will do a left strip print(s.rstrip()) #will do a right strip print(s.find("ell"), 0, len(s)) #to find location of a substring. Use 0 to state where to start the search to till the length of string print(s.count("o")) #counts the number of occurences of a given substring print(s.replace("Hello", "Howdy")) #used to replace a substring, word to get replaced goes first followed by the new word print(s.upper) #will return string in uppercase print(s.lower) #will return string in lowercase print(s.title()) #returns a title case version of the string
true
621c0d35b6e0a2ff8fad1f30b74164b30c09115b
kicksmackbyte/project_euler
/p004.py
589
4.3125
4
""" Find the largest palindrome made from the product of two 3-digit numbers. """ def is_palindrome(i): str_ = str(i) if str_ == str_[::-1]: return True else: return False def main(): num_1 = 999 num_2 = 999 palindromes = [] for i in range(900): a = 999 - i for j in range(900): b = 999-j product = a * b if is_palindrome(product): palindromes.append(product) largest_palindrome = max(palindromes) print(largest_palindrome) if __name__ == "__main__": main()
true
8faa9ef69ed763164ec130d4a91088df7d30030d
satishraut/inter-prep
/oops/methodOverLoadingAndRiding.py
799
4.125
4
''' Override means having two methods with the same name but doing different tasks. It means that one of the methods overrides the other. Like other languages (for example method overloading in C++) do, python does not supports method overloading. We may overload the methods but can only use the latest defined method. ''' class Rectangle(): def __init__(self, lentgh, breadth): self.lentgh = lentgh self.breadth = breadth def getArea(self): print(self.lentgh * self.breadth,"Is area of rectangle") class Square(Rectangle): def __init__(self, side): self.side = side Rectangle.__init__(self,side,side) def getArea(self): print(self.side*self.side,"is area of square") s = Square(4) r = Rectangle(2,4) s.getArea() r.getArea()
true
0bf5883db8abc4f19b9fa91778012fc4a0faa28d
pkiuna/CS490-MachineLearning-Python
/ICP2/ICP2.py
1,350
4.15625
4
class employee: # Members to count employees and find average salary counter = 0 salary = 0 #contructor to initialize family, salary, department using self def _init_(self, name, family, salary_num, department): self.name = name self.family = family self.salary_num = salary_num self.department = department employee.counter += 1 # count of employees employee.salary += salary_num # Average the salaries of employees # calculate average salary def get_avg_salary(self): avg_salary = self.salary / self.counter print("The average salary is: " + str(avg_salary)) return def _init_(self, name, family, salary_num, department): # inherit of employee class when initializing employee._init_(self, name, family, salary_num, department) def main(): emp1 = employee("Paul", "Kiuna", 4000, "IT") emp1.display() emp2 = employee("Rachel", "Morris", 4000, "CS") emp2.display() emp3 = employee("Matthew", "Stocks", 4000, "IT") emp3.display() emp4 = employee("Rachel", "Stills", 4000, "CS") emp4.display() emp5 = employee("Morgan", "Belle", 4000, "IT") emp5.display() emp6 = employee("George", "Kiuna", 4000, "CS") emp6.display() if __name__ == '__main__': main()
true
f162ad816fd042b77c190a314d018ae4f489d12a
ansariimran/small-python-programs
/pattern.py
1,061
4.5
4
def pattern(n): # for i in range(1, n+1): # # print i number of * s in # # each line # print("*" * i) for i in range(1, n+1): li = [ ] # print("INCREMENTED FOR LOOP") for j in range(1, i+1): li.append(j) #print("\n DECREMENTED FOR LOOP") for j in range(i-1, 0, -1): li.append(j) # for num in li: # print(num, end=" ") - This is used for printing all elements of all loop like: 1 1 2 1 1 2 3 2 1 (for n=3) print(" ".join(map(str, li))) li.clear() for i in range(n-1, 0, -1): li = [ ] # print("INCREMENTED FOR LOOP") for j in range(1, i+1): li.append(j) #print("\n DECREMENTED FOR LOOP") for j in range(i-1, 0, -1): li.append(j) # for num in li: # print(num, end=" ") - This is used for printing all elements of all loop like: 1 1 2 1 1 2 3 2 1 (for n=3) print(" ".join(map(str, li))) li.clear() pattern(5)
false
5493eddc6e37f078d9ec50b0ded6d3efaf5e0847
Lynn-Lau/Algorithm-Toolbox
/2nd week/01_Codes/fibonacci_last_digit/fibonacci_last_digit .py
893
4.40625
4
#Uses python2 """ A Simple Program for Coursera Algorithmic Toolbox & The Last Digit of a Large Fibonacci Number & Given an integer n, find the last digit of the nth Fibonacci number Fn. Author: Lynn Lau Date: 2016/07/27 """ ''' Naive Algorithm ''' def Calc_Fib_Lst(n): FibList = [0, 1] #print FibList if n == 0: return FibList[0] elif n == 1: return FibList[1] for n in range(2, n+1): result = FibList[n-1] + FibList[n-2] FibList.append(result) #print FibList return FibList[n]%10 m = int(raw_input('')) print Calc_Fib_Lst(m) ''' Smart Algorithm ''' def Calc_Fib_Lst(n): FibList = [0, 1] #print FibList if n == 0: return FibList[0] elif n == 1: return FibList[1] for n in range(2, n+1): result = FibList[n-1]%10 + FibList[n-2]%10 FibList.append(result) #print FibList return (FibList[n])%10 m = int(raw_input('')) print Calc_Fib_Lst(m)
false
7e24870e885624f70f0532f545823d73e3a16a1a
annamnatsakanyan/HTI-1-Practical-Group-1-Anna-Mnatsakanyan
/Lecture_6/insertion_sort.py
345
4.15625
4
def insertion_sort(num): for i in range(1, len(num)): value_to_insert = num[i] j = i - 1 while j >= 0 and value_to_insert < num[j]: num[j + 1], num[j] = num[j], num[j + 1] j -= 1 numbers = [int(elem) for elem in input("enter the numbers: ").split()] insertion_sort(numbers) print(numbers)
true
46ca0cc0de67bcc58430952e78505260f4b383f4
colinvsyolanda/python
/study/list_tuple_dictionary/python010.py
359
4.125
4
""" 题目:暂停一秒输出,并格式化当前时间。 程序分析:无。 """ import time print(time.localtime()) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) time.sleep(2) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) time.sleep(2) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
false
26eb512c18e30d70e0a383ca748302bfef9a3681
samarthgowda96/pycharprojects
/pal.py
493
4.15625
4
string= input("enter the input"+" ") def isPalindrome(str): length = len(str) first = 0 last = length - 1 palindrome = 1 while first < last: if(str[first] == str[last]): first = first + 1 last = last - 1 continue else: palindrome= 0 break return palindrome palindrome= isPalindrome(string) if(palindrome): print(string+" "+"it is a palindrome") else: print("Please try again :)")
true
37f7995cd0bdebf46e1a3a4776885ea94c301713
poojarkpatel/Testing_Triangle_Classification
/HW01_Pooja_Patel.py
1,702
4.25
4
""" HW01 Triangle classification """ import math class Triangle: """ The class takes length of three sides of triangle and return the type of triangle. """ def __init__(self, side1, side2, side3) -> None: """ init function of class """ self.side1 = float(side1) self.side2 = float(side2) self.side3 = float(side3) def classify_triangle(self) -> str: if self.side1 + self.side2 < self.side3 or self.side3 + self.side1 < self.side2 or self.side3 + self.side2 < self.side1: raise ValueError else: if self.side1 != self.side2 and self.side2 != self.side3 and self.side3 != self.side1: if round((self.side1 ** 2), 2) + round((self.side2 ** 2), 2) == math.ceil((self.side3 ** 2)): return "Right and Scalene Triangle" else: return "Scalene Triangle" elif self.side1 == self.side2 == self.side3: return "Equilateral Triangle" elif self.side1 == self.side2 or self.side2 == self.side3 or self.side3 == self.side1: if (round((self.side1 ** 2), 2) + round(self.side2 ** 2, 2)) == math.ceil((self.side3 ** 2)): return "Right and Isosceles Triangle" else: return "Isosceles Triangle" def __str__(self): return f"{self.side1}, {self.side2}, {self.side3}" if __name__ == '__main__': side_1 = input("Enter first side of triangle: ") side_2 = input("Enter second side of triangle: ") side_3 = input("Enter third side of triangle: ") triangle: Triangle = Triangle(side_1, side_2, side_3)
false
8b89a4b42869fb143357174fcf98e5c0d50170e8
srujanprophet/PythonPractice
/11 - Unit 4/4.1.12.py
407
4.1875
4
str = "Global Warming" print str[-4:] print str[4:9] if str.isalpha() == True: print "It has alphanumeric characters" else: print "It does not have alphanumeric characters" print str.strip("ming") print str.strip("Glob") print str.index('Wa') print str.swapcase() if str.istitle() == True: print "It is in Title Case" else: print "It is not in Title case" print str.replace('a','*')
true
b7856076678d3ee518d06ed63acdd113f195715b
srujanprophet/PythonPractice
/11 - Unit 3/3.3.6.py
203
4.15625
4
def fibonacci(): n = int(input("Enter no. of terms : ")) pre = 0 cur = 1 for i in range(1,n+1): print cur nxt = pre + cur pre = cur cur = nxt fibonacci()
false
f02ac49567bc1f4089fcc75e4307c397ffc9cdf0
saurabhpati/python.beginner
/OperatorsAndConditionals/elif.py
535
4.40625
4
# elif keyword is used to make the else if statement in python # Requirement for this example: User gives the amount. # 1. If amount is less than 1000, discount is 5% # 2. If amount is less than (or equal to) 5000, discount is 10% # 3. If amount is more than 5000, discount is 15% amount = input('Enter the amount: '); amount = int(amount); if amount < 1000: discount = amount * 0.05; elif amount <= 5000: discount = amount * 0.10; else: discount = amount * 0.15; print('The total amount to be paid', amount - discount);
true
fe5b725a5760c7c55a3aeff33b85cce2aaa6aa5a
saurabhpati/python.beginner
/Lists/list-operations.py
1,426
4.5
4
# iterating over a list. testList = [1, 2, 3] ; for x in testList: print(x, end='\n'); # extend will the given list to the list on which extend is called. languagesKnownList = ['c#', 'javascript','python']; languagesKnownList.extend(testList) print('Languages known and extended:', languagesKnownList); # append will only add a single element to the list at the end of the list. languagesKnownList.append('C'); print('The good old forgotten friend: ', languagesKnownList); # pop will remove the last element from the list and return the same. print('Popped', languagesKnownList.pop()); # index will return the lowest index of the required element. print('index of javascript is: ', languagesKnownList.index('javascript')); # insert will add a list at a given index. languagesKnownList.insert(0, 'C'); print('Good old friend is back at index 0: ', languagesKnownList); cleansedList = []; # This loop will try to convert the element in language list into ints, # if successful meaning no exceptions were raised, then value of the element is an integer. # cleansed list will contain only strings. # Note: This is done because if the list contains both strings and integers, # then using sort method will throw an error. for language in languagesKnownList: try: value = int(language); except: cleansedList.append(language); cleansedList.sort(); print('Cleansed list: ', cleansedList);
true
3ec9c0250c484d50af12a557650e415956c1303f
saurabhpati/python.beginner
/OperatorsAndConditionals/arithmetic.py
287
4.3125
4
# This programs intends to highlight between the differences of '/' and '//' operators. x = input('Enter the dividend: '); y = input('Enter the divisor: '); x = int(x); y = int(y); print('x/y = ', x/y); print('x//y = ', x//y); print('divident raised to the power of divisor = ', x**y);
true
a0050a3c5375653743e52283756fbe648cb01e62
kazmanbanj/Practice_on_Python
/file io/script.py
953
4.1875
4
# my_file = open('test.txt') # print(my_file.read()) # my_file.seek(0) # print(my_file.read()) # my_file.seek(0) # print(my_file.read()) # print(my_file.readlines()) # my_file.close() # Standard way to Read, write, append in python # with open('test.txt', mode='r+') as my_file: # print(my_file.readlines()) # with open('test.txt', mode='r+') as my_file: # text = my_file.write(':)') # print(text) # with open('test.txt', mode='a') as my_file: # text = my_file.write('\nthis will append to the text file with the mode a') # print(text) # with open('testAnother.txt', mode='w') as my_file: # text = my_file.write('\nthis will create a new text file with the mode w') # print(text) # file paths try: with open('movedHere/testAnother.txt', mode='r') as my_file: print(my_file.read()) except FileNotFoundError as err: print('file does not exist') except IOError as err: print('IO error')
true
c666e839c06a7dcb299706f8fb77bbccf29d1e70
kb9zzw/arcpy_scripts
/distanceTry.py
1,012
4.1875
4
#Name: distanceTry.py #Purpose: converts miles to kilometers or vice-versa #Usage: distanceTry.py <numerical_distance> <distance_unit> #Example: distanceTry.py 5 miles #Author: Jon Burroughs (jdburrou) #Date: 2/16/2012 import sys # get distance value from user (assume they'll provide it correctly) distance = float(sys.argv[1]) try : # attempt to get units from the user. units = sys.argv[2].lower() except IndexError : # warn user, then set default units to 'miles' print "Warning: no distance_unit was provided. Default unit, miles used." units = "miles" if units == 'miles' : # convert mi to km print "%.1f miles is equivalent to %.1f kilometers." % (distance, distance * 1.609344) elif units == 'kilometers' : # conver km to mi print "%.1f kilometers is equivalent to %.2f miles." % (distance, distance / 1.609344) else : # punt print "I don't know how to convert from '%s', distance_unit should be 'miles' or 'kilometers'." % units
true
6f3d2881cdd2ab5cf54ab085d11b69be44cf38f9
DvidGs/Python-A-Z
/9 - Funciones en Python/ejercicio 6.py
1,515
4.5
4
# Ejercicio 6 # Crea una función que devuelva el MCM (mínimo común múltiplo) de 2 números proporcionados por # parámetro. # PISTA: Aprovecha la función que calcula el MCD de dos números del ejercicio anterior y la función que # calcula el valor absoluto de un número. def bigger(a, b): """ Devuelve el mayor numero de 2 números reales dados. Args: a: Número real b: Número real Return: Número real """ if a >= b: return a return b def lower(a, b): """ Devuelve el menor número de 2 números reales dados. Args a: Número real b: Número real Returns: Número real """ if a <= b: return a return b def mcd(a, b): """ Devuelve el MCD de dos números enteros. Args: a: Número entero b: Número entero Returns: max: Número entero """ r = 0 max = bigger(a, b) min = lower(a, b) while(min > 0): r = min min = max % min max = r return max def absolute_value(x): """ Devuelve el valor absoluto de un número real. Args: x: Número real Returns: Número real """ if x >= 0: return x return -x def mcm(a, b): """ Devuelve el MCM de dos números enteros. Args: a: Número entero b: Número entero Returns: max: Número entero """ return absolute_value(a * b) // mcd(a, b) print(mcm(10, 2))
false
e4c25314eaab9261336eeff4f0160a3ba72ecea6
DvidGs/Python-A-Z
/3 - Operadores de decisión/ejercicio 5.py
1,016
4.3125
4
# Ejercicio 5 # Haz que un usuario introduzca dos números enteros positivos. Suponiendo que el primer número introducido # por el usuario es mayor o igual al segundo número introducido por el usuario, comprueba que la división del # primer número entre el segundo número es entera. # En caso de la división ser entera, devuelve el cociente por pantalla e indica que la división en efecto es entera. # En caso de la división no ser entera, devuelve el cociente y el resto por pantalla e indica que la división entre # los dos números no es entera. ## Divisón exacta 24/6 ## División entera 17/5 uno = int(input("Número uno:")) dos = int(input("Número dos:")) if uno >= dos: resultado = uno % dos if resultado != 0: # Una división es entera cuando el resto es distinto de cero. print("La division es entera") else: cociente = uno / dos print("El cociente de la división es: {}\nSu resto es: {}".format(cociente, resultado)) print("No es Entera")
false
2fbb31d6ea051260551205126fac7c5532ce22e7
qpwoeirut/python_book_work
/book_work/21_Dictionary.py
468
4.34375
4
stanley = {'age': '11', 'birthday': 'August 24, 2005','school': 'Bowman School', 'grade': '6th', 'activities': 'soccer, coding, and video games', 'family': 'Nan Zhong(Father), Yun Luo(Mother), Randy Zhong(Brother)'} print(stanley['school']) today = {'year': '2017', 'month': 'June', 'day': '13'} today['weekday']= 'Tuesday' print('Today is', today['weekday'] + ',' ,today['month'],today['day'] + ',' ,today['year']+'.') print(today) today['day'] = '15' print(today['day'])
false
8713d7b1db28ea750666376aecce9231393655bf
PromytheasN/Project_Euler_Solutions_1-10
/Task 5 Solution.py
1,201
4.1875
4
import numpy def small_divident(): """ This is a function that calculates the smallest divident number, evenly divisable by all numbers between 1 to 20. """ #If our number is evenly divisable with the list bellow, it should be evenly divisable with #1 to 10 as well as all the numbers bellow are primes or multiples of numbers of 1 to 10. #This will increasae the time efficiency of our function. #Here we create an array of our list using NumPy module div_array = numpy.array([20,19,18,17,16,15,14,13,12,11]) #20*19 = 390, that would be the smallest possible number that could be divided both from 20 and 19. #Using that number instead of just adding 20 for each failed attempt will increase time efficiency num = 390 nofound = True while nofound: #Checking if we have evenly division between num and our array div = num % div_array #Checking if all elements in our div list are 0 if all(element == 0 for element in list(div)): nofound = False #If not we increase num and repeat the process else: num += 390 return num
true
afa0a8a76248a73be56eec3d388a23ec11945f96
anandtakawale/classcodes
/optimizations_sem8/fibonacci.py
2,787
4.15625
4
import texttable import math def fibonacciMethod(f, a, b, epsilon): """ Returns minima of the function """ #calculating number of iterations fn = (b - a) / epsilon n = fibFinder(fn) print n k = 0 table = texttable.Texttable() table.add_row(["Iteration", "a", "b", "x1", "x2", "f(x1)", "f(x2)"]) while k <= (n - 3): l = float(b - a) #creating factor obtained from fibonacci series factor = float(fib(n-k-1))/ fib(n-k) x1 = a + (1 - factor) * l x2 = a + factor * l f1 = f(x1) f2 = f(x2) #adding rows to table table.add_row([k, a, b, x1, x2, f1, f2]) #elimination of region if f2 < f1: a = x1 elif f1 < f2: b = x2 else: a = x1 b = x2 k += 1 print table.draw() + '\n' return (x1 + x2) / 2 def fibonacciIter(f, a, b, n): """ Fibonacci search method based on number of iterations reuiqred as as per book f: function to be minimized (a, b): interval of search n: number of iterations required """ L2star = float(fib(n - 2))/ fib(n) * (b - a) j = 2 table = texttable.Texttable() table.add_row(["Function evals", "a", "b", "x1", "x2", "f(x1)", "f(x2)", "L2"]) while j <= n: L1 = b - a if L2star > L1/2.0: x2 = a + L2star x1 = b - L2star else: x2 = b - L2star x1 = a + L2star f1 = f(x1) f2 = f(x2) #adding row to table table.add_row([j, a, b, x1, x2, f1, f2, L2star]) #eliminating correct interval if f2 < f1: a = x1 L2star = float(fib(n - j))/ fib(n - (j - 2)) * (b - a) elif f2 > f1: b = x2 L2star = float(fib(n - j))/ fib(n - (j - 2)) * (b - a) else: a = x1 b = x2 L2star = float(fib(n - j))/ fib(n - (j - 2)) * (b - a) j += 1 j += 1 print table.draw(), '\n' return a, b def fibFinder(fibo): """ Returns number n such that fib(n) > fibo """ n = 1 while fib(n) < fibo: n += 1 return n def f(x): """ Returns value of the function of f(x) """ return x**2 + 54 / x #return x**4 - 15*x**3 + 72*x**2 - 1135*x #return math.exp(x) - x**3 def fib(x, cache = {}): """ Returns fibonacci series by using dynamic programming. Observe use of dictionary cache. """ if x == 0: return 1 elif x == 1: return 1 else: if x not in cache.keys(): cache[x] = fib(x-1) + fib(x-2) return cache[x] if __name__ == '__main__': print fibonacciIter(f, 0, 6, 10)
true
35cd0814bb7aaedc923c533943637886830c0593
AshVijay/Leetcode_Python
/496.py
2,433
4.125
4
""" 496. Next Greater Element I Easy 1103 1685 Add to List Share You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. For number 2 in the first array, there is no next greater number for it in the second array, so output -1. Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4]. Output: [3,-1] Explanation: For number 2 in the first array, the next greater number for it in the second array is 3. For number 4 in the first array, there is no next greater number for it in the second array, so output -1. Note: All elements in nums1 and nums2 are unique. The length of both nums1 and nums2 would not exceed 1000. """ class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: great_dict= {} index_dict = {} #To store corresponding indices across arrays for i in range(len(nums1)): for j in range(len(nums2)): if nums1[i] == nums2[j]: index_dict[nums1[i]] = j #To store largest elements to the right for i in range(len(nums1)) : j = index_dict[nums1[i]]+1 if j == len(nums2): great_dict[i] = -1 while j < len(nums2) : if j == len(nums2) -1 and nums2[j] <= nums1[i] : great_dict[i] = -1 break if nums2[j] > nums1[i] : great_dict[i] = nums2[j] break j+=1 final = [-1 for elm in nums1] for i in range(len(nums1)): final[i] = great_dict[i] return final
true
70ac588cf1ba0c9fd8db5fe5688ed44730e73efe
Tadrop/30_days_of_code
/day9.py
484
4.21875
4
def fibSum(number): if not isinstance(number,int): return 'Invalid input, number must be positive integer' if number == 0 : return 0 elif number < 0: return "Invalid, number can't be negative" elif number > 0: pass num =0 a,c=0,1 while c>=number: a,c= c, a+c if (c%2) == 0 : number+=c return number print(fibSum(10)) print(fibSum(0)) print(fibSum(-3)) print(fibSum('a'))
true
80c70ddc2a5f144314acc68f929a2ef70418c90d
EstherAmponsaa/cssi
/week3/test.py
1,309
4.28125
4
#print('Hello CSSI') #name ='Bill' #name = 55 #print(name) #name = raw_input('Enter your name:') #print('Hi there..') #print(name) #print('na'*16) # print('BATMAN!') #print('Pow!'*3) #user_input = raw_input('Enter anything:') #print('You entered a ', (type(user_input)) #print('raw_input gives us strings') #num1 = raw_input("Enter number #1:") #num2 = raw_input("Enter number #2:") #print(num1 + num2) #print(type(num1+num2)) #print('int(raw_input) gives us int') #num1 = int(raw_input("Enter number #1:")) #num2 = int(raw_input("Enter number #2:")) #print(num1 + num2) #print(type(num1+num2)) #num1 = int(raw_input("Enter number #1:")) #num2 = int(raw_input("Enter number #2:")) #total = num1 + num2 #print("The sum is " + str(total)) #num = int(raw_input("Enter a number:")) #if num > 0: # print("That's a positive number!") #elif num < 0: # print("That's a negive number!") #else: #print("Zero is neither positive nor negative") #x = 18 #if x > 18: #print("You can buy lottery tickets!") #if x > 25: #print("You can also rent a car!") #print("And you can get your own credit card! ") #print("End program.") #x = 1 #while x <= 5: # print(x) # x = x + 1 #string = "hello there" #for letter in string: # print(letter.upper()) #for i in range(5): # print(i)
false
8aabefe65e37fd1b223d5910875332a193e9ce02
EkaterinaBazhanova/Python
/Les3Ex4_2.py
1,059
4.25
4
def my_func_2(x, y): """Выволняет возведение действительного положительного числа в отрицательную целую степень циклом с помощью *.""" power = 1 n = abs(y) + 1 for i in range(1, n): power = power * (1/x) return round(power, 4) def check(): """Проверяет правильность ввода данных пользователем.""" x_1 = float(input("Enter positive number a: ")) if x_1 <= 0: print("Error: The number a must be positive!") return else: try: x_2 = int(input("Enter integer negative number b: ")) except ValueError: print("Error: The number b must be integer!") return if x_2 >= 0: print("Error: The number b must be negative!") return else: result = my_func_2(x_1, x_2) print(f"{x_1} in a power of {x_2} is {result}") print("Let's raise a to the power of b: ") check()
false
69c2bc890089754abd6ca0021ba726b2ebe7844b
Abinesh1991/Numpy-tutorial
/NumpyTutorial8.py
755
4.28125
4
""" Python, Numpy and Probability Random using numpy """ import numpy as np outcome = np.random.randint(1, 7, size=10) print(outcome) # generated 5*4 matrix using the random number range from 1 - 7 """ output: [[4 4 5 4] [4 4 5 2] [3 3 3 4] [3 5 4 5] [6 1 2 6]] """ print(np.random.randint(1, 7, size=(5, 4))) # Random Choices with Python """ choice' is another extremely useful function of the random module. This function can be used to choose a random element from a non-empty sequence. """ # using choice we can pick random from string or list from random import choice professions = ["scientist", "philosopher", "engineer", "priest"] print(choice("abcdefghij")) print(choice(professions)) print(choice(("apples", "bananas", "cherries")))
true
409cb01cecf4af685af65480648c49c8efaf57c0
Abinesh1991/Numpy-tutorial
/NumpyTutorial5.py
2,239
4.1875
4
""" Data type object 'dtype' is an instance of numpy.dtype class. It can be created with numpy.dtype. """ import numpy as np # sample example with int16 data type i16 = np.dtype(np.int16) print(i16) lst = [[3.4, 8.7, 9.9], [1.1, -7.8, -0.7], [4.1, 12.3, 4.8]] A = np.array(lst, dtype=i16) print(A) """ We create a structured array with the 'density' column. The data type is defined as np.dtype([('density', np.int)]). We assign this data type to the variable 'dt' for the sake of convenience. We use this data type in the darray definition, in which we use the first three densities Output: [(393,) (337,) (256,)] The internal representation: array([(393,), (337,), (256,)], dtype=[('density', '<i4')]) """ # defining the dataType for density dt = np.dtype([('density', np.int32)]) # also we can write above code like this dt = np.dtype([('density', 'i4')]) # creating an array x = np.array([(393,), (337,), (256,)], dtype=dt) print(x) print("\nThe internal representation:") print(repr(x)) """ Defining a data type for each fields: S20 - String can contains length 20 i2 - int16 i4 - int32 """ dt = np.dtype([('country', 'S20'), ('density', 'i4'), ('area', 'i4'), ('population', 'i4')]) x = np.array([('Netherlands', 393, 41526, 16928800), ('Belgium', 337, 30510, 11007020), ('United Kingdom', 256, 243610, 62262000), ('Germany', 233, 357021, 81799600), ('Liechtenstein', 205, 160, 32842), ('Italy', 192, 301230, 59715625), ('Switzerland', 177, 41290, 7301994), ('Luxembourg', 173, 2586, 512000), ('France', 111, 547030, 63601002), ('Austria', 97, 83858, 8169929), ('Greece', 81, 131940, 11606813), ('Ireland', 65, 70280, 4581269), ('Sweden', 20, 449964, 9515744), ('Finland', 16, 338424, 5410233), ('Norway', 13, 385252, 5033675)], dtype=dt) print(x[:4]) print(x['density']) print(x['country']) print(x['area'][2:5]) # example1: # defining the user defined data type time_type = np.dtype(np.dtype([('time', [('h', int), ('min', int), ('sec', int)]), ('temperature', float)])) times = np.array([((2, 42, 17), 20.8), ((13, 19, 3), 23.2)], dtype=time_type) print(times) print(times['time']) print(times['time']['h']) print(times['temperature'])
true
8b57cdcbba3d3c0f7d0203ec3be8e29167c11a8d
Helianus/Python-Exercises
/src/SumOfNumbers.py
452
4.25
4
#Given two integers a and b, which can be positive or negative, # find the sum of all the numbers between including them too and return it. # If the two numbers are equal return a or b. # Note: a and b are not ordered! def get_sum(a, b): sum = 0 if a == b: return a elif a > b: for i in range(b, a+1): sum += i else: for i in range(a, b+1): sum += i return sum print(get_sum(0, 5))
true
0dd8bda64e43cea077ab8a390b1f58b1fe75d101
Helianus/Python-Exercises
/src/PairRoot.py
238
4.15625
4
# 0 < pwr < 6 and root^pwr = user input n = int(input("Enter an integer: ")) root, pwd = 0, 0 while root <= n: pwd += 1 if pwd == 6: pwd = 1 root += 1 if root ** pwd == n: print(root, "^", pwd, "is", n)
false
11ef074543b310af32ce9d0b43a2a23111422650
mor16fsu/bch5884
/tempconversion.py
286
4.25
4
#!/usr/bin/env python3 #github.com/mor16fsu/bch5884 import math x=float(input("Please enter a value in degrees Farenheit to convert to degrees Kelvin:")) print (type (x)) x=float(x) y=math.floor(x-32)*5/9+273.15 print (y) print ("The calculation is complete: Degrees Kelvin")
true
6db4d82f13ebcf3bb99365d2b8af9ff458ca5961
puhelan/150
/1. DS/1.1.py
1,364
4.3125
4
''' 1.1 _______________________________________________________________________________ Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures? _______________________________________________________________________________ Notes: 1. with hash map 2. nxn 3. sort and copmare time complexity, memory O(n) = _______________________________________________________________________________ ''' def all_unique_characters(string): alphabet = {} for char in string: if char in alphabet: alphabet[char] += 1 else: alphabet[char] = 1 for x in alphabet.values(): if x > 1: return False return True def all_unique_characters2(string): for char in string: if string.count(char) > 1: return False return True def all_unique_characters3(string): string = ''.join(sorted(string)) for i, char in enumerate(string[:-1]): if char == string[i + 1]: return False return True if __name__ == '__main__': strings = ['az obicham mach i boza', 'superb', 'Kakv0 st@va?', 'уникат', 'уникатт' ] print(strings) print('\n 1. with hash map') print([* map(all_unique_characters, strings)]) print('\n 2. nxn') print([* map(all_unique_characters2, strings)]) print('\n 3. sort and copmare') print([* map(all_unique_characters3, strings)])
true
cdacc8f0adeea4aab139c8bb9d714415fc294c9a
BryceBoley/PythonExercises
/Exercise_2.py
1,059
4.28125
4
# getting user input and checking that it is a number and not zero gas = input("\nWelcome to the fun conversion tool!\n\nPlease enter a number to represent gallons of gasoline: ") while not gas.isdigit() or int(gas) == 0: gas = input("A number you numskull, not a letter or zero!\nEnter your number") # math for conversions gas = float(gas) liter = gas * 3.7854 oil = gas / 19.5 co2 = gas * 20 etoh = (gas * 115000)/75700 cost = gas * 4.00 # print converted values to user using string formatting print("_" * 80 + "\n" + "Original number of gallons is %.1f" % gas) print("_" * 80 + "\n" + "%.1f gallons is the equivalent of %.1f liters" % (gas, liter)) print("%.1f gallons of gasoline requires %.1f barrels of oil" % (gas, oil)) print("%.1f gallons of gasoline produces %.1f pounds of CO2" % (gas, co2)) print("%.1f gallons of gasoline is energy equivalent to %.3f gallons of ethanol" % (gas, etoh)) print("%.1f gallons of gasoline requires %.2f US dollars" % (gas, gas * 4.00)) print("_" * 80 + "\n" + "Thanks for tyring the amazing conversion tool!")
true
c93dc777cf687fa36d79db956d9cf9292eaff5f8
pphubgit/python-2110101
/clique-clip-lecture/final/52-get-key-value-item-from-dicy.py
440
4.3125
4
#key value item in python s.keys() #--> คืน list ของ key ออกมา s.values()#--> list ของ values ออกมา s.items() #--> list ของ [(key,value),(key2,value2)] ออกมา #ประโยชน์ for key in s.keys(): # ถ้าไม่ได้ใส่ เป็น for a in s เหมือน for a in s.keys() print(key) for (k,v) in s.items(): print('key=',k,'value=',v)
false
1429b690d10a055ef3dfcdb7fd855470b5c4a310
Teldrin89/DBPythonTut
/LtP11_custom_exception.py
991
4.15625
4
# it is possible to create a custom exception - it has to be # inherited from the exception class # create a new class for handling custom made exception - use # inheritance of exception build in class class DogNameError(Exception): # initialize the class with init function def __init__(self, *args, **kwargs): # use exception method to initialize Exception.__init__(self, *args, **kwargs) # the try block contains the input from user try: # ask for dog name dogName = input("What is your dogs name: ") # check if in any of the characters for dog name is a digit # using both if statement and for loop inside if any(char.isdigit() for char in dogName): # if there is a digit raise an exception and call # for custom exception created raise DogNameError # exception handling block with custom exception to execute except DogNameError: # printout the error message print("Your dogs name can't contain a number")
true
50b4bc46338d0e7ff766988ea9ed05f565aaa7a0
Teldrin89/DBPythonTut
/Problem_23.py
1,445
4.28125
4
import re # Problem 23: # Use regular expressions to match email addresses # from the list with set rules for what is an email # address (just find how many there are): # 1. 1 to 20 lowercase and uppercase letters, numbers, # plus ._%+- symbols # 2. An @ symbol # 3. 2 to 20 lower case and uppercase letters, numbers # plus .- symbols # 4. A period # 5. 2 to 3 lowercase and uppercase letters # create a dummy list of emails, not all following the rules emailList = "db@aol.com me@.com @apple.com db@.com" # email = "db@.com" # printout how many of email addresses there are that follow # the rules using re.findall - specified characters in [] # brackets and number of characters in {} brackets print("Email Matches: ", len(re.findall("[\w._%+-]{2,20}@" "[\w.-]{2,20}." "[A-Za-z]{2,3}", emailList))) # some additional solution - mine - printout the email address # that fulfills the criteria # first, split string with all addresses and create a list listOfEmails = emailList.split() # run for loop by all email addresses from the list for email in listOfEmails: # use re.search function with the same set of criteria if re.search("[\w._%+-]{2,20}@" "[\w.-]{2,20}." "[A-Za-z]{2,3}", email): # printout email address if criteria are met print("Email: ", email)
true
21c8f84e8b76eff91026f0c155d2a552952b8edb
Teldrin89/DBPythonTut
/LtP13_list_comprehension.py
1,970
4.8125
5
# list comprehension is going to execute an expression # against an iterable - much as "map" and "filter" # while a list comprehension is powerful it has to be used # with cautious to not get overcomplicated # use different methods to obtain the same list # of values: multiplication by 2 using map and lc # a) map print(list(map((lambda x: x*2), range(1,11)))) # b) list comprehension - it is stored in [] brackets # and automatically generates a list (therefore no need # to specify list in expression) print([2 * x for x in range(1, 11)]) # use different methods to obtain the same list # of values: only odds using filter and lc # a) filter - get only odd values print(list(filter((lambda x: x % 2 != 0), range(1, 11)))) # b) list comprehension - use the same expression but # put it in "if" statement inside "for" loop print([x for x in range(1, 11) if x % 2 != 0]) # more complicated example - generate 50 values and take # to the power of 2; then return only multiples of 8 print([i ** 2 for i in range(50) if i % 8 == 0]) # it is also allowed to use multiple "for" loops inside # list comprehension method - prepare a script that # generates a list of 2 other lists multiplied by one # another print([x*y for x in range(1, 3) for y in range(11, 16)]) # it is possible to put list comprehension inside other # list comprehension (lc), example: generate a list of 10 # values, multiply them by 2 and return multiples of 8 print([x for x in [i * 2 for i in range(10)] if x % 8 == 0]) # list comprehension in work with multidimensional lists multi_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # printout the second character from each of inner lists # from multidimensional list print([col[1] for col in multi_list]) # printout diagonal from multidimensional list - this # calls out for the place in array using 2 of the same # values ("[i][i]", hence we get diagonal print([multi_list[i][i] for i in range(len(multi_list))])
true
bc22d61afc37ca167a7550f922397c394f9c4d9a
Teldrin89/DBPythonTut
/Problem17.py
1,317
4.375
4
# Problem 17: # - create a file named "mydata2.txt" - put any type of data # - use methods from LtP8 how to open a file without "with" # (open in "try" block) # - catch FileNotFoundError # - in "else" print contents of the file # - in finally print out some msg that will always be on screen # - try to open nonexistent file mydata3.txt - test # create a try block try: # inside open file using built in method open, by default # it is set to read, remember about encoding format my_file = open("mydata2.txt", encoding="utf-8") # create an except block for handling error - in particular # the error which will handle the missing of file # define the error as variable "ex" except FileNotFoundError as ex: # printout msg in case of an exception print("That file was not found") # printout additional information about the exception print(ex.args) # create an else block - in case it finds the set file else: # printout the information from text file - read function # of assigned variable for the file open method print("File: ", my_file.read()) # close the file my_file.close() # create a "finally" block finally: # printout the massage that will be shown regardless if # the file has been found or not print("Finished working with exception handling")
true
58684c61c8d6dcecc16fb15542f46ef9a6dcffe0
Teldrin89/DBPythonTut
/LtP14_threads_example.py
2,750
4.40625
4
# example of threads usage: whenever threads are used # it is possible to block one of the threads - the # real world script that can utilize this option # will cover a modeling of bank account: let's say # that there is 100$ in the account but there are 3 # different people that can withdraw money from that # account, the script will block the possibility # of withdrawing money from the account while # one of the person is taking the money at a time import threading import time import random # create a class for bank account with threads class BankAccount(threading.Thread): # static variable accountBalance = 100 # initialize a thread with name and amount of # money requested def __init__(self, name, moneyRequest): threading.Thread.__init__(self) # assign name of person that want to # withdraw money self.name = name # get the amount of money to be withdrawn self.moneyRequest = moneyRequest # run property definition def run(self): # create locking property - not to be able # to acquire the money from other threads threadLock.acquire() # access to get the money from account BankAccount.getMoney(self) # release the lock for a thread after first # withdraw to work threadLock.release() # create a static method for getting money @staticmethod def getMoney(customer): # printout the msg about who, how much and # when wants to withdraw money from account print("{} tries to withdraw {}$ at" "{}".format(customer.name, customer.moneyRequest, time.strftime("%H:%M:%S", time.gmtime()))) # what to do in case of enough money in account if BankAccount.accountBalance - customer.moneyRequest > 0: BankAccount.accountBalance -= customer.moneyRequest print("New account balance: " "{}$".format(BankAccount.accountBalance)) # what to do in case there is not enough money else: print("Not enough money in account") print("Current balance: " "{}$".format(BankAccount.accountBalance)) # time to sleep after execution - needed to see the # difference in execution of next threads time.sleep(3) # thread lock method assigned threadLock = threading.Lock() # 3 people wants to take specific amount of money luke = BankAccount("Luke", 1) john = BankAccount("John", 100) jean = BankAccount("Jean", 50) # start all threads luke.start() john.start() jean.start() # join all threads luke.join() john.join() jean.join() # end printout msg print("Execution Ends")
true
56ecd290945ebaceecad8e9ea69386558474eb74
Teldrin89/DBPythonTut
/LtP1.py
999
4.25
4
# Ask the user to input their name and assign # it to a variable named name name = input('What is your name ') # Print out hello followed by the name they entered print('Hello ', name) # Ask the user to input 2 values and store them in variables # num1 and num2 num1, num2 = input('Enter 2 numbers: ').split() # Convert the strings into regular numbers num1 = int(num1) num2 = int(num2) # Add the values entered and store in sum summ = num1 + num2 # Subtract values and store in difference difference = num1 - num2 # Multiply values and store in product product = num1 * num2 # Divide values and store in quotient quotient = num1 / num2 # Use modulus on the values to find the remainder remainder = num1 % num2 # Print results print("{} + {} = {}".format(num1, num2, summ)) print("{} - {} = {}".format(num1, num2, difference)) print("{} * {} = {}".format(num1, num2, product)) print("{} / {} = {}".format(num1, num2, quotient)) print("{} % {} = {}".format(num1, num2, remainder))
true
45f2072b3cf0ab1858f85048ebf2c1672e904e6c
Teldrin89/DBPythonTut
/LtP6_lists.py
1,900
4.21875
4
import random import math # list generated similar as to in problem 11 num_list = [] for i in range(5): num_list.append(random.randrange(1, 10)) # sorting list num_list.sort() # reverse sorting num_list.reverse() # change value at specific index -in this example it inserts # number "10" at index 5 num_list.insert(5, 10) # remove item from list num_list.remove(10) # remove item at specific index num_list.pop(2) for k in num_list: print(k, end=", ") print() # list comprehensions - a way to create a list by doing operations # on each item in a list # this will generate list of 10 items, each multiplied by 2 even_list = [i*2 for i in range(10)] # printout the resulting list for i in even_list: print(i) # Create a list of lists with the same method (using multiple # different calculations) # List of 5 items numberList = [1,2,3,4,5] # List of 5 lists with 3 items in each (to the power of 2,3 and 4) listOfValues = [[math.pow(m, 2), math.pow(m,3), math.pow(m, 4)] for m in numberList] # printout results for i in listOfValues: print(i) print() # create 10x10 list of lists - this one is populated by "0" multiDlist = [[0] * 10 for i in range(10)] for i in multiDlist: print(i) print() # change values in the list multiDlist[0][1] = 10 for i in multiDlist: print(i) print() # Specific indexes for 2D matrix (list of lists) # Establish "empty" (filled with "0") list of lists - 4x4 listTable = [[0]*4 for i in range(4)] # for loops going through 2 dimensions of matrix (call them "x" # and "y") and store the indexes in each value separated by "|" for i in range(4): for j in range(4): listTable[i][j] = "{} : {}".format(i, j) # printout the results - each value and each row in new line for i in range(4): for j in range(4): print(listTable[i][j], end=" | ") print() # printout full list of lists print(listTable)
true
33ba04c4c59b0e51ef8f8e5acd62f2cffb9e05bb
AricA05/Python_OOP
/encapsulation.py
1,480
4.34375
4
#4.Encapsulation '''It is the concept of wrapping data such that the outer world has access only to exposed properties. Some properties can be hidden to reduce vulnerability. This is an implementation of data hiding. For example, you want buy a pair of trousers from an online site. The data that you want is its cost and availability. The number of items present and their location is information that you are not bothered about. Hence it is hidden. In Python this is implemented by creating private, protected and public instance variables and methods. Private properties have double underscore (__) in the start, while protected properties have single underscore (_). By default, all other variable and methods are public. Private properties are accessible from within the class only and are not available for child class(if inherited). Protected properties are accessible from within the class but are available to child class as well. All these restrictions are removed for public properties. The following code snippets is an example of this concept:''' class Person: def __init__(self, name, age): self.name = name self.age = age def _protected_method(self): print("protected method") def __private_method(self): print("privated method") if __name__ == "__main__": p = Person("mohan", 23) p._protected_method() # shows a warning p.__private_method() # throws Attribute error saying no such method exists
true
f7c22e308aa4f6903129e8b7d76842ff5c830e14
dansackett/learning-playground
/project-euler/problem_1.py
321
4.25
4
#!/usr/bin/python """ Multiples of 3 and 5 Problem 1 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. """ limit = 1000 print sum(x for x in xrange(limit) if not x % 3 or not x % 5)
true
d01b142a983b9c682f5412d7c504b642fd847cd3
adimukh1234/python_projects
/hangman1.py
871
4.125
4
import random name = input("What is your name?\n") print("Hello ", name) print("Welcome to the Hangman Game \nBest of luck") words = ["balloon", "hook", "octopus", "communication", "piano", "honey", "playstation"] guesses = '' word = random.choice(words) print("Guess the characters!") turns = 6 # main loop of game while turns > 0: failed = 0 for char in word: if char in guesses: print(char) else: print("_") failed += 1 if failed == 0: print("You win") print("The word is ", word) break # taking user input guess = input("guess any letter: ") guesses += guess if guess not in word: turns -= 1 print("wrong") print(f"You have {turns} turns left") if turns == 0: print("You Lose")
true
ca8a612e654795d55625e199997945549b713a1c
untalinfo/holbertonschool-web_back_end
/0x00-python_variable_annotations/3-to_str.py
296
4.34375
4
#!/usr/bin/env python3 """ Basic annotations - to string """ def to_str(n: float) -> str: """takes a float n as argument and returns the string representation of the float Args: n (float): number Returns: str: convert float to string """ return str(n)
true
a16d910dad34c229805ed9875e638a077216b788
StarTux/DailyCodingProblem
/003-2019-03-07-TreeSerialize.py
1,154
4.125
4
#!/usr/bin/python3 # Problem #3 [Medium] # Given the root to a binary tree, implement serialize(root), # which serializes the tree into a string, and deserialize(s), # which deserializes the string back into the tree. # # For example, given the following Node class class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right DELIM = '|' def serialize(node): result = node.val + DELIM if node.left is not None: result += serialize(node.left) result += DELIM if node.right is not None: result += serialize(node.right) return result def deserialize(str): toks = str.split(DELIM) return deserializeHelper(toks, 0) def deserializeHelper(toks, index): val = toks[index] if len(val) == 0: return None left = deserializeHelper(toks, index + 1) right = deserializeHelper(toks, index + 2) return Node(val, left, right) # The following test should pass: node = Node('root', Node('left', Node('left.left')), Node('right')) assert deserialize(serialize(node)).left.left.val == 'left.left' print(serialize(node))
true
0aebab530dfa54a10e1d98bd2ba6ad0458f85b2b
jp117/codesignal
/Arcade/Intro/010 - commonCharacterCount.py
804
4.125
4
''' https://app.codesignal.com/arcade/intro/level-3/JKKuHJknZNj4YGL32 Given two strings, find the number of common characters between them. Example For s1 = "aabcc" and s2 = "adcaa", the output should be commonCharacterCount(s1, s2) = 3. Strings have 3 common characters - 2 "a"s and 1 "c". Input/Output [execution time limit] 4 seconds (py3) [input] string s1 A string consisting of lowercase English letters. Guaranteed constraints: 1 ≤ s1.length < 15. [input] string s2 A string consisting of lowercase English letters. Guaranteed constraints: 1 ≤ s2.length < 15. [output] integer ''' def commonCharacterCount(s1, s2): count = 0 i = 0 for i in range(len(s1)): if s1[i] in s2: s2 = s2.replace(s1[i], '', 1) count += 1 return count
true
14c11a27484edf19581bca75d54f84ad101b16c0
emmanavarro/holbertonschool-machine_learning
/supervised_learning/0x04-error_analysis/1-sensitivity.py
736
4.21875
4
#!/usr/bin/env python3 """ Calculates sensitivity in a confusion matrix """ import numpy as np def sensitivity(confusion): """ Calculates the sensitivity for each class in a confusion matrix Args: - confusion: is a confusion numpy.ndarray of shape (classes, classes) where row indices represent the correct labels and column indices represent the predicted labels * classes: is the number of classes Return: A numpy.ndarray of shape (classes,) containing the sensitivity of each class """ positive = np.sum(confusion, axis=1) true_positive = np.diagonal(confusion) sensitivity = true_positive / positive return np.array(sensitivity)
true
30f5b94defb435a4bb6d98c51b865b46446ef48c
deepika-13-alt/Python-Assignment
/assignment2/second_smallest.py
1,087
4.34375
4
''' Program: WAP to input 3 numbers and find the second smallest. ''' import re # Declarations regex_float = '[+-]?[0-9]+\.[0-9]+' regex_int = "[-+]?[0-9]+$" small_list = [] small_1 = 0 small_2 = 0 # Taking input from users print("Enter 3 numbers for finding smallest among them") for i in range(3): inp = input("Enter any number to insert: ") if re.search(regex_float, inp): inp = float(inp) small_list.append(inp) elif re.search(regex_int, inp): inp = int(inp) small_list.append(inp) else: print("Invalid data entered!") break # Processing data if len(small_list) == 3: for item in small_list[1:]: if item < small_1: small_2 = small_1 small_1 = item elif small_2 == 0 or small_2 > item: small_2 = item # Display output print("The entered elements are: ", end=" ") for item in small_list: print(item, end=" ") print(f"and, the second smallest number is: {small_2}") else: print("Unable to compute data! Insufficient data received!")
true
248b398e2d84d812ab7dea2614e296faeeae20cd
deepika-13-alt/Python-Assignment
/assignment5/two_list.py
305
4.125
4
''' Concatenate two lists in the following order Input: L1=[1,2]L2=[4,5] Output: L3=[(1,4),(1,5),(2,4),(2,5)] ''' l1 = [1,2] l2 = [4,5] print("Original list 1: ", l1) print("Original list 2: ", l2) l3 = [] for i in l1: for j in l2: tup = (i,j) l3.append(tup) print("Output: ", l3)
false
726db70c7cca49422f9edeefc1edf51d3b09cc1d
dbms-ops/hello-Python
/1-PythonLearning/3-Python-基础知识/10-数据结构-集合.py
2,009
4.125
4
# !/data1/Python2.7/bin/python2.7 # -*-coding:utf-8-*- # date: 2020-1-16 16:57 # user: Administrator # description: set 的常见操作 # # set: # 无序和无重复的list # 1、set的对象不能够是可变对象,字典、列表是不能够添加的,但是元组是可以的 def create_set(): # 创建set # 创建set 通过list或者tuple或者dict作为输入集合 # set 可以用于 list tuple,dict元素的去重操作 num = set([1, 2, 1, 2, 3, 4, 5]) print num, type(num) num = set((1, 2, 3, 23, 41, 2, 4, 1, 5, 1, 2)) print num, type(num) def add_element(): # 添加元素 num = set((1, 2, 3, 23, 41, 2, 4, 1, 5, 1, 2)) num.add(4) # 添加重复元素是没有效果的 num.add(6) print num def add_list(): # 添加列表 num = set((1, 2, 3, 23, 41, 2, 4, 1, 5, 1, 2)) num.add([1, 2, 3, 4]) def add_dict(): # # 添加字典 num = set((1, 2, 3, 23, 41, 2, 4, 1, 5, 1, 2)) num.add({'name': 1, 'sex': 'f'}) print num def add_tuple(): # 添加元组 num = set((1, 2, 3, 23, 41, 2, 4, 1, 5, 1, 2)) num.add((8, 9, 0)) print num def add_list_tuple_string(): # 插入list、tuple、string num = set((1, 2, 3, 23, 41, 2, 4, 1, 5, 1, 2)) num.update([1, 2, 3, 4, 5]) print num num.update((9, 10)) num.update('string') print num def delete_element(): # 删除 num = set((1, 2, 3, 23, 41, 2, 4, 1, 5, 1, 2, 'i', 'r')) num.remove('i') num.remove('r') print num def Traversal_element(): # 循环遍历存取元素 num = set((1, 2, 3, 23, 41, 2, 4, 1, 5, 1, 2, 'i', 'r')) for index, data in enumerate(num): print index, data def Intersection_set(): # set之间的运算 # 交集 num1 = {1, 2, 3, 4} num2 = set((4, 5, 6, 2)) print num1 & num2 print type(num1) # # set最常见的用法是进行数据去重操作 def main(): Traversal_element() if __name__ == '__main__': main()
false
973d55a382f5a2c127655e4f672f6b7c2743ee1c
dbms-ops/hello-Python
/1-PythonLearning/7-面向对象/7-多继承.py
1,104
4.40625
4
# coding=utf-8 # # # !/data1/Python2.7/bin/python27 # # # 多继承:表示子类继承自多个父类 # Father <<<------- Child # Mother <<<------- Child # 声明 Fahter class Father(object): def __init__(self, pocket): self.pocket = pocket def play(self): print "play son" def func(self): print "func" # 声明母类 class Mother(object): def __init__(self, food): self.food = food def eat(self): print "eat" def func(self): print "func2" # Child 继承两个父类:Father,Mother class Child(Father, Mother): # 多继承的初始化,分别调用两个父类的初始化函数来完成子类的初始化 def __init__(self, pocket, food): Father.__init__(self, pocket) Mother.__init__(self, food) def main(): tom = Child(1000, "orange") print tom.pocket print tom.food # 父类中的方法名相同,默认调用的是在括号中排前面的父类中的方法 # tom.func()调用的是Father的func方法 tom.func() if __name__ == "__main__": main()
false
e0bca1e1bf571a39dad643ccd0485b6be44fa473
ZamoraAlexey/hillel_lessons
/lesson7.py
1,123
4.1875
4
def calculate_of_numbers(): first_number = int(input('Enter your first number: ')) second_number = int(input('Enter your second number: ')) choice_function = input('Choice your function (+, -, /, //, *, **, %): ') if choice_function == '+': print(f'{first_number} + {second_number} =', first_number + second_number) elif choice_function == '-': print(f'{first_number} - {second_number} =', first_number - second_number) elif choice_function == '**': print(f'{first_number} ** {second_number} =', first_number ** second_number) elif choice_function == '*': print(f'{first_number} * {second_number} =', first_number * second_number) elif choice_function == '//': print(f'{first_number} // {second_number} =', first_number // second_number) elif choice_function == '/': print(f'{first_number} / {second_number} =', first_number / second_number) elif choice_function == '%': print(f'{first_number} % {second_number} =', first_number % second_number) else: print('Invalid enter or function!') calculate_of_numbers()
false
9ea111f75ba5c9ceb956b78c3ac9f70fdf69540d
tachyonlabs/raspberry_pi_pyladies_presentation
/hello_world_blink.py
1,566
4.28125
4
# See https://github.com/tachyonlabs/raspberry_pi_pyladies_presentation # for information on the wiring and the presentation in general # The Rpi.GPIO library makes it easy for your programs to read from and write to # the Raspberry Pi's GPIO (General Purpose Input/Output) pins import RPi.GPIO as GPIO import time # GPIO.BCM mode selects the pin numbering system of GPIO pin channels # as opposed to GPIO.BOARD mode which uses P1 connector pin numbers GPIO.setmode(GPIO.BCM) # Any Raspberry Pi pin you use needs to be set as either an input or an output # Here we are setting pin GPIO 20 as an output to control the LED (I didn't choose # GPIO pin 20 for any particular reason - you can use whichever GPIO pin or pins # you like so long as you use the same pins in your circuit and your software) led_pin = 20 GPIO.setup(led_pin, GPIO.OUT) # Blink the LED twenty times, with a frequency of one second on, one second off number_of_times_to_blink = 20 number_of_seconds = 1 for i in range(number_of_times_to_blink): # Output high (3.3 volts) on pin 20, to turn the LED on GPIO.output(led_pin, GPIO.HIGH) # Leave the LED on for one second time.sleep(number_of_seconds) # Output low (0 volts) on pin 20, to turn the LED off GPIO.output(led_pin, GPIO.LOW) # Leave the LED off for one second time.sleep(number_of_seconds) # This resets any ports used in your program GPIO.cleanup() # Why not? :-) print("Hello World!") # This will print some general info about your Raspberry Pi print("Raspberry Pi stats: {}".format(GPIO.RPI_INFO))
true
f4a1d0b9f4725cbb845088e97bf460d1931dc301
mdeakyne/IT150
/Blank Class Activities/0119Blank.py
2,694
4.90625
5
""" This assignment is worth 10 points and you should be able to answer the following questions after completing it: What is the difference between a variable and a literal? How do you assign variables in python? How do you deal with errors in python? What are different types of python variables? How do you make a multiline comment? How do you handle exponents in python? What does % do in python? """ print "\nProblem 1----------------Errors-----------------------------" #In this lab, you will deal with many errors. IndentErrors and NameErrors are the most common. #Many times, it's because you've mispelled a variable you did define. #Below there are three errors for you to deal with. Do not delete any lines, just add to the below code. #You may edit the names of variables. print "The variable name contains",name def printName(): name = "Deakyne" print "The variable name contains",name printName() print "The variable name contains",nmae print "\nProblem 2----------------Comments--------------------------" #These are all comments. Make this into a comment Instead Of Commenting Out Every Line Here You Can Quickly Comment Multiple Lines. Please Do So. print "Done with comments" print "\nProblem 3----------------Literals vs. Variables---------------" "This is a literal" # a literal is anything that only has one value. variable = "This is a variable" # a variable can have many values, and can be reassigned. variable = "Something different" # our variable has been reassigned a new value. #below we have a variable named a and a literal 'b'. Add another variable b, and give it any value a = 'b' print "The variable a contains",a print "The variable b contains",b print "The literal a prints as",'a' print "The literal b prints as",'b' print "\nProblem 4-----------------Types-----------------------------" #We will be introducing more types later in the course. Here are four variables, have python print the types #As a reminder, you can use the type function. I'll refresh your memory. f = 3.14 i = 7 s = "Hello there" b = False print "The type of printName is",type(printName) print "The type of f is",type() #fill in these with the appropriate variable, following the example above print "The type of i is",type() print "The type of s is",type() print "The type of b is",type() print "\nProblem 5------------------Math----------------------------" #Codecademy introduced *, +, -, /, ** and % #Use them to figure out the following, and print the result print "3243 + 23424 =", print "10^2", #did you use python syntax? print "10 / 6=", #double check this one, why is there no remainder? print "10 % 6=", #Oh, that's where the remainder went.
true
5108d71e4a691970e833836e65983895f2325fb5
shubhangisiddhapure/DSA_hypervergeq
/step 5/interunion.py
777
4.25
4
# Find the union and intersection of two sorted arrays. def union(list1,list2,len1,len2): union1=[] for i in range(len1): if list1[i] not in union1: union1.append(list1[i]) for j in range(len2): if list2[j] not in union1: union1.append(list2[j]) print(union1) def intersection(list1,list2,len1,len2): for i in range(len2): if list2[i] in list1: print(list2[i]) list1_size=int(input("enter the size of list")) list1=[int(input("enter the elelen1ent ")) for each in range( list1_size)] list2_size=int(input("enter the size of list")) list2=[int(input("enter the elelen1ent ")) for each in range( list2_size)] union(list1,list2,list1_size,list2_size) intersection(list1,list2,list1_size,list2_size)
false
f5e89265b44ab3fc30230ea0a692a23fd91d30b9
shubhangisiddhapure/DSA_hypervergeq
/step 5/leftshift.py
598
4.125
4
def leftshift(arr1,m,n): dictionary={} for i in range(m): key=m+i-n if key < m: dictionary[key]=arr1[i] elif key>=m: dictionary[key-m]=arr1[i] len2=len(dictionary) for j in range(m): arr1[j]=dictionary[j] return print("left shift ",arr1) len1=int (input("enter the size of array 1")) arr1=[int(input(" enter the elements of array")) for each in range(len1)] num=int(input("enter the no by which you want to shift the array elements")) arr2=arr1.copy() print(arr1) arr1.reverse() print(arr1) leftshift(arr1,len1,num)
false
8b0222d0314beb0a3ceb76d601ff1dd7803b8834
jazywica/Computing
/_01_Interactive_Programming_1/_01_Rock-paper-scissors-lizard-Spock.py
2,086
4.3125
4
""" ROCK-PAPER-SCISSORS-LIZARD-SPOCK - simple game: player vs random computer choice """ # use following link to test the program in 'codeskulptor': http://www.codeskulptor.org/#user45_uPVHROOe6b_2.py # The key idea of this program is to equate the strings "rock", "paper", "scissors", "lizard", "Spock" to numbers as follows: # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors import random def name_to_number(name): # this is a helper function that will convert between NAMES and NUMBERS if name == "rock": return 0 elif name == "Spock": return 1 elif name == "paper": return 2 elif name == "lizard": return 3 elif name == "scissors": return 4 else: return "Illegal name" def number_to_name(number): if number == 0: return "rock" elif number == 1: return "Spock" elif number == 2: return "paper" elif number == 3: return "lizard" elif number == 4: return "scissors" else: return "Illegal number" def rpsls(player_choice): player_number = name_to_number(player_choice) computer_number = random.randrange(0, 5) computer_choice = number_to_name(computer_number) print print "Player choose " + player_choice print "Computer choose " + computer_choice difference = (player_number - computer_number) % 5 # first - second = difference, which we then take modulo 5(total amount of elements) so we only have numbrs 0, 1, 2, 3, 4 if difference == 1 or difference == 2: # we have designed the 'wheel' in a way that two elements to the right are win and two to the left is loose... print "Player wins!" elif difference == 3 or difference == 4: # so it is easy to split it into 1,2 and 3,4 print "Computer wins!" else: print "Player and computer tie!" # test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE rpsls("rock") rpsls("Spock") rpsls("paper") rpsls("lizard") rpsls("scissors")
true
6658a147827c0582c57c8c2cfb644a1342ef51ef
arnaudmiribel/streamlit-extras
/src/streamlit_extras/word_importances/__init__.py
2,050
4.15625
4
from typing import List import streamlit as st from .. import extra @extra def format_word_importances(words: List[str], importances: List[float]) -> str: """Adds a background color to each word based on its importance (float from -1 to 1) Args: words (list): List of words importances (list): List of importances (scores from -1 to 1) Returns: html: HTML string with formatted word """ if importances is None or len(importances) == 0: return "<td></td>" assert len(words) == len(importances), "Words and importances but be of same length" tags = ["<td>"] for word, importance in zip(words, importances[: len(words)]): color = _get_color(importance) unwrapped_tag = ( '<mark style="background-color: {color}; opacity:1.0; ' ' line-height:1.75"><font color="black"> {word} ' " </font></mark>".format(color=color, word=word) ) tags.append(unwrapped_tag) tags.append("</td>") html = "".join(tags) return html def _get_color(importance: float) -> str: # clip values to prevent CSS errors (Values should be from [-1,1]) importance = max(-1, min(1, importance)) if importance > 0: hue = 120 sat = 75 lig = 100 - int(50 * importance) else: hue = 0 sat = 75 lig = 100 - int(-40 * importance) return "hsl({}, {}%, {}%)".format(hue, sat, lig) def example(): text = ( "Streamlit Extras is a library to help you discover, learn, share and" " use Streamlit bits of code!" ) html = format_word_importances( words=text.split(), importances=(0.1, 0.2, 0, -1, 0.1, 0, 0, 0.2, 0.3, 0.8, 0.9, 0.6, 0.3, 0.1, 0, 0, 0), # fmt: skip ) st.write(html, unsafe_allow_html=True) __title__ = "Word importances" __desc__ = "Highlight words based on their importances. Inspired from captum library." __icon__ = "❗" __examples__ = [example] __author__ = "Arnaud Miribel"
true
d9760fcbe2c615552887a271c707beb0bc7018b3
sonyarpita/ptrain
/function_recursive.py
260
4.53125
5
def calc_factorial(x): """This is recursive function to find the factorial of an integer""" # return(x*calc_factorial(x-1)) if x == 1: return 1 else: return (x*calc_factorial(x-1)) num=5 fact=calc_factorial(num) print("Factorial of",num,"=",fact)
true
662ed97b3d686b28c2345a53425b37ffd871055d
sonyarpita/ptrain
/ReModule/Metacharacters/alternation.py
222
4.34375
4
import re str = "The stays rain in Spain maui falls mainly in the plain!" #Check if the string contains "falls" or "stays" x=re.findall("falls|stays",str) print(x) if (x): print("match") else: print("No Match")
true
8f167f28002b91f926c295843a0131fa194c04b9
sonyarpita/ptrain
/Advanced_Functions/unzip_1.py
570
4.25
4
#Python code to demonstrate zip() #initialize lists name=["Sony","Arpita", "Das","Susmita"] roll_no=[4,3,6,7] marks=[90,98,89,99] #using zip() to map values mapped=zip(name,roll_no,marks) #converting values to print as set mapped=list(mapped) #printing result values print("Zipped result is: ",end=" ") print(mapped) print("\n") #unzip namez,roll_noz,marksz=zip(*mapped) print("Unzipped results: \n",end=" ") #print initial list print("Name list= ",end=" ") print(namez) print("Roll Number list= ",end=" ") print(roll_noz) print("Marks list= ",end=" ") print(marksz)
true
f63386a5b3cb3c829f318691f3e87fb878d4a56a
sonyarpita/ptrain
/ReModule/Metacharacters/Period.py
235
4.125
4
import re str = "hello world helo" # search for a sequence that starts with "he", followed by two (any)characters, and an "o" x=re.findall("he..o", str) print(x) x=re.findall("he...o", str) print(x) x=re.findall("he.o", str) print(x)
true
3a9d2e9ddcb4ded42e2df4130db0cb1b87e5cf35
sonyarpita/ptrain
/Advanced_Functions/zip_1.py
317
4.28125
4
#Python code to demonstrate zip() #initialize lists name=["Sony","Arpita", "Das","Susmita"] roll_no=[4,3,6,7] marks=[90,98,89,99] #using zip() to map values mapped=zip(name,roll_no,marks) #converting values to print as set mapped=list(mapped) #printing result values print("Zipped result is: ",end=" ") print(mapped)
true
4a709ced79a10b6617a2250456839a61b374f3c8
bezzzon/python-basics
/home_work1/task5.py
1,370
4.125
4
""" - Запросите у пользователя значения выручки и издержек фирмы. - Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). - Выведите соответствующее сообщение. - Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). - Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника. """ debit = float(input("Please input company's debit balance: ")) credit = float(input("Please input company's credit balance: ")) if debit > credit: print('Company works with profit') profitability = (debit - credit) / debit employees = int(input("Please input number of the company's employees: ")) print(f'Profitability is: {profitability * 100}%\nThe profit per one employee: {(debit - credit) / employees}') elif debit < credit: print('Company works with loss') else: print('Company works without either profit or loss')
false
1d406ac301ee070563197fb69a6f7d9c7702b6f5
bezzzon/python-basics
/home_work5/task3.py
956
4.21875
4
""" Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников. """ threshold_amount = 20000 def get_salary(record): return float(record.split('***')[1]) def get_name(record): return record.split('***')[0] with open('task3.txt', 'r', encoding='utf-8') as f: content = f.readlines() for employee in content: if get_salary(employee) <= threshold_amount: print(get_name(employee), 'has the salary less than', threshold_amount) print(f'The average salary is: {sum(list(map(get_salary, content))) / len(content):.2f}')
false
fa584d09f53a69bc362b3c614455df709e181ed4
bezzzon/python-basics
/home_work2/task2.py
1,953
4.34375
4
""" Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). """ arr = [] while True: el = input('Please input some array element: ') # по команде stop прерываем заполнение списка if el != "stop": arr.append(el) else: break arr_even = arr[::2] # получаем список с четными элементами базового списка arr_odd = arr[1::2] # получаем список с нечетными элементами базового списка new_arr = [] # новый список для добавления элементов с измененным порядком i = 0 # переменная-индекс # цикл ограничен количеством замен. Так как замены парные, то замен в 2 раза меньше, # чем количество элементов базового списка. while i < len(arr) // 2: new_arr.append(arr_odd[i]) # сначала добавляем элемент из списка с четными new_arr.append(arr_even[i]) # далее добавляем элемент из списка с нечетными i += 1 # если количество элементов базового списка нечетное, то последний элемент остается на своем месте if len(arr) % 2 != 0: new_arr.append(arr_even[-1]) print(f'Initial array: {arr}') print(f'Formatted array: {new_arr}')
false
4398675df657c5a010f5af7f2400a99a29086809
olijng7/PersonalPracticeVS
/Hangman/Hangman.py
693
4.15625
4
print("Welcome to hangman! V") print('-----------------------') import getpass word = getpass.getpass("What's the word? ") for character in word: answer = word print('_ ', end='') print("") print("Ok, let's go!") print('-------') print('| |') print('|') print('|') print('|') print('|') print('-------') def guess(): letter = input('Guess a letter. ') return letter guess = guess() def findLetter(word): if guess in word: print(guess + ' is in the word!') character.find(word) if character == guess: print(guess, end='') else: print('_ ', end='') print('') guess() else: findLetter(word)
false
bb699c692c649f5a3a6a2a5df0a2ff6b598eb0f2
dubirajara/learning_python
/add_length.py
274
4.125
4
''' write a function that takes a String and returns an list with the length of each word added to each element. ''' def add_length(words): return [f'{i} {str(len(i))}' for i in words.split()] assert add_length('carrot cake') == ['carrot 6', 'cake 4'] # testcase
true
580d495c9f7cf284d7a1bea54e695168e2d29167
WayneChen1994/Python1805
/day02/作业.py
1,182
4.125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # author:Wayne.Chen ''' 闰年: year = int(input("请输入一个年份:")) if (year % 100 != 0 and year % 4 == 0) or (year % 100 == 0 and year % 400 == 0): print(str(year) + "年是闰年") else: print(str(year) + "年不是闰年") ''' ''' 水仙花数: num = int(input("请输入一个三位数:")) a = num // 100 b = num //10 % 10 c = num % 10 if a**3+b**3+c**3 == num: print(str(num)+"是水仙花数") else: print(str(num) + "不是水仙花数") ''' ''' 回文数: num = int(input("请输入一个五位数:")) A = num // 10000 B = num // 1000 % 10 b = num // 10 % 10 a = num % 10 if A==a and B==b: print(str(num)+"是回文数") else: print(str(num) + "不是回文数") ''' ''' 摇色子游戏: import random your_choice = input("押大还是押小?") result = random.choice([1,2,3,4,5,6]) print("得到的点数为:", result) if (result in [1,2,3] and your_choice=="小") or (result in [4,5,6] and your_choice=="大"): print("押中了!庄家喝酒。。。。") else: print("没押中!先干为敬。。。") '''
false
43f7d762fc70feba4edd50dc23c8f08ea6525849
aurorazl/math
/sort/单链表排序.py
2,660
4.15625
4
# 给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。 # 思想: 二分、归并排序 # 技巧:快慢指针 """ 1、判定链表中是否含有环 用两个指针,一个跑得快(每次跑两步),一个跑得慢。如果不含有环,跑得快的那个指针最终会遇到 null,说明链表不含环;如果含有环,快指针最终会超慢指针一圈,和慢指针相遇,说明链表含有环。 if (fast == slow) return true; 2.寻找链表的中点 让快指针一次前进两步,慢指针一次前进一步,当快指针到达链表尽头时,慢指针就处于链表的中间位置。 当链表的长度是奇数时,slow 恰巧停在中点位置;如果长度是偶数,slow 最终的位置是中间偏右: while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) break; } 3.寻找链表的倒数第 k 个元素 使用快慢指针,让快指针先走 k 步,然后快慢指针开始同速前进。 while (k--> 0) fast = fast.next; while (fast != null) { slow = slow.next; fast = fast.next; } 4.已知链表中含有环,返回这个环的起始位置 相遇后,slow从head开始走,hight再走,只需一起走k-m步,大家都在环起点相遇了。 slow = head; while (slow != fast) { fast = fast.next; slow = slow.next; } """ class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode: if not head or not head.next: return head # cut the LinkedList at the mid index. slow,fast = head,head.next # slow = fast = head会让偶数个的链表中点slow偏右。 while fast and fast.next: fast, slow = fast.next.next, slow.next mid, slow.next = slow.next, None # save and cut. # recursive for cutting. left, right = self.sortList(head), self.sortList(mid) # merge `left` and `right` linked list and return it. h = res = ListNode(0) while left and right: if left.val < right.val: h.next, left = left, left.next else: h.next, right = right, right.next h = h.next h.next = left if left else right # 然后将另一个没有遍历完的链表接上即可。 return res.next a = ListNode(1,ListNode(2,ListNode(3,ListNode(4,ListNode(5,ListNode(6,ListNode(7))))))) Solution().sortList(a) while a.next: print(a.val) a = a.next print(a.val)
false
66d50bc8acfe3e1a4a3997170fa10f6f00302f07
kamat-o/MasteringPython
/27_08_2019/AddTwoNumbers.py
239
4.1875
4
# get the input from user num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) #compute the addition result = num1 + num2 #print the result print ("The sum of {0} and {1} is {2}".format(num1,num2,result))
true
a65c5f2d60e78fda18111cbf5498d5855d49bfc7
hina-murdhani/python-project
/pythonProject3/demo/set.py
1,391
4.375
4
# set has no duplicate elements, mutabable set1 = set() print(set1) set1 = set("geeksforgeeks") print(set1) string = 'geeksforgeeks' set1 = set(string) print(set1) set1 = set(["geeks", "for", "geeks"]) print(set1) set1 = set(['1', '2', '3', '4']) print(set1) set1 = set([1, 2, 'geeks', 'for', 3, 3]) # add() method is use for for addign element to the set set1 = set() set1.add(8) set1.add(7) set1.add(9) set1.add((5, 8)) for i in range(1, 6): set1.add(i) print(set1) # to add morethan one elemnet update() method is useful set1 = set([ 4, 5, (6, 7)]) set1.update([10, 11]) print("\nSet after Addition of elements using Update: ") print(set1) # for accessing the element in set for i in set1: print(i, end=" ") # check for element is present or not in set print("Geeks" in set1) # remove() and discard() method use for removing element of set set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) set1.remove(5) set1.remove(6) print(set1) set1.discard(2) set1.discard(3) print(set1) # clear() is used for removing all the elements from the set set1.clear() print(set1) # pop() methos is use for removing element its remove last element and return the last element set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) print("Intial Set: ") print(set1) # Removing element from the # Set using the pop() method set1.pop() print("\nSet after popping an element: ") print(set1)
true
2f4b40b0b435a50c8a59dbb0d3d3eb93cb772e86
hina-murdhani/python-project
/pythonProject3/demo/array.py
1,710
4.3125
4
import array as arr # by importing array module we can generate the array a = arr.array('i', [1, 2, 3]) for i in range(0, 3): print(a[i]) a = arr.array('d', [1.3, 4.5, 6.7]) for i in range(0, 3): print(a[i]) # can add element in array using insert():- at any index ,method and append() method : at the end of array a = arr.array('i', [1, 3, 4]) a.insert(1, 4) for i in range(0, len(a)): print(a[i]) a.append(5) for i in range(0, len(a)): print(a[i]) # can access element using the index for array a = arr.array('i', [1, 2, 3, 4, 5, 6]) # accessing element of array print("Access element is: ", a[0]) # accessing element of array print("Access element is: ", a[3]) # remove() use to remove particular element , pop() return thee removed element , can remove element at particular index a = arr.array('i', [1, 2, 3, 1, 5]) a.pop(2) for i in range(0, len(a)): print(a[i]) a.remove(1) for i in range(0, len(a)): print(a[i]) # array slicing l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = arr.array('i', l1) slice_arr = a[3:8] print(slice_arr) slice_arr = a[5:] print(slice_arr) slice_arr = a[:] print(slice_arr) # searching the element in array using index() method a = arr.array('i', [1, 2, 3, 1, 2, 5]) print(a.index(2)) print(a.index(1)) # for updating the element in array we need to just reassign the value to that index a = arr.array('i', [1, 2, 3, 1, 2, 5]) # printing original array print("Array before updation : ", end="") for i in range(0, 6): print(a[i], end=" ") print("\r") # updating a element in a array a[2] = 6 print("Array after updation : ", end="") for i in range(0, 6): print(a[i], end=" ") print() for i in reversed(range(1, 10, 3)): print(i)
true
9dcd641e1b18997ab78e66fdde81c400eecfce7f
DahlitzFlorian/python-training-beginners
/code/solutions/solution_04.py
263
4.40625
4
# This is a possible solution for exercise_04.py word = input("Enter a word (possible palindrom): ") reversed_word = word[::-1] if word == reversed_word: print("Your submitted word is a palindrom.") else: print("Your submitted word is not a palindrom.")
true
1a020f32b2a6b3a72571371ca42c2534f816c579
mr-parikshith/Python
/S05Q02_MaxMinNumber.py
1,366
4.1875
4
""" S05Q02 - Ask the user to enter a number till he enters 0. Print the maximum and minimum values among all entered numbers. Print the number of single, two and three digit numbers entered. """ def print_CurrentMaxMin(Max, Min): print("Current Maximum Number is ", Max) print("Current Minimum Number is ", Min) def print_FinalMaxMin(Max, Min): print("Final Maximum Number is ", Max) print("Final Minimum Number is ", Min) def EnterNumber(): Number = input("Enter a Number : ") Number = int(Number) MaximumNumber = Number MinimumNumber = Number print_CurrentMaxMin(MaximumNumber, MinimumNumber) while Number != 0: Number = input("Enter a Number : ") Number = int(Number) if Number == 0: print_FinalMaxMin(MaximumNumber, MinimumNumber) break elif Number >= MaximumNumber : MaximumNumber = Number print_CurrentMaxMin(MaximumNumber, MinimumNumber) elif Number <= MinimumNumber: MinimumNumber = Number print_CurrentMaxMin(MaximumNumber, MinimumNumber) else : print_CurrentMaxMin(MaximumNumber, MinimumNumber) else: print_FinalMaxMin(MaximumNumber, MinimumNumber) # Main starts here EnterNumber()
true
1163df1cb6c0cad5800a2f74913a90e5d9bbc9d4
mr-parikshith/Python
/S08Q03_NumberAsString.py
610
4.1875
4
""" S08Q03 Ask the user to enter a number. - If the user enters a number as 5, then generate the following string : - 00001111222233334444 - If the user enters the number as 3, then generate the following string : - 001122 """ def enterNumber(): Number = int(input("Enter Number : ")) while Number != 3 or Number != 5: Number = int(input("Enter Number : ")) #continue if Number == 5: print("00001111222233334444") break elif Number == 3: print("001122") break #Enter main here enterNumber()
true
b54cf1a931e8fa7a9da186d7934fb6e54d1ac9ca
nikitatarasenko17/homework
/Lesson_2/hw_2_task_1.py
1,278
4.21875
4
# Задача №1 # Набрать все примеры посимвольно и заставить их работать, разобраться в их работе # Оператор условия if print ("Give it to me!") number = int(input()) if (number >= 100): print ("Thanks, man!) \n") elif ((number > 10) and (number < 100)): print ("OK :( \n") else: print ("WHAAAAT????") if (number > 1000): print ("!!!!WOOOOWWWW!!! \n") # Операторы сравнения и приоритеты операций x = 5 y = 10 z = 15 if ((x < y) and (y <= z)): print("OK \n") else: print("Bad \n") l1 = [1, 2, 3] l2 = [1, 2, 3] if l1 == l2: print("Yes") else: print("No") if l1 is l2: print("Yes!") else: print("No!") if l1 is not l2: print("Yes!!!") else: print("No!!!") # Альтернативный синтаксис if, замена тернарному оператору test = True result = 'Test is True' if test else 'Test is False' # result = 'Test is True' print(result) test = True print ('ttt' if test else 'fff') # выведет ttt # Еще одна альтернатива тернарному оператору test = True result_2 = test and 'Test is True' or 'Test is False' print(result_2)
false
575f17a57fbf571f6c130a71bcac51fbe3071f74
vladlemos/lets-code-python
/Aula_1/11_calculo.py
681
4.4375
4
''' Faça um programa que peça 2 números inteiros e um número real, calcule e mostre: a)o produto do dobro do primeiro com metade do segundo. b)a soma do triplo do primeiro com o terceiro. c)o terceiro elevado ao cubo. ''' primeiro_numero = int(input('digite um número inteiro: ')) segundo_numero = int(input('digite um número inteiro: ')) terceiro_numero = float(input('digite um número real: ')) print ('o produto do dobro do primeiro com metade do segundo', (primeiro_numero*2) * (segundo_numero / 2) ) print ('a soma do triplo do primeiro com o terceiro: ', (primeiro_numero * 3) + terceiro_numero) print ('o terceiro elevado ao cubo: ', terceiro_numero **3)
false
4c11ef1533db7dc7f2dfebe2239878e69d9ec9c4
mattlorme/python
/coursera/list_8.4.py
823
4.34375
4
#!/usr/bin/python2.7 # 8.4 Open the file romeo.txt and read it line by line. # For each line, split the line into a list of words # using the split() function. # The program should build a list of words. # For each word on each line # check to see if the word is already in the list # and if not append it to the list. # When the program completes, sort and print the resulting # words in alphabetical order. fname = raw_input("Enter file name: ") #if nothing is provided for fname use path /root....../mbox-t.. if len(fname) == 0: fname = '/root/Documents/Python/coursera/data/romeo.txt' fh = open(fname) lst = list() for line in fh: line = line.strip() alst = line.split() for word in alst: if word in lst: continue else: lst.append(word) lst.sort() print lst
true
1dfb0524838174c5f8e91741b8c8d9c8438b5164
GalyaBorislavova/SoftUni_Python_Advanced_May_2021
/4_Comprehensions/02. No Vowels.py
232
4.15625
4
def check_for_vowels(character: chr): if character.lower() in ['a', 'o', 'u', 'e', 'i']: return True return False text = input() no_vowels = [ch for ch in text if not check_for_vowels(ch)] print("".join(no_vowels))
false
b012df090d7ebf8145287d26c3e88410313fd42a
eantaev/problem-solving
/rec_to_iter/simple_method_factorial.py
1,060
4.1875
4
def factorial(n): if n < 2: return 1 return n * factorial(n - 1) # 1 Study the function. # 2 Convert all recursive calls into tail calls. (If you can’t, stop. Try another method.) # 3 Introduce a one-shot loop around the function body. # 4 Convert tail calls into continue statements. # 5 Tidy up. def factorial2(n, acc=1): if n < 2: return acc * 1 return factorial2(n - 1, acc * n) def factorial3(n, acc=1): while True: if n < 2: return acc * 1 return factorial3(n - 1, acc * n) break def factorial4(n, acc=1): while True: if n < 2: return acc * 1 (n, acc) = (n - 1, acc * n) def factorial5(n, acc=1): while n > 1: (n, acc) = (n - 1, acc * n) return acc def test(factorial_fn): assert factorial_fn(2) == 2 assert factorial_fn(1) == 1 assert factorial_fn(3) == 6 assert factorial_fn(4) == 24 assert factorial_fn(5) == 120 test(factorial) test(factorial2) test(factorial3) test(factorial4) test(factorial5)
false
21164843eccf32ab55d740847f8990ec306255de
OmniaSalah/CompilerProject
/regex.py
652
4.3125
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 4 23:00:55 2021 @author: LENOVO """ import rstr import re # ask the user to input the regular expression regex=input("Enter regex :\n") # print examples for strings that accepted print("Examples for regex :\n",rstr.xeger(regex)) # ask the user to input if he want to check some string acceptance check=input("Do you want to check specific string acceptance :Enter Y :\n") # check if the string accepted or not if check =='y' or check=='Y': string=input("Enter string :\n") if re.fullmatch(regex,string): print("accepted") else: print ("not accepted")
true
ac937e2d1d61950723beddbbd3ed6f4f2d5466db
rohegde7/competitive_programming_codes
/Interview-TestPress-Reverse_of_number.py
839
4.1875
4
''' Given a number N, print reverse of number N. Note: Do not print leading zeros in output. For example N = 100 Reverse of N will be 1 not 001. Input: Input contains a single integer N. Output: Print reverse of integer N. Constraints: 1<=N<=10000 ''' number = input() #storing the numeber in string format to iterate through it len_number = len(number) reverse_number = "" flag = 1 #this will be used for avoiding leading zeros, 1 signifies that the 1st non-zero digit is not yet found for i in range(len_number-1, -1, -1): #iterate the string in reverse order if flag == 1 and int(number[i]) == 0: #check for leading zero continue flag = 0 #confirms that we found 1st non-zero digit, now zeros are allowed reverse_number = reverse_number + number[i] print(reverse_number)
true
79cba5c7d8c031964a6648c34191448a774f373a
shenoyrahul444/CS-Fundamentals
/Trees/Flatten Binary Trees.py
1,033
4.25
4
""" Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if root: nodes = [] self.preorder(root, nodes) for i in range(len(nodes) - 1): nodes[i].left = None nodes[i].right = nodes[i + 1] nodes[-1].left = nodes[-1].right = None def preorder(self, root, nodes): if root: nodes.append(root) self.preorder(root.left, nodes) self.preorder(root.right, nodes)
true
13a9a16ed598e6b2f79f666ad34ae0012064e9dd
ashwin-5g/LPTHW
/ex3.py
704
4.375
4
#prompt for chicken count print "I will now count my chickens:" #display hens' count print "Hens", 25 + 30 / 6 #display roosters' count print "Roosters", 100 - 25 * 3 % 4 #display eggs' count print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 #comparison operation in use print "Is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 7 #addition print "What is 3 + 2?", 3 + 2 #subtraction print "What is 5 - 7?", 5 - 7 print "Oh, that's why it's False." print "How about some more." #greater than function print "Is it greater?", 5 > -2 #greater than or equal function print "Is it greater or equal?", 5 >= -2 #less than or equal function print "Is it less or equal?", 5 <= -2
true
e5f554a4ed8abecc6aa1801f68adfdfcf3738593
xiaoyangren6514/python_imooc
/oop/test_object.py
950
4.25
4
class User(object): """ 成员变量,可以通过类名饮用,所有对象共有 如果对象修改了成员变量的值,不会影响其他对象的值 如果通过类名调用直接修改了成员变量的值,那么所有对象对应的值都发生变化,除非对象之前修改过此值 """ address = 'bj' def __init__(self, name, age, weight): self.name = name self._age = age self.__weight = weight def get_weight(self): return self.__weight if __name__ == '__main__': user = User('wangcai', 12, 98) print(user) print(dir(user)) print(user.__dict__) print(user.name) print(user._age) print(user.get_weight()) print(user.address) user.address = 'tj' print(user.address) user2 = User('daqiang', 19, 22) print(user2.address) print(User.address) User.address = 'sd' print(user.address) print(user2.address)
false
90012c431612c0221318d69ee94b8bed263a9736
Garvit-32/Opencv_code
/15_adaptive_thresholding.py
775
4.125
4
import cv2 as cv import numpy as np # Adaptive Thresholding algorithm provide the image in which Threshold values vary over the image as a function of local image characteristics. So Adaptive Thresholding involves two following steps # (i) Divide image into strips # (ii) Apply global threshold method to each strip. img = cv.imread('sudoku.png',0) _, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY) th2 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2); th3 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2); cv.imshow("Image", img) cv.imshow("THRESH_BINARY", th1) cv.imshow("ADAPTIVE_THRESH_MEAN_C", th2) cv.imshow("ADAPTIVE_THRESH_GAUSSIAN_C", th3) cv.waitKey(0) cv.destroyAllWindows()
true
a8dbc4ead47024aaae3146f4860fd8930a4f21b4
cromptonhouse/examplesPi
/hiworld.py
750
4.53125
5
# This is a comment! If we type a # we can type what we want and the computer ignores it! print "hello world" # prints words, know in code as a string - "Hello World" # We are going to learn about variables" # A variable is somewhere (memory) where we can store information" x = 6 # we have assigned the variable x with the number 6 print x # this line prints 6 - as x is 6 x = "Still six" # we have now assigned x with a string, a set of words - "still six" print x # now it prints still 6 ####--------- PRACTICE 1 ---------------#### #Edit the code below to print your name below # print "My name is ...." # x = #put your name in this variable # print x # it`ll print your name
true
53d6443c954e116282e4048a560cc1e0650a9df7
dannydiaz92/MIT_IntroToCS
/Pset2/ps2_hangman.py
2,974
4.375
4
# 6.00 Problem Set 3 # # Hangman # # ----------------------------------- # Helper code # (you don't need to understand this helper code) import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file #Python 2 format #inFile = open(WORDLIST_FILENAME, 'r', 0) #Python 3 inFile = open(WORDLIST_FILENAME, 'r') # line: string line = inFile.readline() # wordlist: list of strings ## wordlist = string.split(line) #(python 2 format) #Python 3 wordlist = line.split() print(" ", len(wordlist), "words loaded.") return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # actually load the dictionary of words and point to it with # the wordlist variable so that it can be accessed from anywhere # in the program wordlist = load_words() # your code begins here! #Computer selects random word word = choose_word(wordlist) print("the secret word is: ", word) #Initalize the number of guesses (tries) guesses = 8 #List of available letters avail_letters = list(string.ascii_lowercase) #Pattern '_ _ _ _' pattern = '_ '*len(word) #Set of letters in word word_letters = set(word) print("Welcome to the game of Hangman!") print("I am thinking of a word that is : ", len(word), " letters long") print("--------------------") # While have not # 1) exhausted guesses and # 2) Have not completed word while (guesses > 0) and (len(word_letters) != 0): print("You have ", guesses, " guesses left.") print("Available letters: ", ''.join(avail_letters)) user_input = input("Please guess a letter: ").lower() if (user_input in word) and (user_input in avail_letters): del avail_letters[avail_letters.index(user_input)] word_letters.remove(user_input) char_index = [index for index, char in enumerate(word) if char == user_input] print('index in word where letter is found: ', char_index) #Trying doing this with a list comprehension for letter_index in char_index: pattern = pattern[:letter_index*2] + user_input + pattern[letter_index*2 + 1:] print("Good guess: ", pattern) print('-----------') elif user_input not in avail_letters: print("Already used that word. Please choose a word in available letters.") else: print("Oops! That letter is not in my word: ", pattern) del avail_letters[avail_letters.index(user_input)] print('-----------') guesses -= 1 if len(word_letters) == 0: print("Congrats, you won!")
true
801f87165fd8036da1aece5348751af8a68dd685
Frootloop11/lectures
/week 10/warm_up.py
576
4.28125
4
""" Take in a file Find and return the longest line in that file print the line number and length character """ def main(): line_number, length = find_longest_line("warm_up.py") print(line_number, length) def find_longest_line(file_name): max_line_number, max_length = -1, 0 with open(file_name, 'r') as in_file: for i, line in enumerate(in_file, 1): # enumerate starts the file at 1 if len(line) > max_length: max_length = len(line) max_line_number = i return max_line_number, max_length main()
true
a6b1d841e0a1ea165b268add0056a77c35164611
kradziko/python
/10_11/wytworniki.py
1,837
4.15625
4
# -*- coding: utf-8 -*- ''' wytworniki (list comprehensions) ''' l = range(1, 21, 2) print l # postac prosta # podwojenie wartosci print[2 * x for x in l] # para x, kwadrat x print [(x, x * x) for x in range(1, 5)] # tabela kodowa ASCII print[(x, ord(x)) for x in "ABCDEF"] # lista zawierajaca 10 pustych list print [[] for x in range(10)] # posta prosta warunkowa # liczby wieksze od 10 print [x for x in l if x > 10] # liczby podzielne przez 3 lub 5 print [x for x in range(1, 20) if not (x % 3) or not (x % 5)] # tabela kodowa ASCII dla samoglosek print [(x, ord(x)) for x in "ABCDEF" if x in "AEIOUY"] # postac rozszerzona # pary kazdy element z kazdym print [(x, y) for x in range(1, 5) for y in range(4, 0, -1)] # roznica miedzy wartoscia z pierwsze i drugiej listy print [x - y for z in range(1, 5) for y in range(4, 0, -1)] # sklejenie napisu z wartosci pochodzacych z trzech list print ['x' + y + 'z' for x in [1, 2] for y in ['A', 'B'] for z in [0, 3]] # postac rozszerzona z jednym warunkiem # para kazdy element z kazdym tylko jezeli pierwszy # element jest mniejszy od drugiego print [(x, y) for x in range(1, 5) for y in range(6, 3, -1) if x < y] # para kazdy element z kazdym tylko jezeli # suma elementow jest mniejsza od 7 print [(x, y) for x in range(1, 5) for y in range(6, 3, -1) if x + y < 7] # para kazdy element z kazdym pod warunkiem ze # pierwszy element jest parzysty lub drugi jest nie parzysty print [(x, y) for x in range(1, 5) for y in range(6, 2, -1) if not (x % 2) or y % 2] # postac rozszerzona z wieloma warunkami # para kazdy element z kazdym pod warunkiem ze pierwszy # element jest parzysty a drugi jest nie parzysty print [(x, y) for x in range(1, 5) if not (x % 2) for y in range(6, 2, -1) if y % 2]
false
06e6492146dc1e08ca2aa72428d72cb2c59431be
nick-lehmann/SnakeCharmerGuide
/games/ninjas.py
744
4.21875
4
""" The wall has been breached and cobras are attacking the castle 🏰 We see that there are 50 cobras approaching 🐍 Fortunately we have special ninjas that can defeat the cobras 🥷 Every ninja can defeat 3 cobras. Can we defeat all the cobras with the ninjas we have? 1. Define a variable "ninjas" and one "cobras" and print if we win or loose based on the variables Bonus Points: Say how many more ninjas do we need to win the fight! """ cobras = 50 ninjas = 20 if ninjas * 3 < cobras: print('The cobras won 🐍') # Bonus remaining_cobras = cobras - ninjas * 3 more_ninjas_needed = remaining_cobras / 3 print(f'We need {more_ninjas_needed} more ninjas to win the fight') else: print('The ninjas won 🥷')
true
78ec49439d956378c5f414bf673cc92f3c3bccda
nick-lehmann/SnakeCharmerGuide
/games/pizza.py
687
4.28125
4
""" Mario is eating a pizza. The pizza is so tasty that every time he eats a slice he wants to say "Mhhhhhh". Every time he eats a slice his hunger gets lowered by 1. If he is full, he stops eating and says "I'm full 🤤" When he is finished he says "Mamma mia! Buonissima! 😋" Say if he is still hungry after eating all the slices Start: Define two variables, "slices" and "hunger" """ slices = 8 hunger = 10 for slice in range(slices): if hunger == 0: print("I'm full 🤤") break hunger = hunger - 1 print(f'Mhhhh 🍕 {slice + 1}') print('Mamma mia! Buonissima! 😋👩‍🍳') if hunger > 0: print(f'...but could eat {hunger} more slice/s 😍')
true
f93c3a294a435212eceb18e67c5e7c5f86a7e403
nick-lehmann/SnakeCharmerGuide
/games/rock_paper_scissors.py
1,841
4.40625
4
""" You want to play rock-paper-scissors against the computer. 1. Define a dictionary for each player that stores its name and current score. 2. Ask the player about his or her name and ask how many round should be played. 3. Each round, ask the player for his or her choice. The computer should pick a random choice. 4. Evaluate each round and print who has won. Bonus Points: Accept different spelling of each choice ('rock', 'Rock', 'rOcK') and maybe even abbreviations. """ from random import choice options = ['rock', 'paper', 'scissor'] user_name = input('What is your name?: ') number_of_rounds = int(input('How many rounds do you want to play?: ')) user_score = 0 computer_score = 0 for index in range(1, number_of_rounds + 1): print('==========') print(f'Round {index}') user_choice = None while not user_choice: raw = input('What is your choice?: ') if not raw.lower() in options: print('Invalid choice') else: user_choice = raw.lower() computer_choice = choice(options) print(f'The computer has chosen {computer_choice}') if user_choice == computer_choice: print('Draw! Nobody wins..') continue # User option is always the first element options_where_user_wins = [ ['rock', 'scissor'], ['scissor', 'paper'], ['paper', 'rock'] ] if [user_choice, computer_choice] in options_where_user_wins: user_score += 1 print(f'{user_name} has won!') else: print(f'The computer has won!') computer_score += 1 print('----------------------') print(f'User: {user_score} -- Computer: {computer_score}') if user_score > computer_score: print(f'{user_name} has won') elif user_score < computer_score: print('Computer has won') else: print('It was a draw')
true
88d46bf4694d95c6f9e62726f88cc21871ccbea6
Greensahil/CS697
/Playground/listAndTuples.py
2,067
4.4375
4
#sequence an object that contains multiple items of data #list is mutable can be changed in place in memory #tuple cannot be modified unless you are reassigining to a different place in memory list = [1,2] print(list) #list is similar to array list in java #list is dynamic and we can change the size #list can be herttogenous list = [1,2, 'some string', 1.34343] print(list) for item in range(len(list)): print(list[item]) print(len(list)) list2 = ['asdas','asdas'] print(list + list2) print(list.extend(list2)) #same thing l1 = [1,2] print(l1*5) #[1, 2, 1, 2, 1, 2, 1, 2, 1, 2] for item in list: print(item) print(list[-1]) #last element in the list #since list are mutable list[1] = 5 #list slicing #start index is inclusive and lst idex is not. Last one is step if -ve it starts from the right l1[1:] #print everything from start to end of the list print(l1[0:5:2]) #check to see if a list contains something print(0 in l1) #add to the end of the list l1.append(9) print(l1.index(9)) #insert at any point in the list l1.insert(1,4) l1.sort() #Remove by value and not index l1.remove(4) #By index and it also returns the value that was removeed print(l1.pop(1)) print(l1) #list are mutable so to copy youcannot do #l2 = l1 #method 1 #l2 =[] #l2 = l2 + l1 #method 2 #l2=l1[::] #method 3 #you can create a loop to copy each element #to copy list from l1.extend() l1.append() will not work #to square each item and create in a different # newList = [len(item) for item in list1] # newList = [item for item in list1 if item < 10 ] #l2 = [item for item in range(1001) if 3 in str(item)] #l2 = [item for item in years if year % 4 ==0 and year % 100! = 0] print("Random numbers") import random #Both starts and stop are both inclusive print(random.randint(0,100)) #More customixation with step. All even numbers print(random.randint(0,100)) for i in range(10): print(random.randint(0,10)) rlist = [random.randint(0,10) for i in range(10)] slist = random.sample(range(0,100),10) #unique number print(rlist)
true
8401ef69843234d30758eecc923f15296cc9b1a3
Greensahil/CS697
/Playground/passwordchecker.py
757
4.3125
4
password = input("Enter a string for password:") validPassword = True #A password must have at least eight characters. if len(password) < 8: validPassword = False #A password consists of only letters and digits if not password.isalnum(): validPassword = False #A password must contain at least two digits #A password must contain at least one uppercase character digitCounter = 0 upperCaseCounter = 0 for index in range(len(password)): if(password[index].isnumeric()): digitCounter += 1 if(password[index].isupper()): upperCaseCounter += 1 if digitCounter < 2: validPassword = False if upperCaseCounter < 1: validPassword = False if validPassword: print("valid password") else: print("invalid password")
true
5a9cae303fbc660ac7566063f5593a78c263dabf
half-rice/daily_programmer
/easy_challenge_1.py
699
4.21875
4
# create a program that will ask the users name, age, and username. have it # tell them the information back, in the format: # your name is (blank), you are (blank) years old, and your username is (blank) # for extra credit, have the program log this information in a file to be # accessed later. file = open("easy_challenge_1_save.txt", "w") name = raw_input("enter your name: ") age = raw_input("enter your age: ") username = raw_input("enter your username: ") print("\nwriting data to file...") file.write(name+"\n") file.write(age+"\n") file.write(username+"\n") print("completed\n\n") print("your name is "+name+", you are "+age+" years old, and your username is "+username) file.close()
true