blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4c05bf6d559bd0275323dbdb217edc1a2208f59c
geekidharsh/elements-of-programming
/arrays/generate_primes.py
613
4.1875
4
# Take an integer argument 'n' and generate all primes between 1 and that integer n # example: n = 18 # return: 2,3,5,7,11,13,17 def generate_primes(n): # run i, 2 to n # any val between i to n is prime, store integer # remove any multiples of i from computation primes = [] #generate a flag array for all element in 0 till n. initialize all items to True is_primes = [False, False] + [True]*(n-1) for p in range(2,n+1): if is_primes[p]: primes.append(p) # remove all multiples of p for i in range(p,n+1,p): is_primes[i] = False return primes print(generate_primes(35))
true
51a3ae2e607f52ab2c79c59344699e52030e1c15
justindarcy/CodefightsProjects
/isCryptSolution.py
2,657
4.46875
4
#A cryptarithm is a mathematical puzzle for which the goal is to find the correspondence between letters and digits, #such that the given arithmetic equation consisting of letters holds true when the letters are converted to digits. #You have an array of strings crypt, the cryptarithm, and an an array containing the mapping of letters and digits, #solution. The array crypt will contain three non-empty strings that follow the structure: [word1, word2, word3], #which should be interpreted as the word1 + word2 = word3 cryptarithm. #If crypt, when it is decoded by replacing all of the letters in the cryptarithm with digits using the mapping in #solution, becomes a valid arithmetic equation containing no numbers with leading zeroes, the answer is true. If it #does not become a valid arithmetic solution, the answer is false. def isCryptSolution(crypt, solution): word3len=len(crypt[2]) num1 = [] num2 = [] num3 = [] def wordgrab(crypt, solution): #here i pull a single word from crypt and pass it to wordtonum. I also pass which # word i'm sending word_count=0 for word in crypt: word_count=word_count+1 word_letter(word,word_count, solution) def word_letter(word, word_count, solution): #here i will pass in a single word and this will pull out each letter #in turn and pass it to letter_num letter_count=0 for letter in word: letter_count+=1 letter_num(letter, word_count, solution,letter_count) def letter_num(letter, word_count, solution,letter_count): # here i take a letter and use solution to translate the letter to a #num and create num1-3 for list in solution: if letter == list[0] and word_count==1: num1.append(list[1]) elif letter == list[0] and word_count==2: num2.append(list[1]) elif letter == list[0] and word_count==3: num3.append(list[1]) if word_count==3 and letter_count==word3len: global answer answer = output(num1, num2, num3) def output(num1, num2, num3): if num1[0]=='0' and len(num1)>1: return False elif num2[0]=='0' and len(num2)>1: return False elif num3[0]=='0' and len(num3)>1: return False number1=int("".join(num1)) number2=int("".join(num2)) number3=int("".join(num3)) if number1 + number2==number3: return True else: return False wordgrab(crypt, solution) return(answer)
true
9c01fc72c243846886a7e1f44e5a0ebcce008f7b
sgirimont/projecteuler
/euler1.py
1,153
4.15625
4
################################### # Each new term in the Fibonacci sequence is generated by adding the previous two terms. # By starting with 1 and 2, the first 10 terms will be: # # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # # By considering the terms in the Fibonacci sequence whose values do not exceed four million, # find the sum of the even-valued terms. ################################### def product_finder(factors, limit): product_list = [] x = 0 if 0 in factors: print('Cannot have a zero as one of the factors.') else: while x < len(factors): if factors[x] > limit: print('Cannot have a factor larger than the limit value.') exit() multiplier = 1 while multiplier <= limit: if factors[x] * multiplier <= limit and factors[x] * multiplier not in product_list: product_list.append(factors[x] * multiplier) else: break multiplier += 1 x += 1 product_list.sort() print(product_list) product_finder([2001, 5032, 8674], 10000)
true
e9acdbfd9ab5a29c06f1e27abcd1d384611c5cf0
chizhangucb/Python_Material
/cs61a/lectures/Week2/Lec_Week2_3.py
2,095
4.21875
4
## Functional arguments def apply_twice(f, x): """Return f(f(x)) >>> apply_twice(square, 2) 16 >>> from math import sqrt >>> apply_twice(sqrt, 16) 2.0 """ return f(f(x)) def square(x): return x * x result = apply_twice(square, 2) ## Nested Defintions # 1. Every user-defined function has a parent environment / frame # 2. The parent of a function is the frame in which it was defined # 3. Every local frame has a parent frame # 4. The parent of a frame is the parent of a function called def make_adder(n): """Return a function that takes one argument k and returns k + n. >>> add_three = make_adder(3) >>> add_three(4) 7 """ def adder(k): return k + n return adder ## Lexical scope and returning functions def f(x, y): return g(x) def g(a): return a + y # f(1, 2) # name 'y' is not defined # This expression causes an error because y is not bound in g. # Because g(a) is NOT defined within f and # g is parent frame is the global frame, which has no "y" defined ## Composition def compose1(f, g): def h(x): return f(g(x)) return h def triple(x): return 3 * x squiple = compose1(square, triple) squiple(5) tripare = compose1(triple, square) tripare(5) squadder = compose1(square, make_adder(2)) squadder(5) compose1(square, make_adder(2))(3) ## Function Decorators # special syntax to apply higher-order functions as part of executing a def statement def trace(fn): """Returns a function that precedes a call to its argument with a print statement that outputs the argument. """ def wrapped(x): print("->", fn, '(', x, ')') return fn(x) return wrapped # @trace affects the execution rule for def # As usual, the function triple is created. # However, the name triple is not bound to this function. # Instead, the name triple is bound to the returned function # value of calling trace on the newly defined triple function @trace def triple(x): return 3 * x triple(12) # The decorator symbol @ may also be followed by a call expression
true
16021ebd861f8d23781064101d52eba228a6f800
mldeveloper01/Coding-1
/Strings/0_Reverse_Words.py
387
4.125
4
""" Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots. """ def reverseWords(s): l = list(s.split('.')) l = reversed(l) return '.'.join(l) if __name__ == "__main__": t = int(input()) for i in range(t): string = str(input()) result = reverseWords(string) print(result)
true
0053bde8153d3559f824aed6a017c528410538ea
JaredD-SWENG/beginnerpythonprojects
/3. QuadraticSolver.py
1,447
4.1875
4
#12.18.2017 #Quadratic Solver 2.4.6 '''Pseudocode: The program is designed to solve qudratics. It finds it's zeros and vertex. It does this by asking the user for the 'a', 'b', and 'c' of the quadratic. With these pieces of information, the program plugs in the variables into the quadratic formula and the formula to solve for the vertex. It then ouputs the information solved for to the user.''' import math print('''Welcome to Quadratic Solver! ax^2+bx+c ''') def FindVertexPoint(A,B,C): if A > 0: x_vertex = (-B)/(2*A) y_vertex = (A*(x_vertex**2))+(B*x_vertex)+C return('Minimum Vertex Point: '+str(x_vertex)+', '+str(y_vertex)) elif A < 0: x_vertex = (-B)/(2*A) y_vertex = (A*(x_vertex**2))+(B*x_vertex)+C return('Maximum Vertex Point: '+str(x_vertex)+', '+str(y_vertex)) def QuadraticFormula(A,B,C): D = (B**2)-(4*(A*C)) if D < 0: return('No real solutions') elif D == 0: x = (-B+math.sqrt((B**2)-(4*(A*C))))/(2*A) return('One solution: '+str(x)) else: x1 = (-B+math.sqrt((B**2)-(4*(A*C))))/(2*A) x2 = (-B-math.sqrt((B**2)-(4*(A*C))))/(2*A) return('Solutions: '+str(x1)+' or '+str(x2)) a = float(input("Quadratic's a: ")) b = float(input("Quadratic's b: ")) c = float(input("Quadratic's c: ")) print('') print(QuadraticFormula(a,b,c)) print(FindVertexPoint(a,b,c))
true
c1b024fe6518776cbeaabb614ca1fa63813b02b7
wellqin/USTC
/PythonBasic/base_pkg/python-06-stdlib-review/chapter-01-Text/1.1-string/py_02_stringTemplate.py
1,422
4.1875
4
### string.Template is an alternative of str object's interpolation (format(), %, +) import string def str_tmp(s, insert_val): t = string.Template(s) return t.substitute(insert_val) def str_interplote(s, insert_val): return s % insert_val def str_format(s, insert_val): return s.format(**insert_val) def str_tmp_safe(s, insert_val): t = string.Template(s) try: return t.substitute(insert_val) except KeyError as e: print('ERROR:', str(e)) return t.safe_substitute(insert_val) val = {'var': 'foo'} # example 01 s = """ template 01: string.Template() Variable : $var Escape : $$ Variable in text: ${var}iable """ print(str_tmp(s, val)) # example 02 s = """ template 02: interpolation %% Variable : %(var)s Escape : %% Variable in text: %(var)siable """ print(str_interplote(s, val)) # example 03 s = """ template 03: format() Variable : {var} Escape : {{}} Variable in text: {var}iable """ print(str_format(s, val)) # example 04 s = """ $var is here but $missing is not provided """ print(str_tmp_safe(s, val)) """ conclusion: - any $ or % or {} is escaped by repeating itself TWICE. - string.Template is using $var or ${var} to identify and insert dynamic values - string.Template.substitute() won't format type of the arguments.. -> using string.Template.safe_substitute() instead in this case """
true
988ab3ba48c2d279c3706a2f12224f3793182a14
wellqin/USTC
/DesignPatterns/behavioral/Adapter.py
1,627
4.21875
4
# -*- coding:utf-8 -*- class Computer: def __init__(self, name): self.name = name def __str__(self): return 'the {} computer'.format(self.name) def execute(self): return self.name + 'executes a program' class Synthesizer: def __init__(self, name): self.name = name def __str__(self): return 'the {} synthesizer'.format(self.name) def play(self): return self.name + 'is playing an electronic song' class Human: def __init__(self, name): self.name = name def __str__(self): return '{} the human'.format(self.name) def speak(self): return self.name + 'says hello' class Adapter: def __init__(self, obj, adapted_methods): self.obj = obj self.__dict__.update(adapted_methods) def __str__(self): return str(self.obj) if __name__ == '__main__': objects = [Computer('Computer')] synth = Synthesizer('Synthesizer') objects.append(Adapter(synth, dict(execute=synth.play))) human = Human('Human') objects.append(Adapter(human, dict(execute=human.speak))) for i in objects: print('{} {}'.format(str(i), i.execute())) print('type is {}'.format(type(i))) print("*" * 20) """ the Computer computer Computerexecutes a program type is <class '__main__.Computer'> the Synthesizer synthesizer Synthesizeris playing an electronic song type is <class '__main__.Adapter'> Human the human Humansays hello type is <class '__main__.Adapter'> """ for i in objects: print(i.obj.name) # i.name
true
a47e31222de348822fbde57861341ea68a4fa5fb
Ph0tonic/TP2_IA
/connection.py
927
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class Connection: """ Class connection which allow to link two cities, contains the length of this connection """ def __init__(self, city1, city2, distance): """ Constructor :param city1: City n°1 :param city2: City n°2 :param distance: distance between the 2 cities """ self.city1 = city1 self.city2 = city2 self.distance = distance def get_linked(self, city): """ get the other city connected via this connection :param city: city from where the connection is coming from :return: city where the connection is going """ return self.city1 if city != self.city1 else self.city2 def __str__(self): """ To String function for debug """ return str(self.city1)+" - "+str(self.city2)
true
92e296b5132802978932b62ddab03030d636785d
elsandkls/SNHU_IT140_itty_bitties
/example_1_list.py
1,593
4.34375
4
# Get our lists from the command line # It's okay if you don't understand this right now import sys list1 = sys.argv[1].split(',') list2 = sys.argv[2].split(',') # # Print the lists. # # Python puts '[]' around the list and seperates the items # by commas. print(list1) print(list2) # # Note that this list has three different types of items # in the container: an Integer, a String, and a Boolean. # list3 = [1,"red", True] print(list3) strList = ['Alice', 'Shahneila', 'Bobx, 'Tariq'] numList = [1, 3.141, 5, 17.1, 100] numList = [] numList.append(4) # create a list aList = [ 'Alice', 'Shahneila', 'Bob', 'Tariq' ] print(aList) # change the second element aList[1] = 'Sean' print(aList) # create an empty list numList = [] # append some items to the empty list numList.append(1) numList.append(2) numList.append(4) print(numList) # insert an element at a specific index numList.insert(2, 3) print(numList) aString = '12345' # use the len() function to get the length of a string print('the string has a length of:') print(len(aString)) aList = [1,2,3,4,5] # you can also use the len() function to get the length of a list print('the list has a length of:') print(len(aList)) myList = [1,3,5,7,9] stop = len(myList) print('the list has ' + str(stop) + ' elements') aRange = range(0, stop) for i in aRange: print(myList[i]) # short version print('a shorter way of creating ranges for looping') for i in range(0, len(myList)): print(myList[i]) # display every second item print('range step of 2') for i in range(0, len(myList), 2): print(myList[i])
true
7add89c47bb6e5b3a49504244acc952a91040d31
MasudHaider/Think-Python-2e
/Exer-5-3(1).py
555
4.21875
4
def is_triangle(length1, length2, length3): case1 = length1 + length2 case2 = length1 + length3 case3 = length2 + length3 if length1 > case3 or length2 > case2 or length3 > case1: print("No") elif length1 == case3 or length2 == case2 or length3 == case1: print("Degenerate triangle") else: print("Yes") prompt = "Enter value for length1: " a = int(input(prompt)) prompt = "Enter value for length2: " b = int(input(prompt)) prompt = "Enter value for length3: " c = int(input(prompt)) is_triangle(a, b, c)
true
afc0ab954176bdcbbb49b4415431c49278c9628c
kchow95/MIS-304
/CreditCardValidaiton.py
2,340
4.15625
4
# Charlene Shu, Omar Olivarez, Kenneth Chow #Program to check card validation #Define main function def main(): input_user = input("Please input a valid credit card number: ") #Checks if the card is valid and prints accordingly if isValid(input_user): print(getTypeCard(input_user[0])) print("The number is valid") else: print("Your credit card number is invalid") #define isvalid returns true if the card is valid def isValid(card_number): valid_card = True #Checks the numbers first check_numbers = (sumOfDoubleEvenPlace(card_number) + sumOfOddPlace(card_number))%10 prefix = getPrefix(card_number) #checks the parameters for the card #not long enough or too long if 13 >= getSize(card_number) >=16: valid_card = False #the numbers don't add up elif(check_numbers != 0): valid_card = False #prefix isn't valid elif prefixMatched(card_number, prefix) == False: print(prefix) valid_card = False return valid_card #sums the even places with double the int def sumOfDoubleEvenPlace(card_number): step = len(card_number)-2 total = 0 while step >= 0: total+= (getDigit(2*int(card_number[step]))) step-=2 return total #Gets the digit for the double even place function, takes out the 10s place and subtracts by one def getDigit(digit): return_digit = digit if(digit >= 10): return_digit = (digit - 10) + 1 return return_digit #Gets the digit for the odd places from the end of the card_number and sums them def sumOfOddPlace(card_number): step = len(card_number)-1 total = 0 while step >= 0: total += int(card_number[step]) step -= 2 return total #Checks the number d if it falls into one of the four categories def prefixMatched(card_number, d): if(int(d) != 4 and int(d) != 5 and int(d) != 6 and int(d) != 37): return False else: return True #returns the size of the card number def getSize(card_number): return len(card_number) #Returns the type of card it is def getTypeCard(num): num = int(num) if(num == 4): return "Your card type is Visa" elif(num == 5): return "Your card type is MasterCard" elif(num == 6): return "Your card type is Discover" else: return "Your card type is American Express" #gets the second number if the card starts with a 3 def getPrefix(card_number): if card_number[0] == "3": return card_number[:2] else: return card_number[0] main()
true
7ba0531979d8aed9f9af85d74a83cd2b5120426f
PythonTriCities/file_parse
/four.py
637
4.3125
4
#!/usr/bin/env python3 ''' Open a file, count the number of words in that file using a space as a delimeter between character groups. ''' file_name = 'input-files/one.txt' num_lines = 0 num_words = 0 words = [] with open(file_name, 'r') as f: for line in f: print(f'A line looks like this: \n{line}') split_line = line.split() print(f'A split line looks like this: \n{split_line}') length = len(split_line) print(f'The length of the split line is: \n{length}') words.append(length) print(f'Words now looks like this: \n{words}') print(f'Number of words: \n{sum(words)}')
true
d2fd477b8c9df119bccb17f80aceda00c61cd82d
Sai-Sumanth-D/MyProjects
/GuessNumber.py
877
4.15625
4
# first importing random from lib import random as r # to set a random number range num = r.randrange(100) # no of chances for the player to guess the number guess_attempts = 5 # setting the conditions while guess_attempts >= 0: player_guess = int(input('Enter your guess : ')) # for checking the players guess = the actual number def check(x): if player_guess == x: print('You Won!!') elif player_guess > x: print('You are a bit on the higher side of the number, try lower!') else: print('Your guess is a bit on the lower side, try higher!') if guess_attempts > 1: check(num) elif guess_attempts == 1: check(num) print('This is your last chance, try making most of it.') else: print('You Lost') guess_attempts -= 1
true
dbef91a7ddfd4100180f9208c3880d9311e2c94c
Arlisha2019/HelloPython
/hello.py
1,319
4.34375
4
#snake case = first_number #camel case =firstNumber print("Hello") #input function ALWAYS returns a String data type #a = 10 # integer #b = "hello" # String #c = 10.45 # float #d = True # boolean #convert the input from string to int #first_number = float(input("Enter first number: ")) #second_number = float(input("Enter second number: ")) #third_number = float(input("Enter third number: ")) #number = int("45") #first_number_as_int = int("45") #second_number_as_int = int("70") #some_result = first_number_as_int + second_number_as_int #result = first_number + second_number + third_number #result = int(first_number) + int(second_number) #print(result) #name = input("Enter your name: ") #print(name) #name = "John" #age = 20 #version = 3.35 # Print will print the value of name variable to tthe screen #print(name) #name = "Mary" #print(name) #string concatcentration first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") city = input("Enter city: ") state = input("Enter State: ") zip_code = input("Enter Zip Code: ") message = "My name is {0},{1} and I live in {2}, {3}, {4}".format(first_name,last_name,city,state,zip_code) #message = "My name is " + first_name + ", " + last_name + ", " + " and I live in " + city + ", " + state + " " + zip_code print(message)
true
ac42e69bac982862edcbed8567653688ee07f186
GaganDureja/Algorithm-practice
/Vending Machine.py
1,686
4.25
4
# Link: https://edabit.com/challenge/dKLJ4uvssAJwRDtCo # Your task is to create a function that simulates a vending machine. # Given an amount of money (in cents ¢ to make it simpler) and a product_number, #the vending machine should output the correct product name and give back the correct amount of change. # The coins used for the change are the following: [500, 200, 100, 50, 20, 10] # The return value is a dictionary with 2 properties: # product: the product name that the user selected. # change: an array of coins (can be empty, must be sorted in descending order). def vending_machine(products, money, product_number): if product_number not in range(1,10): return 'Enter a valid product number' if money < products[product_number-1]['price']: return 'Not enough money for this product' lst = [500,200,100,50,20,10] count = 0 money-= products[product_number-1]['price'] change = [] while money!=0: if money-lst[count]>=0: money-=lst[count] change.append(lst[count]) else: count+=1 return {'product':products[product_number-1]['name'], 'change': change} # Products available products = [ { 'number': 1, 'price': 100, 'name': 'Orange juice' }, { 'number': 2, 'price': 200, 'name': 'Soda' }, { 'number': 3, 'price': 150, 'name': 'Chocolate snack' }, { 'number': 4, 'price': 250, 'name': 'Cookies' }, { 'number': 5, 'price': 180, 'name': 'Gummy bears' }, { 'number': 6, 'price': 500, 'name': 'Condoms' }, { 'number': 7, 'price': 120, 'name': 'Crackers' }, { 'number': 8, 'price': 220, 'name': 'Potato chips' }, { 'number': 9, 'price': 80, 'name': 'Small snack' } ] print(vending_machine(products, 500, 8))
true
47f8c6b8f6c8b01f0bc66d998fdd4c039bf91572
Tallequalle/Code_wars
/Task15.py
728
4.125
4
#A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant). #Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation. import string def is_pangram(s): s = s.lower() alphabet = ['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'] for i in alphabet: if i in s: continue else: return False return True pangram = "The quick, Brown fox jumps over the lazy dog!" is_pangram(pangram)
true
091718f2cf95ce96ff8d3aa2704068d25e650121
wsargeant/aoc2020
/day_1.py
1,383
4.34375
4
def read_integers(filename): """ Returns list of numbers from file containing list of numbers separated by new lines """ infile = open(filename, "r") number_list = [] while True: num = infile.readline() if len(num) == 0: break if "\n" in num: num = num[:-1] number_list.append(int(num)) return(number_list) def sum_2020(filename): """Returns two numbers from number list in filename which sum to 2020 and their product """ number_list = read_integers(filename) target = 2020 for num1 in number_list: num2 = target - num1 if num2 in number_list and num2 != num1: break return num1, num2, num1*num2 def sum_2020_by_3(filename): """Returns three numbers from number list in filename which sum to 2020 and their product """ number_list = read_integers(filename) #reversed_number_list = number_list.copy() #reversed_number_list.reverse() target = 2020 for i in range(len(number_list)): num1 = number_list[i] for j in range(i,len(number_list)): num2 = number_list[j] num3 = target - num1 - num2 if num3 >= 0 and num3 in number_list: return num1, num2, num3, num1*num2*num3 return False print(sum_2020("day_1.txt")) print(sum_2020_by_3("day_1.txt"))
true
08e800c3cdcbfaa6f37a0aa98863a39d8260242c
AsiakN/flexi-Learn
/sets.py
1,880
4.34375
4
# A set is an unordered collection with no duplicates # Basic use of sets include membership testing and eliminating duplicates in lists # Sets can also implement mathematical operations like union, intersection etc # You can create a set using set() or curly braces. You can only create an empty set using the set() method # Another type of set exists called frozenset. Frozenset is immutable but set is mutable basket = {'Apple', 'Banana', 'Avocado', 'pineapple', 'Apple', 'Orange'} print(sorted(basket)) a = set('abracadabra') b = set('alacazam') print(a.intersection(b)) print(a | b) # The " | " operator means or. It sums elements in both sets. Union operation print(a & b) # The " &" operator means and . It finds the elements in both a and b. Intersection operation print(a ^ b) # The " ^ " operator means not. Finds the elements in one set but not in the other set. Symmetric difference print(a.isdisjoint(b)) print(b.issubset(a)) # SET COMPREHENSIONS s = {x for x in 'abracadabra' if x not in 'abc'} print(s) # METHODS IN SETS # 1. UNION #SYNTAX # setA.union(setB) # 2. INTERSECTION # SYNTAX # setA.intersection(setB) # 3. DIFFERENCE # SYNTAX # setA.difference(setB) # 4. SYMMETRIC DIFFERENCE # SYNTAX # setA.symmetric_difference(SetB) # 5. DISJOINT # SYNTAX # setA.isdisjoint(setB) # Returns true or false value # 6. SUBSET # SYNTAX # setA.issubset(setB) # Returns true or false value # 7. SUPERSET # SYNTAX # setA.issuperset(setB) # Returns true or false value # 8. PROPER SUBSET/SUPERSET # MODIFYING SETS # 1. set.add(element) # 2. set.remove(element) # 3. Set.discard(element) # 4. set.pop() # 5. set.clear() numbers = { 24, 67, 89,90, 78,78, 24 } print(sum(numbers)) print(len(numbers))
true
330e62b9b6ff037ff06d0e9a1dc6aa3a930095f0
Alfred-Mountfield/CodingChallenges
/scripts/buy_and_sell_stocks.py
881
4.15625
4
""" Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. """ def max_profit(nums: list): if not nums: return 0 profit = price = 0 for num in reversed(nums): price = max(num, price) profit = max(profit, price - num) return profit if __name__ == "__main__": print(f"[7, 1, 5, 3, 6, 4]: {max_profit([7, 1, 5, 3, 6, 4])}") print(f"[7, 6, 4, 3, 1]: {max_profit([7, 6, 4, 3, 1])}") print(f"[7, 1, 5, 3, 6, 4]: {max_profit([7, 1, 5, 3, 6, 4])}") print(f"[7, 5, 3, 2, 1]: {max_profit([7, 5, 3, 2, 1])}") print(f"[7, 4, 10, 2, 6, 11]: {max_profit([7, 4, 10, 2, 6, 11])}")
true
35e9d5de6afa12398a59af95f454097f3231d4ad
SaikumarS2611/Python-3.9.0
/Packages/Patterns_Packages/Symbols/Rectangle.py
926
4.34375
4
def for_rectangle(): """Shape of 'Rectangle' using Python for loop """ for row in range(6): for col in range(8): if row==0 or col==0 or row==5 or col==7: print('*', end = ' ') else: print(' ', end = ' ') print() def while_rectangle(): """Shape of 'Rectangle' using Python while loop """ row = 0 while row<6: col = 0 while col<8: if row==0 or col==0 or row==5 or col==7: print('*', end = ' ') else: print(' ', end = ' ') col += 1 print() row += 1
true
b7cf0ad56f664cab16423ec3baeaea62603d29bb
claraqqqq/l_e_e_t
/102_binary_tree_level_order_traversal.py
1,178
4.21875
4
# Binary Tree Level Order Traversal # Given a binary tree, return the level order traversal of its # nodes' values. (ie, from left to right, level by level). # For example: # Given binary tree {3,9,20,#,#,15,7}, # 3 # / \ # 9 20 # / \ # 15 7 # return its level order traversal as: # [ # [3], # [9,20], # [15,7] # ] # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def levelOrder(self, root): if root is None: return [] curNodes = [root] result = [] while curNodes: curNodeVals = [] nextNodes = [] for node in curNodes: curNodeVals.append(node.val) if node.left: nextNodes.append(node.left) if node.right: nextNodes.append(node.right) result.append(curNodeVals) curNodes = nextNodes return result
true
cdd09dafb35bc0077d004e332ab48436810224a7
claraqqqq/l_e_e_t
/150_evaluate_reverse_polish_notation.py
1,079
4.28125
4
# Evaluate Reverse Polish Notation # Evaluate the value of an arithmetic expression in Reverse Polish Notation. # Valid operators are +, -, *, /. Each operand may be an integer or another expression. # Some examples: # # ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 # ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 class Solution: # @param tokens, a list of string # @return an integer def evalRPN(self, tokens): stack = [] for element in tokens: if element not in "+-*/": stack.append(element) else: num2 = int(stack.pop()) num1 = int(stack.pop()) if element == "+": stack.append(str(num1 + num2)) elif element == "-": stack.append(str(num1 - num2)) elif element == "*": stack.append(str(num1 * num2)) elif element == "/": if num1 * num2 > 0: stack.append(str(num1 / num2)) else: stack.append(str(-(abs(num1) / abs(num2)))) return int(stack[0])
true
ec541b14059808cf538ba11ffa9645488d70f4f4
BuseMelekOLGAC/GlobalAIHubPythonHomework
/HANGMAN.py
1,602
4.1875
4
print("Please enter your name:") x=input() print("Hello,"+x) import random words = ["corona","lung","pain","hospital","medicine","doctor","ambulance","nurse","intubation"] word = random.choice(words) NumberOfPrediction = 10 harfler = [] x = len(word) z = list('_' * x) print(' '.join(z), end='\n') while NumberOfPrediction > 0: y = input("Guess a letter:") if y in words: print("Please don't tell the letter that you've guessed before!") continue elif len(y) > 1: print("Please just enter one letter!!!") continue elif y not in word: NumberOfPrediction -= 1 print("Misestimation.You have {} prediction justification last!".format(NumberOfPrediction)) else: for i in range(len(word)): if y == word[i]: print("Correct Guess!") z[i] = y words.append(y) print(' '.join(z), end='\n') answer = input("Do you still want to guesss all of the word? ['yes' or 'no'] : ") if answer == "yes": guess = input("You can guess all of the word then : ") if guess == word: print("Congrats!You know right!!!") break else: NumberOfPrediction -= 1 print("Misestimation! You have {} prediction justification last".format(NumberOfPrediction)) if NumberOfPrediction== 0: print("Oh no,you don't have any prediction justification.You lost the game.Your hangman is hanged hahah!") break
true
cc0b8ef1943eb8b6b5b42870be3387bbde4f8001
MindCC/ml_homework
/Lab02/Question/lab2_Point.py
2,008
4.46875
4
# -*- coding: cp936 -*- ''' ID: Name: ''' import math class Point: ''' Define a class of objects called Point (in the two-dimensional plane). A Point is thus a pair of two coordinates (x and y). Every Point should be able to calculate its distance to any other Point once the second point is specified. άƽϵPoint㣩Point2xy Pointʵּ2֮ķdistanceTo( Point ) ''' def __init__(self, x, y): self.__x = x self.__y = y def distance_to(self, other): ''' 㲢selfother֮ľ ''' # sqrt(x^2+y^2) return math.sqrt((self.__x - other.__x) ** 2 + (self.__y - other.__y) ** 2) def __str__(self): ''' صַʾ(x,y) ''' return '(%d,%d)' % (self.__x, self.__y) class Line: ''' Define a class of objects called Line. Line(ߣ Every Line is a pair of two Points. Line2 Lines are created by passing two Points to the Line constructor. A Line object must be able to report its length, which is the distance between its two end points. ''' def __init__(self, p1, p2): self.__p1 = p1 self.__p2 = p2 def length(self): ''' ʾߵ2֮ľ ''' return self.__p1.distance_to(self.__p2) def __str__(self): ''' ߵַʾ(x1,y1)--(x2,y2) ''' return str(self.__p1) + '--' + str(self.__p2) if __name__ == "__main__": p1 = Point(0, 3) print(p1) assert str(p1) == "(0,3)" p2 = Point(4, 0) print(p2) assert str(p2) == "(4,0)" print(p1.distance_to(p2)) # should be 5.0 line1 = Line(p1, p2) print(line1) assert str(line1) == "(0,3)--(4,0)" print(line1.length()) # should be 5.0 print(Line(Point(0, 0), Point(1, 1)).length())
true
d29faa39dec07a25caa6383e0ecbe35edebbb4c5
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/minimumDominoRotationsForEqualRow.py
2,392
4.4375
4
""" Minimum Domino Rotations For Equal Row In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i-th domino, so that A[i] and B[i] swap values. Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same. If it cannot be done, return -1. Example 1: Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by A and B: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. Example 2: Input: A = [3,5,1,2,3], B = [3,6,3,3,4] Output: -1 Explanation: In this case, it is not possible to rotate the dominoes to make one row of values equal. """ """ Greedy Time: O(N) since here one iterates over the array Space: O(1) """ class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: def check(x): """ Return min number of swaps if one could make all elements in A or B equal to x. Else return -1. """ # how many rotations should be done # to have all elements in A equal to x # and to have all elements in B equal to x rotations_a = rotations_b = 0 for i in range(n): # rotations coudn't be done if A[i] != x and B[i] != x: return -1 # A[i] != x and B[i] == x elif A[i] != x: rotations_a += 1 # A[i] == x and B[i] != x elif B[i] != x: rotations_b += 1 # min number of rotations to have all # elements equal to x in A or B return min(rotations_a, rotations_b) n = len(A) rotationsA = check(A[0]) # If one could make all elements in A or B equal to A[0] rotationsB = check(B[0]) # If one could make all elements in A or B equal to B[0] if rotationsA != -1 and rotationsB != -1: return min(rotationsA, rotationsB) elif rotationsA == -1: return rotationsB else: return rotationsA
true
1b399e72edc812253cacad330840ed59cf0194c9
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/diameterOfBinaryTree.py
1,290
4.3125
4
""" Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example: Given a binary tree 1 / \ 2 3 / \ 4 5 Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. Note: The length of path between two nodes is represented by the number of edges between them. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None """ Time Complexity: O(N). We visit every node once. Space Complexity: O(N), the size of our implicit call stack during our depth-first search. """ class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 self.res = 0 self.depth(root) return self.res-1 # -1 because length is defined as the number of edges def depth(self, node): if not node: return 0 left = self.depth(node.left) right = self.depth(node.right) self.res = max(self.res, left+right+1) return max(left, right) + 1
true
f490e6054c9d90343cab89c810ca2c649d8138fe
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/mergeIntervals.py
1,167
4.125
4
""" Merge Intervals Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. """ # Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e """ Time: O(nlogn) Space: O(n) """ class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ start, end, result = [], [], [] for interval in intervals: st, en = interval.start, interval.end start.append(st) end.append(en) start.sort() end.sort() i = 0 while i < len(intervals): st = start[i] while i < len(intervals) - 1 and start[i + 1] <= end[i]: i += 1 en = end[i] result.append([st, en]) i += 1 return result
true
99e25be34833e876da74bb6f53a62edf745be9a5
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/sortedSquares.py
2,053
4.25
4
""" Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2: Input: [-7,-3,2,3,11] Output: [4,9,9,49,121] Note: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A is sorted in non-decreasing order. """ """ Time Complexity: O(N log N), where N is the length of A. Space Complexity: O(N). """ class Solution: def sortedSquares(self, A: List[int]) -> List[int]: return sorted(x*x for x in A) """ Approach 2: Two Pointer Intuition Since the array A is sorted, loosely speaking it has some negative elements with squares in decreasing order, then some non-negative elements with squares in increasing order. For example, with [-3, -2, -1, 4, 5, 6], we have the negative part [-3, -2, -1] with squares [9, 4, 1], and the positive part [4, 5, 6] with squares [16, 25, 36]. Our strategy is to iterate over the negative part in reverse, and the positive part in the forward direction. Algorithm We can use two pointers to read the positive and negative parts of the array - one pointer j in the positive direction, and another i in the negative direction. Now that we are reading two increasing arrays (the squares of the elements), we can merge these arrays together using a two-pointer technique. Time Complexity: O(N), where N is the length of A. Space Complexity: O(N). """ class Solution(object): def sortedSquares(self, A): N = len(A) # i, j: negative, positive parts j = 0 while j < N and A[j] < 0: j += 1 i = j - 1 ans = [] while 0 <= i and j < N: if A[i]**2 < A[j]**2: ans.append(A[i]**2) i -= 1 else: ans.append(A[j]**2) j += 1 while i >= 0: ans.append(A[i]**2) i -= 1 while j < N: ans.append(A[j]**2) j += 1 return ans
true
33e938d5592965fa2c772c5c958ced297ee18955
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/flipEquivalentBinaryTree.py
1,531
4.1875
4
""" Flip Equivalent Binary Trees For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations. Write a function that determines whether two binary trees are flip equivalent. The trees are given by root nodes root1 and root2. """ """ There are 3 cases: If root1 or root2 is null, then they are equivalent if and only if they are both null. Else, if root1 and root2 have different values, they aren't equivalent. Else, let's check whether the children of root1 are equivalent to the children of root2. There are two different ways to pair these children. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None """ Time Complexity: O(min(N_1, N_2)) where N_1, N_2N are the lengths of root1 and root2. Space Complexity: O(min(H_1, H_2)) are the heights of the trees of root1 and root2. """ class Solution: def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: if root1 is None and root2 is None: return True if not root1 or not root2 or root1.val != root2.val: return False return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right)) or (self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left))
true
302f7ed1d4569abaf417efddff2c2b1721146207
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/maxStack.py
2,794
4.25
4
""" Max Stack Design a max stack that supports push, pop, top, peekMax and popMax. push(x) -- Push element x onto stack. pop() -- Remove the element on top of the stack and return it. top() -- Get the element on the top. peekMax() -- Retrieve the maximum element in the stack. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one. Example 1: MaxStack stack = new MaxStack(); stack.push(5); stack.push(1); stack.push(5); stack.top(); -> 5 stack.popMax(); -> 5 stack.top(); -> 1 stack.peekMax(); -> 5 stack.pop(); -> 1 stack.top(); -> 5 Note: -1e7 <= x <= 1e7 Number of operations won't exceed 10000. The last four operations won't be called when stack is empty. """ """ A regular stack already supports the first 3 operations and max heap can take care of the last two. But the main issue is when popping an element form the top of one data structure how can we efficiently remove that element from the other. We can use lazy removal (similar to Approach #2 from 480. Sliding Window Median) to achieve this is in average O(log N) time. """ class MaxStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.maxHeap = [] self.toPop_heap = {} #to keep track of things to remove from the heap self.toPop_stack = set() #to keep track of things to remove from the stack def push(self, x): """ :type x: int :rtype: void """ heapq.heappush(self.maxHeap, (-x,-len(self.stack))) self.stack.append(x) def pop(self): """ :rtype: int """ self.top() x = self.stack.pop() key = (-x,-len(self.stack)) self.toPop_heap[key] = self.toPop_heap.get(key,0) + 1 return x def top(self): """ :rtype: int """ while self.stack and len(self.stack)-1 in self.toPop_stack: x = self.stack.pop() self.toPop_stack.remove(len(self.stack)) return self.stack[-1] def peekMax(self): """ :rtype: int """ while self.maxHeap and self.toPop_heap.get(self.maxHeap[0],0): x = heapq.heappop(self.maxHeap) self.toPop_heap[x] -= 1 return -self.maxHeap[0][0] def popMax(self): """ :rtype: int """ self.peekMax() x,idx = heapq.heappop(self.maxHeap) x,idx = -x,-idx self.toPop_stack.add(idx) return x # Your MaxStack object will be instantiated and called as such: # obj = MaxStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.peekMax() # param_5 = obj.popMax()
true
5851ff675353f950e8a9a1c730774a35ab54b8db
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/stringConversion.py
2,321
4.25
4
""" Given 2 strings s and t, determine if you can convert s into t. The rules are: You can change 1 letter at a time. Once you changed a letter you have to change all occurrences of that letter. Example 1: Input: s = "abca", t = "dced" Output: true Explanation: abca ('a' to 'd') -> dbcd ('c' to 'e') -> dbed ('b' to 'c') -> dced Example 2: Input: s = "ab", t = "ba" Output: true Explanation: ab -> ac -> bc -> ba Example 3: Input: s = "abcdefghijklmnopqrstuvwxyz", t = "bcdefghijklmnopqrstuvwxyza" Output: false Example 4: Input: s = "aa", t = "cd" Output: false Example 5: Input: s = "ab", t = "aa" Output: true Example 6: Input: s = "abcdefghijklmnopqrstuvwxyz", t = "bbcdefghijklmnopqrstuvwxyz" Output: true Both strings contain only lowercase English letters. """ """ Time Complexity: O(s) Space Complexity: O(s) This seems like those mapping problems of one string to another on steroids. After we modify a certain letter, the new letter for that group may be the same as a later letter in s. So we'd want to use a placeholder for certain mappings, but at what point do we run out of placeholders? Definitely when we're using all 26 letters, but is that the only time? It seems like it's very hard to prove that, given all the potential overlaps of mappings that may occur. If that is the reality though, I'd say as long as we can map every letter in s to the same letter in b, and as long as there aren't 26 letters (or if there are 26 letters, the strings must be identical), then we can do the conversion... """ def convert(s, t): if len(s) != len(t): return False if s == t: return True dict_s = {} # match char in s and t unique_t = set() # count unique letters in t for i in range(len(s)): if (s[i] in dict_s): if dict_s[s[i]] != t[i]: return False else: dict_s[s[i]] = t[i] unique_t.add(t[i]) if len(dict_s) == 26: return len(unique_t) < 26 return True if __name__ == '__main__': assert convert('abca', 'dced') == True assert convert('ab', 'ba') == True assert convert('abcdefghijklmnopqrstuvwxyz', 'bcdefghijklmnopqrstuvwxyza') == False assert convert('aa', 'cd') == False assert convert('ab', 'aa') == True assert convert('abcdefghijklmnopqrstuvwxyz', 'bbcdefghijklmnopqrstuvwxyz') == True
true
de1cdd7c24ce9e56af7baaf562ad915960eb246d
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/uniquePaths.py
1,433
4.15625
4
""" Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? """ """ DP (recursion is 2^n) Time: O(m*n) Space: O(m*n) => can be reduced to just storing one row to O(n) space """ class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [[0 for _ in range(m)] for _ in range(n)] dp[0][0] = 1 for i in range(n): for j in range(m): if i == 0 or j == 0: dp[i][j] = 1 else: dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[-1][-1] """ Math Way """ # math C(m+n-2,n-1) def uniquePaths1(self, m, n): if not m or not n: return 0 return math.factorial(m+n-2)/(math.factorial(n-1) * math.factorial(m-1)) class Solution: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ grid = [[1 for i in range(m)] for _ in range(n)] for i in range(n): for j in range(m): if not i or not j: continue grid[i][j] = grid[i - 1][j] + grid[i][j - 1] return grid[n - 1][m - 1]
true
e81fb3440413a2ca42df459fec604df7d2aad8b8
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/largestSubarrayLengthK.py
1,764
4.1875
4
""" Largest Subarray Length K Array X is greater than array Y if the first non matching element in both arrays has a greater value in X than Y. For example: X = [1, 2, 4, 3, 5] Y = [1, 2, 3, 4, 5] X is greater than Y because the first element that does not match is larger in X. and if A = [1, 4, 3, 2, 5] and K = 4, the result is [4, 3, 2, 5] """ # my interpretation is that we can look at all the possible starting indices for a starting array and compare the first value. All elements are unique (distinct), so one value within an array will always be larger or smaller than another--giving us the largest subarray if we just compare that first index. # if A is all unique """ Time: O(N), space: O(1) """ def solution(a, k): # store the first starting index for a subarray as the largest since len(a) will be <= k first_idx = 0 for x in range(1, len(a)-k+1): # check indices where a subarray of size k can be made # replace the largest first index if a larger value is found first_idx = x if a[first_idx] < a[x] else first_idx return a[first_idx:first_idx+k] def solution2(a, k): first_idx = 0 for x in range(1, len(a) - k + 1): # compare values at each index for the would be sub arrays for i in range(k): # replace the largest index and break out of the inner loop is larger value is found if a[first_idx + i] <= a[x + i]: first_idx = x break # if the current stored largest subarray is larger than the current subarray, move on else: break return a[first_idx:first_idx+k] if __name__ == '__main__': assert solution(a=[1, 4, 3, 2, 5], k=4) == [4, 3, 2, 5] assert solution2(a=[1, 4, 3, 2, 5], k=4) == [4, 3, 2, 5] assert solution2(a=[1, 4, 4, 2, 5], k=4) == [4, 4, 2, 5]
true
2b4e64d837993111fde673235c80dc26e3ded912
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/reconstructItinerary.py
2,112
4.375
4
""" Reconstruct Itinerary Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Note: If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. All airports are represented by three capital letters (IATA code). You may assume all tickets form at least one valid itinerary. Example 1: Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] Output: ["JFK", "MUC", "LHR", "SFO", "SJC"] Example 2: Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order. """ """ DFS Time: O(N) where N is number of tickets Note: sort in reverse first so we can have the graph to contain the smallest lexical order so we can guarantee the lexical order of the itinerary can be as good as possible """ class Solution: # Iterative def findItinerary(self, tickets: List[List[str]]) -> List[str]: graph = collections.defaultdict(list) for src, dest in sorted(tickets, reverse=True): graph[src].append(dest) res = [] stack = ['JFK'] while stack: while graph[stack[-1]]: stack.append(graph[stack[-1]].pop()) res.append(stack.pop()) return res[::-1] # Recursive def findItinerary(self, tickets): targets = collections.defaultdict(list) for a, b in sorted(tickets)[::-1]: targets[a] += b, route = [] def visit(airport): while targets[airport]: visit(targets[airport].pop()) route.append(airport) visit('JFK') return route[::-1]
true
768b7b2bb0dd863b28c6ff657a3819fc4ae6162a
akuks/Python3.6---Novice-to-Ninja
/Ch9/09-FileHandling-01.py
634
4.21875
4
import os # Prompt User to Enter the FileName fileName = str(input("Please Enter the file Name: ")) fileName = fileName.strip() while not fileName: print("Name of the File Cannot be left blank.") print("Please Enter the valid Name of the File.") fileName = str(input("Please Enter the file Name: ")) fileName = fileName.strip() # Check if the file Entered by the User exists if not os.path.exists(fileName): print(fileName, " does not exists") print("Exiting the Program") exit(1) print("File Name Entered by the User is : ", fileName) fh = open(fileName, 'r') for line in fh: print(line)
true
848ff8ae6cb99f3f6b768df53ebd4d9fd9486cfe
akuks/Python3.6---Novice-to-Ninja
/Ch8/08-tuple-01.py
204
4.125
4
# Create Tuple tup = (1, 2, 3, "Hello", "World") print(tup) # Looping in Tuple for item in tup: print (item) # in operator b = 4 in tup print(b) # Not in Operator b = 4 not in tup print (b)
true
bbed894c316e17e8cdbde0ed2d0db28ddd6d2285
pbscrimmage/thinkPy
/ch5/is_triangle.py
1,108
4.46875
4
''' is_triangle.py Author: Patrick Rummage [patrickbrummage@gmail.com] Objective: 1. Write a function is_triangl that takes three integers as arguments, and prints either "yes" or "no" depending on whether a triangle may be formed from the given lengths. 2. Write a function that prompts the user to input three lengths, converts them to integers, and uses is_triangle to test whether the given lengths can form a triangle. ''' def test_lengths(): values = [ ['a', 0], ['b', 0], ['c', 0] ] for v in values: # get input and validate valid = False while not valid: v[1] = int(raw_input("Enter a value for %s: " % v[0])) if v[1] < 1: print "a, b, and c must be positive integers!" else: valid = True is_triangle(values[0][1], values[1][1], values[2][1]) def is_triangle(a, b, c): var_list = [a, b, c] for v in var_list: lcopy = var_list[:] lcopy.remove(v) if v > sum(lcopy): print "No." print "Yes." test_lengths()
true
a3338b41d3399b462b32674111f28e465782f6f2
abbye1093/AFS505
/AFS505_U1/assignment3/ex16.py
1,309
4.4375
4
#reading and writing files #close: closes the file, similar to file > save #read: reads contents of files #readline: reads just one readline #truncate: empties the file #write('stuff') : writes 'stuff' to file #seek(0): moves the read/write location to the beginning of the files from sys import argv script, filename = argv #getting filename from the argv entry when opening/running py file print(f"We're goint to erase {filename}.") print("If you don't want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN.") input("?") #want input from user while script is running print("Opening the file...") target = open(filename, 'w') #opening the file in write mode, instead of default read print("Truncating the file. Goodbye!") #truncating empties the file target.truncate() print("Now I'm going to ask you for three lines.") #asks for user input for each line line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: ") print("I'm going to write these to the file.") #will this work? nope, target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print("And finally, we close it.") #close aka file > save target.close() #run close with no parameter changes on target
true
72d72c40a3279d64be8b7677e71761aed1b7155f
ggggg/PythonAssignment-
/exchange.py
452
4.1875
4
# get currency print('enter currency, USD or CAD:') currency = input().upper() # get the value print('Enter value:') value = float(input()) # usd if (currency == 'USD'): # make calculation and output result print('The value in CAD is: $' + str(value * 1.27)) # cad elif (currency == 'CAD'): # make calculation and output result print('The value in USD is: $' + str(value * 0.79)) # currency not found else: print('Currency not found.')
true
efea3fc1186254cd2a2b40171114de6af466a8cd
angelaannjaison/plab
/15.factorial using function.py
312
4.21875
4
def fact(n): f=1 if n==0:print("The factorial of ",n,"is 1") elif(n<0):print("factorial does not exit for negative numbers") else: for i in range(1,n+1): f=f*i print("The factorial of ",n,"is",f) n=int(input("To find factorial:enter a number = ")) fact(n)
true
754c02472453ab001c18bb13f5118aa0851ada80
angelaannjaison/plab
/17.pyramid of numbers.py
258
4.15625
4
def pyramid(n): for i in range(1,n+1):#num of rows for j in range(1,i+1):#num of columns print(i*j,end=" ") print("\n")#line space n=int(input("To construct number pyramid:Enter number of rows and columns: ")) pyramid(n)
true
e500b5ef5f72359ba07c06ed10ec2b3e12dabfb6
angelaannjaison/plab
/to find largest of three numbers.py
297
4.1875
4
print("To find the largest among three numbers") A = int(input("Enter first number = ")) B = int(input("Enter second number = ")) C = int(input("Enter third number = ")) if A>B and A>C: print(A," is greatest") elif B>C: print(B," is greatest") else: print(C,"is greatest")
true
8e3aeedca99b9abff8282876fbf5b655c1f10a76
mtouhidchowdhury/CS1114-Intro-to-python
/Homework 3/hw3q4.py
787
4.46875
4
#homework 3 question 4 #getting the input of the sides a = float(input("Length of first side: ")) b = float(input("Length of second side: ")) c = float(input("Length of third side: ")) if a == b and b == c and a ==c :# if all sides equal equalateral triangle print("This is a equilateral triangle") elif a == b or a == c or b == c:# if two sides equal isosceles triangle print("this is a isoseles triangle") elif (a == b or a == c or b == c) and (a**2 + b**2 == c**2 or a**2 + c**2 == b**2 or c**2 + b**2 == a**2): print("this is an isosceles right triangle ")#if two sides equal and pythagorean formula fits its isosceles right triangle else:#if none of the conditions apply its neither print("neither equalateral nor isosceles right triangle")
true
e2836dded795cfd45e297f05d467e04c35901858
mtouhidchowdhury/CS1114-Intro-to-python
/Homework 7/hw7q3.py
1,710
4.1875
4
#importing module import random #generating a random number and assign to a variable randomNumber = random.randint(1,100) #set number of guesses to 0 and how many remain to 5 numberGuesses= 0 guessRemain = 5 #first guess userGuess = int(input("please enter a number between 1 and 100: ")) # minus from guess remain and adding to number of guesses guessRemain -= 1 numberGuesses += 1 # making bounds for the ranges lowerBound = 0 upperBound = 101 #if first guess correct then goes to if otherwise goes to else if userGuess == randomNumber: print("Your Correct!") #loop till guesses remaining is 0 and user's guess is the number else: while guessRemain != 0 and userGuess != randomNumber : if userGuess < randomNumber: lowerBound = userGuess userGuessLine = "Guess again between "+ str(lowerBound + 1) + " and " + str(upperBound - 1) + ". You have " + str(guessRemain) + " guesses remaining: " userGuess = int(input (userGuessLine)) guessRemain -= 1 numberGuesses += 1 elif userGuess > randomNumber: upperBound = userGuess userGuessLine = "Guess again between " + str(lowerBound + 1) + " and "+ str(upperBound - 1) + ". You have " + str(guessRemain) + " guesses remaining: " userGuess = int(input (userGuessLine)) guessRemain -= 1 numberGuesses += 1 #output if won tells how many guesses took if lost then tells user that he/she lost if userGuess == randomNumber: line= "Congrats! you guessed the answer in " + str(numberGuesses) + " guesses!" print(line) else: print ("You ran out of guesses")
true
a12107517ff64eb1332b2dcfcbe955419bc5d935
kelvin5hart/calculator
/main.py
1,302
4.15625
4
import art print(art.logo) #Calculator Functions #Addition def add (n1, n2): return n1 + n2 #Subtraction def substract (n1, n2): return n1 - n2 #Multiplication def multiply (n1, n2): return n1 * n2 #Division def divide(n1, n2): return n1 / n2 opperators = { "+": add, "-":substract, "*": multiply, "/": divide } def calculator(): num1 = float(input("What's the first number? \n")) nextCalculation = True for i in opperators: print (i) while nextCalculation: operator = input("Pick an operation from the line above: ") if operator not in opperators: nextCalculation = False print("Your entry was invalid") calculator() num2 = float(input("What's the next number? \n")) operation = opperators[operator] result = operation(num1, num2) print(f"{num1} {operator} {num2} = {result}") continueCalculation = input(f"Type 'y' to continue calculating with {result}, or type 'n' to start a new calculation or 'e' to exit. \n").lower() if continueCalculation == "y": num1 = result elif continueCalculation == "n": nextCalculation = False calculator() elif continueCalculation == "e": nextCalculation = False else: print("Invalid Entry") nextCalculation = False calculator()
true
36f1263ebdbaf546d5e6b6ad874a0f8fc51ef65a
andredupontg/PythonInFourHours
/pythonInFourHours.py
1,628
4.1875
4
# Inputs and Outputs """ name = input("Hello whats your name? ") print("Good morning " + name) age = input("and how old are you? ") print("thats cool") """ # Arrays """ list = ["Volvo", "Chevrolet", "Audi"] print(list[2]) """ # Array Functions """ list = ["Volvo", "Chevrolet", "Audi"] list.insert(1, "Corona") list.remove("Corona") list.clear() list.pop() list.index("Volvo) """ # Functions """ def myFirstFunction(): print("Hello this is my first function! ") print("NEW PROGRAM") myFirstFunction() """ # Return Function """ def powerNumber(number): return number * number print("NEW PROGRAM") print(powerNumber(3)) """ # If & Else """ age = 0 if age >= 18: print("Overage") elif age < 18 and age > 0: print("Underage") else: print("Not even born") """ # While Loops """ i = 0 while i < 4: print("Haha") i += 1 print("End of the loop") """ # For Loopss """ fruits = ["apple", "orange", "banana"] for x in fruits: print(x) """ # Class & Objects """ class Student: def __init__(self, name, age, career): self.name = name self.age = age self.career = career student = Student("Andre", 22, "systems engineering") print(student.name) print(student.age) print(student.career) """ # Class Methods """ class Student: def __init__(self, name, age, career): self.name = name self.age = age self.career = career def calculateSalaryByAge(self): if self.age < 60 and self.age >= 18: return 3000 else: return 0 student = Student("Andre", 22, "Systems Engineering") print(student.calculateSalaryByAge()) """
true
f4ac6f727eda468a18aaaeb59489940150419e63
Tanushka27/practice
/Class calc.py
423
4.125
4
print("Calculator(Addition,Subtraction,Multiplication and Division)") No1=input("Enter First value:") No1= eval(No1) No2= input("Enter Second value:") No2= eval(No2) Sum= No1+No2 print (" Sum of both the values=",Sum) Diff= No1-No2 print("Difference of both values=",Diff) prod= No1*No2 print("Product of both the values=",prod) Div= No1/No2 print ("Division of the value is=",Div) mod= No1%No2 print ("remainder is=",mod)
true
9ab6fc2ba3ae33bc507d257745279687926d62d2
khushbooag4/NeoAlgo
/Python/ds/Prefix_to_postfix.py
1,017
4.21875
4
""" An expression is called prefix , if the operator appears in the expression before the operands. (operator operand operand) An expression is called postfix , if the operator appears in the expression after the operands . (operand operand operator) The program below accepts an expression in prefix and outputs the corresponding postfix expression . """ # prefixtopostfix function converts a prefix expression to postfix def prefixtopostfix(exp): stack = [] n = len(exp) for i in range(n - 1, -1, -1): if exp[i].isalpha(): stack.append(exp[i]) else: op1 = stack.pop() op2 = stack.pop() stack.append(op1 + op2 + exp[i]) print("the postfix expresssion is : " + stack.pop()) # Driver Code if __name__ == "__main__": exp = input("Enter the prefix expression : ") prefixtopostfix(exp) """ Sample I/O: Enter the prefix expression : *+abc the postfix expresssion is : ab+c* Time complexity : O(n) space complexity : O (n) """
true
9adc4c2e16a6468b7c39231425c0c7f2a3b6f843
khushbooag4/NeoAlgo
/Python/ds/Sum_of_Linked_list.py
2,015
4.25
4
""" Program to calculate sum of linked list. In the sum_ll function we traversed through all the functions of the linked list and calculate the sum of every data element of every node in the linked list. """ # A node class class Node: # To create a new node def __init__(self, data): self.data = data self.next = None # Class Linked list class LinkedList: # create a empty linked list def __init__(self): self.head = None # Function to insert elements in linked list def push(self, data): newNode = Node(data) temp = self.head newNode.next = self.head # If linked list is not None then insert at last if self.head is not None: while (temp.next != self.head): temp = temp.next temp.next = newNode else: newNode.next = newNode # For the first node self.head = newNode # Function to print given linked list def print_List(self): temp = self.head if self.head is not None: while (True): print(temp.data) temp = temp.next if (temp == self.head): break # Function to calculate sum of a Linked list def sum_ll(self, head): sum_ = 0 temp = self.head if self.head is not None: while True: sum_ += temp.data temp = temp.next return sum_ # Initialize lists as empty by creating Linkedlist objects head = LinkedList() # Pushing elements into LinkedList n = int(input("Enter the no. of elements you want to insert: ")) for i in range(n): number = int(input(f"Enter Element {i + 1}: ")) head.push(number) print("Entered Linked List: ") head.print_List() sum_ = head.sum_ll(head) print(f"\nSum of Linked List: {sum_}") """ Time Complexity: O(n) Space Complexity: O(n) SAMPLE INPUT/OUTPUT: Entered Circular Linked List: 20 30 40 50 Sum of Linked List: 140 """
true
ca903edb902b818cd3cda5ad5ab975f12f99d467
khushbooag4/NeoAlgo
/Python/search/three_sum_problem.py
2,643
4.15625
4
""" Introduction: Two pointer technique is an optimization technique which is a really clever way of using brute-force to search for a particular pattern in a sorted list. Purpose: The code segment below solves the Three Sum Problem. We have to find a triplet out of the given list of numbers such that the sum of that triplet equals to another given value. The Naive Approach is to calculate the sum of all possible triplets and return the one with the required sum or None. This approach takes O(N^3) time to run. However, by using Two pointer search technique we can reduce the time complexity to O(N^2). Method: Three Sum Problem using Two Pointer Technique """ def three_sum_problem(numbers, sum_val): """ Returns a triplet (x1,x2, x3) in list of numbers if found, whose sum equals sum_val, or None """ # Sort the given list of numbers # Time complexity: O(N.logN) numbers.sort() size = len(numbers) # Two nested loops # Time complexity: O(N^2) for i in range(size-3+1): # Reduce the problem to two sum problem two_sum = sum_val - numbers[i] # Initialize the two pointers left = i+1 right = size-1 # Search in the array until the two pointers overlap while left < right: curr_sum = numbers[left] + numbers[right] # Update the pointers if curr_sum < two_sum: left += 1 elif curr_sum > two_sum: right -= 1 else: # Return the numbers that form the desired triplet return "({},{},{})".format(numbers[i], numbers[left], numbers[right]) # No triplet found return None def main(): """ Takes user input and calls the necessary function """ # Take user input numbers = list(map(int, input("Enter the list of numbers: ").split())) sum_val = int(input("Enter the value of sum: ")) # Find the triplet triplet = three_sum_problem(numbers, sum_val) if triplet is None: print(f"No triplet found with sum: {sum_val}") else: print(f"{triplet} is the triplet with sum: {sum_val}") if __name__ == "__main__": # Driver code main() """ Sample Input 1: Enter the list of numbers: 12 3 4 1 6 9 Enter the value of sum: 24 Sample Output 1: (3,9,12) is the triplet with sum: 24 Time Complexity: For sorting: O(N.log N) For two-pointer technique: O(N^2) T = O(N.log N) + O(N^2) T = O(N^2) """
true
8d08dac477e5b8207c351650fef30b64da52c64a
khushbooag4/NeoAlgo
/Python/math/roots_of_quadratic_equation.py
1,544
4.34375
4
'''' This is the simple python code for finding the roots of quadratic equation. Approach : Enter the values of a,b,c of the quadratic equation of the form (ax^2 bx + c ) the function quadraticRoots will calculate the Discriminant , if D is greater than 0 then it will find the roots and print them otherwise it will print Imaginary!! ''' import math class Solution: def quadraticRoots(self, a, b, c): d = ((b*b) - (4*a*c)) if d<0: lst=[] lst.append(-1) return lst D = int(math.sqrt(d)) x1 = math.floor((-1*b + D)/(2*a)) x2 = math.floor((-1*b - D)/(2*a)) lst = [] lst.append(int(x1)) lst.append(int(x2)) lst.sort() lst.reverse() return lst # Driver Code Starts if __name__ == '__main__': # For the values of a,b,c taking in a list in one line eg : 1 2 3 print("Enter the values for a,b,c of the equation of the form ax^2 + bx +c") abc=[int(x) for x in input().strip().split()] a=abc[0] b=abc[1] c=abc[2] # Making a object to class Solution ob = Solution() ans = ob.quadraticRoots(a,b,c) if len(ans)==1 and ans[0]==-1: print("Imaginary Roots") else: print("Roots are :",end=" ") for i in range(len(ans)): print(ans[i], end=" ") print() ''' Sample Input/Output: Enter the values for a,b,c of the equation of the form ax^2 + bx +c 1 2 1 Output: Roots are : -1 -1 Time Complexity : O(1) Space Complexity : O(1) '''
true
e88f786eb63150123d9aba3a3dd5f9309d825ca1
khushbooag4/NeoAlgo
/Python/math/positive_decimal_to_binary.py
876
4.59375
5
#Function to convert a positive decimal number into its binary equivalent ''' By using the double dabble method, append the remainder to the list and divide the number by 2 till it is not equal to zero ''' def DecimalToBinary(num): #the binary equivalent of 0 is 0000 if num == 0: print('0000') return else: binary = [] while num != 0: rem = num % 2 binary.append(rem) num = num // 2 #reverse the list and print it binary.reverse() for bit in binary: print(bit, end="") #executable code decimal = int(input("Enter a decimal number to be converted to binary : ")) print("Binary number : ") DecimalToBinary(decimal) ''' Sample I/O : Input : Enter a decimal number to be converted into binary: 8 Output: Binary number: 1000 Time Complexity : O(n) Space Complexity : O(1) '''
true
170fef88011fbda1f0789e132f1fadb71ebca009
khushbooag4/NeoAlgo
/Python/cp/adjacent_elements_product.py
811
4.125
4
""" When given a list of integers, we have to find the pair of adjacent elements that have the largest product and return that product. """ def MaxAdjacentProduct(intList): max = intList[0]*intList[1] a = 0 b = 1 for i in range(1, len(intList) - 1): if(intList[i]*intList[i+1] > max): a = i b = i+1 max = intList[i]*intList[i+1] return(a, b, max) if __name__ == '__main__': intList = list(map(int, input("\nEnter the numbers : ").strip().split())) pos1, pos2, max = MaxAdjacentProduct(intList) print("Max= ", max, " product of elements at position ", pos1, ",", pos2) """ Sample Input - Output: Enter the numbers : -5 -3 -2 Max= 15 product of elements at position 0 , 1 Time Complexity : O(n) Space Complexity : O(1) """
true
99f2401aa02902befcf1ecc4a60010bb8f02bc32
khushbooag4/NeoAlgo
/Python/other/stringkth.py
775
4.1875
4
''' A program to remove the kth index from a string and print the remaining string.In case the value of k is greater than length of string then return the complete string as it is. ''' #main function def main(): s=input("enter a string") k=int(input("enter the index")) l=len(s) #Check whether the value of k is greater than length if(k>l): print(s) #If k is less than length of string then remove the kth index value else: s1='' for i in range(0,l): if(i!=k): s1=s1+s[i] print(s1) if __name__== "__main__": main() ''' Time Complexity:O(n),n is length of string Space Complexity:O(1) Input/Output: enter a string python enter the index 2 pyhon '''
true
a5336ab6b2ac779752cab97aee3dcca16237a4d7
dkrajeshwari/python
/python/prime.py
321
4.25
4
#program to check if a given number is prime or not def is_prime(N): if N<2: return False for i in range (2,N//2+1): if N%i==0: return False return True LB=int(input("Enter lower bound:")) UB=int(input("Enter upper bound:")) for i in range(LB,UB+1): if is_prime(i): print(i)
true
204a83101aee7c633893d87a111785c3884829de
dkrajeshwari/python
/python/bill.py
376
4.125
4
#program to calculate the electric bill #min bill 50rupee #1-500 6rupees/unit #501-1000 8rupees/unit #>1000 12rupees/unit units=int(input("Enter the number of units:")) if units>=1 and units<=500: rate=6 elif units>=501 and units<=1000: rate=8 elif units>1000: rate=12 amount=units*rate if amount<50: amount=50 print(f"Units used:{units},Bill amount:{amount}")
true
458273bb73e4b98f097fbb87cfa531f994f55fc7
vaishnavi59501/DemoRepo1
/samplescript.py
2,635
4.59375
5
#!/bin/python3 #this scipt file contains list,tuple,dictionary and implementation of functions on list,tuple and Dictionary #list #list is collection of objects of different types and it is enclosed in square brackets. li=['physics', 'chemistry', 1997, 2000] list3 = ["a", "b", "c", "d"] print(li[1]) #accessing first element in list li print(li) #diplaying the list li print(li[:2]) #displaying range of elements in list print(li*2) #displaying list li two times using repetition operator(*) l=li+list3 print(l) #concatenating two lists and displaying it #updating list li[2]='physics' print(li) a=1997 print(a in li) #returns true if a is member of list otherwise false print(len(li)) #returns the no of elements in list print(max(list3)) #returns maximum element in list list3 print(min(list3)) #returns minimum element in list list3 list3=list3+["e","f"] #adding elements to the list print(list3) tuple1=(1,2,3,4,5) print("tuple :",tuple1) #converting sequence of elements (e.g. tuple) to list print("tuple converted to list ",list(tuple1)) print(list1.count(123)) #returns the number of occurence of the element in the list print(list3) del list3[3] #deletes the element at index 3 in list3 print(list3) #tuple #tuple is similar to list but the difference is elements are enclosed using braces () and here updating tuple is not valid action. tup=(23,) #declaring tuple with single element along with character comma print(tup) print(tup+(34,36,37)) #adding elements to tuple print(len(tup)) #returns the no of elements in tuple print(tuple(li)) #converts list li to tuple #Dictionary #Dictionary is kind of hash table type whicl has key-value pairs dict1={1:"apple",2:"orange"} #declaring dictionary with key:value pair, here key can be of numeral or string datatype print(dict1) print(dict1[2]) #getting the value of key 2 print(dict1.keys()) #extracting keys set from dictionary print(dict1.values()) #extracting values set form dictionary dict1[3]="grapes" #adding new key value pair print(dict1) #del dict1[3] print(dict1[1]) print(len(dict1)) # returns the no of key-value pairs in dictionary dict1 print(str(dict1)) # displays dict1 in string representation print(type(dict1)) # returns the type of dict1 dict2=dict1.copy() #copying dict1 to dict2 print(dict2) dict3=dict.fromkeys(list3,"value") #converting list to dictionary with default value-"value" print(dict3) print(dict1.get(2)) #accessing value of key 2 in dictionary print(dict1.get(4,"pears")) print(dict1) dic={4:"avacado"} dict1.update(dic) #adding new key-value pair to existing dict1 by update() method print(dict1)
true
46d85c6a471072788ab8ec99470f0b27e9d1939d
cscosu/ctf0
/reversing/00-di-why/pw_man.py
1,614
4.125
4
#!/usr/bin/env python3 import sys KEY = b'\x7b\x36\x14\xf6\xb3\x2a\x4d\x14\x19' SECRET = b'\x13\x59\x7a\x93\xca\x49\x22\x79\x7b' def authenticate(password): ''' Authenticates the user by checking the given password ''' # Convert to the proper data type password = password.encode() # We can't proceed if the password isn't even the correct length if len(password) != len(SECRET): return False tmp = bytearray(len(SECRET)) for i in range(len(SECRET)): tmp[i] = password[i] ^ KEY[i] return tmp == SECRET def get_pw_db(file_name): ''' Constructs a password database from the given file ''' pw_db = {} with open(file_name) as f: for line in f.readlines(): entry, pw = line.split('=', 1) pw_db[entry.strip()] = pw.strip() return pw_db def main(): ''' Main entry point of the program. Handles I/O and contains the main loop ''' print('Welcome to pw_man version 1.0') password = input('password: ') if not authenticate(password): print('You are not authorized to use this program!') sys.exit(1) pw_db = get_pw_db(sys.argv[1]) print('Passwords loaded.') while True: print('Select the entry you would like to read:') for entry in pw_db.keys(): print('--> {}'.format(entry)) selected = input('Your choice: ') try: print('password for {}: {}'.format(selected, pw_db[selected])) except KeyError: print('unrecognized selection: {}'.format(selected)) print('please') if __name__ == '__main__': main()
true
438658b5f7165211e7ec5dec55b63097c5852ede
alshore/firstCapstone
/camel.py
527
4.125
4
#define main function def main(): # get input from user # set to title case and split into array words = raw_input("Enter text to convert: ").title().split() # initialize results variable camel = "" for word in words: # first word all lower case if word == words[0]: word = word.lower() # add word to results string camel += word else: # all other words remain in title case and # get added to the results string camel += word # print results to console print camel # call main function main()
true
33735735d54ebe3842fca2fa506277e2cd529734
georgemarshall180/Dev
/workspace/Python_Play/Shakes/words.py
1,074
4.28125
4
# Filename: # Created by: George Marshall # Created: # Description: counts the most common words in shakespeares complete works. import string # start of main def main(): fhand = open('shakes.txt') # open the file to analyzed. counts = dict() # this is a dict to hold the words and the number of them. for line in fhand: line = line.translate(string.punctuation) #next lines strip extra stuff out and format properly. line = line.lower() line = line.replace('+',' ') words = line.split() for word in words: # counts the words. if word not in counts: counts[word] = 1 else: counts[word] += 1 # Sort the dictionary by value lst = list() for key, val in counts.items(): lst.append((val, key)) lst.sort(reverse=True) # sorts the list from Greatest to least. # print the list out. for key, val in lst[:100]: print(key, val) # runs this file if it is main if __name__ == "__main__": main()
true
ddbedd13893047ab7611fe8d1b381575368680a6
ryanSoftwareEngineer/algorithms
/arrays and matrices/49_group_anagrams.py
1,408
4.15625
4
''' Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] ''' def groupAnagrams( strs): output = [] map = {} map_i = 0 for i in strs: b = i[:] b= "".join(sorted(b)) if b in map: output[map[b]].append(i) else: map[b] = map_i output.append([i]) map_i += 1 return output def attempttwo(strs): # iterate through strs # for every iteration of strs iterate through single string # create array 0 to 26 to hold counts # array of 26 from 0 to 26 represents count for each character # convert to string of ints or tuple(array) # use hash table to store string of counts answer = {} for word in strs: alphabet = [0]*26 for char in word: alphabet[ord(char.lower())-ord('a')] += 1 str_result = str(alphabet) if str_result in answer: answer[str_result].append(word) else: answer[str_result] = [word] return list(answer.values()) strs = ["eat","tea","tan","ate","nat","bat"] print(attempttwo(strs))
true
57cd15146c5a663a0ccaa74d2187dce5c5dc6962
PabloLSalatic/Python-100-Days
/Days/Day 2/Q6.py
498
4.1875
4
print('------ Q 6 ------') # ?Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. # ?Suppose the following input is supplied to the program: # ?Hello world # ?Practice makes perfect # *Then, the output should be: # *HELLO WORLD # *PRACTICE MAKES PERFECT lines = [] while True: line = input('linea: ') if line: lines.append(line.upper()) else: break for line in lines: print(line)
true
7902ec6be552b5e44af3e0c73335acd52c7cb3e7
44858/lists
/Bubble Sort.py
609
4.28125
4
#Lewis Travers #09/01/2015 #Bubble Sort unsorted_list = ["a", "d", "c", "e", "b", "f", "h", "g"] def bubble_sort(unsorted_list): list_sorted = False length = len(unsorted_list) - 1 while not list_sorted: list_sorted = True for num in range(length): if unsorted_list[num] > unsorted_list[num+1]: list_sorted = False unsorted_list[num], unsorted_list[num+1] = unsorted_list[num+1], unsorted_list[num] return unsorted_list #main program sorted_list = bubble_sort(unsorted_list) print(sorted_list)
true
90b59d5607388d4f18382624219a9fcfd7c9cf17
LorenzoY2J/py111
/Tasks/d0_stairway.py
675
4.3125
4
from typing import Union, Sequence from itertools import islice def stairway_path(stairway: Sequence[Union[float, int]]) -> Union[float, int]: """ Calculate min cost of getting to the top of stairway if agent can go on next or through one step. :param stairway: list of ints, where each int is a cost of appropriate step :return: minimal cost of getting to the top """ prev_1, prev = stairway[0], stairway[1] for cost in islice(stairway, 2, len(stairway)): current = cost + min(prev_1, prev) prev_1, prev = prev, current return prev if __name__ == '__main__': stairway = [1, 3, 5, 1] print(stairway_path(stairway))
true
15242cc4f007545a85c3d7f65039678617051231
LorenzoY2J/py111
/Tasks/b1_binary_search.py
841
4.1875
4
from typing import Sequence, Optional def binary_search(elem: int, arr: Sequence) -> Optional[int]: """ Performs binary search of given element inside of array :param elem: element to be found :param arr: array where element is to be found :return: Index of element if it's presented in the arr, None otherwise """ first = 0 last = len(arr) - 1 while first <= last: mid = (last + first) // 2 if elem == arr[mid]: break elif elem < arr[mid]: last = mid - 1 else: first = mid + 1 else: return None while mid > 0 and arr[mid - 1] == elem: mid -= 1 return mid def main(): elem = 10 arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(binary_search(elem, arr)) if __name__ == '__main__': main()
true
7941328e4cb2d286fefd935541e2dab8afde61c0
SACHSTech/ics2o1-livehack---2-Maximilian-Schwarzenberg
/problem2.py
771
4.59375
5
""" ------------------------------------------------------------------------------- Name: problem2.py Purpose: To check if the inputted sides form a triangle. Author: Schwarenberg.M Created: 23/02/2021 ------------------------------------------------------------------------------ """ # Welcome message print("Welcome to the Triangle Checker") print("---") # Input triangle sides side1 = int(input("Enter the length of the first side: ")) side2 = int(input("Enter the length of the second side: ")) side3 = int(input("Enter the length of the third side: ")) print("---") # processing and output of data if side1 + side2 >= side3 or side1 + side3 >= side2 or side3 + side2 >= side1: print("The figure is a triangle.") else: print("The figure is NOT a triangle.")
true
9b3495345e4f4ad9648dcca17a8288e62db1220e
sriniverve/Python_Learning
/venv/tests/conditions.py
271
4.21875
4
''' This is to demonstrate the usage of conditional operators ''' temperature = input('Enter the temperature:') if int(temperature) > 30: print('This is a hot day') elif int(temperature) < 5: print('This is a cold day') else: print('This is a pleasant day')
true
1140a8dd58988892ecca96673ffe3d2c1bf44564
sriniverve/Python_Learning
/venv/tests/guessing_number.py
395
4.21875
4
''' This is an example program for gussing a number using while loop ''' secret_number = 9 guess_count = 0 guess_limit = 3 while guess_count < guess_limit: guess_number = int(input('Guess a number: ')) guess_count += 1 if guess_number == secret_number: print('You guessed it right. You Win!!!') break else: print('You are have exhausted your options. Sorry!!!')
true
01b3319010f240b6ddfdd0b5ae3e07f201a9a046
sriniverve/Python_Learning
/venv/tests/kg2lb_converter.py
285
4.21875
4
''' This program is to take input in KGs & display the weight in pounds ''' weight_kg = input('Enter your weight in Kilograms:') #prompt user input weight_lb = 2.2 * float(weight_kg) #1 kg is 2.2 pounds print('You weight is '+str(weight_lb)+' pounds')
true
23d110cff79eb57616586da7f78c7ac6d4e7a957
vmmc2/Competitive-Programming
/Sets.py
1,369
4.4375
4
#set is like a list but it removes repeated values #1) Initializing: To create a set, we use the set function: set() x = set([1,2,3,4,5]) z = {1,2,3} #To create an empty set we use the following: y = set() #2) Adding a value to a set x.add(3) #The add function just works when we are inserting just 1 element into our set #3) Adding more than one element to a set x.update([34,45,56]) #To do this, we use the update function. #We can also pass another set to the update function y = {1,2,3} a = {4,5,6} y.update(a, [34,45,56]) #4) Removing a specific value from a set #We can use two different functions to do this same action: remove() and discard() a.remove(1) or a.discard(1) #The problem with remove() is that if we are trying to remove a value that doesn`t exist in the set, we are going to get a key error. #On the other hand, if we try to discard a value that doesn`t exist, then we don`t get any type of error. In other words, it works just fine. So, ALWAYS use the discard() method. s1 = {1,2,3} s2 = {2,3,4} s3 = {3,4,5} #5) Intersection Method s4 = s1.intersection(s2) # s4 = {2,3} s4 = s1.intersection(s2, s3) # s4 = {3} #6) Difference Method s4 = s1.difference(s2) # s4 = {1} s4 = s2.difference(s1) # s4 = {4} #OBSERVATION: We can pass multiple sets as arguments to these different methods. #7) Sym Difference s4 = s1.symmetric_difference(s2)
true
768ce4a45879ad23c94de8d37f33f7c8c50dca24
AmangeldiK/lesson3
/kall.py
795
4.1875
4
active = True while active: num1 = int(input('Enter first number: ')) oper = input('Enter operations: ') num2 = int(input('Enter second number: ')) #dict_ = {'+': 'num1 + num2', '-': 'num1 - num2', '*': 'num1 * num2', '/': 'num1 / num2'} if oper == '+': print(num1+num2) elif oper == '-': print(num1-num2) else: if oper == '*': print(num1*num2) elif oper == '/': try: num1 / num2 == 0 except ZeroDivisionError: print('Division by zero is forbidden!') else: print(num1/num2) else: print('Wrong operations') continue_ = input('If you want continue click any button and Enter, if not click to Enter: ')
true
230616616f10a6207b4a407b768afaabb846528a
SynthetiCode/EasyGames-Python
/guessGame.py
744
4.125
4
#This is a "Guess the number game" import random print('Hello. What is your nombre?') nombre = input() print('Well, ' + nombre + ', I am thining of a numero between Uno(1) y Veinte(20)') secretNumber =random.randint(1,20) #ask player 6 times for guessesTaken in range(0, 6): print ('Take a guess:' ) guess = int(input()) if guess < secretNumber: print ('Your guess is too low.') elif guess > secretNumber: print ('Your guess is too high.') else: break # <-- This condition is the correct guess! if guess ==secretNumber: print ('Good job, ' + nombre + '! You guessed my number in ' + str(guessesTaken+1)+ ' guesses!') else: print ('Nope, the number I was thinking of was: ' + str(secretNumber)) print ('Better luck next time')
true
fb038cc7201cd3302a5eeedf9fd86511d6ff2cf6
mdanassid2254/pythonTT
/constrector/hashing.py
422
4.65625
5
# Python 3 code to demonstrate # working of hash() # initializing objects int_val = 4 str_val = 'GeeksforGeeks' flt_val = 24.56 # Printing the hash values. # Notice Integer value doesn't change # You'l have answer later in article. print("The integer hash value is : " + str(hash(int_val))) print("The string hash value is : " + str(hash(str_val))) print("The float hash value is : " + str(hash(flt_val)))
true
0e6b136b69f36b75e8088756712889eb45f1d24a
Kaden-A/GameDesign2021
/VarAndStrings.py
882
4.375
4
#Kaden Alibhai 6/7/21 #We are learning how to work with strings #While loop #Different type of var num1=19 num2=3.5 num3=0x2342FABCDEBDA #How to know what type of date is a variable print(type(num1)) print(type(num2)) print(type(num3)) phrase="Hello there!" print(type(phrase)) #String functions num=len(phrase) print(phrase[3:7]) #from 3 to 6 print(phrase[6:]) #from index to the end print(phrase*2) #print it twice #concadentation --> joining strings phrase = phrase + "Goodbye" print(phrase) print(phrase[2:num-1]) while "there" in phrase: print("there" in phrase) phrase="changed" print(phrase) # make 3 string variables print them individually #"print s1+s2" #print st2+st3 #print st1+st2+st3 phrase1="Lebron" phrase2=">" phrase3="MJ" print(phrase1) print(phrase2) print(phrase3) print(phrase1+phrase2) print(phrase2+phrase3) print(phrase1+ " ", phrase2+ " ",phrase3)
true
f7aac03275b43a35f790d9698b94e76f93207e7d
abokareem/LuhnAlgorithm
/luhnalgo.py
1,758
4.21875
4
""" ------------------------------------------ |Luhn Algorithm by Brian Oliver, 07/15/19 | ------------------------------------------ The Luhn Algorithm is commonly used to verify credit card numbers, IMEI numbers, etc... Luhn makes it possible to check numbers (credit card, SIRET, etc.) via a control key (called checksum, it is a number of the number which makes it possible to check the others). If a character is incorrect, then Luhn's algorithm will detect the error. Starting with the right-most digit, double every other digit to the left of it. Then all of the undoubled and doubled digits together. If the total is a multiple of 10, then the number passes the Luhn Algorithm. For Luhn to be true: (double digits + undoubled digits) % 10 == 0 ======================================================================================================================== """ def luhn_algorithm_test(number): digit_list = list(map(int, str(number))) luhn_digits = [] total = 0 for digit in digit_list[-2::-2]: double_digit = digit * 2 if double_digit >= 10: double_digit = double_digit - 9 luhn_digits.append(double_digit) digit_list.remove(digit) total = sum(digit_list) + sum(luhn_digits) if total % 10 == 0: return "Luhn Algorithm Test Passed" else: return "Luhn Algorithm Test Failed" def main(): while True: try: number = int(input("Please enter a number: ")) print(luhn_algorithm_test(number)) except ValueError: print("Sorry, please input numbers only.") continue else: break if __name__ == '__main__': main()
true
f4e4beb1d2975fd523ca7dd744aa7a96e686373a
WeiyiDeng/hpsc_LinuxVM
/lecture7/debugtry.py
578
4.15625
4
x = 3 y = 22 def ff(z): x = z+3 # x here is local variable in the func print("+++ in func ff, x = %s; y = %s; z = %s") %(x,y,z) return(x) # does not change the value of x in the main program # to avoid confusion, use a different symbol (eg. u) instead of x in the function print("+++ before excuting ff, x = %s; y = %s") %(x,y) y = ff(x) print("+++ after excuting ff, x = %s; y = %s") %(x,y) # in ipython>>> run debugtry.py # outputs: # before ff: x = 3, y = 22 # within ff: z = 3, x = 6, y = 22 # after ff: x = 3, y = 6
true
f0778146abc57271d1587461b9893289fd65dc86
bedoyama/python-crash-course
/basics/ch4__WORKING_WITH_LISTS/2_first_numbers.py
358
4.375
4
print("range(1,5)") for value in range(1, 5): print(value) print("range(0,7)") for value in range(0, 7): print(value) print("range(7)") for value in range(7): print(value) print("range(3,7)") for value in range(3, 7): print(value) print("range(-1,2)") for value in range(-1, 2): print(value) numbers = list(range(4)) print(numbers)
true
8b8e3c886a6d3acf6a0c7718919c56f354c3c912
bedoyama/python-crash-course
/basics/ch5__IF_STATEMENTS/3_age.py
338
4.15625
4
age = 42 if age >= 40 and age <= 46: print('Age is in range') if (age >= 40) and (age <= 46): print('Age is in range') if age < 40 or age > 46: print('Age is older or younger') age = 39 if age < 40 or age > 46: print('Age is older or younger') age = 56 if age < 40 or age > 46: print('Age is older or younger')
true
2b03e816c33cfdcfd9b5167de46fda66c7dda199
angelavuong/python_exercises
/coding_challenges/grading_students.py
981
4.125
4
''' Name: Grading Students Task: - If the difference between the grade and the next multiple of 5 is less than 3, round grade up to the next multiple of 5. - If the value of grade is less than 38, no rounding occurs as the result will still be a failing grade. Example: grade = 84 will be rounded to 85 grade = 29 will not be rounded because it is less than 40 ''' #!/bin/python3 import sys def solve(grades): # Complete this function new_list = [] for each in grades: if (each < 38): pass else: if (each%5 >= 3): remainder = 5 - (each%5) each = remainder + each elif(each%5 == 0): pass else: pass new_list.append(each) return new_list n = int(input().strip()) grades = [] grades_i = 0 for grades_i in range(n): grades_t = int(input().strip()) grades.append(grades_t) result = solve(grades) print ("\n".join(map(str, result)))
true
570b9f3e710d94baf3f4db276201a9c484da4a71
angelavuong/python_exercises
/coding_challenges/count_strings.py
573
4.125
4
''' Name: Count Sub-Strings Task: Given a string, S, and a substring - count the number of times the substring appears. Sample Input: ABCDCDC CDC Sample Output: 2 ''' def count_substring(string,sub_string): counter = 0 length = len(sub_string) for i in range(len(string)): if (string[i] == sub_string[0]): if (string[i:(i+length)] == sub_string): counter += 1 else: pass return counter string = input().strip() sub_string = input().strip() count = count_substring(string,sub_string) print(count)
true
aa378a188bce0e97a0545221e65f148838b3650c
angelavuong/python_exercises
/coding_challenges/whats_your_name.py
536
4.1875
4
''' Name: What's Your Name? Task: You are given the first name and last name of a person on two different lines. Your task is to read them and print the following: Hello <firstname> <lastname>! You just delved into python. Sample Input: Guido Rossum Sample Output: Hello Guido Rossum! You just delved into python. ''' def print_full_name(a, b): print("Hello " + a + " " + b + "! You just delved into python.") if __name__ == '__main__': first_name = raw_input() last_name = raw_input() print_full_name(first_name, last_name)
true
d5d229788bf6391a3be21f75c54166a1b836b3e4
6reg/pc_func_fun
/rev_and_normalized.py
519
4.15625
4
def reverse_string(s): reversed = "" for i in s: reversed = i + reversed return reversed def normalize(s): normalized = "" for ch in s: if ch.isalpha(): normalized += ch.lower() return normalized def is_palindrome(s): normalized = normalize(s) rev = reverse_string(normalized) return normalized == rev print(is_palindrome("Hello")) print(is_palindrome("A man, a plan, a canal - Panama!")) print(is_palindrome("kayak")) print(is_palindrome("Goodbye"))
true
cd916150b60d80e1def43eb10aaafd65429badb1
lumeng/repogit-mengapps
/data_mining/wordcount.py
2,121
4.34375
4
#!/usr/bin/python -tt ## Summary: count words in a text file import sys import re # for normalizing words def normalize_word(word): word_normalized = word.strip().lower() match = re.search(r'\W*(\w+|\w\W+\w)\W*', word_normalized) if match: return match.group(1) else: return word_normalized def count_word_in_file(filename): #my_file = open(filename, 'rU', 'utf-8') my_file = open(filename, 'rU') word_dict = {} for line in my_file: words = line.split() for w in words: # mengToDo: improve word normalization logic # What Google's n-gram data set uses? w_normalized = normalize_word(w) if w_normalized in word_dict: word_dict[w_normalized] += 1 else: word_dict[w_normalized] = 1 return word_dict def print_word_count(filename): """counts how often each word appears in the text and prints: word1 count1 word2 count2 ... in order sorted by word. 'Foo' and 'foo' count as the same word """ word_count_dict = sorted(count_word_in_file(filename).items()) for word, count in word_count_dict: print word, count return word_count_dict def get_count(word_count_tup): return word_count_tup[1] def print_top_words(filename, size=50): """prints just the top 20 most common words sorted by sizeber of occurrences of each word such that the most common word is first.""" word_count_dict = count_word_in_file(filename) sorted_word_count_dict = sorted(word_count_dict.items(), key=get_count, reverse=True) for word, count in sorted_word_count_dict[:size]: print word, count ### def main(): if len(sys.argv) != 3: print 'usage: ./wordcount.py {--count | --topwords} file' sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == '--count': print_word_count(filename) elif option == '--topwords': print_top_words(filename) else: print 'unknown option: ' + option sys.exit(1) if __name__ == '__main__': main() # END
true
f65486941b6ee5852a4aaf2bf6547b7d5d863dd9
blei7/Software_Testing_Python
/mlist/binary_search.py
1,682
4.3125
4
# binary_search.py def binary_search(x, lst): ''' Usage: The function applies the generic binary search algorithm to search if the value x exists in the lst, and returns a list contains: TRUE/FAlSE depends on whether the x value has been found, x value, and x position indice in list Argument: x: numeric lst: sorted list of numerics Return: a list contains: - first element is a logical value (TRUE/FALSE) - second element is a numeric value of x - third element is a numeric in range of 0 to length(list) where 0 indicates the element is not in the list Examples: binary_search(4, [1,2,3,4,5,6]) >>> [TRUE,4,3] binary_search(5, [10,100,200,300]) >>> [FALSE,5,0] ''' # Raise error if input not a list if type(lst) != list: raise TypeError("Input must be a list") # Raise error if input is not integer (eg. float, string...) for i in lst: if type(i) != int: raise TypeError("Input must be list of intergers") # Raise error if input values less than 1000 if max(lst) >= 1000: raise ValueError("Input values exceed 1000. Please limit range of input values to less than 1000.") #binary search algorithm #empty list if len(lst) == 0: return [False, x, 0] low = 0 high = len(lst)-1 while low <= high: mid = (low + high) //2 if lst[mid] < x: low = mid + 1 elif x < lst[mid]: high = mid - 1 else: return [True, x, mid] return [False, x, 0]
true
612c8ca841d8da2fc2e8e00f1a14fb22126d1277
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/ways-to-climb-stairs/main.py
2,336
4.1875
4
# Problem : Given a staircase of n steps and a set of possible steps that we can climb at a time # named possibleSteps, create a function that returns the number of ways a person can take to reach the # top of the staircase. # Ex : Input : n = 5, possibleSteps = {1,2} # Output : 8 # Explanation : Possible ways are - 11111, 1112, 1121, 1211, 2111, 122, 212, 221 # Think recursively with a few examples and see if there is any pattern to the solution # When n=0 , possibleSteps = {1,2} - Output = 1 # When n = 1, possibleSteps = {1,2} - Output = 1 # When n = 2, possibleSteps = {1,2} - Output = 2 # When n = 3, possibleSteps = {1,2} - Output = 3 # When n = 4, possibleSteps = {1,2} - Output = 5 # When n = 5, possibleSteps = {1,2} - Output = 8 # The output is a fibonacci sequence : 1,1,2,3,5,8 # The recursive relation here is f(n) = f(n-1) + f(n-2) # # This is because to climb any set of steps n, if the solution is f(n), # then we can find f(n) by finding the solution to climb n-1 steps + 1 step OR n-2 steps and 2 steps, # ie to reach the top we must be either 1 step away from it or 2 steps away from it. # That's why f(n) = f(n-1) + f(n-2) # # Similarly when possibleSteps = {2,3,4}, then to reach any step n, we must be either 2 steps # away from it or 3 steps away from it or 4 steps away from it. # f(n) = f(n-2) + f(n-3) + f(n-4) # If the set of possibleSteps is of length m, then the time complexity is O(m^n) # This can be improved with dynamic programing def waysToClimb01(n, possibleSteps): if n == 0: return 1 noWays = 0 for steps in possibleSteps: if n-steps > 0: noWays += waysToClimb01(n-steps, possibleSteps) return noWays # With dynamic programming consider an array that holds the number of ways to climb n steps. # So, for possibleSteps = {2,3,4} # arr[i] = arr[i-2] + arr[i-3] + arr[i-4] # # arr = 1 0 1 1 2 2 4 5 # n=0 n=1 n=2 n=3 n=4 n=5 n=6 n=7 def waysToClimb02(n, possibleSteps): arr = [0] * (n+1) # n+1 because to consider n steps we need to also consider the 0th step arr[0] = 1 for i in range(1,n+1): for j in possibleSteps: if i-j >= 0: arr[i] += arr[i-j] return arr[n]
true
14adf897de38f2d27bc32c8bc7d298b9f1ffbbed
ChrisStreadbeck/Python
/learning_notes/lambdas.py
440
4.1875
4
#Lambda is a tool used to wrap up a smaller function and pass it to other functions full_name = lambda first, last: f'{first} {last}' def greeting(name): print(f'Hi there {name}') greeting(full_name('kristine', 'hudgens')) #so it's basically a short hand function (inline) and it allows the name to be called # simply later on in the second function. #Can be used with any type of code, but it's most commonly used for mathmatics
true
f91112d5f2d441cb357b52d77aa72c74d586fc73
Shady-Data/05-Python-Programming
/studentCode/Recursion/recursive_lines.py
928
4.53125
5
''' 3. Recursive Lines Write a recursive function that accepts an integer argument, n. The function should display n lines of asterisks on the screen, with the first line showing 1 asterisk, the second line showing 2 asterisks, up to the nth line which shows n asterisks. ''' def main(): # Get an intger for the number of lines to print num_lines = int(input('Enter the number of lines to print: ')) # call the recursive_lines function with the start of 1 and end of num_lines recursive_lines('*', num_lines) # define the recursive_lines function # parameters: str pat, int num_lines def recursive_lines(p_pat, p_stop): # base case if len(p_pat) == p_stop if len(p_pat) == p_stop: print(p_pat) else: # print the pattern and return recursive lines p_pat + '*', p_stop print(p_pat) return recursive_lines(p_pat + '*', p_stop) # Call the main function main()
true
630e3b1afa907f03d601774fa4aec19c8ae1fbbb
Shady-Data/05-Python-Programming
/studentCode/cashregister.py
1,718
4.3125
4
''' Demonstrate the CashRegister class in a program that allows the user to select several items for purchase. When the user is ready to check out, the program should display a list of all the items he or she has selected for purchase, as well as the total price. ''' # import the cash register and retail item class modules import CashRegisterClass import RetailItemClass as ri from random import randint # generate a list of retail item to test with items = { 'Jacket': {'desc': 'Jacket', 'units' : 12, 'price' : 59.95}, 'Designer Jeans': {'desc': 'Designer Jeans', 'units' : 40, 'price' : 34.95}, 'Shirt': {'desc': 'Shirt', 'units' : 20, 'price' : 24.95} } # Create and empty list to store the items retail_items = [] # generate an object for each entry for key in items.keys(): # add the object to the list retail_items.append(ri.RetailItem(items[key]['desc'], items[key]['units'], items[key]['price'])) def main(): # Instanstiate a Class Register object register = CashRegisterClass.CashRegister() # add an item to the cash register register.purchase_item(retail_items[randint(0, 2)]) # display the items in the register # register.show_items() # add 5 more items to the register for x in range(5): register.purchase_item(retail_items[randint(0, 2)]) print('Show items before clear:') # Display the details of the items purchased register.show_items() # display the total of the items print(f'\n\tTotal: ${register.get_total():,.2f}') # clear the register register.clear() print('\nShow Items after clear:') # display the items in the register register.show_items() # call the main function main()
true
443db5f0cfbc98abc074444ad8fccdf4a891491c
Shady-Data/05-Python-Programming
/studentCode/CellPhone.py
2,681
4.53125
5
""" Wireless Solutions, Inc. is a business that sells cell phones and wireless service. You are a programmer in the company’s IT department, and your team is designing a program to manage all of the cell phones that are in inventory. You have been asked to design a class that represents a cell phone. The data that should be kept as attributes in the class are as follows: ​ • The name of the phone’s manufacturer will be assigned to the __manufact attribute. • The phone’s model number will be assigned to the __model attribute. • The phone’s retail price will be assigned to the __retail_price attribute. ​ The class will also have the following methods: • An __init__ method that accepts arguments for the manufacturer, model number, and retail price. • A set_manufact method that accepts an argument for the manufacturer. This method will allow us to change the value of the __manufact attribute after the object has been created, if necessary. • A set_model method that accepts an argument for the model. This method will allow us to change the value of the __model attribute after the object has been created, if necessary. • A set_retail_price method that accepts an argument for the retail price. This method will allow us to change the value of the __retail_price attribute after the object has been created, if necessary. • A get_manufact method that returns the phone’s manufacturer. • A get_model method that returns the phone’s model number. • A get_retail_price method that returns the phone’s retail price. """ class CellPhone: # define the __init__ method with 3 attributes def __init__(self, p_manufacturer, p_model, p_msrp): self.__manufact = p_manufacturer self.__model = p_model self.__retail_price = p_msrp # define set_manufact to modify the __manufact attribute, if necessary def set_manufact(self, p_manufact): self.__manufact = p_manufact # define set_model to modify the __model attribute, if necessary def set_model(self, p_model): self.__model = p_model # define set_retail_price to modify the __retail_price attribute, if necessary def set_retail_price(self, p_msrp): self.__retail_price = p_msrp # define get_manufact to return the __manufact attribute def get_manufact(self): return self.__manufact # define get_model to return the __model attribute def get_model(self): return self.__model # define get_retail_price to return the __retail_price attribute def get_retail_price(self): return self.__retail_price
true
915a6111d78d3bd0566d040f9342ddb59239c467
Shady-Data/05-Python-Programming
/studentCode/Recursion/recursive_printing.py
704
4.46875
4
''' 1. Recursive Printing Design a recursive function that accepts an integer argument, n, and prints the numbers 1 up through n. ''' def main(): # Get an integer to print numbers up to stop_num = int(input('At what number do you want this program to stop at: ')) # call the recursive print number and pass the stop number recursive_print(1, stop_num) # define the recursive_print function the start parameter the stop parameter def recursive_print(p_start, p_stop): # base case, print 1 if p_start == p_stop: print(p_stop) # recursive case else: print(p_start) return recursive_print(p_start + 1, p_stop) # call the main function main()
true
c4d39fadba7f479ce554198cd60c7ce4574c2d6b
Shady-Data/05-Python-Programming
/studentCode/Recursion/sum_of_numbers.py
874
4.40625
4
''' 6. Sum of Numbers Design a function that accepts an integer argument and returns the sum of all the integers from 1 up to the number passed as an argument. For example, if 50 is passed as an argument, the function will return the sum of 1, 2, 3, 4, . . . 50. Use recursion to calculate the sum. ''' def main(): # get the stop number stop_num = int(input('Enter the number to stop at: ')) # print the return of the sum_of_nums function with stop_num as an argument print(sum_of_nums(stop_num)) # Debug check print sum of ints in range + 1 # print(sum([x for x in range(stop_num + 1)])) # Define sum_of_nums() function # parameters: p_stop def sum_of_nums(p_stop): # base case: if p_stop == 0: return 0 # recursive case: else: return p_stop + sum_of_nums(p_stop - 1) # Call the main function main()
true
96387763eafc4c2ee210c866e43f30ebd9fbb6b5
Vinod096/learn-python
/lesson_02/personal/chapter_4/14_pattern.py
264
4.25
4
#Write a program that uses nested loops to draw this pattern: ## # # # # # # # # number = int(input("Enter a number : ")) for r in range (number): print("#", end="",sep="") for c in range (r): print(" ", end="",sep="") print("#",sep="")
true
d4420e85272e424bdf66086eda6912615d805096
Vinod096/learn-python
/lesson_02/personal/chapter_3/09_wheel_color.py
1,617
4.4375
4
#On a roulette wheel, the pockets are numbered from 0 to 36. The colors of the pockets are #as follows: #• Pocket 0 is green. #• For pockets 1 through 10, the odd-numbered pockets are red and the even-numbered #pockets are black. #• For pockets 11 through 18, the odd-numbered pockets are black and the even-numbered #pockets are red. #• For pockets 19 through 28, the odd-numbered pockets are red and the even-numbered #pockets are black. #• For pockets 29 through 36, the odd-numbered pockets are black and the even-numbered #pockets are red. #Write a program that asks the user to enter a pocket number and displays whether the #pocket is green, red, or black. The program should display an error message if the user #enters a number that is outside the range of 0 through 36. number = int(input("enter a number : ")) if number >= 0 and number <= 36: print("number is in range") else: print("out of range") if number == 0: print("green") if number >= 1 and number < 10: if number % 2 == 0 : print("odd-numbered pockets are red") else: print("even-numbered pockets are black") if number >= 11 and number <= 18: if number % 2 == 0 : print("even-numbered pockets are red") else: print("odd-numbered pockets are black") if number >= 19 and number <= 28: if number % 2 == 0 : print("even-numbered pockets are black.") else: print("odd-numbered pockets are red") if number >= 29 and number <= 36: if number % 2 == 0: print("even-numbered pockets are red") else: print("odd-numbered pockets are black")
true
6411437fe4e73b46d8756a61d44f929a83c8dbf7
Vinod096/learn-python
/lesson_02/personal/chapter_6/03_line_numbers.py
386
4.34375
4
#Write a program that asks the user for the name of a file. The program should display the #contents of the file with each line preceded with a line number followed by a colon. The #line numbering should start at 1. count = 0 file = str(input("enter file name :")) print("file name is :", file) content = open(file, 'r') for i in range(0, 10): i += count + 1 print(f"{i} :",i)
true
b09e8d2cd18d517e904889ecf2809f1f1392e7eb
Vinod096/learn-python
/lesson_02/personal/chapter_4/12_population.py
1,321
4.71875
5
#Write a program that predicts the approximate size of a population of organisms. The #application should use text boxes to allow the user to enter the starting number of organisms, #the average daily population increase(as a percentage), and the number of days the #organisms will be left to multiply. For example, assume the user enters the following values: #Starting number of organisms: 2 #Average daily increase: 30% #Number of days to multiply: 10 #The program should display the following table of data: #Day Approximate Population #1 2 #2 2.6 #3 3.38 #4 4.394 #5 5.7122 #6 7.42586 #7 9.653619 #8 12.5497 #9 16.31462 #10 21.209 size = 0 Starting_number_of_organisms = int(input("Starting_number_of_organisms : ")) daily_increase = int(input("daily increase : ")) Average_daily_increase = daily_increase / 100 print("Average daily increase :",Average_daily_increase) number_of_days_to_multiply = int(input("number_of_days_to_multiply : ")) print("Day Approximate Population :") for number_of_days_to_multiply in range (1,number_of_days_to_multiply + 1): Starting_number_of_organisms = (Starting_number_of_organisms * Average_daily_increase) + Starting_number_of_organisms print(f"{number_of_days_to_multiply} {Starting_number_of_organisms}")
true
f5a8090ff67003d79e2f431256d4b277381c8dd7
Vinod096/learn-python
/lesson_02/personal/chapter_3/01_Day.py
757
4.40625
4
#Write a program that asks the user for a number in the range of 1 through 7. The program #should display the corresponding day of the week, where 1 = Monday, 2 = Tuesday, #3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday, and 7 = Sunday. The program should #display an error message if the user enters a number that is outside the range of 1 through 7. days_number = int(input("Enter a number : ")) if days_number == 1 : print("monday") elif days_number == 2 : print("tuesday") elif days_number == 3 : print("wednesday") elif days_number == 4 : print("thursday") elif days_number == 5 : print("friday") elif days_number == 6 : print("saturday") elif days_number == 7 : print("sunday") else: print("out of days_number")
true
7feb19a5121eeb321f0b2a187852cae0becb4c4f
Vinod096/learn-python
/lesson_02/personal/chapter_2/ingredient.py
1,022
4.40625
4
total_no_of_cookies = 48 cups_of_sugar = 1.5 cups_of_butter = 1 cups_of_flour = 2.75 no_of_cookies_req = round(int(input("cookies required :"))) print("no of cookies required in roundup : {0:2f} ".format(no_of_cookies_req)) req_sugar = (no_of_cookies_req / total_no_of_cookies) * cups_of_sugar print("no of cups of sugar_required : {0:.2f}".format(req_sugar)) req_butter = (no_of_cookies_req / total_no_of_cookies) * cups_of_butter print("no of cups of butter_required : {0:.2f}".format(req_butter)) flour_req = (no_of_cookies_req / total_no_of_cookies) * cups_of_flour print("no of cups of flour_required : {0:.2f}".format(flour_req)) #Question : #A cookie recipe calls for the following ingredients: #• 1.5 cups of sugar #• 1 cup of butter #• 2.75 cups of flour #The recipe produces 48 cookies with this amount of the ingredients. Write a program that #asks the user how many cookies he or she wants to make, and then displays the number of #cups of each ingredient needed for the specified number of cookies.
true
dd42d5e406efde3b62d76588eeb37a7470edafe8
Vinod096/learn-python
/lesson_02/personal/chapter_8/01_initials.py
463
4.5
4
#Write a program that gets a string containing a person’s first, middle, and last names,and then display their first, middle, and last initials. For example, if the user enters John William Smith the program should display J. W. S. first_name = str(input("Enter First Name : ")) middle_name = str(input("Enter Middle Name : ")) last_name = str(input("Enter Last Name : ")) print("Initials of persons names : ", '\n',first_name[0],'\n', middle_name[0],'\n', last_name[0])
true
ad1f65388986962de297bba5f1219809634fccd3
Vinod096/learn-python
/lesson_02/personal/chapter_4/09_ocean.py
380
4.28125
4
#Assuming the ocean’s level is currently rising at about 1.6 millimeters per year, create an #application that displays the number of millimeters that the ocean will have risen each year #for the next 25 years. rising_oceans_levels_per_year = 1.6 years = 0 for i in range (1,26): years = rising_oceans_levels_per_year * i print(f"rising levels per {i} year : {years}")
true