blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
e5cd322b04d126d2283dd2be8caed59f1985ef17
Xuehong-pdx/python-code-challenge
/caesar.py
667
4.1875
4
from string import ascii_lowercase as lower from string import ascii_uppercase as upper size = len(lower) message = 'Myxqbkdevkdsyxc, iye mbkmuon dro myno' def caesar(message, shift): """ This function returns a caesar (substitution) cipher for a given string where numbers, punctuation, and other non-alphabet characters were passed through unchanged. Letter case is preserved. """ l_shift = {c:lower[(i+shift)%size] for i,c in enumerate(lower)} u_shift = {c:upper[(i+shift)%size] for i,c in enumerate(upper)} l_shift.update(u_shift) sf = [l_shift.get(c, c) for c in message] return ''.join(sf) print(caesar(message, 16))
true
cde0d233f7e9d53bd8e501fae8365584dadb402b
VitBomm/Algorithm_Book
/1.12/1_1_is_multiple.py
355
4.3125
4
# Write a short Python function, is_multiple(n, m), that takes two integer values and returns True if n # is a multiple of m, n = mi for some integer i, and False otherwise # def is_multiple(n, m): if n/m % 1 == 0: return True return False n = eval(input("Input your n: ")) m = eval(input("Input your m: ")) print(str(is_multiple(n,m)))
true
ce4a2f26dff9b7aae290e08ea4e02a6054f4e650
SBCV/Blender-Addon-Photogrammetry-Importer
/photogrammetry_importer/utility/type_utility.py
385
4.15625
4
def is_int(some_str): """ Return True, if the given string represents an integer value. """ try: int(some_str) return True except ValueError: return False def is_float(some_str): """ Return True, if the given string represents a float value. """ try: float(some_str) return True except ValueError: return False
true
52ae20a0eadb2ac4e684ef4920f6c105d6187a6d
jeffsnguyen/Python
/Level 1/Homework/Section_1_3_Functions/Exercise 5/variance_dof.py
1,003
4.40625
4
''' Type: Homework Level: 1 Section: 1.3: Functions Exercise: 4 Description: Create a function that calculates the variance of a passed-in list. This function should delegate to the mean function (this means that it calls the mean function instead of containing logic to calculate the mean itself, since mean is one of the steps to calculating variance). ''' from mean_passedin_list import mean # Return variance of a list, with degree of freedom def variance(list, degOfFreedom = 1): mean_list = mean(list) # Calculate mean l_temp = [(i - mean_list)**2 for i in list] # Initialize list of (x - mean)**2 return sum(l_temp) / (len(list) - degOfFreedom) def main(): # Initialize a list l = [1, 2, 3, 8, 9, 10] # Population Variance dof = 0 print('Variance = ' + str(variance(l, dof))) # Sample Variance dof = 1 print('Variance = ' + str(variance(l, dof))) ####################### if __name__ == '__main__': main()
true
55568741e62e8f4da5189d2582f58916995cd8a3
jeffsnguyen/Python
/Level_3/Homework/Section_3_2_Generators_101/Exercise_1/num_iterable.py
883
4.46875
4
# Type: Homework # Level: 3 # Section: 3.2: Generators 101 # Exercise: 1 # Description: Contains the tests to iterate through a list of numbers # Create a list of 1000 numbers. Convert the list to an iterable and iterate through it. ####################### # Importing necessary packages from random import random, seed ####################### ############################################### def main(): # Set seed to generate pseudo-random number seed(1) # Generate list l using list comprehension l = [random() for i in range(0, 1000)] # Convert to an iterable listIter = iter(l) # iterate through list l, Exception Stop Iteration will be raise when it reaches the end of the list. while True: print(next(listIter)) ############################################### ####################### if __name__ == '__main__': main()
true
a6948de57520137916bd17f153148e83f51d3f35
jeffsnguyen/Python
/Level 1/Homework/Section_1_5_Dicts_and_Sets/Exercise 2/name_usuk.py
2,581
4.21875
4
''' Type: Homework Level: 1 Section: 1.5 Dicts and Sets Exercise: 2 Description: Create two sets: Set 1 should contain the twenty most common male first names in the United States and Set 2 should contain the twenty most common male first names in Britain (Google it). Perform the following: a. Find the first names that appear in both sets. b. Find the first names that appear in the United States set, but not Britain. c. Find the first names that appear in the Britain set, but not United States. d. Use a set comprehension to create a subset of names that have more than five letters. ''' def main(): # Set 1 contain the twenty most common male first names in the United States name_set_us = set(['James', 'John', 'Robert', 'Michael', 'William', 'David', 'Richard', 'Charles', 'Joseph', 'Thomas', 'Christopher', 'Daniel', 'Paul', 'Mark', 'Donald', 'George', 'Kenneth', 'Steven', 'Edward', 'Brian']) # Set 1 contain the twenty most common male first names in the United Kingdom name_set_uk = set(['Noah', 'Oliver', 'Leo', 'Archie', 'Alfie', 'Logan', 'Oscar', 'George', 'Freddie', 'Charlie', 'Harry', 'Arthur', 'Jacob', 'Muhammad', 'Jack', 'Thomas', 'Henry', 'James', 'William', 'Joshua']) # Find first names that appear in both sets using intersection name_usuk = name_set_us.intersection(name_set_uk) print('First names that appear in both US and UK:\n', name_usuk) # Find the first names that appear in the United States set, but not UK using difference name_us_notuk = name_set_us.difference(name_set_uk) print('First names that appear in US but not UK:\n', name_us_notuk) # Find the first names that appear in the Britain set, but not United States. name_uk_notus = name_set_uk.difference(name_set_us) print('First names that appear in UK but not US:\n', name_uk_notus) # Use a set comprehension to create a subset of names that have more than five letters. # Create a set of unique names from US and UK using union name_us_plus_uk = name_set_us.union(name_set_uk) # Set comprehension to filter only names that have more than five letters name_fiveletters = {name for name in name_us_plus_uk if len(name) > 5} print('Names that have more than five letters from US and UK:\n', name_fiveletters) ####################### if __name__ == '__main__': main()
true
92209793e197de9c33c0d3f6c219455620de4282
jeffsnguyen/Python
/Level 1/Homework/Section_1_6_Packages/Exercise 2/anything_program/hello_world_take_input/take_input_triangle/take_input/take_input.py
332
4.25
4
''' Type: Homework Level: 1 Section: 1.1 Variables/ Conditionals Exercise: 4 Description: Create a program that takes input from the user (using the input function), and stores it in a variable. ''' def take_input(): var = input('Input anything: ') # Take user's input and store in variable var print(var)
true
c0f0fbf101b3a648ef5dfd24d760fdcca394c260
jeffsnguyen/Python
/Level_3/Homework/Section_3_3_Exception_Handling/Exercise_2/divbyzero.py
1,719
4.4375
4
# Type: Homework # Level: 3 # Section: 3.3: Exception Handling # Exercise: 2 # Description: Contains the tests for handling div/0 exception # Extend exercise 1) to handle the situation when the user inputs something other than a number, # using exception handling. If the user does not enter a number, the code should provide the user # with an error message and ask the user to try again. # Note that this is an example of duck typing. ####################### # Importing necessary packages ####################### ############################################### ############################################### def main(): # Program takes 2 input from user, handle input exception # If no input exception, handle division by 0 exception and print result of division # Also catch other unknown exceptions # 1st try-except block to handle input try: x = float(input('Input a number: ')) # take input and convert to float y = float(input('Input a number: ')) except ValueError as valueEx: # handle non-number exception, for example: string print(valueEx) pass except Exception as ex: # handle other unknown exception print('Unknown error: ' + str(ex)) pass else: # 2nd try-except block to handle division try: print('Division result = ', x/y) except ZeroDivisionError as divZeroEx: # handle div/0 exception print(divZeroEx) pass except Exception as ex: # handle other unknown exception print('Unknown error: ' + str(ex)) ############################################### ####################### if __name__ == '__main__': main()
true
a1f40e6da78edd81dadd58f19b78490f33aeb4ea
jeffsnguyen/Python
/Level_4/Lecture/string_manipulation_lecture.py
1,778
4.46875
4
# string manipulation lecture def main(): s = 'This is my sample string' # indexing print(s[0]) print(s[-1]) print() # slicing print(s[0:2:3]) print(s[:3]) print() # upper: create a new string, all uppercase print(s.upper()) print() # lower: create a new string, all lowercase print(s.lower()) print() # count the letter in the string, case sensitive print(s.count('t')) print(s.count('is')) print(s.count('x')) # if none found, return 0 print() # s.index() return the index of the sub string inside the string, first occurence only print(s.index('is')) #print(s.index('x')) # get value error print() print(s.find('x')) # similar to index but return -1 if not found s = ' This is my spaced string ' print(s) print(s.strip()) # strip the spaces inside the string print() s = ' This is my spaced string....' print(s) print(s.strip('.')) # strip the specified value from the string # Dealing with file path f = 'C:\\Users\\username\\desktop\\filename.txt' print(f) f.split('\\') # split each directory in the path print(f.split('\\')) l = f.split('\\') print(l) print('\\'.join(l)) # join each directory in the list with the \\ g = f.rsplit('\\', 1) # split the file name from the rest of the directory print(g) print() # Replace print(s) print(s.replace(' ', '')) print(s.replace('T', 'l')) print() s = 'My new string' print(s.startswith(('My'))) # check starting portion of string print(s.startswith(('The'))) print(s.endswith(('ng'))) print(s.endswith(('ng1'))) ####################### if __name__ == '__main__': main()
true
5afb09b8eb3c629211076857bfc6b1f859d28f46
jeffsnguyen/Python
/Level_4/Lecture/string_formatting_lecture.py
1,421
4.21875
4
# string formatting lecture def main(): age = 5 print('Ying is %i years old'%age) # format flag i = integer print('Ying is %f years old'%age) # format flag f = float print('Ying is %.1f years old' % age) # format flag f = floag, truncate it 1 decimal place print('Ying is %e years old' % age) # format flag e= exponential print('%s is 5 years old' %'Ying') # format flag s = string print() name = 'Ying' age = 5 print('%s is %i years old'%(name, age)) # multiple format flag print() print('{0} is {1} years old'.format(name, age)) # better because python figure out the type # better because python figure out the type, descriptive and use keyword arg so order doesn't matter print('{name} is {age} years old'.format(name = name, age = age)) print('Same is {:.1f} years old'.format(5.75)) # specify decimal print('Same is {:,.1f} years old'.format(100000)) # specify decimal print() # f string name = 'Julie' print(f'Hello {name}') height = 61.23 print(f'{round(height)}') # evaluate any expression inside the f string print() heightDict = {'Julie': 65, 'Sam':75, 'Larry':64} name = 'Sam' print(f'{name} is {heightDict[name]} inches') # floating point precision using f string print(f'{name} is {heightDict[name]:,.2f} inches') ####################### if __name__ == '__main__': main()
true
8251f87063be621d270c55e3c3849c758ae2f28b
jeffsnguyen/Python
/Level 1/Homework/Section_1_3_Functions/Exercise 1/day_of_week.py
1,320
4.3125
4
''' Type: Homework Level: 1 Section: 1.3: Functions Exercise: 1 Description: Write a function that can print out the day of the week for a given number. I.e. Sunday is 1, Monday is 2, etc. It should return a tuple of the original number and the corresponding name of the day. ''' import sys # Look up the day number and return matching tuple of weekday name and the day number def day_of_week(x): # Set up week and day reference list week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] day = [1, 2, 3, 4, 5, 6, 7] # Return the tuple of (week, day) in the zip object if day match the lookup variable return [(week, day) for week, day in zip(week, day) if day == x] def main(): print('This program takes an integer value and return a matching tuple of weekday, day number') try: # Exception handling if user enter anything that is not an integer from 1 -> 7 lookup_day = int(input('Enter an integer from 1 -> 7: ')) if lookup_day not in range(1,8): sys.exit('Must be a integer from 1 -> 7') except: sys.exit('Must be a integer from 1 -> 7') # Display the matching tuple print(day_of_week(lookup_day)) ####################### if __name__ == '__main__': main()
true
0e7639bd5f7fc3b37bfa0cdbcd091fd94121e827
jeffsnguyen/Python
/Level_3/Homework/Section_3_2_Generators_101/Exercise_4/fibonacci.py
2,283
4.46875
4
# Type: Homework # Level: 3 # Section: 3.2: Generators 101 # Exercise: 4 # Description: Contains the tests to modified fn() method to generate Fibonacci sequence # Modify the Fibonacci function from Exercise 1.3.2 to be a generator function. Note that the function # should no longer have any input parameter since making it a generator allows it to return the # infinite sequence. Do the following: # a. Display the first and second values of the Fibonacci sequence. # b. Iterate through and display the next 100 values of the sequence. ####################### # Importing necessary packages ####################### ############################################### # Fibonacci generator def fn(): fibo = [] # Initialize empty list num = -1 # Set count value # For the first 2 values, yield specific constants and append to empty list # For subsequent values, yield using fibonacci formula and append to list while True: num += 1 if num == 0: yield 0 fibo.append(0) elif num == 1: yield 1 fibo.append(1) else: yield fibo[num-2] + fibo[num-1] fibo.append(fibo[num-2] + fibo[num-1]) ############################################### def main(): # Testing block 1 # Scenario: # This block will: # 1. Test modified fn() function by printing out the first 2 value of Fibonacci sequence # 2. Test modified fn() function by printing out the next 100 value of Fibonacci sequence ############################################### # Test 1 # 1.1 Test modified fn() function by printing out the first 2 value of Fibonacci sequence print('Test 1.1. Printing out the first 2 value of Fibonacci sequence') fib = fn() print(next(fib)) print(next(fib)) print() # 1.2 Test modified fn() function by printing out the next 100 value of Fibonacci sequence (#3 to #102) print('Test 1.2. Test modified fn() function by printing out the next 100 value of Fibonacci sequence (#3 to #102)') for i in range (0,101): print(next(fib)) i +=1 ############################################### ####################### if __name__ == '__main__': main()
true
5792af4a3d9edc774bba3c6cf4bb7cba31ef6b0d
jeffsnguyen/Python
/Level_3/Homework/Section_3_1_Advanced_Functions/Exercise_1/test_hypotenuse.py
1,140
4.375
4
# Type: Homework # Level: 3 # Section: 3.1: Advanced Functions # Exercise: 1 # Description: This contains the method to test the hypotenus of a right triangle # Create a stored lambda function that calculates the hypotenuse of a right triangle; it should take # base and height as its parameter. Invoke (test) this lambda with different arguments. # Importing necessary packages ####################### from math import sqrt def main(): # Testing block # Scenario: # This block will: # 1. Test the calcHypotenuse lambda function ############################################### # Test 1.1 # Scenario: Test the calcHypotenuse method to calculate the hypotenuse of a right triangle using lambda function. print('Test 1.1') calcHypotenuse = lambda base, height: sqrt(base**2 + height**2) print(calcHypotenuse(3, 4)) print(calcHypotenuse(20, 21)) print(calcHypotenuse(119, 120)) print(calcHypotenuse(696, 697)) print(calcHypotenuse(4059, 4060)) print() ############################################### ####################### if __name__ == '__main__': main()
true
4f999f411dc875269cba559dcdfdcc478f3bdd7b
BrandonOdiwuor/Problem-Solving-With-Algorithms-and-Data-Structures
/queue/queue.py
691
4.125
4
class Queue: def __init__(self): self.queue_list = [] def is_empty(self): ''' Returns a boolean indicating if the Queue is empty Wost Case Complexity O(1) ''' return self.queue_list == [] def size(self): ''' Returns the size of the Queue Worst Case Complexity O(1) ''' return len(self.queue_list) def enqueue(self, item): ''' Adds an adds and element to the end of the Queue Worst Case Complexity O(1) ''' self.queue_list.insert(0, item) def dequeue(self): ''' Removes the firt item from the Queue Wost Case Complexity O(1) ''' return self.queue_list.pop()
true
5def4ffc1d4aa1f09363d0a3d3e86661085c23b0
damingus/CMPUT174
/weather1.py
407
4.4375
4
#This program sees whether 2 inputted temperatures are equal or not #assign 'a' to the first temperature we ask for and 'b' for the next a = input("What is the first temperature? ") b = input("What is the second temperature? ") #we convert 'a' into a string from an integer a = str(a) b = str(b) if a == b: print(a + " and " + b + " are equal!") else: print(a + " and " + b + " are NOT equal!")
true
3bb05110f4e61837f3033087526ee6f96e418f8d
andrew1236/python
/organism population calculator.py
864
4.1875
4
#ask user for number of intital organisms, the average increases of organisms, and how many days to calcualte def calculate_organism_population(): organisms=int(input('Enter number of organisms:')) average_increase =int(input('Enter average daily increase:')) days=int(input('Enter number of days to multiply:')) counter=days-days+1 days=days-days+1 print('DAY APPROXIMATE POPULATION') print('-------------------------------') while counter<=10: organisms=organisms*(1+average_increase/100) if days==1: organisms=organisms-.600 print(days," ", format(organisms, '.0f')) if days>1 and days<10: print(days," ", format(organisms, '.3f')) if days==10: print(days," ", format(organisms, '.3f')) days+=1 counter+=1
true
e03234ead130d80f81f623ad279e8a1987578390
Muhammadtawil/Python-Lessons
/set-part1.py
822
4.3125
4
# ----------------------------- # -- Set -- # --------- # [1] Set Items Are Enclosed in Curly Braces # [2] Set Items Are Not Ordered And Not Indexed # [3] Set Indexing and Slicing Cant Be Done # [4] Set Has Only Immutable Data Types (Numbers, Strings, Tuples) List and Dict Are Not # [5] Set Items Is Unique # ----------------------------- # Not Ordered And Not Indexed mySetOne = {"Mark", "edwen", 100} print(mySetOne) # print(mySetOne[0]) # Slicing Cant Be Done mySetTwo = {1, 2, 3, 4, 5, 6} # print(mySetTwo[0:3]) # Has Only Immutable Data Types # mySetThree = {"Osama", 100, 100.5, True, [1, 2, 3]} # unhashable type: 'list' mySetThree = {"Osama", 100, 100.5, True, (1, 2, 3)} print(mySetThree) # Items Is Unique mySetFour = {1, 2, "Mark", "Edwen", "Mark", 1} print(mySetFour)
true
2f9b3ee9e458ca2e53599ca5a3a1befd90d04268
dshipman/devtest
/part_2_6.py
621
4.25
4
""" Write a short docstring for the function below, so that other people reading this code can quickly understand what this function does. You may also rename the functions if you can think of clearer names. """ def create_step_function(start_time, end_time, value): """ Create a step function that takes a single input ('time'), and returns <value> if that input is between start_time and end_time (inclusive), otherwise 0.0 """ def step_function(time): if start_time <= time <= end_time: y = value else: y = 0.0 return y return step_function
true
d91fc95f364e491f76c5c341aa5d777caa2c1911
AmirMoshfeghi/university_python_programming
/Functions/wine_house.py
1,549
4.46875
4
# Working with Functions # Making a house wine project # Wine Temperature must be closely controlled at least most of the time. # The program reads the temperature measurements of the wine container # during the fermentation process and tells whether the wine is ruined or not. def main(): # Get number of measurements from the user number = int(input("Enter the number of measurements: ")) # The entered number should not be negative or zero if number <= 0: print("The number of measurements must be a positive number.") # Check the status of the wine if check_temperature(number): print("Your wine is ready.") def check_temperature(number): # count -> steps start from one, # alarm -> for checking if two numbers in a row are out in range, # per -> for count percentage count = 1 alarm = 0 per = 0 # calculate 10% of total number of measurements percent = number * 0.1 while count <= number: temp = int(input("Enter the temperature {}: ".format(count))) # Check if the measured number is in acceptable range if temp not in range(20, 26): alarm += 1 per += 1 else: alarm = 0 # Go to next step count += 1 # Wine is ruined if 2 measurements in a row # or 10% of total inputs are out of range if alarm == 2 or per > percent: print("The wine is ruined") break # if everything went fine else: return True main()
true
ae430661d281a65275da7d7230c35096d68c593e
Jayu8/Python3
/assert.py
636
4.125
4
""" It tests the invariants in a code The goal of using assertions is to let developers find the likely root cause of a bug more quickly. An assertion error should never be raised unless there’s a bug in your program. assert is equivalent to: if __debug__: if not <expression>: raise AssertionError """ # Asserts a = 5 # checks if a = 5 assert(a == 5) # uncommenting the below code will throw assertion error #assert(a == 6) def KelvinToFahrenheit(Temperature):   assert (Temperature >= 0),"Colder than absolute zero!"   return ((Temperature-273)*1.8)+32 print KelvinToFahrenheit(273) print int(KelvinToFahrenheit(505.78))
true
b2d675b96a26428a9bd8695a2425a1d0f09dfe59
netteNz/Python-Programming-A-Concise-Introduction
/problem2_5.py
1,296
4.21875
4
'''Problem 2_5: Let's do a small simulation. Suppose that you rolled a die repeatedly. Each time that you roll the die you get a integer from 1 to 6, the number of pips on the die. Use random.randint(a,b) to simulate rolling a die 10 times and printout the 10 outcomes. The function random.randint(a,b) will generate an integer (whole number) between the integers a and b inclusive. Remember each outcome is 1, 2, 3, 4, 5, or 6, so make sure that you can get all of these outcomes and none other. Print the list, one item to a line so that there are 10 lines as in the example run. Make sure that it has 10 items and they are all in the range 1 through 6. Here is one of my runs. In the problem below I ask you to set the seed to 171 for the benefit of the auto-grader. In this example, that wasn't done and so your numbers will be different. Note that the seed must be set BEFORE randint is used. problem2_5() 4 5 3 1 4 3 5 1 6 3 Problem 2_5:''' import random def problem2_5(): """ Simulates rolling a die 10 times.""" # Setting the seed makes the random numbers always the same # This is to make the auto-grader's job easier. random.seed(171) # don't remove when you submit for grading for r in range(0,10): print(random.randint(1,6)) #print(problem2_5())
true
f3db3ba1af9a34c6b223dd1d4d0e55c99e1319fe
prudhvireddym/CS5590-Python
/Source/Python/ICP 2/Stack Queue.py
852
4.15625
4
print("Enter Elements of stack: ") stack = [int(x) for x in input().split()] con ="yes" while con[0]=="y": ans = input("Enter 0 for push\n1 for pop\n2 to print stack\n3 for Top most element : ") while ans == "0": a = int(input("Enter the element to append")) stack.append(a) print(stack) con =input("Do you want to continue y or n") break while ans == "1": print("Stack element poped is:") print(stack.pop()) con = input("Do you want to continue y or n") break while ans == "2": print("Stack elements are:") print(stack) con = input("Do you want to continue y or n") break while ans == "3": print("The stop of the stack is: ") print(stack[-1]) con = input("Do you want to continue y or n") break
true
2853c45cb2b7883d73a62a288916aa026c6db2be
aligol1/beetroot111
/lesson37.py
1,421
4.59375
5
"""Task 1 Create a table Create a table of your choice inside the sample SQLite database, rename it, and add a new column. Insert a couple rows inside your table. Also, perform UPDATE and DELETE statements on inserted rows. As a solution to this task, create a file named: task1.sql, with all the SQL statements you have used to accomplish this task""" import sqlite3 db = sqlite3.connect('task0111.sql') sql = db.cursor() #создание табл sql.execute("""CREATE TABLE IF NOT EXISTS users(userid INT PRIMARY KEY, first_name TEXT, lastname TEXT); """) db.commit() #переименование табл sql.execute(""" ALTER TABLE users RENAME TO usersdb """) db.commit() #добавление новой колоны sql.execute(""" ALTER TABLE usersdb ADD COLUMN 'nickname''TEXT' """) db.commit() #добавление данных sql.execute(""" INSERT INTO usersdb VALUES (1,"Igor","Ivanov","kokshka"); """) db.commit() sql.execute(""" INSERT INTO usersdb VALUES (2,"Oleg","Petrov","Frider"); """) db.commit() sql.execute(""" INSERT INTO usersdb VALUES (3,"John","Malkovic","NEO"); """) db.commit() #удаление записи sql.execute(""" DELETE FROM usersdb WHERE userid = '1' """) db.commit() #редактирование sql.execute(""" UPDATE usersdb SET first_name = 'Ira' WHERE userid = '2' """) db.commit() for value in db.execute("SELECT * FROM usersdb"): print(value)
true
69eaa079f4ad20db8c19efa7af08adcdcf174e1a
aligol1/beetroot111
/lesson14.py
2,240
4.65625
5
"""Lesson 14 Task 1 Write a decorator that prints a function with arguments passed to it. NOTE! It should print the function, not the result of its execution! For example: "add called with 4, 5" def logger(func): pass @logger def add(x, y): return x + y @logger def square_all(*args): return [arg ** 2 for arg in args]""" def logger(func): def wraper(*args): print(f'{func.__name__} called with {args}') return func(*args) return wraper @logger def add(*args): return sum(arg for arg in args) @logger def square_all(*args): return [arg ** 2 for arg in args] if __name__ == '__main__': add(5, 6) square_all(8, 9, 10) """Lesson 14 Task 2 Write a decorator that takes a list of stop words and replaces them with * inside the decorated function def stop_words(words: list): pass @stop_words(['pepsi', 'BMW']) def create_slogan(name: str) -> str: return f"{name} drinks pepsi in his brand new BMW!" assert create_slogan("Steve") == "Steve drinks * in his brand new *!" """ StopList = ['pepsi', 'BMW'] def stop_words(words:list): def replace_word(func): def wraper(*args): text = func(*args) for word in words: text = text.replace(word, '*') return text return wraper return replace_word @stop_words(StopList) def create_slogan(name: str, lastname: str): return f'{name} {lastname} drinks pepsi in his brand new BMW!' if __name__ == '__main__': print(create_slogan('john','Wick')) """Task 3 Write a decorator `arg_rules` that validates arguments passed to the function. A decorator should take 3 arguments: max_length: 15 type_: str contains: [] - list of symbols that an argument should contain If some of the rules' checks returns False, the function should return False and print the reason it failed; otherwise, return the result. ``` def arg_rules(type_: type, max_length: int, contains: list): pass @arg_rules(type_=str, max_length=15, contains=['05', '@']) def create_slogan(name: str) -> str: return f"{name} drinks pepsi in his brand new BMW!" assert create_slogan('johndoe05@gmail.com') is False assert create_slogan('S@SH05') == 'S@SH05 drinks pepsi in his brand new BMW!' """
true
7a85e32340f82247a32ce4f234a38b3b30c9ffc9
Gwinew/To-Lern-Python-Beginner
/Tutorial_from_Flynerd/Lesson_4_typesandvariables/Task2.py
817
4.21875
4
# Make a list with serial movie # # Every serial movie should have assigned rate in scale 1-10. # Asking users what they serial movie want to see. # In answer give they rate value. # Asking user if they want to add another serial movie and rate. # Add new serial movie to the list. # -*- coding: utf-8 -*- dictserial={"Soprano":6,"Dark":9,"Rick and Morty":8} listserial=list(dictserial.keys()) name=input("Hi! Welcome to serial movie data base.\n{}\nWhat serial movie want to see?\n".format(listserial)) enter=input("{} have {} in rating.\nPress Enter to continue".format(name, dictserial[name])) newserial=input("If you want to add a new serial to the list, write the name\n") newserialrate=input("Write a rate\n") dictserial[newserial]=newserialrate print("This is a new list with rates:\n{}".format(dictserial))
true
b1077695d8b814286c878c7d809eed423b224f72
Gwinew/To-Lern-Python-Beginner
/Tutorial_from_Flynerd/Lesson_3_formattingsubtitles/Task2.py
886
4.125
4
# -*- coding: utf-8 -*- # # Create a investment script which will have information about: # -Inital account status # -Annual interest rate # -The number of years in the deposit # # Result show using any formatting text. # enter=input("Hi! This is Investment script.\nI want to help you to count your money impact at the end of the deposit.\nPlease press \"Enter\" to continue") name=input("Before we start, I would like to ask you, what\'s your name?\n") rate=float(input("Hi {}. Write what interest rate you want to have. (in percentage)\n".format(name))) inpu=float(input("Can you input initial account status? (in PLN)\n")) time=int(input("Please enter, how long you want to keep your money in deposit? (in month)\n")) ratep=rate/100 year=time/12 end=(inpu*time*ratep/12)+inpu print("{} you will have {:.4f} PLN after {} months ({:.1f} years) in deposit".format(name,end,time,year))
true
931c283cfe56acb0b02c9e26205980a3fda9f4ff
Gwinew/To-Lern-Python-Beginner
/Pluralsight/Intermediate/Unit_Testing_with_Python/1_Unit_Testing_Fundamentals/2_First_Test/test_phonebook.py
1,405
4.1875
4
"""Given a list of names and phone numbers. Make a Phonebook Determine if it is consistent: - no number is a prefix of another - e.g. Bob 91125426, Anna 97625992 - Emergency 911 - Bob and Emergency are inconsistent """ import unittest #class PhoneBook: # Right-click, choose Refactor, and choose Move... to phonebook.py # pass from phonebook import PhoneBook class PhoneBookTest(unittest.TestCase): def test_lookup_by_name(self): phonebook = PhoneBook() # Click alt+enter and choose a create new class phonebook.add("Bob", '12345') # PyCharm is highlight a word which needed to define -> click right ande choose 'Add method add() to class PhoneBook' number = phonebook.lookup("Bob") # Click 'Add method lookup() to class PhoneBook' self.assertEqual("12345", number) # To initiate test we need use to command line: # python -m unittest # error: AssertionError: '12345' != None # We can add unittest to PyCharm: # Click 'Add Configuration' # Click '+' # Choose Python test # Choose Unittest # Name configuration: Unittest # Add a path to script which we want to test (or folder if script using more files) # If test is failed then we see on the left yellow cross. # For Working interactively: An IDE like PyCharm # For Continues integration: A Command Line Test Runner
true
ee0eb65582ce9db9cc635038101221a257bbc5f6
Aa-yush/Learning-Python
/BMICalc.py
331
4.28125
4
weight = float(input("Enter your weight in kg : ")) height = float(input("Enter your height in meters : ")) BMI = weight / (height**2) if(BMI <= 18.5): print("Underweight") elif(BMI >18.5 and BMI <= 24.9): print("Normal weight") elif(BMI>24.9 and BMI<=29.9): print("Overweight") else: print("Obesity")
true
8a2edf5d14180fefe7c387a81465edb89c12eca0
rohit98077/python_wrldc_training
/24_read_write_text_files.py
816
4.375
4
''' Lesson 2 - Day 4 - read or write text files in python ''' # %% # read a text file # open the file for reading with open("dumps/test.txt", mode='r') as f: # read all the file content fStr = f.read() # please note that once again calling f.read() will return empty string print(fStr) # this will print the whole file contents # %% # load all lines into a list with open("dumps/test.txt", mode='r') as f: # load all the lines of the file into an array textLines = f.readlines() print(textLines) # %% # writing text to a file # with mode = 'w', old text will be deleted # with mode = 'a', the new text will be appended to the old text with open("dumps/test.txt", mode='w') as f: f.write("The first line\n") f.write("This is the second line\nThis the third line") # %%
true
b096fbd435e5058f59aa46d546a0a4ade727fa69
rohit98077/python_wrldc_training
/13_pandas_dataframe_loc.py
574
4.125
4
''' Lesson 2 - Day 3 - Pandas DataFrame loc function loc function is used to access dataframe data by specifying the row index values or column values ''' #%% import pandas as pd # create a dataframe df = pd.DataFrame([[2, 3], [5, 6], [8, 9]], index=['cobra', 'viper', 'sidewinder'], columns=['max_speed', 'shield']) print(df) # %% # select rows with index as 'viper', 'cobra' but all columns df2 = df.loc[['viper', 'cobra'], :] # %% # select rows with index as 'viper', 'cobra' and columns as 'max_speed' df2 = df.loc[['viper', 'cobra'], ['max_speed']] # %%
true
0e66cef7b14800d47a750139d943d8c439338232
fengkaiwhu/A_Byte_of_Python3
/example/addr_book.py
1,812
4.1875
4
#!/usr/bin/env python # coding=utf-8 # Filename: addr_book.py class addr_book: '''Represent an addr_book''' book = {} def __init__(self, book): addr_book.book = book def get_book(self): return addr_book.book def add_person(self): name = input('Please input name-->') address = input('Please input address-->') phone = input('Please input phone-->') from person import person person = person(name, address, phone) if person.name in addr_book.book.keys(): print('The person already exists') else: addr_book.book[person.name] = person del person def del_person(self): name = input('Please input name-->') if name not in addr_book.book.keys(): print('The person is not exists') else: addr_book.book.pop(name) def modify_person(self): name = input('Please input name-->') if name not in addr_book.book.keys(): print('The person is not exists') else: person = addr_book.book[name] print('Original infomation Name: {0}, address: {1}, phone: {2}'.format(name, person.address, person.phone)) person.name = input('Please input new name-->') person.address = input('Please input new address-->') person.phone = input('Please input new phone-->') def show_person(self): if len(addr_book.book.keys()) == 0: print('Address book is empty.') else: for name, person in addr_book.book.items(): print('Name: {0}, address: {1}, phone:{2}'.format(person.name, person.address, person.phone)) if __name__ == '__main__': addr_book = addr_book() addr_book.add_person()
true
85ca3ab76550a0092f926eb777a834246c85c557
RyanWaltersDev/NSPython_chapter3
/travel_dest.py
729
4.71875
5
#Ryan Walters Nov 21 2020 -- Practicing the different sorting methods with travel destinations #Initial list travel_dest = ['tokyo', 'venice', 'amsterdam', 'osaka', 'wales', 'dublin'] #Printing as a raw Python list and then in order print(travel_dest) print(sorted(travel_dest)) #Printing in reverse alphabetical order without a permanent change to the list print(travel_dest) print(sorted(travel_dest, reverse=True)) #Using reverse method to change the order and then back again print(travel_dest) travel_dest.reverse() print(travel_dest) travel_dest.reverse() print(travel_dest) #Alphabetical sorting and reverse permanent travel_dest.sort() print(travel_dest) travel_dest.sort(reverse=True) print(travel_dest) #END OF PROGRAM
true
d0d118fe3a88f33f1c18d12c565e9e83620fe9f8
spettigrew/cs2-codesignal-practice-tests
/truck_tour.py
2,736
4.5
4
""" Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N - 1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petrol. You can start the tour at any of the petrol pumps. Calculate the first point from where the truck will be able to complete the circle. Consider that the truck will stop at each of the petrol pumps. The truck will move one kilometer for each litre of the petrol. Input Format The first line will contain the value of N. The next N lines will contain a pair of integers each, i.e. the amount of petrol that petrol pump will give and the distance between that petrol pump and the next petrol pump. Constraints: 1 <= N <= 10^5 1 <= amount of petrol, distance <= 10^9 Output Format An integer which will be the smallest index of the petrol pump from which we can start the tour. Sample Input 3 1 5 10 3 3 4 Sample Output 1 Explanation We can start the tour from the second petrol pump. """ #!/bin/python3 import os import sys # # Complete the truckTour function below. # def truckTour(petrolpumps): # # Write your code here. # # answer the question, can we make it around the circle starting at a given index # first thing we do when we get to a pump: # take all the petrol available # second -> try to go to the next pump: # if our current is > distance, then we can make it there # travel to the next one: # increment our index, subtract the distance from current # if we make it back to our starting point, then we can answer true start = 0 current = 0 petrol = 0 while start <= len(petrolpumps): petrol += petrolpumps[current][0] petrol -= petrolpumps[current][1] if petrol < 0: # we didn't make it to the next one start = current + 1 current = start petrol = 0 continue current = (current + 1) % len(petrolpumps) # OR # current += 1 # if current >= len(petrolpumps): # current = 0 if current == start: return start return None if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) petrolpumps = [] for _ in range(n): petrolpumps.append(list(map(int, input().rstrip().split()))) result = truckTour(petrolpumps) fptr.write(str(result) + '\n') fptr.close()
true
53ba03e8e1cbb013f566be89f6b0df2722a7319d
spettigrew/cs2-codesignal-practice-tests
/roman-to-integer.py
2,820
4.25
4
""" Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. Example 1: Input: s = "III" Output: 3 Example 2: Input: s = "IV" Output: 4 Example 3: Input: s = "IX" Output: 9 Example 4: Input: s = "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. Example 5: Input: s = "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. Constraints: 1 <= s.length <= 15 s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). It is guaranteed that s is a valid roman numeral in the range [1, 3999]. """ # if you need the index, do a range loop. If you need the value, do a for/in loop. If you need both, do an enumerate (returns index, and value) class Solution: def romanToInt(self, roman): numerals = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, 'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900 } # init i as our starting index i = 0 # init num to hold the resulting addition of the found roman numerals num = 0 # iterate the string while i < len(roman): # if there are 2 chars to check and they are both in numerals if i + 1 < len(roman) and roman[i:i + 2] in numerals: # add the integer version of the found 2 character roman numeral to # the num var num += numerals[roman[i:i + 2]] # increment counter by 2 since we found a 2 character roman numeral i += 2 else: # add the integer version of the found roman numeral to the num var num += numerals[roman[i]] # increment counter by 1 since we found a single character roman # numeral i += 1 return num
true
d9bc3016a040ecb9b68e404cf4a9244ed6ee81a6
spettigrew/cs2-codesignal-practice-tests
/anagrams.py
2,712
4.46875
4
""" A student is taking a cryptography class and has found anagrams to be very useful. Two strings are anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not. The student decides on an encryption scheme that involves two large strings. The encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Determine this number. Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and a anagrams. Any characters can be deleted from either of the strings. Example a = 'cde' b = 'dcf' Delete e from a and f from b so that the remaining strings are cd and dc which are anagrams. This takes 2 character deletions. Function Description Complete the makeAnagram function in the editor below. makeAnagram has the following parameter(s): string a: a string string b: another string Returns int: the minimum total characters that must be deleted Input Format The first line contains a single string, a. The second line contains a single string, b. Constraints 1 <= |a|, |b| < = 10^4 The strings a and b consist of lowercase English alphabetic letters, ascii[a-z]. Sample Input cde abc Sample Output 4 Explanation Delete the following characters from the strings make them anagrams: Remove d and e from cde to get c. Remove a and b from abc to get c. It takes 4 deletions to make both strings anagrams. """ #!/bin/python3 import math import os import random import re import sys # Complete the makeAnagram function below. def makeAnagram(a, b): letters = {} for letter in letters(a): if letter not in letter: createLetter() incrementLetter() for letter in letters(b): if letter in letters: if letter > 0: matchLetter() else: incrementLetter() else: createLetter() incrementLetter() result = 0 for letter in letter: result += letters[letter] def createLetter(): letters: { letter: 0 } def incrementLetter(): letters: { letter: + 1 } def matchLetter(): letters: { letter: - 1 } if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') a = input() b = input() res = makeAnagram(a, b) fptr.write(str(res) + '\n') fptr.close()
true
307c0d178659494d3639d78df5f4b1bd1dfc9607
thomasmcclellan/pythonfundamentals
/02.01_strings.py
525
4.21875
4
# Strings hold text info and hold "" or '' # Can have [] 'hello' "hello" "I'm a dog" my_string = 'abcdefg' print(my_string) print(my_string[0]) print(my_string[3:]) print(my_string[:3]) #Goes up to, BUT NOT INCLUDING the number print(my_string[2:5]) print(my_string[::]) print(my_string[::2]) #The number is the step size (goes up by two) # Strings are IMMUTIBLE x = my_string.upper() print(x) y = my_string.lower() print(y) z = my_string.capitalize() print(z) two_words = 'Hello world' t = two_words.split() print(t)
true
d7c16c08b73fa5b2a45356431d35416a2e30155e
alaasal95/problem-solving
/Convert_second _to_hour_min_second.py
323
4.15625
4
''' ----->Ex:// read an integer value(T) representing time in seconds and converts it to equivalent hours(hr),minutes(mn)and second(sec) ''' p1=int p2=int p3=int second=4000 p1=second%60 p2=second/60 print('p2_',p2) p3=p2%60 print('p2',p2) p2=p2/60 print(p2 ,":",p3,":",p1)
true
06e6aa8918528136b1b4a56e463dcfb369580261
emmanuelthegeek/Python-Exercises
/Widgets&gizmos.py
1,130
4.25
4
#An online retailer sells two products. widgets and gizmos. Each widget weighs 75 grams, while each gizmo weighs 112 grams. #Write a program that displays the total weight of an order, in kilograms, given two variables containing the number of widgets #and gizmos. #Solution # 1 widget = 75g # 1 gizmos = 112g # 1000g = 1kg CustomerName = input('Kindly provide your name ') try: Widget_quantity_ordered = float(input('How many quantities of widgets do you need? ')) Gizmos_quantity_ordered = float(input('How many quantities of gizmos do you want? ')) Total_Widget_weight_in_grams = Widget_quantity_ordered * 75 Total_Gizmos_weight_in_grams = Gizmos_quantity_ordered * 112 Total_weight_of_an_order_in_grams = Total_Widget_weight_in_grams + Total_Gizmos_weight_in_grams Total_weight_of_an_order_in_kilograms = Total_weight_of_an_order_in_grams / 1000 print(f"Dear {CustomerName}, you have just ordered {Total_weight_of_an_order_in_kilograms}kg of widgets and gizmos") except: print('Quantities should be in whole numbers') finally: print(f"Thank you {CustomerName} for doing business with us")
true
6cc0e043bd8778e825fa2fd6748518a6e641a5f9
MihaiDinca1000/Game
/Exercitii/Test_inheritance.py
2,254
4.59375
5
''' In this Python Object-Oriented Tutorial, we will be learning about inheritance and how to create subclasses. Inheritance allows us to inherit attributes and methods from a parent class. This is useful because we can create subclasses and get all of the functionality of our parents class, and have the ability to overwrite or add completely new functionality without affecting the parents class in any ways. ''' class Angajat: marire = 1.04 nr_angajati = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@gmail.com' Angajat.nr_angajati += 1 def nume_Angajat(self): return '{} {}'.format(self.first, self.last) def aplica_marire(self): self.pay = int(self.pay * self.marire) class Dezvoltator(Angajat): marire = 1.1 def __init__(self, first, last, pay, statut): super().__init__(first, last, pay) # Angajat.__init__(self, first, last, pay) e acelasi lucru ca linia de mai sus self.statut = statut class Manager(Angajat): def __init__(self, first, last, pay, statut, angajati = None): super().__init__(first, last, pay) if angajati is None: self.nr_angajati = [] else: self.angajati = angajati def add_ang(self, ang): if ang not in self.angajati: self.angajati.append(ang) def remove_ang(self, ang): if ang in self.angajati: self.angajati.remove(ang) def print_ang(self): for ang in self.angajati: print('-->',ang.nume_Angajat()) an1 = Angajat('Sebastian', 'Bach', 67500) dev1 = Dezvoltator('Gigi', 'Becali', 180000, 'cioban cu bani') dev2 = Dezvoltator('viorica', 'Dancila', 26000, 'premier analfabet') # print(help(an1)) iti arata totul despre acest angajat +mostenirea manager1 = Manager('Liviu', 'Dracnea', 400000, 'furacios cu in parlament', [dev2, dev1]) manager1.remove_ang(dev1) manager1.print_ang() # print(manger1.angajati) # print(dev1.email) # print(dev2.statut) # print(dev1.pay) # dev1.aplica_marire() # print(dev1.pay)
true
43bdd743c29efec4b9756ce9d6ecd8f5bcf61b99
porregu/unit3
/unitproject.py
1,336
4.21875
4
def arearectangle(a,b): """ solve the area of the rectangle :param a: heigth :param b: with :return: return the fucntion to do it more times """ return a*b def withh():# dpuble (h) because dosent let me put one # with called by the user """ make the user tell the with :return: the function so we know the number and we can make the calculation """ a=float(input("what is the with")) return a def lenght():# lenght called by the user """ user called the lenght :return: return the function to make the calculations """ b=float(input("what is the lenght")) return b def height():# height called by the user """ user called height :return: return the function to make the claculations """ c=float(input("what ois the height")) return c def instructions(): print("this is gonna calculate the surace area of a rectangle with the length, with and height choosed by the user") def calculations():#surface area calculations a =withh() b=lenght() c=height() top=arearectangle(a,b) bottom=arearectangle(b,a) front=arearectangle(c,b) back=arearectangle(b,c) left=arearectangle(c,a) right=arearectangle(a,c) total=top+bottom+right+left+front+back instructions() print(total) calculations()
true
b6d777bda60b89b9880543ecdd6f132a111b039e
tanay2098/homework4
/task2.py
1,023
4.15625
4
import random # importing package random nums = [] # initializing an empty list called nums for i in range(0,2): # Loop for 2 elements nums.append(random.randint(0,10)) # generating 2 numbers between 0 to 10 and appending them in the list t1 = tuple(nums) # converting list into a tuple named t1 correct_answer = (int)(t1[0] * t1[1] )# converting product of first and second element of tuple into integer and storing it print("How much is",t1[0],"times",t1[1],"? ") # Displaying the question temp = 0 # a variable to store sentinel value while(temp<1): user_answer = int(input("->"))# prompting user to enter the answer if user_answer==correct_answer: # Comparing the user's answer with correct answer print("done") # If answer is right then display done temp= temp +1 # incrementing the value in variable by 1, so as to exit the loop else: print(t1[0],"times",t1[1],"is not,",user_answer,"please try again: ")# if answer is wrong then prompt user to enter the correct answer
true
f76f683497bbf7caff26732105b355888d3160e1
damiannolan/python-fundamentals
/current-time.py
224
4.1875
4
# Problem 2 - Current Time import time; import datetime; # Print the the date and time using 'time' print("Current time is : ", time.asctime(time.localtime(time.time()))) print("Today's date is: ", datetime.date.today())
true
82bd6970962a9f11921c2dc8892969dacad895c8
srholde2/Project-4
/queue.py
1,103
4.28125
4
class Queue: # queue class constructor def __init__(self): self.queue = ["car", "car", "car", "car", "car"] def enqueue(self): item = input("Please enter the item you wish to add to the queue: ") self.queue.append(item) def dequeue(self): item = self.queue.pop(0) print("You have just removed item from queue: ", item) def size(self): for x in range (len(self.queue)): print(self.queue[x]) queue = Queue() newitem = Queue() while True: print("") print("Python Implementation of a Queue") print("********************************") print("1. Create a new object") print("2. Add a new item to the queue") print("3. Remove item from the queue") print("********************************") menu_choice = int(input("Please enter your menu choice: ")) print("") print("") if menu_choice == 1: newitem.enqueue() elif menu_choice == 2: queue.enqueue() elif menu_choice == 3: queue.dequeue()
true
1050e66e270df03c2c88cb35e5d4bf364de138b7
hiranmayee1123/Hacktoberfest-2021
/windowslidingproblem.py
1,013
4.21875
4
#This technique shows how a nested for loop in some problems can be converted to a single for loop to reduce the time complexity. #Let’s start with a problem for illustration where we can apply this technique – #Given an array of integers of size ‘n’. #Our aim is to calculate the maximum sum of ‘k’ #consecutive elements in the array. #Input : arr[] = {100, 200, 300, 400} k = 2 Output : 700 Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20} k = 4 Output : 39 We get maximum sum by adding subarray {4, 2, 10, 23} of size 4. Input : arr[] = {2, 3} k = 3 Output : Invalid There is no subarray of size 3 as size of whole array is 2. import sys INT_MIN = -sys.maxsize - 1 def maxSum(arr, n, k): max_sum = INT_MIN for i in range(n - k + 1): current_sum = 0 for j in range(k): current_sum = current_sum + arr[i + j] max_sum = max(current_sum, max_sum) return max_sum arr = [1, 4, 2, 10, 2, 3, 1, 0, 20] k = 4 n = len(arr) print(maxSum(arr, n, k))
true
3a7e5870dc242615ee553d0f00295ace995c470a
green-fox-academy/klentix
/Topic 5 Data Structure/List Introduction 1.py
810
4.5625
5
namelist = ['William'] namelist.extend(['Jony', 'Amanda']) # add on multiple items in the list print("No. of name", len(namelist)) # print total number of items print("Name list: ", namelist) # print out each element print("the 3rd name is:", namelist[2]) #iterate through a list and print out individual name for i in namelist: print(i) #iterate through a list and print out individual name with index number for num,name in enumerate (namelist,start = 1): print("{}. {}".format(num,name)) #remove 2nd name namelist.pop(1) print("after remove 2nd name: ", namelist) #iterate through a list in reverse order namelist.reverse() for k in namelist: print("name in reversed order: ", k) #remove all element namelist.clear() print ("namelist after remove all: ", namelist) print("\nend")
true
ce86046945bc3f35b226e37d29f8be3d4f36b893
PramitaPandit/Rock-Paper-Scissor
/main.py
2,492
4.4375
4
#Rock-Paper-Scissor game # import random #step1: Stating game instructions print('Rules of Rock-Paper-Scissor are as follows:\n Rock v/s Paper -> Paper wins \n Rock v/s Scissor -> Rock wins \n Scissor v/s Paper -> Scissor wins ') # Step2: Taking user input user = input('Enter your name: ') while True: player_choice = input('Enter a choice: \n a. Rock \n b. Paper \n c. Scissor \n ').lower() # Step3: Checking for invalid input if player_choice == 'a' or player_choice == 'b' or player_choice == 'c': print('Good luck ' + user) else: while player_choice != 'a' or player_choice != 'b' or player_choice != 'c': player_choice = input('Invalid choice. Please enter your choice again: ').lower() break; # Step4: Initializing value of choice_name variable corresponding to the choice value if player_choice == 'a': player_choice_name = 'Rock' elif player_choice == 'b': player_choice_name = 'Paper' else: player_choice_name = 'Scissor' #step5: Creating a list of possible choices for computer possible_choice = ['Rock', 'Paper', 'Scissor'] #step6: Computer chooses randomly from the available choices Computer_choice = possible_choice[random.randint(0,2)] print('Computer chooses ' + Computer_choice) ##step7: Game conditions if player_choice_name == Computer_choice: print(f"Both players selected {Computer_choice}. It's a tie!") elif player_choice_name == 'Rock': if Computer_choice == 'Scissor': print('Rock smashes Scissor. You win!') else: print('Paper covers Rock. You lose!') elif player_choice_name == 'Paper': if Computer_choice == 'Rock': print('Paper covers Rock. You win!') else: print('Scissor cuts Paper. You lose!') elif player_choice_name == 'Scissor': if Computer_choice == 'Paper': print('Scissor cuts Paper. You win!') else: print('Rock smashes Scissor. You lose!') #step8: Asking user wish to continue Option = input('Do you want to play again? \n 1. Yes \n 2. No \n') while Option < '1' or Option > '2': Option = input('Invalid choice. Please enter your choice again: ') if Option == '1': print('Get ready for the next round!') else: break #step9: Thanking the player after coming out the while loop print('Thanks for playing ' + user)
true
3dfecdcc2e10e2a8726896802dbed82b8ceef96c
FX-Wood/python-intro
/name_length.py
291
4.375
4
# Exercise 3: # Write a script that asks for a name and prints out, "Your name is X characters in length." # Replace X with the length of the name without the spaces!!! name = input('Please enter your name: \n > ') print(f"Your name is {len(name.replace(' ', ''))} characters in length")
true
04a659e77718a85fad089298850585a77cdb9d00
FX-Wood/python-intro
/collections/print_names.py
246
4.40625
4
# Exercise 1 # Create a list named students containing some student names (strings). # Print out the second student's name. # Print out the last student's name. students = ["Fred", "Alice", "Bob", "Susie"] print(students[1]) print(students[-1])
true
c7dbc874de58b7713d58d422a399f09efebbe726
deepakkadarivel/python-programming
/7_file_processing/7_2_search_in_file.py
946
4.28125
4
""" “Write a program to prompt for a file name, and then read through the file and look for lines of the form: X-DSPAM-Confidence:0.8475” Pseudo code 1. Read file name from user 2. open file 3. Handle No file exception 4. Iterate through files for text and increment count 5. print total count """ import sys file_name = input('Enter file name: ') try: file_hand = open(file_name) except OSError: print('File cannot be opened:', file_name) sys.exit(0) search_value = 'X-DSPAM-Confidence:' count = 0 line_count = 0 for line in file_hand: if not line.startswith(search_value): continue value_pos = line.find(':') value = line[value_pos + 1:].strip() count += float(value) line_count += 1 try: average = count/line_count except ZeroDivisionError: print('Zero lines found with for', search_value) sys.exit(0) print('Average spam confidence:', count/line_count)
true
f2d750dadce5e8cf3359b18e806ba763842042e9
deepakkadarivel/python-programming
/6_1_reverse_string.py
567
4.40625
4
""" Write a while loop that starts at the last character in the string and works it’s way through first character in the string, printing each letter in a separate line except backwards. TODO 1: Accept a string from io TODO 2: Find the length of the string TODO 3: decrement len and print character in len with new line TODO 4: stop iteration and once len is less than 0 """ value_string = input('Enter a string: ') value_length = len(value_string) while value_length > 0: value_length -= 1 print(value_string[value_length])
true
8915bb5963f3b0accb33e02d68fba4a8c3bf7628
deepakkadarivel/python-programming
/6_2_letter_count.py
757
4.375
4
""" Find the count of a letter in a word. Encapsulate the code in a function named count, and generalize it so that it accepts the string and letter as an argument. TODO 1: Accept input for a word and letter to search for. TODO 2: Define a count function that accepts word and letter as parameter to count the number of occurrences in word. - Define a variable that will increment for each occurrence of letter - print the total count """ def count(word, letter): letter_count = 0 for character in word: if character == letter: letter_count = letter_count + 1 print(letter_count) word_input = input('Enter Word: ') letter_input = input('Enter Letter: ') count(word_input, letter_input)
true
6a154af4ddbf024665295fdfab72fe4d6f828de8
Jrbrown09/Brown-Assignment5
/.vscode/exercise6.py
2,138
4.4375
4
from helpers import * ''' Exercise 6 Calories from Fat and Carbohydrates This program calculates the calories from fat and carbohydrates that the user consumed. The calorie amounts are calculated using the input from the user in carbohydrates and fat. ''' ''' Define the 'main' function ''' def main(): fat_grams_entered = get_fat_grams() carb_grams_entered = get_carb_grams() fat_calories = calculate_fat_calories(fat_grams_entered) carb_calories = calculate_carb_calories(carb_grams_entered) display_calories_output(fat_calories, carb_calories) ''' Defines the function for the user input of the number of grams of fat entered return fat_grams, the number of grams of fat entered by the user ''' def get_fat_grams(): fat_grams = getFloat("Please enter the number of grams of fat you consume: ") return fat_grams ''' Defines the function for the user input of the number of grams of carbohydrates entered return carb_grams, the number of grams of carbohydrates entered by the user ''' def get_carb_grams(): carb_grams = getFloat("Please enter the number of grams of carbs you consume: ") return carb_grams ''' Defines the function for calculating the number of calories of fat that the user has consumed @param fat_grams return fat_calories, calories from fat calculated ''' def calculate_fat_calories(fat_grams): fat_calories = fat_grams * 9 return format(fat_calories, ",.1f") ''' Defines the function for calculating the number of calories of carbohydrates that the user has consumed @param carb_grams return carb_calories, calories from carbohydrates calculated ''' def calculate_carb_calories(carb_grams): carb_calories = carb_grams * 4 return format(carb_calories, ",.1f") ''' Defines the function for displaying the output of the calories from carbohydrates and fat calculated from the user @param fat_calories @param carb_calories ''' def display_calories_output(fat_calories, carb_calories): print("You have consumed ", str(fat_calories), " calories from fat.") print("You have consumed ", str(carb_calories), " calories from carbohydrates.") main()
true
32b144e97cd8f10500b1848ebd8af4599ae66d12
markvassell/Python
/test/multiplication_table.py
1,248
4.21875
4
import math print("This is test multiplication table: Still in progress") file_name = "Multiples.txt" try: #opens a file to write to mult_file = open(file_name, "w") while (True): try: inp_range = int(input("Please enter how many multiplication tables you would like to generate: ")) if(inp_range <= 0): print("Please only enter numeric values that are greater than zero: ") continue break except ValueError: print("Plase only enter a numeric value") continue for i in range(1,inp_range+1): for j in range(1,inp_range+1): mult_file.write(str(i*j) + "\n") mult_file.write("\n") mult_file.close() print("The tables were successfully written to the file!") except: print("An error occured while trying to write the random numbers to", file_name) #used to find the range #http://pythoncentral.io/pythons-range-function-explained/ #learned about for loops in python #http://www.tutorialspoint.com/python/python_for_loop.htm #errors and exceptions #https://docs.python.org/2/tutorial/errors.html #how to write to a file in python. #http://learnpythonthehardway.org/book/ex16.html
true
c52dac3f89683c8ade4f3bc4f81b4a9ff350cc1d
surendhar-code/python_practice
/program1.py
306
4.3125
4
#python program to interchange first and last elements in a list. def firstlast(list1,n): beg=list1[0] end=list1[n] print("The first and last element of the list {0} is {1} and {2}\n".format(list1,beg,end)) list1=list(range(0,5)) print(list1) n=(len(list1))-1 firstlast(list1,n)
true
60b5cb899cef0911bd7d7a775cfbb7ea557aa01f
Robdowski/code-challenges
/running_sum_1d.py
739
4.125
4
""" This problem asks to keep a running total of the sum of a 1 dimensional array, and add that sum to each item in the array as we traverse. To do this, we can simply declare a variable, running sum, and add it to each item in the array as we traverse. We need to add the sum to the item in the array, while storing the original value of the item in a temporary variable to add to the running sum. Example output [1, 2, 3, 4] --> [1, 3, 6, 10] Runtime Complexity: O(n) Space Complexity: O(1) """ class Solution: def runningSum(self, nums): running_sum = 0 for i in range(len(nums)): temp = nums[i] nums[i] += running_sum running_sum += temp return nums
true
2d516c584352f0d835fc8f9f7dc076fd032e8af3
N0l1Na/Algorithms_Python
/PIL006/PIL006.py
1,306
4.25
4
""" PIL - The exercise is taken from the Pilshchikov's Pascal problem book Task 8.7 page 40 Regular types: vectors Using the Gender and Height arrays, determine: a) The name of the tallest man b) The average height of women Creator Mikhail Mun """ import random array = [] total_height_women = 0 amount_women = 0 max_height = None names = ("Valeria", "Gena", "Eugene", "Nikola", "Maria", "Nina", "Sasha", "Tanya", "Fedor", "Shura") genders = ("woman", "man", "man", "man", "woman", "woman", "woman", "woman", "man", "woman") for i in range(0, 10): # gender determination output_gender = print(names[i] + " " + str(genders[i])) # height determination generate_random_height = random.randrange(140, 201) output_age = print(names[i] + " (" + str(generate_random_height) + "sm)") # max the height of the man if genders[i] == "man": # add element in the list array.append(str(generate_random_height)) # find max element of the list max_height = max(array) # average function elif genders[i] == "woman": amount_women = amount_women + 1 total_height_women = total_height_women + generate_random_height print("Max the height of the man " + str(max_height)) print("Average women= " + str(total_height_women / amount_women))
true
ec6e1871e6a55516a520a49b11dcd267d7dbb28a
nguyenthanhthao1908/classpython_basic_online
/rewrite_code_resource_w/dictionary/bai9.py
235
4.3125
4
"""Write a Python program to iterate over dictionaries using for loops.""" D = {"Name": "Thao", "Age": 20, 19: 8} # for i in D.items(): # print(i) # solution 2: for key, value in D.items(): print(key, "is:", D[key])
true
aa2b00e3bcd8cc17d08ef67e68ab65aaa64c0435
nguyenthanhthao1908/classpython_basic_online
/rewrite_code_resource_w/dictionary/bai15.py
226
4.15625
4
"""Write a Python program to get the maximum and minimum value in a dictionary. """ D = {3: 30, 2: 20, 19: 8} print("Maximum:", max(D.keys(), key=(lambda k: D[k]))) print("Minimum:", min(D.keys(), key=(lambda k: D[k])))
true
6c952a8e00c4a823828985e353e4ff04c5c747c8
Bigg-Iron/152_001
/C_activities/C10.py
2,963
4.1875
4
""" 10.1.2: Modify a list. Modify short_names by deleting the first element and changing the last element to Joe. Sample output with input: 'Gertrude Sam Ann Joseph' ['Sam', 'Ann', 'Joe'] """ # user_input = input() # short_names = user_input.split() # ''' Your solution goes here ''' # del short_names[0] # del short_names[-1] # short_names.append('Joe') # print(short_names) """ 10.2.1: Reverse sort of list. Sort short_names in reverse alphabetic order. Sample output with input: 'Jan Sam Ann Joe Tod' ['Tod', 'Sam', 'Joe', 'Jan', 'Ann'] """ # user_input = input() # short_names = user_input.split() # ''' Your solution goes here ''' # short_names.sort() # short_names.reverse() # print(short_names) """ 10.3.1: Get user guesses. Write a loop to populate the list user_guesses with a number of guesses. The variable num_guesses is the number of guesses the user will have, which is read first as an integer. Read integers one at a time using int(input()). Sample output with input: '3 9 5 2' user_guesses: [9, 5, 2] """ # num_guesses = int(input()) # user_guesses = [] # ''' Your solution goes here ''' # for index in range(num_guesses): # user_guesses.append(int(input())) # print('user_guesses:', user_guesses) """10.3.2: Sum extra credit. Assign sum_extra with the total extra credit received given list test_grades. Full credit is 100, so anything over 100 is extra credit. For the given program, sum_extra is 8 because 1 + 0 + 7 + 0 is 8. Sample output for the given program with input: '101 83 107 90' Sum extra: 8""" # user_input = input() # test_grades = list(map(int, user_input.split())) # contains test scores # sum_extra = -999 # Initialize 0 before your loop # ''' Your solution goes here ''' # sum_extra = 0 # for grade in test_grades: # if (grade > 100): # sum_extra += grade - 100 # print('Sum extra:', sum_extra) """10.3.3: Hourly temperature reporting. Write a loop to print all elements in hourly_temperature. Separate elements with a -> surrounded by spaces. Sample output for the given program with input: '90 92 94 95' 90 -> 92 -> 94 -> 95 Note: 95 is followed by a space, then a newline. """ # user_input = input() # hourly_temperature = user_input.split() # ''' Your solution goes here ''' # for temp in hourly_temperature: # if temp == hourly_temperature[-1]: # print(temp, '') # else: # print(temp, end=' -> ') """10.5.1: Print multiplication table. Print the two-dimensional list mult_table by row and column. Hint: Use nested loops. Sample output with input: '1 2 3,2 4 6,3 6 9': 1 | 2 | 3 2 | 4 | 6 3 | 6 | 9 """ user_input= input() lines = user_input.split(',') # This line uses a construct called a list comprehension, introduced elsewhere, # to convert the input string into a two-dimensional list. # Ex: 1 2, 2 4 is converted to [ [1, 2], [2, 4] ] mult_table = [[int(num) for num in line.split()] for line in lines] ''' Your solution goes here ''' print(mult_table)
true
f683cbbba69ce43dbcf7aa072a7b5890b123aadb
kennylugo/Tweet_Generator_Data_Structures_-_Probability
/1.3_anagram_generator.py
1,343
4.15625
4
import sys, random # THIS ANAGRAM GENERATOR IS NOT WORKING YET # method signature def generate_anagram(): # the list method will break a word apart and add each letter to a list data structure list_of_letters_from_word_input = list(sys.argv[1]) # we store the count of the elements in the list above length_of_word_list = len(list_of_letters_from_word_input) possible_indexes = length_of_word_list - 1 new_anagram = [] for letter in range(-1, length_of_word_list): random_integer = random.randint(0, possible_indexes) list_of_letters_from_word_input[letter], list_of_letters_from_word_input[random_integer] = list_of_letters_from_word_input[random_integer],list_of_letters_from_word_input[letter] new_anagram.append(list_of_letters_from_word_input[random_integer]) # new_anagram.append(list_of_letters_from_word_input[random_integer]) concatenate_indexes = "".join(list_of_letters_from_word_input) newer_anagram = "".join(new_anagram) print concatenate_indexes, newer_anagram # create method # convert the letters in the input variable into a list # loop over the list # create a random integer from 0 to #oflettersInword # assign that randomInt to an index in the list holding the letters for the word_file # return the new word generate_anagram()
true
0af53ed79a3d2df089f628732cd0f0989ef4e26c
abdullahclarusway/Python_Assignments
/Assignment_9.py
214
4.28125
4
name = input("Please enter your name:").title() my_name = "Abdullah" if name == my_name: print("Hello, {}! The password is: W@12".format(my_name)) else: print("Hello, {}! See you later.".format(name))
true
5f1df607c99984af8b32cabeb6d38bb9b85d91e3
srinisha2628/new_practice
/cuberoot.py
358
4.125
4
x= int(input("enter a number\n")) ans=0 while ans**3 < abs(x): ans+=1 if(ans**3!= abs(x)): print("it is not a perfect cube") else: if(x<0): ans = -ans print("cube root of "+ str(x)+" is "+ str(ans)) cube=int(input("enter a number")) for guess in range(cube+1): if(guess**2==cube): print("cube root of",cube ,"is",guess)
true
076f59fedeb631a4284093eab8358526ea1390a5
mewilczynski/python-classwork
/program41.py
865
4.375
4
#Marta Wilczynski #February 2nd, 2016 © #Chapter 4 assignment program41.py #Start program #Import math since we will be using PI #Set up a range of numbers, using the for loop. #Calculate area of a circle with "radius", where the equation # will be area = (PI * (radius ** 2)) #Calculate circumfrence with "radius", # where the equation will be circumfrence = (2 * PI * radius) #Format and display the radii, areas, and circumfrences. #End program #import math import math #Start the loop, for radius in range(10, 51, 10): area = (math.pi * (radius ** 2)) #Calculate the area circumfrence = (2 * math.pi * radius) #calculate the circumfrence print(format(radius, '5,.3f'), '\t', format(area, '9,.3f'), '\t', format(circumfrence, '7,.3f')) #Format the numbers into a column, aligning the decimal points and going to 3 decimal points
true
b496deacdbb5b1098a24631825f11221a2cbfcb6
mewilczynski/python-classwork
/order32.py
1,681
4.21875
4
#Marta Wilczynski #February 2nd, 2016 © #order32.py #Start program. #Get the number of t-shirts being purchased from the user, #assign to variable "amountOfShirts". #Calculate amountOfShirts * 12.99, assign to variable "priceOfShirts". #Assign number 8.99 to variable "shipping". #Determine discounts by looking at amount of shirts being bought. #If amountOfShirts >= 12, calculate (priceOfShirts) - (priceOfShirts * 0.3) #If amountOfShirts >= 6 and <=11, #calculate (priceOfShirts) - (priceOfShirts * 0.2) + shipping #If amountOfShirts >= 3 and <=5, #calculate (priceOfShirts) - (priceOfShirts * 0.1) + shipping #If amountOfShirts == 1 or == 2, calculate (priceOfShirts) + shipping #Assign calculated price of shirts to variable "finalPrice". #Display the amount needed to pay. #Ask user for amount of t-shirts amountOfShirts = int(input("How many shirts are you buying? ")) #Assign base price of shirts to variable "priceOfShirts" priceOfShirts = float(amountOfShirts * 12.99) #Assign shipping price to variable "shipping" shipping = float(8.99) #Determine whether or not the user qualifies for discounts if amountOfShirts >= 12: finalPrice = ((priceOfShirts) - (priceOfShirts * 0.3)) else: if amountOfShirts >= 6 and amountOfShirts <= 11: finalPrice = ((priceOfShirts) - (priceOfShirts * 0.2) + shipping) else: if amountOfShirts >= 3 and amountOfShirts <= 5: finalPrice = ((priceOfShirts) - (priceOfShirts * 0.1) + shipping) else: finalPrice = ((priceOfShirts) + shipping) #Display the final price of the shirts. print ("Your total comes to $", format(finalPrice, ',.2f'), sep='')
true
61a787ee69c3e67a8fbaab6c6d057aeab66245e6
Manish-bitpirate/Hacktoberfest
/python files/story_maker_by_cyoa.py
2,019
4.125
4
name=input("What's your name?") print("Treasure Hunter, a custom story by " + name ) print("You are a brave explorer that was recognized by the world and found an ancient Mayan temple!") opt1=input("Do you walk in? y/n?") opt2="" opt3="" opt4="" if opt1=="y": print("You walk in, your footsteps echoing in the dark. You turn on a flashlight and came across two paths.") opt2=input("You look down the first path and see jewels glinting in the darkness. You look down the left and hear a low hissing sound like snakes. Which path did you take? r/l? ") if opt2=="r": print("You walk down the path and found a treasure box stuffed with gems! You stuff a few handfuls of diamond, ruby, and sapphire into your backpack, and come across another crossroad.") opt3=input("At the second intersection, you peer into the darkness and don't see anything. The choice is your's to make. r/l? ") if opt3=="l": print("You found the treasure room! You walked in and found ancient treasures!") opt4=input("The door closes on you! You're trapped! Do you give up hope or keep looking? give up/ keep looking? ") if opt4=="keep looking": print("You kept looking, and found a piston mechanism that led you up to a stairway out. You escaped with a ton of jewels, and a story to be told for generations to come!") if opt1=="n": print("You return and report your findings. You are stripped of your rights as an adventurer and are looked down upon as a coward.") if opt2=="l": print("You walk down the descending staircase and look up. A venomous spider thought to be long extinct bit you and as your vision faded, you were alone.") if opt3=="r": print("You find the Emperor's tomb. You decided to take the coffin up for the museums. But as you did, the lid was pushed off, and the ankhet the emperor was wearing cursed you to be forever stuffed into a bottle.") if opt4=="give up": print("The world forgot you and your name fades, as your bones turn to dust...")
true
8fde712d6f525b47c1989497f3dbd086c61c7041
SAMLEVENSON/ACET
/Factorialwi.py
233
4.125
4
def main(): print("To find the Factorial of a Number") a= int(input("Enter the Number:")) if(a>=20) fact =1 for i in range(1,a + 1): fact = fact*i print(fac) if __name__ == '__main__': main()
true
9eb5f962bc60fa4c74d117fab1c7234562f1266d
anantkaushik/Data-Structures-and-Algorithms
/Data-Structures/Graphs/bfs.py
1,458
4.125
4
""" Graph traversal means visiting every vertex and edge exactly once in a well-defined order. While using certain graph algorithms, you must ensure that each vertex of the graph is visited exactly once. The order in which the vertices are visited are important and may depend upon the algorithm or question that you are solving. During a traversal, it is important that you track which vertices have been visited. The most common way of tracking vertices is to mark them. Breadth First Search (BFS) There are many ways to traverse graphs. BFS is the most commonly used approach. BFS is a traversing algorithm where you should start traversing from a selected node (source or starting node) and traverse the graph layerwise thus exploring the neighbour nodes (nodes which are directly connected to source node). You must then move towards the next-level neighbour nodes. As the name BFS suggests, you are required to traverse the graph breadthwise as follows: - First move horizontally and visit all the nodes of the current layer - Move to the next layer """ def bfs(graph, root): visited, queue = set(), [root] visited.add(root) while queue: vertex = queue.pop(0) print(vertex) for neighbour in graph[vertex]: if neighbour not in visited: visited.add(neighbour) queue.append(neighbour) graph = {0: [2], 1: [0,2], 2: [3], 3: [1,2]} bfs(graph, 2) # return 2 3 1 0
true
2964932bc4395158beb2ee0eba705ee180eaac84
dbzahariev/Python-and-Django
/Python-Basic/exam_preparation_1/part_1/task_4.py
539
4.1875
4
best_player_name = '' best_player_goal = -1 while True: text = input() if text == 'END': break player_name = text player_goals = int(input()) if player_goals > best_player_goal: best_player_name = player_name best_player_goal = player_goals if player_goals >= 10: break print(f"{best_player_name} is the best player!") if best_player_goal >= 3: print(f'He has scored {best_player_goal} goals and made a hat-trick !!!') else: print(f'He has scored {best_player_goal} goals.')
true
0adc5800f99519b907a6939fee2c38ebc950da38
chaosWsF/Python-Practice
/leetcode/0326_power_of_three.py
710
4.34375
4
""" Given an integer, write a function to determine if it is a power of three. Example 1: Input: 27 Output: true Example 2: Input: 0 Output: false Example 3: Input: 9 Output: true Example 4: Input: 45 Output: false Follow up: Could you do it without using any loop / recursion? """ from math import log10 class Solution: def isPowerOfThree1(self, n): """The solution cannot pass if we use log or log2 due to precision errors.""" return (n > 0) and ((log10(n) / log10(3)) % 1 == 0) def isPowerOfThree2(self, n): """The integer has the limit 32bits, 3**19 < 2**31 - 1 < 3**20""" return (n > 0) and (1162261467 % n == 0)
true
ba66e9707f75734abd0a2bfb61c9c74655f4ed62
chaosWsF/Python-Practice
/leetcode/0035_search_insert_position.py
1,291
4.15625
4
""" Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Output: 4 Example 4: Input: [1,3,5,6], 0 Output: 0 """ class Solution: def searchInsert(self, nums, target): """binary search""" a = 0 b = len(nums) - 1 while a <= b: c = (a + b) // 2 m = nums[c] if m < target: a = c + 1 elif m == target: return c else: b = c - 1 return a def searchInsert2(self, nums, target): """python's sorted()/list.sort()""" return sorted(nums + [target]).index(target) def searchInsert3(self, nums, target): """linear search""" if nums[0] >= target: return 0 for i in range(len(nums) - 1): if nums[i] < target <= nums[i + 1]: return i + 1 if nums[-1] == target: return len(nums) - 1 else: return len(nums)
true
6c9a0b00945ee3ea85cc7430ec2b40e660d05d4e
chaosWsF/Python-Practice
/leetcode/0532_k-diff_pairs_in_an_array.py
1,281
4.1875
4
""" Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. Example 1: Input: [3, 1, 4, 1, 5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of unique pairs. Example 2: Input:[1, 2, 3, 4, 5], k = 1 Output: 4 Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). Example 3: Input: [1, 3, 1, 5, 4], k = 0 Output: 1 Explanation: There is one 0-diff pair in the array, (1, 1). Note: The pairs (i, j) and (j, i) count as the same pair. The length of the array won't exceed 10,000. All the integers in the given input belong to the range: [-1e7, 1e7]. """ from collections import Counter class Solution: def findPairs(self, nums, k): if k < 0: return 0 elif k == 0: return len([x for x in Counter(nums).values() if x > 1]) else: nums = set(nums) return len([i for i in nums if i + k in nums])
true
99b3a845267202d53a1f0e9e346b8bcb0a21a577
chaosWsF/Python-Practice
/leetcode/0020_valid_parentheses.py
1,707
4.1875
4
""" Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true """ class Solution: def isValid(self, s): """use stack""" if not s: return True if len(s) % 2 == 1: return False pars = {')': '(', ']': '[', '}': '{'} stack = [] for ss in s: if ss in pars: if len(stack) == 0: return False if pars[ss] == stack[-1]: stack.pop() else: return False else: stack.append(ss) return len(stack) == 0 def isValid2(self, s): """use replace""" if not s: return True if len(s) % 2 == 1: return False pars = {'(': ')', '[': ']', '{': '}'} while s: flag = 0 for par in pars.items(): par = ''.join(par) if par in s: s = s.replace(par, '') else: flag += 1 if flag == 3: return False else: return True
true
ee5da787fc7206823a2f764e883ca3d3ecbf5caf
chaosWsF/Python-Practice
/leetcode/0344_reverse_string.py
1,092
4.25
4
""" Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters. Example 1: Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"] Example 2: Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"] """ class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ for i in range(len(s) // 2): s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i] def reverseString1(self, s): # 204ms s[:] = s[::-1] def reverseString2(self, s): # 196ms s.reverse() def reverseString3(self, s): # 196ms head = 0 tail = len(s) - 1 while head < tail: tmp = s[head] s[head] = s[tail] s[tail] = tmp head += 1 tail -= 1
true
c70a497fa0a9db39e3f4546fd96775912458e71d
chaosWsF/Python-Practice
/leetcode/0027_remove_element.py
1,988
4.25
4
""" Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Example 1: Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,1,2,2,3,0,4,2], val = 2, Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length. Clarification: Confused why the returned value is an integer but your answer is an array? Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. Internally you can think of this: // nums is passed in by reference. (i.e., without making a copy) int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); } """ class Solution: def removeElement(self, nums, val): """direct solution""" i = 0 while i < len(nums): if nums[i] == val: del nums[i] else: i += 1 return len(nums) def removeElement2(self, nums, val): """use filter""" tmp = list(filter(lambda x: x != val, nums)) nums[:len(tmp)] = tmp del nums[len(tmp):] # nums[len(tmp):] = [] return len(nums)
true
bcd5d58a4b1789a205e03f69fe2458b9b4a5b5a2
chaosWsF/Python-Practice
/leetcode/0088_merge_sorted_array.py
2,069
4.21875
4
""" Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Example: Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] """ class Solution: """ Do not return anything, modify nums1 in-place instead. """ def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ # back assigning while m > 0 and n > 0: if nums1[m-1] > nums2[n-1]: nums1[m+n-1] = nums1[m-1] m -= 1 else: nums1[m+n-1] = nums2[n-1] n -= 1 if m == 0: nums1[:n] = nums2[:n] # if n == 0: # return # if m == 0: # nums1[:n] = nums2 # i, j = 0, 0 # while i < m and j < n: # if nums1[i] > nums2[j]: # nums1[i+1:] = nums1[i:-1] # nums1[i] = nums2[j] # j += 1 # m += 1 # i += 1 # if i == m: nums1[m:] = nums2[j:] def merge1(self, nums1, m, nums2, n): """Two Pointers""" i = 0 j = 0 while j < n: while i < m and nums1[i] <= nums2[j]: i += 1 if i == m: nums1[m:] = nums2[j:] break nums1[i+1:] = nums1[i:-1] nums1[i] = nums2[j] i += 1 m += 1 j += 1 def merge2(self, nums1, m, nums2, n): """Builtin Method""" if not nums2: return nums1 nums1[m:] = nums2 nums1.sort()
true
dd0ca36d22e09a8278608bbd0c02f554bc9cab26
chaosWsF/Python-Practice
/leetcode/1002_find_common_characters.py
1,281
4.15625
4
""" Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer. You may return the answer in any order. Example 1: Input: ["bella","label","roller"] Output: ["e","l","l"] Example 2: Input: ["cool","lock","cook"] Output: ["c","o"] Note: 1. 1 <= A.length <= 100 2. 1 <= A[i].length <= 100 3. A[i][j] is a lowercase letter """ from collections import Counter from functools import reduce class Solution: def commonChars1(self, A): def helper(cnt1, cnt2): if len(cnt1) > len(cnt2): cnt1, cnt2 = cnt2, cnt1 res = {} for key in cnt1: if key in cnt2: res[key] = min(cnt1[key], cnt2[key]) return res return [key for key, val in reduce(helper, map(Counter, A)).items() for _ in range(val)] def commonChars2(self, A): res = Counter(A[0]) for i in range(1, len(A)): res &= Counter(A[i]) return list(res.elements())
true
674ef5c016216bb2e64195ccb36ccb056773a720
chaosWsF/Python-Practice
/leetcode/0434_number_of_segments_in_a_string.py
546
4.15625
4
""" Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. Please note that the string does not contain any non-printable characters. Example: Input: "Hello, my name is John" Output: 5 """ class Solution: def countSegments1(self, s): return len(s.split()) def countSegments2(self, s): res = 0 for i in range(len(s)): if (i == 0 or s[i - 1] == ' ') and s[i] != ' ': res += 1 return res
true
400142c7d92f56ad7af22a82663441976791369d
JQuinSmith/learning-python
/ex15.py
813
4.34375
4
# imports the module from sys import argv # the script, and the text file are used as modules script, filename = argv # Assuming "open" opens the file being passed into it for use in the rest of the script. txt = open(filename) # # Serves up the filename based on what is entered into the terminal. # print ("Here's your file %r:" % filename) # # Prints the variable "txt". ".read()", I assume, is a Python native function that reads the content of the file being opened by txt. # print (txt.read()) # just a string being printed print ("Type the filename again:") # input prompt with "> " as the...prompt indicator? file_again = raw_input("> ") # variable that holds the basic function "open" txt_again = open(file_again) # reads the file being input during the raw_input prompt. print (txt_again.read())
true
71678e32831ef0554e88ee5e916b749ba0a8ced9
Program-Explorers/Random_Password_Generator
/random_password.py
1,963
4.21875
4
# import statements #Random Password Generator import random import string def greeting(): print("This programs makes your password more secure based on a word you provide!" + "\nIt increases the strenth of your password by adding random letters and digits before or after the word\n") class password_generator(): def __init__(self, word, length=8): self.word = word self.length = length def random_char(self): characters = string.ascii_letters + string.digits pass_list = [] len_to_add = self.length - len(self.word) while len_to_add != 0: len_to_add -= 1 random_chars = random.choice(characters) pass_list.append(random_chars) return pass_list def letters_to_add(self, to_add): list_word = list(self.word) length_of_to_add = len(to_add) while length_of_to_add != 0: popped = to_add.pop() rand_choice = random.randint(0, 1) if rand_choice == 0: list_word.insert(0, popped) elif rand_choice == 1: list_word.append(popped) length_of_to_add -= 1 return list_word def main(): print('\n' * 10) greeting() word = input("Enter in a word for your random password: ") length_word = int(input("How many random characters do you want in your password: ")) while len(word) > length_word: print('Sorry your word is longer than the passwords length') word = input("Enter in a word for your random password: ") length_word = int(input("How many random characters do you want in your password: ")) users_password = password_generator(word, length_word) add_to_word = users_password.random_char() the_password = users_password.letters_to_add(add_to_word) print(f"\n\nYour new password is \n{''.join(the_password)}") if __name__ == "__main__": main()
true
1cb20485ce03458d71b766dc450d2b9f624f8e21
Benjamin-Menashe/Project_Euler
/problem1.py
470
4.25
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 3 10:09:34 2021 @author: Benjamin """ # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. import numpy as np fives = np.array(range(0,1000,5)) threes = np.array(range(0,1000,3)) fifteens = np.array(range(0,1000,15)) Answer = sum(fives) + sum(threes) - sum(fifteens) print(Answer)
true
8d208cee28c4dc5fa45b42d4a7e57e2508840a3d
Yasaman1997/My_Python_Training
/Test/lists/__init__.py
1,599
4.375
4
zoo_animals = ["pangolin", "cassowary", "sloth", "dog"]; # One animal is missing! if len(zoo_animals) > 3: print "The first animal at the zoo is the " + zoo_animals[0] print "The second animal at the zoo is the " + zoo_animals[1] print "The third animal at the zoo is the " + zoo_animals[2] print "The fourth animal at the zoo is the " + zoo_animals[3] animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index = animals.index("duck") # Use index() to find "duck" # Your code here! animals.insert(duck_index, "cobra") print animals # Observe what prints after the insert operation start_list = [5, 3, 1, 2, 4] square_list = [] # Your code here! for x in start_list: square_list.append(x**2) square_list.sort() print square_list my_list = [1, 9, 3, 8, 5, 7] for number in my_list: # Your code here for number in my_list: print 2 * number # Assigning a dictionary with three key-value pairs to residents: residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} print residents['Puffin'] # Prints Puffin's room number print residents['Sloth'] print residents['Puffin'] # Prints Puffin's room number print residents['Burmese Python'] menu = {} # Empty dictionary menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair print menu['Chicken Alfredo'] # Your code here: Add some dish-price pairs to menu! menu['pizza'] = 2.50 menu['soup'] = 1.50 menu['Salad'] = 5.50 print "There are " + str(len(menu)) + " items on the menu." print menu
true
810e9b7a1d47e4c5e19b452bb3ecda92a5cd79d1
zerojpyle/learningPy
/ex19_practice.py
590
4.15625
4
# define a function to do some math # I'm trying to find 10 ways to run a function def my_calc(number1, number2): print(f"First, {number1} + {number2} = {number1 + number2}!") print(f"Second, {number1} x {number2} = {number1 * number2}!") print(f"And that's it! Come back later and maybe you'll get more.\n") # 1 my_calc(3,5) # 2 print('Hit enter to run "my_calc"') input(">") my_calc(4,5) # 3 num1 = input('Pick a number: ') num2 = input('Pick another number: ') my_calc(int(num1), int(num2)) # 4 print("Pick two numbers") my_calc(int(input("1st: ")), int(input("2nd: ")))
true
ea825b27fe780710ee9520c77bc7bdd9b69b6515
zerojpyle/learningPy
/ex6.py
887
4.4375
4
# define variable with a number types_of_people = 10 # define a variable as a literal string x = f"There are {types_of_people} types of people." # define a couple strings as variables binary = "binary" do_not = "don't" # define a variable as a literal string y = f"Those who know {binary} and those who {do_not}." # print x & y literal strings print(x) print(y) # print more literal strings directly, with embedded literal strings x & y print(f"I said: {x}") print(f"I also said: '{y}'") # define a variable with a boolean hilarious = False # define a variable with a string joke_evaluation = "Isn't that joke so funny?! {}" # print the variable, adding the boolean that's formatted to be a string print(joke_evaluation.format(hilarious)) # define more strings w = "This is the left side of..." e = "a string with a right side." # combine and then print two strings print(w + e)
true
a0f73784a1ad1a2971e71c9844e3d48c9eeed9a1
cyber-holmes/Centimeter_to_meter-and-inches_python
/height_cm.py
418
4.4375
4
#Goal:Convert given Height from Centimeter to Meter and Inches. #Step1:Take the input. height = input("Enter the Height in Centimeter: ") #Step2:Calculate the value of Meter from Centimeter. meter = height/100.0 #Step3:Calculate the value of Inch from Centimeter. inch = height/2.54 #Step4:Print the Height in Meter. print "Height in Meter: ",meter,"m" #Step5:Height in Inch. print "Height in Inch: ",inch,"in"
true
7377dab7bacfc1c807b49f473775fea650c305b3
starmap0312/python
/libraries/enumerate_zip.py
849
4.78125
5
print("1) enumerate():") # 1) enumerate(iterable): # return enumerate object that can be used to iterate both the indices and values of passed-in iterable for index, value in enumerate(["one", "two", "three"]): print(index, value) # 2) zip(iterable1, iterable2): # return an iterator of tuples, where the i-th tuple contains the i-th element from each of the passed-in iterables # use zip() to iterate multiple lists simultaneously print("2) zip(), iterating multiple lists simultaneously") alist = ["a1", "a2", "a3"] blist = ["b1", "b2", "b3"] clist = ["c1", "c2", "c3"] print(zip(alist, blist, clist)) for a, b, c in zip(alist, blist, clist): print(a, b, c) print("use zip() with argument unpacking") multilists = [["a1", "a2", "a3"], ["b1", "b2", "b3"], ["c1", "c2", "c3"]] for a, b, c in zip(*multilists): print(a, b, c)
true
9dc6900c0eb28775c0e4e8f9fbb353f0a57f6af9
xploreraj/HelloPython
/algos/programs/ZeckendorfsTheorem.py
479
4.28125
4
''' Print non-consecutive fibonacci numbers summing up to a given number ''' # return nearest fibonacci num lesser or equal to argument def nearest_fibo_num(num): a, b = 0, 1 while True: if a + b > num: break temp = b b = a + b a = temp return b if __name__ == '__main__': num = int(input('Enter number and hit enter: ')) while num>0: f = nearest_fibo_num(num) print(f, end=' ') num -= f
true
2dcff43bb6f73d3b5141178c3374911344e3c4aa
ronaldaguerrero/practice
/python2/python/fundamentals/lambdas.py
1,291
4.6875
5
# # Example 1 # # create a new list, with a lambda as an element # my_list = ['test_string', 99, lambda x : x ** 2] # # access the value in the list # # print(my_list[2]) # will print a lambda object stored in memory # # invoke the lambda function, passing in 5 as the argument # print(my_list[2](5)) # # Example 2 # # define a function that takes one input that is a function # def invoker(callback): # # invoke the input pass the argument 2 # print(callback(2)) # invoker(lambda x: 2 * x) # invoker(lambda y: 5 + y) # # Example 3 # add10 = lambda x: x + 10 # store lambda expression in a variable # print(add10(2)) # returns 12 # print(add10(98)) # returns 108 # # Example 4? # def incrementor(num): # start = num # return lambda x: num + x # incrementor(5) # Example 5 # create a list # my_arr = [1,2,3,4,5] # define a function that squares values # def square(num): # return num ** 2 # # invoke map function # print(list(map(square, my_arr))) # Example 6 my_arr = [1,2,3,4,5] print(list(map(lambda x: x ** 2, my_arr))) # invoke map, pass in a lambda as the first argument # why are lambdas useful? When we only need a function once, we don't need to define a function and unnecessarily consume memory and complicate our code, just to produce the same result:
true
d2331f4d0ae550d79cc36677b8d55a4c92153840
zahraaliaghazadeh/python
/functions_intro/banner.py
2,242
4.15625
4
# def banner_text(text=" ", screen_width=80): def banner_text(text: str = " ", screen_width: int = 80) -> None: """ Print a string centred, with ** either side. :param text: The string to print. An asterisk (*) will result in a row of asterisks. The default will print a blank line, with a ** border at the left and right edges. :param screen_width: The overall width to print within (including the 4 spaces for the ** either side). :raises ValueError: if the supplied string is too long to fit. """ # when combining argument annotation and default value use space around = # either use annotation on all or don't use it at all # screen_width = 80 # screen_width = 50 if len(text) > screen_width - 4: # To raise an exception in Python raise ValueError("String {0} is larger than specified width {1}" .format(text, screen_width)) # print("EEK!!") # print("THE TEXT IS TOO LONG TO FIT IN THE SPECIFIED WIDTH") if text == "*": print("*" * screen_width) else: centered_text = text.center(screen_width -4) output_string = "**{0}**".format(centered_text) print(output_string) # you have to put , 66 after the "" in these if you want to have # a value for the 2 arguments, but when you put a default value # inside the function definition, you dont have to pass in that value # in the execution banner_text("*") banner_text("Always look on the bright side of life...") banner_text("If life seems jolly rotten,") banner_text("There s something you ve forgotten!") banner_text("And that s to laugh and smile and dance and sing") # if nothing is passed here you need to pass a default value for text banner_text() banner_text(screen_width=60) banner_text("When you are feeling in the dumps") banner_text("Don't be silly chumps,") banner_text("Just purse your lips and whistle - that s the thing") banner_text("And...always look on the bright side of life...") banner_text("*") # result = banner_text("Nothing is returned") # print(result) # # numbers = [4, 4, 7, 5, 8, 3, 9, 6, 1] # print(numbers.sort()) # Tele Type # Punch Card # ANSI sequence # ANSI escape code
true
5fdfa562e309a1adf91d366bfe03937faa133888
zahraaliaghazadeh/python
/NU-CS5001/lab02/adder.py
463
4.1875
4
# num1 = float(input("Enter a first value: ")) # num2 = float(input("Enter a second value: ")) # sum = num1 + num2 # print("The sum of {} + {} is {}".format(num1, num2, sum)) # ================================== # same code with function dedinition def main(): num1 = float(input("Enter a first value: ")) num2 = float(input("Enter a second value: ")) sum = num1 + num2 print("The sum of {} + {} is {}".format(num1, num2, sum)) main()
true
ac9d5c265190401c2e11d2b144cbf16961da09a2
snalahi/Python-Basics
/week3_assignment.py
2,114
4.4375
4
# rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month (in inches) # with every month separated by a comma. Write code to compute the number of months that have more than 3 inches of # rainfall. Store the result in the variable num_rainy_months. In other words, count the number of items with values > 3.0. rainfall_mi = "1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85" rain_list = rainfall_mi.split(", ") num_rainy_months = 0 for i in rain_list: if float(i) > 3.0: num_rainy_months += 1 # The variable sentence stores a string. Write code to determine how many words in sentence start and end with the same letter, # including one-letter words. Store the result in the variable same_letter_count. sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking" same_letter_count = 0 sent_list = sentence.split() for i in sent_list: if i[0] == i[-1]: same_letter_count += 1 # Write code to count the number of strings in list items that have the character w in it. Assign that number to the variable # acc_num. items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"] acc_num = 0 for i in items: if "w" in i: acc_num += 1 # Write code that counts the number of words in sentence that contain either an “a” or an “e”. Store the result in the variable # num_a_or_e. sentence = "python is a high level general purpose programming language that can be applied to many different classes of problems." sent_list = sentence.split() num_a_or_e = 0 for i in sent_list: if "a" in i or "e" in i: num_a_or_e += 1 # Write code that will count the number of vowels in the sentence s and assign the result to the variable num_vowels. For this problem, # vowels are only a, e, i, o, and u. s = "singing in the rain and playing in the rain are two entirely different situations but both can be fun" vowels = ['a','e','i','o','u'] num_vowels = 0 for i in s: if i in vowels: num_vowels += 1
true
06dbe5531992d6c6df8feb30c6b97b17b113b824
Daksh-ai/swapcase-of-string
/string swapcase.py
216
4.21875
4
def swapcase(string): return s.swapcase() s=input("Enter The String") sub=swapcase(s) print(sub) #example-->input=Daksh output-->dAKSH #in genrally we say that its used to change the case of string and vice-versa
true
4a5c254c5d241a0c09862ca7995b1652932cd858
arvagas/Sorting
/src/recursive_sorting/recursive_sorting.py
1,557
4.125
4
# TO-DO: complete the helpe function below to merge 2 sorted arrays def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # TO-DO count = 0 while count < elements: if len(arrA) == 0: merged_arr[count] = arrB[0] arrB.pop(0) elif len(arrB) == 0: merged_arr[count] = arrA[0] arrA.pop(0) elif arrA[0] >= arrB[0]: merged_arr[count] = arrB[0] arrB.pop(0) elif arrA[0] <= arrB[0]: merged_arr[count] = arrA[0] arrA.pop(0) count += 1 return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # TO-DO # keep on splitting the array until the length is one if len(arr) < 2: return arr else: # (1) split up the array in half and have it be recursive # first half of the given array arr_one = merge_sort(arr[:len(arr)//2]) # second half of the given array arr_two = merge_sort(arr[len(arr)//2:]) # (2) run the helper function to merge return merge(arr_one, arr_two) return arr # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr
true
654e27532d4de8711c90cdb88e30006c8702751a
srimanikantaarjun/Object_Oriented_Programming_Fundamentals
/08 Constructor in Inheritance.py
868
4.34375
4
class A: def __init__(self): print("in A init") def feature1(self): print("Feature 1 is working") def feature2(self): print("Feature 2 is working") class B: def __init__(self): super().__init__() print("in B init") def feature3(self): print("Feature 3 is working") def feature4(self): print("Feature 4 is working") # a1 = A() # b1 = B() # If we create object of sub class it will first try to find init of Sub class, if it is not found then it will call # init of Super class # If we use super(). then it will call init of Super class then call init of Sub class class C(A, B): def __init__(self): super().__init__() print("in C init") c1 = C() # METHOD RESOLUTION ORDER # To represent Super class we use super(). method
true
9853a2266d1acbf23b8bba45db882b0b444fa030
hari2pega/Python-Day-wise-Practice-Sheets
/Hari_July 27th_Practice Sheet - Numbers and Introduction to List.py
1,862
4.53125
5
#!/usr/bin/env python # coding: utf-8 # In[1]: #Commenting the Line #What ever has been written after the Hash symbol, It will be considered as Comment #Numbers #Integers 2+3 # In[2]: #Numbers 3-2 # In[3]: #Float - It will be give the decimal value - Declaring in Decimal is called Float 0.1+0.2 # In[8]: # Assigning Numbers X=2 Y=8 Z=4 X+Y+Z # In[9]: #Advance approach of aasignment X,Y,Z = 9,4,6 X+Y+Z # In[10]: #Constants in Python: A constant in a Python is like a variable whose value says the same approach -- # -- through out the life of the program # In python we will be declaring the constant variables in Capital Letters or Capital case MAX_CONNECTION = 100 # In[13]: #*** Introduction to List - Data type # 1. List is an Mutable data type -- All modifications done on this # 2. String is a Immutable data type # 3. Alist is a collection of items in a particular order. # 4. How to define a List - [] - Separated by Commas (,) # Eg: Bicycles = ['Hero','Redline', 'Atlas', 'Trek', 'Ranger'] Bicycles = ['Hero','Redline','Atlas','Trek','Ranger'] print(Bicycles) # In[19]: # How to print a Individual element from a list? # Ans: With the help of indexing # **** From where Index will start -- Point 0 -- But not 1 **** # Want to print first element from the List? Bicycles = ['Hero','Redline','Atlas','Trek','Ranger'] print (Bicycles[0]) # In[20]: Bicycles = ['Hero','Redline','Atlas','Trek','Ranger'] print (Bicycles[3]) # In[21]: Bicycles = ['Hero','Redline','Atlas','trek','Ranger'] print (Bicycles[3].title()) # In[22]: Bicycles = ['Hero','Redline','Atlas','Trek','ranger'] print (Bicycles[4].upper()) # In[23]: Bicycles = ['Hero','Redline','Atlas','Trek','Ranger'] print (Bicycles[4].lower()) # In[24]: Bicycles = ['Hero','Redline','Atlas','Trek','Ranger'] print (Bicycles[2]) # In[ ]:
true
74402dc7fb9d97f14ecaebf30b201a5b96a7e7e3
dogeplusplus/DailyProgrammer
/222balancingwords.py
1,304
4.3125
4
def balance_word(word): '''the position and letter itself to calculate the weight around the balance point. A word can be balanced if the weight on either side of the balance point is equal. Not all words can be balanced, but those that can are interesting for this challenge. The formula to calculate the weight of the word is to look at the letter position in the English alphabet (so A=1, B=2, C=3 ... Z=26) as the letter weight, then multiply that by the distance from the balance point, so the first letter away is multiplied by 1, the second away by 2, etc. As an example: STEAD balances at T: 1 * S(19) = 1 * E(5) + 2 * A(1) + 3 * D(4))''' letter_list = list(word) letter_weights = list(map(lambda x: ord(x) - 64, letter_list)) # calculate the alphabetical position of the letter based on lowercase ordinal for i, letter in enumerate(letter_list): position_weights = list(map(lambda x: x - i, range(len(letter_list)))) total_weights = [x*y for (x,y) in zip(letter_weights,position_weights)] if sum(total_weights) == 0: return ('%s %s %s - %d') % (''.join(letter_list[:i]), word[i] ,''.join(word[i+1:]), abs(sum(total_weights[:i]))) return word, 'does not balance.' print(balance_word('STEAD')) print(balance_word('CONSUBSTANTIATION')) print(balance_word('UNINTELLIGIBILITY'))
true
e90b652e9b9d921a5d3ca94e1b299ce07e07812f
sfmajors373/PythonPractice
/OddTest.py
364
4.1875
4
#Input largestoddnumbersofar = 0 counter = 0 #Test/Counter while counter < 10: x = int(input("Enter a number: ")) if x%2 == 1: if x > largestoddnumbersofar: largestoddnumbersofar = x counter = counter + 1 print(counter) #Output if counter == 10: print ("The largest odd number is " + str(largestoddnumbersofar))
true
02673b7a8aaac520aec772ab345391aae54ab1d8
Vlad-Mihet/MergeSortPython
/MergeSortAlgorithm.py
2,189
4.3125
4
import random # Generating a random Array to be sorted # If needed, the random elements assignment could be removed, so a chosen array could be sorted ArrayToBeSorted = [random.randint(-100, 100) for item in range(15)] def MergeSort (array, left_index, right_index): if left_index >= right_index: return middle = (left_index + right_index) // 2 MergeSort(array, left_index, middle) MergeSort(array, middle + 1, right_index) Merge(array, left_index, right_index, middle) def Merge(array, left_index, right_index, middle): # Make copies of each half of the initial array left_array = array[left_index:middle + 1] right_array = array[middle + 1:right_index + 1] # Track the position we're in in both halves of the array (left and right arrays) left_array_index = 0 right_array_index = 0 sorting_index = left_index #Go through the elements of each array until we've run out of elements in any of them while left_array_index < len(left_array) and right_array_index < len(right_array): # The smallest element between the left and right arrays will be placed in the original array if left_array[left_array_index] <= right_array[right_array_index]: array[sorting_index] = left_array[left_array_index] left_array_index += 1 else: array[sorting_index] = right_array[right_array_index] right_array_index += 1 # After we've sorted an element, we increment the position so we can add the other elements sorting_index += 1 # After we've run our of elements in the arrays, we check for any elements that might have been left out while left_array_index < len(left_array): array[sorting_index] = left_array[left_array_index] left_array_index += 1 sorting_index += 1 while right_array_index < len(right_array): array[sorting_index] = right_array[right_array_index] right_array_index += 1 sorting_index += 1 print(ArrayToBeSorted) MergeSort(ArrayToBeSorted, 0, len(ArrayToBeSorted) - 1) print(ArrayToBeSorted)
true
5f4783efff3f567033bff8c2752602a13a3b7b2e
jackfish823/Hangman_Python
/Guess.py
597
4.125
4
import re #lib to search in a string def is_valid_input(letter_guessed): # checks if the function the input letter_guessed is good spread_guess = re.findall('[A-Za-z]', letter_guessed) #list of the guess_input of only english if len(letter_guessed) == len(spread_guess): if len(letter_guessed) == 1: return True else: return False else: return False word_input = input("Enter word: ") word_len = int(len(word_input)) print("_ " * word_len) #print the _ _ _ _ guess_input = input("\nGuess a letter: ") #to guess the letter
true
ecfc083467a06ff836565a89858b8218e64bd56b
npradha/multTables
/multTables.py
386
4.28125
4
while True: print("\n") print("What number do you want the multiplication table of?") num = input() print("\n") for mul in range(13): answer = num * mul print(str(num) + " x " + str(mul) + " = " + str(answer)) print("\n") print("Do you want to input another number? (y/n)") ans = raw_input() if ans == 'y': continue else: break print("\n") print("Happy Learning!!")
true
53b5e0a564b279e63ceb6458310fcbaeec68d933
DustinRPeterson/lc101
/crypto/vigenere.py
2,230
4.125
4
#Encrypts text using the vignere algorithm (https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) from helpers import alphabet_position, rotate_character #import alphabet_position and rotate_character from helpers.py lower_case_dict = dict() #create dictionary for lowercase letters upper_case_dict = dict() #create dictionary for uppercase letters def create_lower(lower_string): #fill in the lower case dictionary where [a==0, z==25] dict_index = 0 for c in lower_string: lower_case_dict[dict_index] = c dict_index += 1 def create_upper(upper_string): #fill in the lower case dictionary where [A==0, Z==25] dict_index = 0 for c in upper_string: upper_case_dict[dict_index] = c dict_index += 1 def encrypt(text, rot): #Encrypts the text, uses helpers.rotate_character() rotation_list = list() #create the list that will store the numbers to rotate for each character in cypher rotation_num = 0 new_text = '' for i in rot: #use the rotation_list to store the position of each letter in the cypher word used rotation_list.append(alphabet_position(i)) print(rotation_list) for c in text: if c.isalpha() == True: try: #rotate the character by the amount given in the rotation_list rotation = rotation_list[rotation_num] new_text += rotate_character(c, rotation) rotation_num += 1 #move to the next amount in rotation list except IndexError: #if rotation_num is moved out of the rotation_list index reset to 0 rotation_num = 0 rotation = rotation_list[rotation_num] new_text += rotate_character(c, rotation) rotation_num += 1 else: #if not alphabetic charcter do not change new_text += c return new_text def main(): create_lower('abcdefghijklmnopqrstuvwxyz') create_upper('ABCDEFGHIJKLMNOPQRSTUVWXYZ') message = input("Type a message: ") rotate = input("Encryption string: ") encrypted_message = encrypt(message, rotate) print(encrypted_message) if __name__ == "__main__": main()
true