blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
32ecb9b4cfe42fc63007e72ac3c8778fa8121ad5
huang-zp/pyoffer
/my_queue.py
646
4.125
4
class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.stack_in = [] self.stack_out = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.stack_in.append(x) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ if not self.stack_out: while self.stack_in: self.stack_out.append(self.stack_in.pop()) return self.stack_out.pop() else: return self.stack_out.pop()
true
aee36a7523ad8fc3de06ef7b047aff60fa3ab0d6
ADmcbryde/Collatz
/Python/recursive/coll.py
2,842
4.25
4
# CSC330 # Assignment 3 - Collatz Conjecture # # Author: Devin McBryde # # # def collatzStep(a): counter = 0 if (a == 1): return counter elif ( (a%2) == 1) : counter = collatzStep(a*3+1) else: counter = collatzStep(a/2) counter = counter + 1 return counter #The program is programmed as a function since local references are faster # than global variable references and speeds up the inner while loop def collatz(): #stores the top ten highest values and the steps to 1 # and initializes the array to zeroes maxValues = [[0 for x in range(2)]for y in range(10)] #stores the top ten highest values and the steps to 1 minVal = 0 col = long(0) #initialize x for the loop x = 2 #Main loop that goes through all values between 2 and 5000000000 # Top value has the L suffix since literals are interpreted as integers # This is a while loop instead since range(x) would produce an # array that would take over 20-40 gigabytes to store, depending # on if the array would store 4 or 8 byte integers. This can # also be solved by using xrange() instead, which uses iterators # instead, but its behavior is less well understood while(x < 1000000): alreadyexists = False #reset the next two values for the new number #col holds the value of the iterated number col = x #count tracks the number of iterations total count = 0 count = collatzStep(col) #Here we avoid having a value with a duplicate number of steps using the boolean flag #Need to add loop #Here we check if the count is larger than the smallest count recorded and add if it is for z in range(10): if (count == maxValues[z][0]): alreadyexists = True if (count > maxValues[minVal][0] and not(alreadyexists)): #here we replace the value of the smallest count for y in range(10): if(y == minVal): maxValues[y][0] = count maxValues[y][1] = x #we now reset the minVal to look for the new lowest count value minVal = 0 #search for the smallest count size in maxValues for y in range(10): if(maxValues[y][0] < maxValues[minVal][0]): minVal = y #increment x for the while loop to go to the next x += 1 #Now we perform a basic selection sort on the step count before printing for i in range(0,9): minValue = maxValues[i][0]; minColNum = maxValues[i][1]; minLocale = i; for j in range(i+1,10): if(minValue < maxValues[j][0]): minValue = maxValues[j][0]; minColNum = maxValues[j][1]; minLocale = j; tempVal = maxValues[i][0]; tempNum = maxValues[i][1]; maxValues[i][0] = minValue; maxValues[minLocale][0] = tempVal; maxValues[i][1] = minColNum; maxValues[minLocale][1] = tempNum; #print the maxValues array for i in range(10): print "Value: " , maxValues[i][1] , " Steps Taken: " , maxValues[i][0] collatz()
true
0d075a750c9745eb97a2577db4b7c7cf2407d903
ergarrity/coding-challenges
/missing-number/missing.py
1,009
4.21875
4
"""Given a list of numbers 1...max_num, find which one is missing in a list.""" def missing_number(nums, max_num): """Given a list of numbers 1...max_num, find which one is missing. *nums*: list of numbers 1..[max_num]; exactly one digit will be missing. *max_num*: Largest potential number in list >>> missing_number([7, 3, 2, 4, 5, 6, 1, 9, 10], 10) 8 """ nums_dict = {} # Creates keys for all possible numbers in list and sets all values to False for i in range(max_num): nums_dict[i+1] = False # Iterates over nums and changes value to True for each num key for num in nums: nums_dict[num] = True # Iterates over nums_dict and returns key with false value (this will be # missing number) for key in nums_dict: if nums_dict[key] == False: return key if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASS. NICELY DONE!\n")
true
8717208247c2d4f9eb24522c1b54ec33ce41789c
kwozz48/Test_Projects
/is_num_prime.py
613
4.1875
4
#Asks the user for a number and determines if the number is prime or not number_list = [] def get_integer(number = 'Please enter a number: '): return int(input(number)) def is_number_prime(): user_num = get_integer() number_list = list(range(2, user_num)) print (number_list) i = 0 a = 0 while i < user_num - 2: if user_num % number_list[i] == 0: a += 1 i += 1 else: i += 1 if a > 0: print ('The number is not prime') else: print ('The number is prime') return () answer = is_number_prime()
true
0eb55829a0aee6d7136f91550e89b9bb738f4e73
Scertskrt/Ch.08_Lists_Strings
/8.1_Months.py
722
4.40625
4
''' MONTHS PROGRAM -------------- Write a user-input statement where a user enters a month number 1-13. Using the starting string below in your program, print the three month abbreviation for the month number that the user enters. Keep repeating this until the user enters 13 to quit. Once the user quits, print "Goodbye!" months = "JanFebMarAprMayJunJulAugSepOctNovDec" ''' done = False month = int(input("Please pick a month(1-12) or quit ")) months = "JanFebMarAprMayJunJulAugSepOctNovDec" while done == False: if month > 12 or month < 1: print("Goodbye!") done = True break end = month*3 print(months[end-3:end]) month = int(input("Please pick a month(1-12) or quit(13) "))
true
539fadb2fc145e48a70950cd77d804d77c9cec07
roachaar/Python-Projects
/national debt length.py
1,937
4.5
4
############################################################################## # Computer Project #1: National Debt # # Algorithm # prompt for national debt and denomination of currency # user inputs the above # program does simple arithmetic to calculate two pieces of information # 1: national debt as a height in miles of stacked currency # 2: this height compared to the distance between the earth and moon # lastly, the program displays these values to the user ############################################################################## national_debt_str = input('Enter the national debt: ') #user inputs his or her\ #nation's national debt denomination_str = input('Enter a denomination of currency: ') #user\ #inputs a chosen denomination of the same currency as the national debt is\ #given in national_debt_float = float(national_debt_str) #we identify these as the values\ #in which they are meant to be denomination_int = int(denomination_str) #again BILL_HEIGHT=.0043 #in inches INCHES_PER_FOOT= 12 #inches per foot FEET_PER_MILE=5280 #feet per mile AVG_DISTANCE_BETWEEN_EARTH_AND_MOON=238857 #in miles height_of_national_debt_float = (national_debt_float/denomination_int)*\ (BILL_HEIGHT)/(INCHES_PER_FOOT)/(FEET_PER_MILE) #we use dimensional analysis to\ #get the height in miles compared_to_moon_float= (national_debt_float/denomination_int)*(BILL_HEIGHT)/\ (INCHES_PER_FOOT)/(FEET_PER_MILE)/(AVG_DISTANCE_BETWEEN_EARTH_AND_MOON) #same\ #thing here, only we now divide by the distance between the earth and the moon print('The height of your national debt in miles of your chosen denomination of\ currency is:',height_of_national_debt_float) print('The ratio of this height and the distance between the earth and the moon\ is:' ,compared_to_moon_float) #these 2 values are printed for the user to see
true
3597d031334cadd8da79740431f5941c2adb38c5
BeryJAY/Day4_challenge
/power/power.py
531
4.34375
4
def power(a,b): #checking data type if not((isinstance(a,int) or isinstance(a,float)) and isinstance(b,int)): return "invalid input" #The condition is such that if b is equal to 1, b is returned if(b==1): return(a) #If b is not equal to 1, a is multiplied with the power function and called recursively with arguments as the base and power minus 1 if(b!=1): return(a*power(a,b-1)) #the final result is then output if __name__ == '__main__': print("Result:",power(2,5))
true
511d35743234e26a4a93653af24ee132b3a62a7a
AntoanStefanov/Code-With-Mosh
/Classes/1- Classes.py
1,465
4.6875
5
# Defining a list of numbers numbers = [1, 2] # we learned that when we use the dot notation, we get access to all methods in list objects. # Every list object in Python has these methods. # numbers. # Wouldn't that be nice if we could create an object like shopping_cart and this object would have methods # like this: # shopping_cart.add() # shopping_cart.remove() # shopping_cart.get_total() # Another example: # Would be nice if we could have a point object with methods. # point.draw() # point.move() # point.get_distance() * between point x and point y # Here come classes # A class is a blueprint for creating new objects. # Throughout the course you have heard the term class. # For example: let's define a variable and set it to integer and print it's type x = 1 print(type(x)) # We see a class of int # So in Python we have a class called int for creating integers. Similarly, we have classes for creating booleans, # lists, dictionaries and so on. # EVERY OBJECT WE HAVE IN PYTHON IS CREATED USING A CLASS WHICH IS A BLUEPRINT FOR CREATING OBJECTS OF THAT TYPE. # # In this section you're going to learn how to create custom classes like customer, shopping_cart, point and so on. # Before that let's define a few terms. # 1. Class: blueprint for creating new objects # 2. Object: instance of a class # Example: # Class: Human (this class will define all the attributes of humans) then we could create objects # Objects: John, Mary, ...
true
a8f7dceb7daec1a665e215d9d99eeb620e73f398
AntoanStefanov/Code-With-Mosh
/Exceptions/7- Cost of Raising Exceptions.py
1,849
4.5
4
# As I explained in the last lecture, when writing your own functions, # prefer not to raise exceptions, because those exceptions come with a price. # That's gonna show you in this lecture. # From the timeit module import function called timeit # with this function we can calculate the execution time of some code. # This is how it works. Imagine you want to calculate the execution time of # this code. # We define a variable code1 and set it to string # This string should include our code so using triple quotes code # for multiple lines. One piece of code inside string with triple quotes from timeit import timeit code1 = ''' def calculate_xfactor(age): if age <= 0: raise ValueError('Age cannot be 0 or less.') return age / 10 try: calculate_xfactor(-1) except ValueError as error: pass ''' # Now we call timeit # - first arg = python code , second arg(keyword arg) = number of exectutions print('first code=', timeit(code1, number=10000)) # This function returns the exectution time of the code after 10 000 repetitions. # DIfferent approach ### 4 times faster code2 = ''' def calculate_xfactor(age): if age <= 0: None return age / 10 xfactor = calculate_xfactor(-1) if xfactor == None: pass ''' print('second code=', timeit(code2, number=10000)) # that's so because we execute the code 10 000 times # 1 time execution no difference # If you are building a simple application for a few users raising exceptions # in your functions is not going to have a bad impact on the performance of your app. # But if you are building application where performance and scaleability is important, # then it's better to raise exceptions when you really have to . # if you can handle the situation with a simple if statement, think twice for exceptions. # Raise exceptions if YOU REALLY HAVE TO !
true
1f7f8382c688f22fe10e8057185ce55307c90b1d
AntoanStefanov/Code-With-Mosh
/Exceptions/4- Cleaning Up.py
706
4.375
4
# There are times that we need to work with external resources like files, # network connections, databases and so on. Whenever we use these resources, # after, after we're done we need to release them. # For example: when you open a file, we should always close it after we're done, # otherwise another process or another program may not be able to open that file. try: file = open('name') age = int(input('Age: ')) xfactor = 10 / age except (ValueError, ZeroDivisionError): print('You didnt enter a valid age.') else: print("No exceptions were thorwn.") finally: # always executed clause with or without exception # and we use it to release external resources file.close()
true
a12230a5edc331e0989940c8ecd1243b9415aba9
daria-andrioaie/Fundamentals-Of-Programming
/a12-911-Andrioaie-Daria/main.py
2,983
4.46875
4
from random import randint from recursive import recursive_backtracking from iterative import iterative_backtracking def print_iterative_solutions(list_of_numbers): """ The function calls the function that solves the problem iteratively and then prints all the found solutions. :param list_of_numbers: the list of numbers for which we want to determine all the possibilities to insert between them the operators + and – such that by evaluating the expression the result is positive. """ list_of_solutions = iterative_backtracking(list_of_numbers) number_of_solutions = len(list_of_solutions) if number_of_solutions == 0: print('There are no solutions for the given set of numbers') else: for solution in list_of_solutions: print(solution) print(str(number_of_solutions) + ' SOLUTIONS: ') print('\n') print('\n') def print_recursive_solutions(list_of_numbers): """ The function calls the function that solves the problem recursively and then prints all the found solutions. :param list_of_numbers: the list of numbers for which we want to determine all the possibilities to insert between them the operators + and – such that by evaluating the expression the result is positive. """ list_of_solutions = [] recursive_backtracking(list_of_solutions, [], list_of_numbers) number_of_solutions = len(list_of_solutions) if number_of_solutions == 0: print('There are no solutions for the given set of numbers') else: for solution in list_of_solutions: print(solution) print(str(number_of_solutions) + ' SOLUTIONS: ') print('\n') print('\n') def initialise_numbers(number_of_elements): """ The function computes a random sequence of natural number. :param number_of_elements: the total number of elements in the sequence :return: the sequence of numbers, represented as a list """ list_of_numbers = [] for iteration in range(number_of_elements): natural_number = randint(1, 100) list_of_numbers.append(natural_number) return list_of_numbers def print_menu(): print('1. Solve recursively.') print('2. Solve iteratively') print('3. Exit.') print('\n') def start(): available_options = {'1': print_recursive_solutions, '2': print_iterative_solutions} number_of_elements = int(input('Enter a natural number greater than 9: ')) list_of_numbers = initialise_numbers(number_of_elements) not_finished = True while not_finished: print_menu() user_option = input('Enter option: ') if user_option in available_options: available_options[user_option](list_of_numbers) elif user_option == '3': not_finished = False else: print('Bad command') start()
true
41891f9a090ead7873bf5c006f423238a48f05db
daria-andrioaie/Fundamentals-Of-Programming
/a12-911-Andrioaie-Daria/iterative.py
2,158
4.5
4
from solution import is_solution, to_string def find_successor(partial_solution): """ The function finds the successor of the last element in the list. By "successor" of an element we mean the next element in the list [0, +, -]. :param partial_solution: array containing the current partial solution :return: True, if the last element has a successor, False, otherwise """ if partial_solution[-1] == 0: partial_solution[-1] = '+' return True elif partial_solution[-1] == '+': partial_solution[-1] = '-' return True return False def iterative_backtracking(list_of_numbers): """ The function uses the concept of backtracking to search the whole space of solutions, and keeps the found solutions in a list that will be returned. :param list_of_numbers: the list of numbers for which we want to determine all the possibilities to insert between them the operators + and – such that by evaluating the expression the result is positive. :return: the resulted solutions """ list_of_solutions = [] partial_solution = [0] while len(partial_solution): current_element_has_successor = find_successor(partial_solution) if current_element_has_successor: if is_solution(partial_solution, list_of_numbers): printable_solution = to_string(partial_solution, list_of_numbers) list_of_solutions.append(printable_solution) elif len(partial_solution) == len(list_of_numbers) - 1: # the solution array is full, but does not # represent a solution partial_solution.pop() else: partial_solution.append(0) # go to the next element in order to complete # the solution else: # go back with one step in the partial solution partial_solution.pop() return list_of_solutions
true
48f7e3ee1d356eda254447e928321e6d7a8402c8
samsolariusleo/cpy5python
/practical02/q07_miles_to_kilometres.py
661
4.3125
4
# Filename: q07_miles_to_kilometres.py # Author: Gan Jing Ying # Created: 20130207 # Modified: 20130207 # Description: Program that converts miles to kilometres and kilometres to miles # before printing the results # main # print headers print("{0:6s}".format("Miles") + "{0:11s}".format("Kilometres") + "{0:11s}".format("Kilometres") + "{0:6s}".format("Miles")) # define for loop for miles in range(1,11): convert_to_kilo = miles * 1.609 convert_to_miles = (miles + 3) * 5 / 1.609 print("{0:<6}".format(miles) + "{0:<11.3f}".format(convert_to_kilo) + "{0:<11}".format((miles + 3) * 5) + "{0:<6.3f}".format(convert_to_miles))
true
2e1e1897d6e0c4f92ee6815c9e1bb607dee10024
samsolariusleo/cpy5python
/practical02/q12_find_factors.py
562
4.4375
4
# Filename: q12_find_factors.py # Author: Gan Jing Ying # Created: 20130207 # Modified: 20130207 # Description: Program that displays the smallest factors of an integer. # main # prompt for integer integer = int(input("Enter integer: ")) # define smallest factor factor = 2 # define a list list_of_factors = [] # find factors while factor < integer: while integer % factor != 0: factor = factor + 1 list_of_factors.append(factor) integer = integer//factor # return results print("The smallest factors are " + str(list_of_factors)[1:-1] + ".")
true
750d0ff689da9aa8aea56e2e9b248df47ed51057
samsolariusleo/cpy5python
/practical02/q05_find_month_days.py
956
4.625
5
# Filename: q05_find_month_days.py # Author: Gan Jing Ying # Created: 20130207 # Modified: 20130207 # Description: Program that displays number of days in the month of a particular # year. # main # prompt for month month = int(input("Enter month: ")) # prompt for year year = int(input("Enter year: ")) # define list of months allmonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] # define list of days alldays = ["31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31", "29"] # check if month is feb # if month is feb, then check if year is leap year # if both are true, days is 29 # else, days are normal if month == 2 and year % 4 == 0: print(allmonths[month-1] + " " + str(year) + " has " + alldays[-1] + " days") else: print(allmonths[month-1] + " " + str(year) + " has " + alldays[month-1] + " days")
true
cce715b6938e2f5c16d6ee158ebfa7e15b4e0645
samsolariusleo/cpy5python
/practical02/q11_find_gcd.py
725
4.28125
4
# Filename: q11_find_gcd.py # Author: Gan Jing Ying # Created: 20130207 # Modified: 20130207 # Description: Program to find the greatest common divisor of two integers. # main # prompt user for the two integers integer_one = int(input("Enter first integer: ")) integer_two = int(input("Enter second integer: ")) # find out which is the smaller of integer_one and integer_two if integer_one > integer_two: d = integer_two elif integer_one < integer_two: d = integer_one else: print("The greatest common divisor is " + str(integer_one) + ".") exit() # find greatest divisor while integer_one % d != 0 or integer_two % d != 0: d = d - 1 # return results print("The greatest common divisor is " + str(d) + ".")
true
8254638df080d0a3b76a0dddd42cf41e393dfed7
samsolariusleo/cpy5python
/practical01/q1_fahrenheit_to_celsius.py
453
4.28125
4
# Filename: q1_fahrenheit_to_celsius.py # Author: Gan Jing Ying # Created: 20130122 # Modified: 20130122 # Description: Program to convert a temperature reading from Fahrenheit to Celsius. #main # prompt to get temperature temperature = float(input("Enter temperature (Fahrenheit): ")) # calculate temperature in Celsius temperature = (5/9) * (temperature - 32) # display result print("Temperature in Celsius: {0:.2f}".format(temperature))
true
8e1570c6e03ec4817ab65fdba077df7bad1e97da
justintrudell/hootbot
/hootbot/helpers/request_helpers.py
490
4.46875
4
import itertools def grouper(iterable, n): """ Splits an iterable into groups of 'n'. :param iterable: The iterable to be split. :param n: The amount of items desired in each group. :return: Yields the input list as a new list, itself containing lists of 'n' items. """ """Splits a list into groups of three.""" it = iter(iterable) while True: chunk = tuple(itertools.islice(it, n)) if not chunk: return yield chunk
true
73d37bf82e89c293e0e0fd86e99d74ec79b3b275
SRAH95/Rodrigo
/input_statement.py
1,748
4.15625
4
"""message = input("Tell me something, and I will repeat it back to you: ") print(message)""" ######################################################################################## '''name = input("Please enter your name: ") print("Hi, " + name.title() + "!")''' ######################################################################################## prompt = "If you tell us who you are, we can personalize the message you see." prompt += "\nWhat is your first name? " name = input(prompt) print("\nHello, " + name.title() + "!") ######################################################################################## '''age = input("How old are you? ") age = int(age) print(age >= 18) ''' ######################################################################################## '''height = input("How tall are you, in inches? ") height = int(height) if height >= 36: print("\nYou're tall enough to ride!") else: print("\nYou'll be able to ride when you're a little older.")''' ######################################################################################## """prompt = "\nEven or Odd number." prompt += "\nPlease, enter a number: " odd = input(prompt) odd = int(odd) if odd % 2 == 0: print("---> " + str(odd) + " is an even number.") else: print("---> " + str(odd) + " is an odd number.")""" ######################################################################################## """people = input("\nHow many people are going to dinner toningth?\n ") people = int(people) if people <= 8: print("There is an avilable table, wait for the waitress please") else: print("You have to wait for an avilable table, sorry")""" ########################################################################################
true
ba982e9794b3cbaaa034584cbb1f2017068f5ce5
Pranalihalageri/Python_Eduyear
/day5.py
516
4.125
4
1. list1 = [5, 20, 4, 45, 66, 93, 1] even_count, odd_count = 0, 0 # iterating each number in list for num in list1: # checking condition if num % 2 == 0: even_count += 1 else: odd_count += 1 print("Even numbers in the list: ", even_count) print("Odd numbers in the list: ", odd_count) 2. list1 = [10, 20, 4, 45, 99] # sorting the list list1.sort() # printing the last element print("Largest element is:", list1[-1]) print("minimum element is:", *list1[:1])
true
b0398f9d1751611c505aa530849336dbb7f3ef00
Ran05/basic-python-course
/ferariza_randolfh_day4_act2.py
1,153
4.15625
4
''' 1 Write a word bank program 2 The program will ask to enter a word 3 The program will store the word in a list 4 The program will ask if the user wants to try again. The user will input Y/y if yes and N/n if no 5 If yes, refer to step 2. 6 If no, Display the total number of words and all the words that user entered. ''' <<<<<<< HEAD ======= 1 Write a word bank program 2 The program will ask to enter a word 3 The program will store the word in a list 4 The program will ask if the user wants to try again. The user will input Y/y if yes and N/n if no 5 If yes, refer to step 2. 6 If no, Display the total number of words and all the words that user entered. ''' >>>>>>> 4f0a6fb087d8f2ddb4b87fea98c0c42a7cbbfbc8 wordList = [] a = (str(input("Please Enter a word: "))) wordList.append(a) question = input("Do you want to add more words?: ") <<<<<<< HEAD if question == True: print(str(input("Please Enter a word: "))) else: wordList.append(a) ======= while question == "Y" or "Yes": print(a) if question == "N" or "no": break print(wordList) >>>>>>> 4f0a6fb087d8f2ddb4b87fea98c0c42a7cbbfbc8
true
92151c4a1ceca1910bd60785b2d5d030559cd241
niteshrawat1995/MyCodeBase
/python/concepts/classmethods.py
1,481
4.125
4
# Class methods are methods wich take class as an argument (by using decorators). # They can be used as alternate constructors. class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_of_emps += 1 def full_name(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.pay = self.pay * self.raise_amount @classmethod def set_raise_amount(cls, amount): cls.raise_amount = amount @classmethod def from_string(cls, emp_str): first, last, pay = emp_str.split('-') # need to always return the cls(Employee) object. return cls(first, last, pay) @staticmethod def is_workday(day): if day.weekday() == 5 or day.weekday() == 6: return False else: return True emp_1 = Employee('Nitesh', 'Rawat', 20000) emp_2 = Employee('Vikas', 'Sharma', 30000) # Employee.set_raise_amount(1.05) # print(Employee.raise_amount) # print(emp_1.raise_amount) # print(emp_2.raise_amount) #emp_str_1 = 'John-Doe-70000' #emp_str_2 = 'Amy-Smith-70000' #emp_str_3 = 'Angier-Santos-000' emp_str_1 = Employee.from_string('John-Doe-70000') # print(emp_str_1.full_name()) import datetime my_date = datetime.date(2018, 5, 27) print(Employee.is_workday(my_date))
true
5f109dfef4214b33302401e473d9b115a65bffa5
niteshrawat1995/MyCodeBase
/python/concepts/getters&setters&deleters.py
1,284
4.15625
4
# getters,setters and deleters can be implemented in python using property decorators. # property decorators allows us to define a mehtod which we can access as an attribute. # @property is the pythonic way of creating getter and setter. class Employee(object): def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay # getter-like @property def email(self): print('getting email') return '{}.{}@company.com'.format(self.first, self.last) # getter-like @property def fullname(self): print('getting fullname') return '{} {}'.format(self.first, self.last) # setter-like @fullname.setter def fullname(self, name): print('setting fullname') first, last = name.split(' ') self.first = first self.last = last # deleter-like @fullname.deleter def fullname(self): prin('deleting fullname') self.first = None self.last = None print('Delete name!') emp1 = Employee('Nitesh', 'Rawat', '20000') # we now cannot set the attribute like this: #emp1.email = 'Nitesh.chopra@gmail.com' # To do the above task we need a setter print(emp1.fullname) # print(emp1.email) emp1.fullname = 'Time Tom' print(emp1.fullname)
true
e78334b2ae75714172fad80bf81e8c76497f7cb5
scantea/hash-practice
/hash_practice/exercises.py
2,554
4.3125
4
def grouped_anagrams(strings): """ This method will return an array of arrays. Each subarray will have strings which are anagrams of each other Time Complexity: O(n) Space Complexity: O(1) """ freq_hash = {} for word in strings: key = ''.join(sorted(word)) if key not in freq_hash.keys(): freq_hash[key] = [] freq_hash[key].append(word) values_list = [] for value in freq_hash.values(): values_list.append(value) return values_list def top_k_frequent_elements(nums, k): """ This method will return the k most common elements In the case of a tie it will select the first occuring element. Time Complexity: O(n) Space Complexity: O(n) """ if nums == []: return nums freq_table = {} for num in nums: if num in freq_table: freq_table[num] += 1 else: freq_table[num] = 1 max_freq = 0 common_elemnts = [] for key, value in freq_table.items(): if freq_table[key] > max_freq: max_freq = freq_table[key] common_elemnts.append(key) elif freq_table[key] == max_freq: common_elemnts.append(key) return common_elemnts def valid_sudoku(table): """ This method will return the true if the table is still a valid sudoku table. Each element can either be a ".", or a digit 1-9 The same digit cannot appear twice or more in the same row, column or 3x3 subgrid Time Complexity: O(n)3 Space Complexity: O(n) """ for col in range(0, len(table)): column_hash = {} for square in table[col]: if square != ".": if square not in column_hash: column_hash[square] = 1 else: return False for row in range(3): for col in range(3): block_dict = {} block = [ table[3*row][3*col:3*col+3], # finding index in sudoku board table[3*row+1][3*col:3*col+3], table[3*row+2][3*col:3*col+3] ] for segment in block: for elem in segment: if elem != ".": if elem in block_dict: return False else: block_dict[elem] = 1 return True
true
5b119b5d6ee2dfeb455b174a2b2332de7cd7a6a7
sivaram143/python_practice
/conditions/ex_01.py
202
4.3125
4
#!/usr/bin/python # program to check whether a given no is even or ood num = input("Enter any number:") if num % 2 == 0: print("{0} is even".format(num)) else: print("{0} is odd".format(num))
true
fdc9e5dc5a169d1178cf3efa9e1f70a2f42576a1
rcoady/Programming-for-Everyone
/Class 1 - Getting Started with Python/Assignment4-6.py
982
4.375
4
# Assignment 4.6 # Write a program to prompt the user for hours and rate per hour using raw_input to # compute gross pay. Award time-and-a-half for the hourly rate for all hours worked # above 40 hours. Put the logic to do the computation of time-and-a-half in a function # called computepay() and use the function to do the computation. The function should # return a value. Use 45 hours and a rate of 10.50 per hour to test the program # (the pay should be 498.75). You should use raw_input to read a string and float() # to convert the string to a number. Do not worry about error checking the user input # unless you want to - you can assume the user types numbers properly. def computepay(h, r): if h > 40: overtime = h - 40 total = (40 * r) + ((overtime * r) * 1.5) else: total = (h * r) return total hrs = raw_input("Enter Hours:") hrs = float(hrs) rate = raw_input("Enter Rate:") rate = float(rate) p = computepay(hrs, rate) print p
true
73b0b07826794a242dde684f94f946581c180949
Dszymczk/Practice_python_exercises
/06_string_lists.py
803
4.40625
4
# Program that checks whether a word given by user is palindrome def is_palindrome(word): return word == word[::-1] word = "kajak" # input("Give me some word please: ") reversed_word = [] for index in range(len(word) - 1, -1, -1): reversed_word.append(word[index]) palindrome = True for i in range(len(word)): if word[i] != reversed_word[i]: palindrome = False if palindrome: print("Word is palindrome") # string based program <- much faster way print("\n\nstring based program") reversed_word = word[::-1] print(reversed_word) if reversed_word == word: print("Word is palindrome") # Shorter code if word == word[::-1]: print("\n\nWord is palindrome") # Using function if is_palindrome(word): print("\n\n(3) Word is palindrome")
true
6fcd96b8c44668ccac3b4150d9b6c411b325bcc0
mm/adventofcode20
/day_1.py
2,436
4.375
4
"""AoC Challenge Day 1 Find the two entries, in a list of integers, that sum to 2020 https://adventofcode.com/2020/day/1 """ def find_entries_and_multiply(in_list, target): """Finds two entries in a list of integers that sum to a given target (also an integer), and then multiply those afterwards. """ two_numbers = None # We can use the idea of "complements" here. First, we'll start # an indices dict, which will have key = the number itself, and the # value equal to its index. indices = {} for i in range(0, len(in_list)): # Get the "complement" -- for this current value, what is the # extra value I need to add up to my target? complement = target - in_list[i] # e.g if in_list[i] = 1995, target = 2020, => complement = 25 # Does this value exist in my list? This is where the indices dict # comes in handy! if complement in indices: # Return the two numbers! two_numbers = (in_list[i], in_list[indices[complement]]) else: # Otherwise, add it to our indices list. It might match # up well with another number! indices[in_list[i]] = i if two_numbers: print(f"Two numbers found which add up to {target}: {two_numbers}") return two_numbers[0]*two_numbers[1] else: return None def find_three_entries_for_target(in_list, target): """Finds three integers which add up to a given target (also an integer), and multiply them afterwards. """ three_numbers = None # What we can do (sort of brute-force-y) is fix a number as we go through the # list, set a new target and then run the *two-integer* version of this problem # on the rest of the list. for i in range(0, len(in_list)): new_target = target - in_list[i] # Now, perform the two-integer solution on the *rest* of the list # (pretend this number isn't even there) two_number_product = find_entries_and_multiply(in_list[i+1:], new_target) if two_number_product: return in_list[i] * two_number_product def input_file_to_list(filepath): num_list = [] with open(filepath, 'r') as in_file: for line in in_file: num_list.append(int(line.strip())) return num_list in_numbers = input_file_to_list('inputs/day_1.txt') print(find_three_entries_for_target(in_numbers, 2020))
true
7252e716f0bb533d1a612728caf027276883e0ef
git4rajesh/python-learnings
/String_format/dict_format.py
800
4.5625
5
### String Substitution with a Dictionary using Format ### dict1 = { 'no_hats': 122, 'no_mats': 42 } print('Sam had {no_hats} hats and {no_mats} mats'.format(**dict1)) ### String Substitution with a List using Format ### list1 = ['a', 'b', 'c'] my_str = 'The first element is {}'.format(list1) print(my_str) ### List extraction my_str = 'The first element is {0}, the second element is {1} and third element is {2}'.format(*list1) print(my_str) ### String Substitution with a Tuple using Format ### tuple1 = ('one', 'second', 'third') my_str = 'The first element is {0}, the second element is {1} and third element is {2}'.format(*tuple1) print(my_str) ### String Substitution with a String variable using Format ### my_name = 'Rajesh' my_str = 'Hi {0}'.format(my_name) print(my_str)
true
79618644a020eaa269bc7995d650afed3043b411
ravitej5226/Algorithms
/backspace-string-compare.py
1,312
4.15625
4
# Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. # Example 1: # Input: S = "ab#c", T = "ad#c" # Output: true # Explanation: Both S and T become "ac". # Example 2: # Input: S = "ab##", T = "c#d#" # Output: true # Explanation: Both S and T become "". # Example 3: # Input: S = "a##c", T = "#a#c" # Output: true # Explanation: Both S and T become "c". # Example 4: # Input: S = "a#c", T = "b" # Output: false # Explanation: S becomes "c" while T becomes "b". # Note: # 1 <= S.length <= 200 # 1 <= T.length <= 200 # S and T only contain lowercase letters and '#' characters. class Solution(object): def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ clean_S=[] clean_T=[] for i in range(len(S)): if(S[i]=='#'): clean_S.pop() if len(clean_S)>0 else '' else: clean_S.append(S[i]) for i in range(len(T)): if(T[i]=='#'): clean_T.pop() if len(clean_T)>0 else '' else: clean_T.append(T[i]) return "".join(clean_S)=="".join(clean_T) s=Solution() print(s.backspaceCompare("ab##","c#d#"))
true
08815d5371e53a75f10ec4d2b0b9bba1747a6fa6
ravitej5226/Algorithms
/zigzag-conversion.py
1,458
4.15625
4
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) # P A H N # A P L S I I G # Y I R # And then read line by line: "PAHNAPLSIIGYIR" # Write the code that will take a string and make this conversion given a number of rows: # string convert(string text, int nRows); # convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ output=[]; if s=='': output='' return output if numRows==1: return s for i in range(0,numRows): start_index=i; alt=True; temp=0 if start_index<len(s): output.append(s[start_index]); else: break; while start_index<len(s): if temp>0: output.append(s[start_index]); if(alt): temp=2*(numRows-1-i); else: temp=2*(i); start_index=start_index+temp; alt=not alt; return ''.join(output) s=Solution(); print(s.convert('PAYPALISHIRING',3))
true
5fa0a0ab95042208eb2bef0dc47498c34056dda6
arthuroe/codewars
/6kyu/sort_the_odd.py
2,963
4.25
4
''' You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. Example sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] ''' import sys def sort_array(source_array): print(source_array) # Traverse through all array elements for i in range(len(source_array)): if source_array[i] % 2 != 0: min_idx = i for j in range(i, len(source_array)): if source_array[j] % 2 != 0: if source_array[min_idx] > source_array[j]: min_idx = j else: continue # Swap the found minimum element with the first element source_array[i], source_array[min_idx] = source_array[min_idx], source_array[i] print(source_array) return source_array sort_array([64, 25, 12, 22, 11, 5, 8, 3]) print() sort_array([4, 25, 1, 2, 10, 7, 8, 3]) print() sort_array([5, 3, 1, 8, 0]) print() sort_array([5, 3, 2, 8, 1, 4]) print() sort_array([]) '''----other solutions----''' def sort_array(arr): odds = sorted((x for x in arr if x % 2 != 0), reverse=True) return [x if x % 2 == 0 else odds.pop() for x in arr] def sort_array(source_array): odds = iter(sorted(v for v in source_array if v % 2)) return [next(odds) if i % 2 else i for i in source_array] def sort_array(numbers): evens = [] odds = [] for a in numbers: if a % 2: odds.append(a) evens.append(None) else: evens.append(a) odds = iter(sorted(odds)) return [next(odds) if b is None else b for b in evens] from collections import deque def sort_array(array): odd = deque(sorted(x for x in array if x % 2)) return [odd.popleft() if x % 2 else x for x in array] def sort_array(source_array): return [] if len(source_array) == 0 else list(map(int, (','.join(['{}' if a % 2 else str(a) for a in source_array])).format(*list(sorted(a for a in source_array if a % 2 == 1))).split(','))) def sort_array(source_array): odd = sorted(list(filter(lambda x: x % 2, source_array))) l, c = [], 0 for i in source_array: if i in odd: l.append(odd[c]) c += 1 else: l.append(i) return l def sort_array(source_array): # retrieve the odd values sorted_array = sorted([value for value in source_array if value % 2 != 0]) # insert the even numbers in the original place for index, value in list(enumerate(source_array)): if value % 2 == 0: sorted_array.insert(index, value) return sorted_array ''' ----tests----- Test.assert_equals(sort_array([5, 3, 2, 8, 1, 4]), [1, 3, 2, 8, 5, 4]) Test.assert_equals(sort_array([5, 3, 1, 8, 0]), [1, 3, 5, 8, 0]) Test.assert_equals(sort_array([]),[]) '''
true
78576dc109ab336280899a740fbc2f3797563e52
bryansilva10/CSE310-Portfolio
/Language_Module-Python/Shopping-Cart_Dictionary/cart.py
1,423
4.21875
4
#var to hold dictionary shoppingCart = {} #print interface print(""" Shopping Options ---------------- 1: Add Item 2: Remove Item 3: View Cart 0: EXIT """) #prompt user and turn into integer option = int(input("Select an option: ")) #while user doesn't exit program while option != 0: if option == 1: #add item #prompt user for item and qty item = input("Enter an item: ") #if item already exists in cart if item in shoppingCart: print("Item already in cart") qty = int(input("Enter quantity: ")) #update qty shoppingCart[item] += qty #if it does not else: qty = int(input("Enter quantity: ")) #add qty to the item key shoppingCart[item] = qty elif option == 2: #remove item # prompt user for itme to be removed item = input("Enter an item: ") #remove it del (shoppingCart[item]) elif option == 3: #loop through items in cart for item in shoppingCart: #print each item print(item, ":", shoppingCart[item]) elif option != 0: #in case user enters invalid option print("Please enter a valid option") option = int(input("\n\nSelect an option: ")) #when loop breaks and exits else: print("You closed the program...")
true
9b72b3dd6d3aba0798f18f06ab37bdf0c39a339a
xu2243051/learngit
/ex30.py
858
4.125
4
#!/usr/bin/python #coding:utf-8 #================================================================ # Copyright (C) 2014 All rights reserved. # # 文件名称:ex30.py # 创 建 者:许培源 # 创建日期:2014年12月09日 # 描 述: # # 更新日志: # #================================================================ import sys reload(sys) sys.setdefaultencoding('utf8') people = 130 cars = 40 buses = 15 if cars > people: print "We should take the cars." elif cars < people: print "We should not take the cars." else: print "We can't decide." if buses > cars: print "That's too many buses." elif buses < cars: print "Maybe we could take the buses." else: print "We still can't decide." if people > buses: print "Alright, let's just take the buses." else: print "Fine, let's stay home then."
true
3c4cb233be63715f662d6f81f76feae91e51ac85
cupofteaandcake/CMEECourseWork
/Week2/Code/lc1.py
1,787
4.375
4
#!/usr/bin/env python3 """A series of list comprehensions and loops for creating sets based on the bird data provided""" __appname__ = 'lc1.py' __author__ = 'Talia Al-Mushadani (ta1915@ic.ac.uk)' __version__ = '0.0.1' __license__ = "License for this code" birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7), ('Delichon urbica','House martin',19), ('Junco phaeonotus','Yellow-eyed junco',19.5), ('Junco hyemalis','Dark-eyed junco',19.6), ('Tachycineata bicolor','Tree swallow',20.2), ) ## Conventional loop for creating list containing birds' latin names birds_latin = set() for species in birds: birds_latin.add(species[0]) #searches for and adds all of the first variables for each species, which is the latin name print(birds_latin) ## Conventional loop for creating list containing birds' common names birds_common = set() for species in birds: birds_common.add(species[1]) #searches for and adds all of the second variables for each species, which is the common name print(birds_common) ## Conventional loop for creating list containing birds' mean body masses birds_mean_body_mass = set() for species in birds: birds_mean_body_mass.add(species[2]) #searches for and adds all of the third variables for each species, which is the mean body mass print(birds_mean_body_mass) ## List comprehension for creating list containing birds' latin names birds_latin_lc = set([species[0] for species in birds]) print(birds_latin_lc) ## List comprehension for creating list containing birds' common names birds_common_lc = set([species[1] for species in birds]) print(birds_common_lc) ## List comprehension for creating list containing birds' mean body masses birds_mbm_lc = set([species[2] for species in birds]) print(birds_mbm_lc)
true
0b4d452a26c2b44684c2eae50ba622c56dd97f4f
kriti-ixix/python2batch
/python/Functions.py
614
4.125
4
''' Functions are of two types based on input: - Default - Parameterised Based on return type: - No return - Some value is returned ''' ''' #Function definition def addTwo(first, second): #first = int(input("Enter first number: ")) #second = int(input("Enter second number: ")) third = first + second print("The sum is: ", third) print("Addition!") #Function calling addTwo(5, 10) addTwo(30, 20) x = 40 y = 50 addTwo(x, y) ''' def addTwo(first, second): third = first + second return third x = addTwo(5, 10) y = addTwo(20, 30) print("The sums are ", x, " ", y)
true
2bbe8852b53fe5d099afbbd8a310704c04c0423b
mecosteas/Coding-Challenges
/count_words.py
1,260
4.375
4
""" Given a long text string, count the number of occurrences of each word. Ignore case. Assume the boundary of a word is whitespace - a " ", or a line break denoted by "\n". Ignore all punctuation, such as . , ~ ? !. Assume hyphens are part of a word - "two-year-old" and "two year old" are one word, and three different words, respectively. Return the word counts as a string formatted with line breaks, in alphanumeric order. Example: "I do not like green eggs and ham, I do not like them, Sam-I-Am" Output: i 2 do 2 not 2 like 2 green 1 eggs 1 and 1 ham 1 them 1 sam-i-am 1 Also Valid: and 1 do 2 eggs 1 green 1 ham 1 i 2 like 2 not 2 sam-i-am 1 them 1 """ def count_words(text): word_table = {} for word in text.split(): word = word.strip(".,~?!").lower() if word_table.get(word) == None: word_table[word] = 1 else: word_table[word] += 1 return '\n'.join(f'{word} {freq}' for word, freq in word_table.items()) text = "I do not like green eggs and ham, \nI do not like them, Sam-I-Am" # print(text) # text_arr = text.split() # print(text_arr) # text_arr = [word.strip(".,~?!").lower() for word in text_arr] # print(text_arr) # text = ''.join(text_arr) # print(text) print(count_words(text))
true
507e4a5ea9054c11509e8d6f678d74aa6c3f545e
sleepingsaint/DS-ALG
/DS/linkedList.py
2,724
4.21875
4
# defining stack element object class Element(object): def __init__(self, value): self.value = value self.next = None # defining stack object class Stack(object): def __init__(self, head=None): self.head = head # helper class functions # function to add elements def append(self, new_element): if self.head: current = self.head while current.next: current = current.next current.next = Element(new_element) else: self.head = Element(new_element) # function to see the position of the element def get_position_value(self, position): current = self.head counter = 1 if position < 1: return None else: while current and counter <= position: if counter == position: return current.value current = current.next counter += 1 return None # function to insert an element at an certain position # Inserting at position 3 means between the 2nd and 3rd elements def insert_element(self, index, new_element): if self.head: current = self.head counter = 1 if index == 1: e = Element(new_element) e.next, self.head = self.head, e elif index > 1: while current and counter < index - 1: current = current.next counter += 1 if not current: print('cannot insert the element') else: e = Element(new_element) e.next, current.next = current.next, e # function to delete an first node with given value def delete(self, value): if self.head: current = self.head previous = None while current.value != value and current.next: previous = current current = current.next if current.value == value: if previous: previous.next = current.next else: self.head = current.next else: return None # initializing the stack stck = Stack() # adding elements stck.append(1) stck.append(2) stck.append(3) # getting position # inserting element stck.insert_element(2, 4) stck.delete(3) print(stck.get_position_value(1)) print(stck.get_position_value(2)) print(stck.get_position_value(3)) print(stck.get_position_value(4)) stck.insert_element(500, 6) print(stck.get_position_value(1)) print(stck.get_position_value(2)) print(stck.get_position_value(3))
true
d5891584688ff83c60bf74fc7611c625f57b14db
Sukanyacse/Assignment_2
/assignment 2.py
254
4.1875
4
numbers=(1,2,3,4,5,6,7,8,9) count_even=1 count_odd=-1 for value in range(1,10): if(value%2==0): count_even=count_even+1 else: count_odd=count_odd+1 print("Number of even numbers:",count_even) print("Number of odd numbers:",count_odd)
true
e644585b9b3a99f72e3ed4fc948ecb26ca0465f0
moheed/python
/languageFeatures/python_using_list_as_2d_array.py
1,976
4.5625
5
#NOTE: creating list with comprehension creates many #pecularities.. as python treats list with shallow copy... #for example arr=[0]*5 #=== with this method, python only creates one integer object with value 5 and #all indices point to same object. since all are zero initially it doesn't matter. arr[0]=5 #when we modify arr[0], it creates a new int object with val=5 and makes the zero-index point #new object. print(arr) #this works expected. #however, arr2=[[0]*5]*5 #expecting 5x5 matrix filled with zero print(arr2) arr2[0][0]=1 #expecting only 0,0 to be 1.. but o/p? print(arr2) #[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]] #HOW all elements of first column are changed... Weired??? #This is because list works in shallow way... as shown for arr(1-d array) #however, when we declare a 2-d arr, that means all indices in a given inner [](ie col) point to single integer object 0 #when we update by arr2[0][0]=x, what we are doing is, updating the first element of inner[](ie col) #since all row-indices for that col point to same object, it updates all first values of given col. """ Similarly, when we create a 2d array as “arr = [[0]*cols]*rows” we are essentially the extending the above analogy. 1. Only one integer object is created. 2. A single 1d list is created and all its indices point to the same int object in point 1. 3. Now, arr[0], arr[1], arr[2] …. arr[n-1] all point to the same list object above in point 2. The above setup can be visualized in the image below. One way to check this is using the ‘is’ operator which checks if the two operands refer to the same object. Best Practice: If you want to play with matrix run the LOOP and ensure all mxn objects are allocated.! # Using above second method to create a # 2D array rows, cols = (5, 5) arr=[] for i in range(cols): col = [] for j in range(rows): col.append(0) arr.append(col) print(arr) """
true
92a753e7e633025170d55b3ebdb9f2487b3c4fa0
HayleyMills/Automate-the-Boring-Stuff-with-Python
/Ch6P1_TablePrinter.py
1,352
4.4375
4
##Write a function named printTable() that takes a list of lists of strings ##and displays it in a well-organized table with each column right-justified. ##Assume that all the inner lists will contain the same number of strings. ##For example, the value could look like this: ##tableData = [['apples', 'oranges', 'cherries', 'banana'], ## ['Alice', 'Bob', 'Carol', 'David'], ## ['dogs', 'cats', 'moose', 'goose']] ##Your printTable() function would print the following: ## ## apples Alice dogs ## oranges Bob cats ##cherries Carol moose ## banana David goose #def printTable(): #input is a list of strings #output is an orgniased table with each column rjust tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] rows = len(tableData) #number of lists cols = len(tableData[0]) #number of cols maxlength = 0 for i in range(0,(rows)): #loop for number of rows for x in tableData[i]: #loop for the each item in the row if maxlength < len(x): #find the max length of the words maxlength = len(x) for k in range(0, (cols)): for v in range(0, (rows)): print((tableData[v][k]).rjust(maxlength), end = ' ') print()
true
e317905dca19712d90a62f463a4f782bd22668e5
Ahmad-Magdy-Osman/IntroComputerScience
/Classes/bankaccount.py
1,195
4.15625
4
######################################################################## # # CS 150 - Worksheet #11 --- Problem #1 # Purpose: Practicing User-Defined Classes. # # Author: Ahmad M. Osman # Date: December 9, 2016 # # Filename: bankaccount.py # ######################################################################## class BankAccount: #Bank Account Class #Creating account and initiating balance value def __init__(self, balance=0): self.balance = balance #Returning the account's current balance value def getBalance(self): return self.balance #Setting the account's balance to the value of amount def setBalance(self, amount): self.balance = amount #Depositing the value of amount into the account's balance def deposit(self, amount): print("$%.2f will be deposited." %(amount)) self.balance += amount #Withdrawing the value of amount from the account if the balance is sufficient def withdraw(self, amount): if self.balance >= amount: print("$%.2f will be withdrawn." %(amount)) self.balance -= amount else: print("Insufficient funds") #Printing account balance def __str__(self): display = "Account Balance: " + ("$%.2f" %(self.balance)) return display
true
b19db0ac2fef12e825b63552fbd0b298fcb632ec
Ahmad-Magdy-Osman/IntroComputerScience
/Turtle/ex10.py
859
4.65625
5
###################################### # # CS150 - Interactive Python; Python Turtle Graphics Section, Exercise Chapter - Exercise 10 # Purpose: Drawing a clock with turtles # # Author: Ahmad M. Osman # Date: September 22, 2016 # # Filename: ex10.py # ##################################### #Importing turtle module import turtle #Initiating window canvas window = turtle.Screen() window.bgcolor("lightgreen") #Initiating clock turtle clock = turtle.Turtle() clock.shape("turtle") clock.color("blue") clock.hideturtle() clock.speed(0) clock.pensize(5) clock.pu() clock.setposition(0, 0) clock.stamp() #Drawing clock for i in range(12): clock.left(30) clock.forward(125) clock.pd() clock.forward(10) clock.pu() clock.forward(25) clock.stamp() clock.forward(-160) #Waiting for user to exit through clocking on the turtle program screen window.exitonclick()
true
bbcefac3f0243ed8df81ed8a4875626b78ab3ca4
iangraham20/cs108
/labs/10/driver.py
976
4.5
4
''' A driver program that creates a solar system turtle graphic. Created on Nov 10, 2016 Lab 10 Exercise 5 @author: Ian Christensen (igc2) ''' import turtle from solar_system import * window = turtle.Screen() window.setworldcoordinates(-1, -1, 1, 1) ian = turtle.Turtle() ss = Solar_System() ss.add_sun(Sun("SUN", 8.5, 1000, 5800)) ss.add_planet(Planet("EARTH", .475, 5000, 0.6, 'blue')) try: ss.add_planet( Planet(input('Please enter the name of the planet: '), float(input('Please enter the radius of the planet: ')), float(input('Please enter the mass of the planet: ')), float(input('Please enter the distance of the planet from the origin: ')), input('Please enter the color of the planet: '))) except ValueError as ve: print('ValueError occurred:', ve) except TypeError as te: print('TypeError occurred:', te) except: print('Unknown Error') #Keep the window open until it is clicked window.exitonclick()
true
0e75d78ea6d8540a5417a8014db80c0b84d32cc9
iangraham20/cs108
/projects/07/find_prefix.py
1,677
4.125
4
''' A program that finds the longest common prefix of two strings. October 25, 2016 Homework 7 Exercise 7.3 @author Ian Christensen (igc2) ''' # Create a function that receives two strings and returns the common prefix. def common_prefix(string_one, string_two): ''' A function that compares two strings, determines the common prefix and returns the result. ''' # Create necessary variables. prefix_results = '' character = 0 # Begin while loop to compare strings. while character <= (len(string_one) - 1) and character <= (len(string_two) - 1): # Begin if statement to compare the characters of the two strings. if string_one[character] == string_two[character]: # Add appropriate values to the variables. prefix_results += string_one[character] character += 1 # Once the prefix has been found exit the if statement. else: break # Return the results and exit the function. return prefix_results # Create a function that runs tests on the function named common_prefix. def test_common_prefix(): ''' A function that calls common_prefix, tests the results, and prints a boolean expressions. ''' assert(common_prefix('', '') == '') assert(common_prefix('abc123', '') == '') assert(common_prefix('abcDefg', 'abcdefg') == 'abc') assert(common_prefix('abcde5g', 'abcdefg') == 'abcde') assert(common_prefix('12345f7', '1234567') == '12345') test_common_prefix() # Create a user input for common_prefix. print(common_prefix(input('Please enter first string: '), input('Please enter second string: ')))
true
50b03235f4a71169e37f3ae57654b7a37bcb9d10
adamsjoe/keelePython
/Week 3/11_1.py
246
4.125
4
# Write a Python script to create and print a dictionary # where the keys are numbers between 1 and 15 (both included) and the values are cube of keys. # create dictonary theDict = {} for x in range(1, 16): theDict[x] = x**3 print(theDict)
true
86e3aa25fd4e4878ac12d7d839669eda99a6ea1c
adamsjoe/keelePython
/Week 1/ex3_4-scratchpad.py
964
4.125
4
def calc_wind_chill(temp, windSpeed): # check error conditions first # calc is only valid if temperature is less than 10 degrees if (temp > 10): print("ERROR: Ensure that temperature is less than or equal to 10 Celsius") exit() # cal is only valid if wind speed is above 4.8 if (windSpeed < 4.8): print("ERROR: Ensure that wind speed greater than 4.8 km/h") exit() # formula for windchill v = windSpeed**0.16 chillFactor = 13.12 + 0.6215 * temp - 11.37 * v + 0.3965 * temp * v return chillFactor def convertToKMH(mphSpeed): return mphSpeed * 1.609 # test values temperature = 5 windSpeed = convertToKMH(20) # call the fuction to calculate wind chill wind_chill = calc_wind_chill(temperature, windSpeed) # print a string out print("The wind chill factor is ", wind_chill, " Celsius") # print a pretty string out print("The wind chill factor is ", round(wind_chill, 2), " Celsius")
true
d3ab5cfe7bb1ff17169b2b600d21ac2d7fabbf70
adamsjoe/keelePython
/Week 8 Assignment/scratchpad.py
1,193
4.125
4
while not menu_option: menu_option = input("You must enter an option") def inputType(): global menu_option def typeCheck(): global menu_option try: float(menu_option) #First check for numeric. If this trips, program will move to except. if float(menu_option).is_integer() == True: #Checking if integer menu_option = 'an integer' else: menu_option = 'a float' #Note: n.0 is considered an integer, not float except: if len(menu_option) == 1: #Strictly speaking, this is not really required. if menu_option.isalpha() == True: menu_option = 'a letter' else: menu_option = 'a special character' else: inputLength = len(menu_option) if menu_option.isalpha() == True: menu_option = 'a character string of length ' + str(inputLength) elif menu_option.isalnum() == True: menu_option = 'an alphanumeric string of length ' + str(inputLength) else: menu_option = 'a string of length ' + str(inputLength) + ' with at least one special character'
true
8a527fd405d5c59c109252f58527d9b4d5e73eeb
sahaib9747/Random-Number-Picker
/App_Manual.py
607
4.125
4
# starting point import random number = random.randint(1, 1000) attempts = 0 while True: # infinite loop input_number = input("Guess the number (berween 1 and 1000):") input_number = int(input_number) # converting to intiger attempts += 1 if input_number == number: print("Yes,Your guess is correct!") break # finish the game if true if input_number > number: print("Incorrect! Please try to guess a smaller number") else: print("Incorrect! Please try to guess a larger number") print("You Tried", attempts, "Times to find the correct number")
true
19eff193956da31d7bf747a97c0c0a7fe5da9f91
Sukhrobjon/Codesignal-Challenges
/challenges/remove_duplicates.py
433
4.1875
4
from collections import Counter def remove_all_duplicates(s): """Remove all the occurance of the duplicated values Args: s(str): input string Returns: unique values(str): all unique values """ unique_s = "" s_counter = Counter(s) for key, value in s_counter.items(): if value == 1: unique_s += key return unique_s s = "zzzzzzz" print(remove_all_duplicates(s))
true
e18278d472ab449a3524864656540432b7efbfb9
robinsuhel/conditionennels
/conditionals.py
365
4.34375
4
name = input("What's your name: ") age = int(input("How old are you: ")) year = str(2017-age) print(name + " you born in the year "+ year) if age > 17: print("You are an adult! You can see a rated R movie") elif age < 17 and age > 12: print("You are a teenager! You can see a rated PG-13 movie") else: print("You are a child! You can only see rated PG movies")
true
43264f35f210963e7b6aeda37a534bc52302fec5
wscheib2000/CS1110
/gpa.py
966
4.21875
4
# Will Scheib wms9gv """ Defines three functions to track GPA and credits taken by a student. """ current_gpa = 0 current_credit_total = 0 def add_course(grade, num_credit=3): """ This function adds a class to the gpa and credit_total variables, with credits defaulting to 3. :param grade: Grade in the class :param num_credit: How many credits the class was worth :return: Does not return any values """ global current_gpa, current_credit_total current_gpa = (current_gpa * current_credit_total + grade * num_credit) / (current_credit_total + num_credit) current_credit_total = current_credit_total + num_credit def gpa(): """ This function returns the current GPA. :return: Current GPA, rounded to 2 decimal places """ return round(current_gpa, 2) def credit_total(): """ This function returns the current credit total. :return: Current credit total """ return current_credit_total
true
583480d2f366d7fcbf1a9f16c03c40c8e3f1248b
SeanLuTW/codingwonderland
/lc/lc174.py
2,254
4.15625
4
""" 174. Dungeon Game The demons had captured the princess (P) and imprisoned her in the bottom-top corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers). In order to reach the princess as quickly as possible, the knight decides to move only topward or leftward in each step. Write a function to determine the knight's minimum initial health so that he is able to rescue the princess. For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path top-> top -> left -> left. -2 (K) -3 3 -5 -10 1 10 30 -5 (P) Note: The knight's health has no upper bound. Any room can contain threats or power-ups, even the first room the knight enters and the bottom-top room where the princess is imprisoned. """ """ intuition: TC:O(n^2) SC:O(m*n) """ # class Solution: # def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] r = len(dungeon) c = len(dungeon[0]) #create dp table dp = [[0 for _ in range (c)] for _ in range (r)] print (dp) #initailze the right bottom corner as 1 dp[-1][-1] = 1 # print (dp) for i in range (r-2,-1,-1):#handling column and start from the top print (i,c) dp[i][c-1] = max(1,dp[i+1][c-1]-dungeon[i+1][c-1]) # print (dp) for j in range (c-2,-1,-1):#handling row and start from the bottom row print(j,r) dp[r-1][j] = max(1,dp[r-1][j+1]-dungeon[r-1][j+1]) # print (dp) for i in range (r-2,-1,-1): for j in range (c-2,-1,-1): print(i,j) top = max(1,dp[i][j+1]-dungeon[i][j+1]) print (top) left = max(1,dp[i+1][j]-dungeon[i+1][j]) print (left) dp[i][j] = min(top,left) print (max(1,dp[0][0]-dungeon[0][0]))
true
30a665a286f0dcd8bd5d60d78fae0d1669f2e0c1
SeanLuTW/codingwonderland
/lc/lc1464.py
761
4.25
4
""" 1464. Maximum Product of Two Elements in an Array Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). Example 1: Input: nums = [3,4,5,2] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. Example 2: Input: nums = [1,5,4,5] Output: 16 Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16. Example 3: Input: nums = [3,7] Output: 12 """ nums = [3,4,5,2] nums.sort()#asc order # max1 = nums[-1]-1 # max2 = nums[-2]-1 # print (max1*max2) print ((nums[-1]-1)*(nums[-2]-1))
true
a0f06e65c70862194f25bee20a4ad1eed82ae586
dharmit/Projects
/Numbers/mortgage.py
460
4.25
4
#!/usr/bin/env python def mortgage_calculator(months, amount, interest): final_amount = amount + ((amount * interest)/100) return int(final_amount / months) if __name__ == "__main__": amt = int(raw_input("Enter the amount: ")) interest = int(raw_input("Enter the interest rate: ")) months = int(raw_input("Enter the number of months: ")) print "Mortgage to be paid per month is: %d" % mortgage_calculator (months, amt, interest)
true
baf234ed556488a5d5a8f1229b5bf69958b232e1
krakibe27/python_objects
/Bike.py
802
4.125
4
class Bike: def __init__(self,price,max_speed): self.price = price self.max_speed = max_speed self.miles = 200 #self.miles = self.miles + self.miles def displayInfo(self): print "Price :", self.price print "max_speed :" + self.max_speed print "total miles :", self.miles return self def ride(self): k = self.miles/10 for i in range(10,self.miles,10): #k = self.miles/10 print "Miles increased by :", i return self def reverse(self): for i in reversed(range(10,self.miles,10)): print "Reversed Miles by 10 :", i return self bike1 = Bike(200,'10 mph') #print bike1.displayInfo().ride().reverse() print bike1.displayInfo()
true
832a79bbaf9f1961dc580f064efbf1903057d803
OnurcanKoken/Python-GUI-with-Tkinter
/6_Binding Functions to Layouts.py
1,154
4.3125
4
from tkinter import * #imports tkinter library root = Tk() #to create the main window #binding a function to a widget #define a function def printName(): print("My name is Koken!") #create a button that calls a function #make sure there is no parantheses of the function button_1 = Button(root, text="Print my name", command=printName) button_1.pack() """ there is another way to do this we will deal with an evet it is being used for smt that occurs such as button click from the user or mouse movement or button click on the keyboard smt that user can do bind takes two parameters; what event are you waiting for to occur and what function do you want to call """ #define a function #we have an event at this time def printName2(event): print("Again, My name is Koken!") #make sure there is no parantheses of the function button_2 = Button(root, text="Again, Print my name") button_2.bind("<Button-1>", printName2) #left mouse button button_2.pack() root.mainloop() #makes sure it is being shown continuously, on the screen #for more info: https://www.youtube.com/watch?v=RJB1Ek2Ko_Y&t=1s&list=PL6gx4Cwl9DGBwibXFtPtflztSNPGuIB_d&index=2
true
36c4a847bad96bae252543ca9c12fb6ac5dc1abc
Juan55Camarillo/pattern-designs
/strategy.py
1,433
4.625
5
''' Strategy pattern designs example it allows make an object can behave in different ways (which will be define in the moment of its instantiation or make) ''' from __future__ import annotations from abc import ABC, abstractmethod from typing import List class Map(): def __init__(self, generateMap: GenerateMap) -> None: self._generateMap = generateMap @property def generateMap(self) -> generateMap: return self._generateMap @generateMap.setter def generateMap(self, generateMap: GenerateMap) -> None: self._generateMap = generateMap def RandomSeed(self) -> None: print("Generating a random location of the objects:") result = self._generateMap.randomizer([" Map size: 1212", " Enemies location: 2737", " Dungeons Location: 6574"]) print(",".join(result)) class Generator(ABC): @abstractmethod def randomizer(self, data: List): pass class WaterLand(Generator): def randomizer(self, data: List) -> List: return sorted(data) class EarthLand(Generator): def randomizer(self, data: List) -> List: return reversed(sorted(data)) class main(): map1 = Map(WaterLand()) print("Generating a random map of water.") map1.RandomSeed() print() map2 = Map(EarthLand()) print("Generating a random map of earth.") map1.RandomSeed()
true
a34063f6b6ba6e086b633508fad186b4e9622df7
sachinsaini4278/Data-Structure-using-python
/insertionSort.py
622
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 2 07:18:31 2019 @author: sachin saini """ def insertion_sort(inputarray): for i in range(size): temp=inputarray[i] j=i while(inputarray[j-1]>temp and j >=1): inputarray[j]=inputarray[j-1]; j=j-1 inputarray[j]=temp print("Enter the size of input array") size=int(input()) print("Enter the ", size ," elements of array") inputarray=[int(x) for x in input().split()] print("elements before sorting ",inputarray) insertion_sort(inputarray) print("elements after sorting ",inputarray)
true
9259a3b6575504831a6c9a4601035771b48e1ced
mattwright42/Decorators
/decorators.py
1,560
4.15625
4
# 1. Functions are objects # def add_five(num): #print(num + 5) # add_five(2) # 2. Functions within functions # def add_five(num): # def add_two(num): # return num + 2 #num_plus_two = add_two(num) #print(num_plus_two + 3) # add_five(10) # 3. Returning functions from functions # def get_math_function(operation): # + or - # def add(n1, n2): # return n1 + n2 # def sub(n1, n2): # return n1 - n2 # if operation == '+': # return add # elif operation == '-': # return sub #add_function = get_math_function('+') #sub_function = get_math_function('-') #print(sub_function(4, 6)) # 4. Decorating a function # def title_decorator(print_name_function): # def wrapper(): # print("Professor:") # print_name_function() # return wrapper # def print_my_name(): # print("Matt") # def print_joes_name(): # print("Joe") #decorated_function = title_decorator(print_joes_name) # decorated_function() # 5. Decorators # def title_decorator(print_name_function): # def wrapper(): # print("Professor:") # print_name_function() # return wrapper # @title_decorator # def print_my_name(): # print("Matt") # @title_decorator # def print_joes_name(): # print("Joe") # print_my_name() # print_joes_name() # 6. Decorators w/ Parameters def title_decorator(print_name_function): def wrapper(*args, **kwargs): print("Professor:") print_name_function(*args, **kwargs) return wrapper @title_decorator def print_my_name(name, age): print(name + " you are " + str(age)) print_my_name("Shelby", 60)
true
f5edb7b29e99421eff0a071312619d011e833038
lucipeterson/Rock-Paper-Scissors
/rockpaperscissors.py
2,800
4.125
4
#rockpaperscissors.py import random print("~~ Rock, Paper, Scissors ~~") weapon_list = ["rock", "paper", "scissors"] user = input("Rock, paper, or scissors? ") while user.lower() not in weapon_list: user = input("Rock, paper, or scissors? ") computer = random.choice(weapon_list) print("Computer chooses " + computer + ".") if computer == "rock": if user.lower() == "rock": print("It's a tie!") elif user.lower() == "paper": print("Paper smothers rock. You win!") elif user.lower() == "scissors": print("Rock crushes scissors. You lose.") if computer == "paper": if user.lower() == "rock": print("Paper smothers rock. You lose.") elif user.lower() == "paper": print("It's a tie!") elif user.lower() == "scissors": print("Scissors cut paper. You win!") if computer == "scissors": if user.lower() == "rock": print("Rock crushes scissors. You win!") elif user.lower() == "paper": print("Scissors cut paper. You lose.") elif user.lower() == "scissors": print("It's a tie!") again = input("Play again? ") while again.lower() == "yes": user = input("Rock, paper, or scissors? ") while user.lower() not in weapon_list: user = input("Rock, paper, or scissors? ") computer = random.choice(weapon_list) print("Computer chooses " + computer + ".") if computer == "rock": if user.lower() == "rock": print("It's a tie!") again = input("Play again? ") elif user.lower() == "paper": print("Paper smothers rock. You win!") again = input("Play again? ") elif user.lower() == "scissors": print("Rock crushes scissors. You lose.") again = input("Play again? ") if computer == "paper": if user.lower() == "rock": print("Paper smothers rock. You lose.") again = input("Play again? ") elif user.lower() == "paper": print("It's a tie!") again = input("Play again? ") elif user.lower() == "scissors": print("Scissors cut paper. You win!") again = input("Play again? ") if computer == "scissors": if user.lower() == "rock": print("Rock crushes scissors. You win!") again = input("Play again? ") elif user.lower() == "paper": print("Scissors cut paper. You lose.") again = input("Play again? ") elif user.lower() == "scissors": print("It's a tie!") again = input("Play again? ") if again.lower() != "yes": print("Game Over")
true
ef949c39755d56c5dbf3ef5bd9212bfb36a2df92
aseemchopra25/Integer-Sequences
/Juggler Sequence/juggler.py
706
4.21875
4
# Program to find Juggler Sequence in Python # Juggler Sequence: https://en.wikipedia.org/wiki/Juggler_sequence # The juggler_sequence function takes in a starting number and prints all juggler # numbers starting from that number until it reaches 1 # Keep in mind that the juggler sequence has been conjectured to reach 1 eventually # but this fact has not yet been proved def juggler_sequence(n): seq = [n] while seq[-1] != 1: if seq[-1] % 2 == 0: seq.append(int(seq[-1] ** 0.5)) else: seq.append(int(seq[-1] ** 1.5)) return seq if __name__ == "__main__": x = int(input("Enter a number for Juggler Sequence: ")) print(juggler_sequence(x))
true
f013a0c4604d3a39edf17405d34a5a1ff4722167
aseemchopra25/Integer-Sequences
/Golomb Sequence/Golomb.py
1,460
4.25
4
# A program to find the nth number in the Golomb sequence. # https://en.wikipedia.org/wiki/Golomb_sequence def golomb(n): n = int(n) if n == 1: return 1 # Set up a list of the first few Golomb numbers to "prime" the function so to speak. temp = [1, 2, 2, 3, 3] # We will be modifying the list, so we will use a while loop to continually check if we can get the nth number yet. while len(temp) < n: # Here comes the fun part. Starting with 0, we loop through every number (i) lower than n to build the Golomb list as much as we need. for i in range(n): # If the list is longer than (i), we skip it. if len(temp) > i: continue # If the list ISN'T longer than (i), which it shouldn't be, we do some stuff. else: # We set a variable for the final value in the list, so we can increment it as we go. lastval = temp[-1] # We grab the number at the lastval index in the list, and set that to be our range. # We add lastval+1 (the next element in the sequence) to the list (range) times, and then move to the next (i) for x in range(temp[lastval]): temp.append(lastval + 1) # Once we have extended the list to or beyond the length of n, we can now grab the number in position n in the list! return temp[n - 1] print(golomb(input("Enter n> ")))
true
0b8cfda80341f33b7ec168156f82dcc2dc32e618
anildhaker/DailyCodingChallenge
/GfG/Mathematical Problems/fibMultpleEff.py
695
4.21875
4
# Efficient way to check if Nth fibonacci number is multiple of a given number. # for example multiple of 10. # num must be multiple of 2 and 5. # Multiples of 2 in Fibonacci Series : # 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 …. # every 3rd number - is divisible by 2. # Multiples of 5 in Fibonacci Series : # 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 …… # Every 5th number is divisible by 5. # => Every 15th number will be divisible by 10. So we only need to check if n is divisible # by 15 or not. We do not have to calculate the nth Fib number. def isDivisibleby_10(n): if n % 15 == 0: return True return False # time complexity - O(1)
true
87e12cbe64f2cfcdf00157e8bc34e39485f64773
anildhaker/DailyCodingChallenge
/GfG/Mathematical Problems/makePerfectSq.py
842
4.1875
4
# Find minimum number to be divided to make a number a perfect square. # ex - 50 dividing it by 2 will make it perfect sq. So output will be 2. # A number is the perfect square if it's prime factors have the even power. # all the prime factors which has the odd power should be multiplied and returned(take 1 element at once). import math def findMinNum(n): # 2 is only even number so counting the power of 2 count = 0 ans = 1 while n % 2 == 0: count += 1 n = int(n // 2) # if count is not even then we must remove one 2. if count % 2 != 0: ans = ans * 2 for i in range(3, int(math.sqrt(n)) + 1, 2): count = 0 while n % i == 0: count += 1 n = int(n // i) if count % 2 != 0: ans = ans*i if n > 2: ans = ans * n return ans print(findMinNum(72))
true
bc28541b378f69e1b7ef435cff0f4094c4ca75e2
PSDivyadarshini/C-97
/project1.py
298
4.21875
4
myString=input("enter a string:") characterCount=0 wordCount=1 for i in myString : characterCount=characterCount+1 if(i==' '): wordCount=wordCount+1 print("Number of Word in myString: ") print(wordCount) print("Number of character in my string:") print(characterCount)
true
8aff8f034cb41fa3efa60a2441b29e8cd056d3aa
katteq/data-structures
/P2/problem_1.py
1,315
4.34375
4
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if number == 0 or number == 1: return number start = 0 end = number res = 0 i = 0 while not res: i += 1 if start == end: res = start break median = round(end - (end-start)/2) number_sqrt = median*median if number_sqrt == number: res = median break number_sqrt_next = (median+1)*(median+1) if number_sqrt > number: end = median else: if number_sqrt_next > number: res = median break start = median return round(res) print("Pass" if (3 == sqrt(9)) else "Fail") print("Pass" if (0 == sqrt(0)) else "Fail") print("Pass" if (4 == sqrt(16)) else "Fail") print("Pass" if (1 == sqrt(1)) else "Fail") print("Pass" if (5 == sqrt(27)) else "Fail") print("Pass" if (75 == sqrt(5625)) else "Fail") print("Pass" if (123 == sqrt(15129)) else "Fail") print("Pass" if (1234 == sqrt(1522756)) else "Fail") print("Pass" if (274003 == sqrt(75078060840)) else "Fail") print("Pass" if (18 == sqrt(345)) else "Fail")
true
23766aad682eccf45ca95ba6cd539d82568a7192
blbesinaiz/Python
/displayFormat.py
286
4.125
4
#Program Title: Formatted Display #Program Description: Program takes in a string, and outputs the text # with a width of 50 import sys string = input("Please enter a string: ") for i in range(10): sys.stdout.write('['+str(i)+']') print(string)
true
e2b69836a22a3feda9a41bdc13c7a7761a276faf
tomcusack1/python-algorithms
/Arrays/anagram.py
841
4.125
4
def anagram(str1, str2): ''' Anagram function accepts two strings and returns true/false if they are valid anagrams of one another e.g. 'dog' and 'god' = true :string str1: :string str2: :return: boolean ''' str1 = str1.replace(' ', '').lower() str2 = str2.replace(' ', '').lower() # Edge case check if len(str1) != len(str2): # There are differing numbers of letters return False count = {} for letter in str1: if letter in count: count[letter] += 1 else: count[letter] = 1 for letter in str2: if letter in count: count[letter] -= 1 else: count[letter] = 1 for k in count: if count[k] != 0: return False return True print anagram('abc', 'abc')
true
b66019522fe2066decb573e28901a0014f73f41d
guilmeister/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
274
4.15625
4
#!/usr/bin/python3 def uppercase(str): result = '' for letters in str: if ord(letters) >= 97 and ord(letters) <= 122: result = result + chr(ord(letters) - 32) else: result = result + letters print("{:s}".format(result))
true
dac58c8d8c1ad1f712734e2d33407c270ba38aae
cloudavail/snippets
/python/closures/closure_example/closure_example.py
1,039
4.375
4
#!/usr/bin/env python # objective: create and explain closures and free variables def add_x(x): def adder(num): # closure: # adder is a closure # # free variable: # x is a free variable # x is not defined within "adder" - if "x" was defined within adder # if would be local and would be printed by "local()" # x is not a parameter, either, only "num" is passed in return x + num return adder add_5 = add_x(5) # sets add_5 equal to the return value of add_x(5) # the return value of add_x(5) is a function # that returns x (which we defined as 5) + an num # # def adder(num): # return 5 + num # # add_5 is a function print 'add_5 is a {}.'.format(add_5.__class__) print add_5(10) # and another example, generating a function "add_10" with the x # variable closed over add_10 = add_x(10) print 'add_10 is a {}.'.format(add_10.__class__) print add_10(21) # the functions add_5 and add_10 have closed over the "x" # which is bound for each function
true
293ae711c7822c3d67b20ae236d6c9d4445b4ee7
sonalisharma/pythonseminar
/CalCalc.py
2,514
4.3125
4
import argparse import BeautifulSoup import urllib2 import re def calculate(userinput,return_float=False): """ This methos is used to read the user input and provide and answer. The answer is computed dircetly using eval method if its a numerical expression, if not the wolfram api is used to get the appropriate answer. Parameters: userinput : This is a string, passed by the user in command line e.g. "3*4+12" or "mass of moon in kgs" return_float: This is to provide the output format, when specified as true then float is returned Execution: calculate("3*4+12", return_float=True) Output: The result is either a float or a string """ try: #This is to make sure user does not provide remve, delete or other sys commands in eval #eval is used purely for numeric calculations here. if (bool(re.match('.*[a-zA-Z].*', userinput, re.IGNORECASE))): raise Exception ("Try with wolfram") else: ans = eval(userinput) if return_float: ans = float(re.findall(r'\d+', ans)) return ans except Exception: data = urllib2.urlopen('http://api.wolframalpha.com/v2/query?appid=UAGAWR-3X6Y8W777Q&input='+userinput.replace(" ","%20")+'&format=plaintext').read() soup = BeautifulSoup.BeautifulSoup(data) keys = soup.findAll('plaintext') if (keys): #Printing the first returned rresult of the query. The first result is the heading, second #result is the actual value hence printing [1:2] for k in keys[1:2]: ans = k.text else: ans = "Sorry! No results found, try another question!" return ans def test_1(): assert abs(4.0 - calculate("2**2")) < 0.001 def test_2(): assert calculate("total states in US") == '50' def test_3(): assert calculate("56*3+1000%2") == '168' def test_4(): assert 'Alaska' in calculate("largest state in US") def test_5(): assert '8' in calculate("planets in our solar system") if __name__ == '__main__': parser = argparse.ArgumentParser(description='Evaluating command line expressions') parser.add_argument('-s', action="store",help='Enter an expression to evaluate e.g. 3*4-5*6 or "mass of moon in kgs" , make sure the string is provided within quotes') try: results = parser.parse_args() ans = calculate(results.s,return_float=True) if ans=="": ans="Sorry! No results found, try another question!" print "You Asked: %s" %results.s print "Answer: %s" %ans except: print "There is an error in your input, check help below" parser.print_help()
true
e06b35be36c3eed153be97a95a5aa802b9c33008
khanma1962/Data_Structure_answers_Moe
/100 exercises/day10.py
2,799
4.34375
4
''' Question 31 Question: Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. ''' def print_dict(start = 1, end = 20): d = {} for i in range(start, end+1): # print(i) d[i] = i ** 2 print(d) # print_dict() ''' Question 32 Question: Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only. ''' def print_dict2(start = 1, end = 20): d = {} for i in range(start, end+1): # print(i) d[i] = i ** 2 for j in d.keys(): print(j, end = " ") print('\n') for j in d.values(): print(j, end = " ") # print_dict2() ''' Question 33 Question: Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). ''' def print_list(start = 1 , end = 20): lst = [] for i in range(start, end + 1): lst.append(i ** 2) print(lst) # print_list() ''' Question 34 Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. ''' def print_list(start = 1 , end = 20): lst = [] for i in range(start, end + 1): lst.append(i ** 2) for i in range(5): print(lst[i], end = ' ') # print_list() ''' Question 35 Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. ''' def print_list(start = 1 , end = 20): lst = [] for i in range(start, end + 1): lst.append(i ** 2) for i in range(5): print(lst[len(lst) - i - 1], end = ' ') # print(lst[-i:]) print(lst[-5:]) # print_list() ''' Question 36 Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. ''' def print_list(start = 1 , end = 20): lst = [] for i in range(start, end + 1): lst.append(i ** 2) for i in range(5, len(lst)): # print(i) print(lst[i], end = ' ') # print(lst[-i:]) print(lst[5:]) # print_list() ''' Question 37 Question: Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). ''' def print_tuple(start = 1, end = 20): lst = [] for i in range(start, end + 1): lst.append(i ** 2) print(tuple(lst)) print_tuple()
true
3e19b68db20afb1391f15588b5b559546479eb76
3l-d1abl0/DS-Algo
/py/Design Patterns/Structural Pattern/decorator.py
1,356
4.25
4
''' Decorator Pattern helps us in adding New features to an existing Object Dynamically, without Subclassing. The idea behind Decorator Patter is to Attach additional responsibilities to an object Dynamically. Decorator provide a flexible alternative to subclassing for extending Functionality. ''' class WindowInterface: def build(self): pass class Window(WindowInterface): def build(self): print("Building Window") class AbstractWindowDecorator(WindowInterface): """ Maintain a reference to a Window Object and define an interface that conforms to Window's Interface. """ def __init__(self, window): self._window = window def build(self): pass class BorderDecorator(AbstractWindowDecorator): def add_border(self): print("Adding Border") def build(self): self.add_border() self._window.build() class VerticalSBDecorator(AbstractWindowDecorator): def add_vertical_scroll_bar(self): print("Adding Vertical Scroll Bar") def build(self): self.add_vertical_scroll_bar() self._window.build() class HorizontalSBDecorator(AbstractWindowDecorator): def add_horizontal_scroll_bar(self): print("Adding Horizontal Scroll Bar") def build(self): self.add_horizontal_scroll_bar() self._window.build()
true
a9c3eaf87fb86da5486d03a66ca702d6d27f083e
Nikoleta-v3/rsd
/assets/code/src/find_primes.py
697
4.3125
4
import is_prime import repeat_divide def obtain_prime_factorisation(N): """ Return the prime factorisation of a number. Inputs: - N: integer Outputs: - a list of prime factors - a list of the exponents of the prime factors """ factors = [] potential_factor = 1 while N > 1: potential_factor += 1 if is_prime.is_prime(potential_factor): N, exponent = repeat_divide.repeat_divide_number(N, potential_factor) if exponent > 0: factors.append((potential_factor, exponent)) return factors print(obtain_prime_factorisation(2 ** 3 * 11 * 23)) print(obtain_prime_factorisation(7))
true
4923d24d114c3ce22708e6f941fe5cc89e660547
EmonMajumder/All-Code
/Python/Guest_List.py
1,399
4.125
4
#Don't forget to rename this file after copying the template for a new program! """ Student Name: Emon Majumder Program Title: IT Programming Description: Data_to_file """ def main(): #<-- Don't change this line! #Write your code below. It must be indented! fileName=input("File Name: ") accessMode=input("Access Mode: ") myfile=open(fileName,accessMode) while True: guestName=input("Please enter your name: ") myfile.write(guestName+" , ") while True: guestAge=input("Please enter your age: ") if guestAge.isnumeric()==True: guestAge=int(guestAge) if guestAge>0 and guestAge<150: myfile.write("{0}\n".format(guestAge)) break else: print("Incorrect input.") else: print("Incorrect input.") while True: decision=input("Want to leave? (yes/no): ") if decision.lower()=="yes" or decision.lower()=="no" or decision.lower()=="y" or decision.lower()=="n" : break else: print("please input yes or no only") if decision.lower()=="yes" or decision.lower()=="y": myfile.close() break #Your code ends on the line above #Do not change any of the code below! if __name__ == "__main__": main()
true
e1457e85ef66c4807ffcb5446b89813e27644908
EmonMajumder/All-Code
/Python/Leap_Year.py
1,319
4.4375
4
#Don't forget to rename this file after copying the template for a new program! """ Student Name: Emon Majumder Program Title: IT Programming Description: Leap_year """ #Pseudocode # 1. Define name of the function # 2. Select variable name # 3. Assign values to 3 variable for input %4, 100 & 400 # 4. determine if input is devisible by 4, 100 and 400 as needed through if logic # 5. return value from the function if leap year or not # 6. Assign input to a variable for year to check # 7. Call function and assign value to a variable # 8. print the result def main(): #<-- Don't change this line! #Write your code below. It must be indented! def leapyearteller (year): remainderFor4=year%4 remainderFor100=year%100 remainderFor400=year%400 if remainderFor4==0 and remainderFor100>0: decision= "is a Leap year" elif remainderFor400==0: decision= "is a Leap year" else: decision= "is not a Leap year" return decision yeartoCheck=int(input("Please enter the year that you want to check if it is a leap year: ")) decision=leapyearteller (yeartoCheck) print("{0} {1}".format(yeartoCheck,decision)) #Your code ends on the line above #Do not change any of the code below! if __name__ == "__main__": main()
true
a595f993f1f05e9bd3552213aca426ca69610ab1
LarisaOvchinnikova/Python
/HW2/5 - in column.py
401
4.3125
4
# Print firstname, middlename, lastname in column firstName = input("What is your first name? ") middleName = input("What is your middle name? ") lastName = input("What is your last name? ") m = max(len(firstName), len(lastName), len(middleName)) print(firstName.rjust(m)) print(middleName.rjust(m)) print(lastName.rjust(m)) print(f"{firstName.rjust(m)}\n{middleName.rjust(m)}\n{lastName.rjust(m)}")
true
ef36ed78ceee68ae2d14c1bb4a93605c164c9795
LarisaOvchinnikova/Python
/1 - Python-2/10 - unit tests/tests for python syntax/variable assignment1.py
682
4.15625
4
# Name of challenger # Variable assignment # Create a variable with the name `pos_num` and assign it the value of any integer positive number in the range from 10 to 200, both inclusive. #Open test class TestClass(object): def test_1(self): """Type of variable is int""" assert type(pos_num) == int, f'expected type of value should be int' def test_2(self): """Variable is positive number""" assert pos_num > 0, f'expected value should be positive' def test_3(self): """Variable is in valid range""" assert 10 <= pos_num <= 200, f'expected value should be in the range from 10 to 200' #Completed solution pos_num = 100
true
04f9664ad8d43e67c386a917ee8b28127b32315d
LarisaOvchinnikova/Python
/1 - Python-2/4 - strings functions/Determine the properties of a string.py
1,124
4.25
4
#Print word " has lowercase letters" if it has only lowercase alphabet characters # Print word " has uppercase letters" # if it has only uppercase alphabet characters # Print word " has so many letters. Much wow." # if it has both uppercase and lowercase alphabet characters but no digits # Print word " has digits" if # it has only digits # Print word " has digits and lowercase letters" # if it has digits and only lowercase letters # Print word " has digits and uppercase letters" # if it has digits and only uppercase letters # Print word " has all kinds of stuff" # if it has digits and both uppercase and lowercase letters word = input("Enter word: ") if word.isdigit(): print("Has digits") elif word.isalpha(): if word.islower(): print("Has lowercase") elif word.isupper(): print("Has uppercase") else: print("Has upper and lower") elif word.isalnum(): if word.islower(): print("Has lowercase and digits") elif word.isupper(): print("Has uppercase and digits") else: print("Has upper and lower and digits") help() #вызов помощи
true
703bd7118ff467dc98f9b6a3802ca1b74df9e2a5
itsmesanju/pythonSkills
/leetCode/7.reverseInteger.py
912
4.15625
4
''' Given a 32-bit signed integer, reverse digits of an integer. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Example 4: Input: x = 0 Output: 0 ''' class Solution: def reverse(self, x: int) -> int: if str(x).startswith("-"): x = str(x) x = str(x[1:]) rev=x[::-1] result="-"+rev else: result=int(str(x)[::-1]) range1= -2**31 range2= 2**31 if result in range(range1,range2): return result else: return 0
true
132c2bba74dfd857faaf3ed42033376e3e9dfb0c
ACNoonan/PythonMasterclass
/ProgramFlow/aachallenge.py
287
4.21875
4
number = 5 multiplier = 8 answer = 0 # iterate = 0 # add your loop after this comment # My Soultion: # while iterate < multiplier: # answer += number # iterate += 1 # The solution she told you not to worry about for i in range(multiplier): answer += number print(answer)
true
915de4df06984d86f0237064bb6d0bf015a1d893
v2webtest/python
/app.py
307
4.25
4
print("Starting programme..") enType: int = int(input("\n\nEnter program type.. ").strip()) print(enType) # Checking of Type and printing message if enType == 1: print("-- Type is First.") elif enType == 2: print("-- Type is Second.") else: print("-- Unknown Type!") print("End of program.")
true
b9be0492e6edd04f2f5bf78d3ea0ec63915baed4
Ayon134/code_for_Kids
/tkinter--source/evet.py
649
4.3125
4
#handling button click #when you press button what will happen import tkinter #create a window window = tkinter.Tk() window.title("Welcome to Tkinter World :-)") window.geometry('500x500') label = tkinter.Label(window, text = "Hello Word!", font=("Arial Bold", 50)) label.grid(column=0, row=0) def clicked(): label.configure(text="button is clicked !!") bton = tkinter.Button(window, text = "Click me",bg="orange",fg="red",command=clicked) bton.grid(column=1, row=0) #label.grid(column=0, row=0) #this function calls the endless loop of the window, #so the window will wait for any user interaction till we close it. window.mainloop()
true
9df7f613f1f637be2df86dd57d4b255abd91b932
infantcyril/Python_Practise
/Prime_Count_Backwards.py
2,061
4.1875
4
check_a = 0 a = 0 def prim(check,a): check_a = 0 while (check_a == 0): try: check_a = 1 a = int(input("Enter the Number from where you want to start searching: ")) if (a <= 2): check_a = 0 print("Please enter a value greater than 2, There is no Prime number before", a) continue except ValueError: print("Input should be a Positive Integer Value") check_a = 0 for x in range((a-1),1,-1): for num in range(2,x): if(x%num == 0): break else: print("The prime number that comes first when we count backwards from" ,a, "is:",x) break prim(check_a,a) ''' TEST CASE: Sample Input : 3 || Expected Output: The prime number that comes first when we count backwards from 3 is:2 Sample Input : 15 || Expected Output: The prime number that comes first when we count backwards from 56 is:13 Sample Input : 2100 || Expected Output: The prime number that comes first when we count backwards from 2100 is:2111 Sample Input : 10000 || Expected Output: The prime number that comes first when we count backwards from 10000 is: 9973 ------------------------------------------- Input | Output ------------------------------------------- 56 | The prime number that comes first when we count backwards from 56 is: 53 ------------------------------------------- asd | Enter a positive integer value ------------------------------------------- @#$ | Enter a positive integer value ------------------------------------------- 2.5 | Enter a positive integer value ------------------------------------------- -2 | Please enter a value greater than 2, There is no Prime number before -2. ------------------------------------------- 0 | Please enter a value greater than 2, There is no Prime number before 0. ------------------------------------------- '''
true
722d462d7142bc66c5abcbcf23867507d5f116cb
r4isstatic/python-learn
/if.py
417
4.4375
4
#!/usr/bin/env python #This takes the user's input, stores it in 'name', then runs some tests - if the length is shorter than 5, if it's equal to, and if it equals 'Jesse'. name = raw_input('Please type in your name: ') if len(name) < 5: print "Your name is too short!" elif len(name) == 5: print "Your name is the perfect length!" if name == "Jesse": print "Hey, Jesse!" else: print "You have a long name!"
true
1c9ec18cd80266e53d4e2f01d73dc0c9fb0099f0
npradaschnor/algorithms_module
/caesar_cipher.py
960
4.34375
4
# Based on Caesar's Cipher #Substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number (offset) of positions down the alphabet. #In this case is upper in the alphabet def encrypt(plain_text, offset): cipher_text = "" for i in plain_text: #for every char in text inputted numerical_value = ord(i) #unicode value of the char if i.isupper(): #if is uppercase adjusted = ((numerical_value + offset - 65) % 26) + 65 #uppercase A = 65 (ASCII). The %26 wraps around, so Y = A and Z = B cipher_text += chr(adjusted) #get the correspondent char elif numerical_value == 32: #32 = space, this intends to preserve the spaces between words cipher_text += i else: #if is lowercase adjusted=((numerical_value + offset - 97) % 26) + 97 #lowercase a = 97 (ASCII) cipher_text += chr(adjusted) return cipher_text print(encrypt("hello lads", 2)) print(encrypt("are we human", 2))
true
3bbce6604801ae9019975edc3ce0e07ea347b90c
npradaschnor/algorithms_module
/odd_position_elements_array.py
1,141
4.15625
4
#Write an algorithm that returns the elements on odd positions in an array. #Option 1 using 2 functions def range_list(array): array = range(0,len(array)) i = [] for e in array: i.append(e) return i def odd_index(array): oddl = [] a = range_list(array) for n in a: if n%2 != 0: #the index cannot be even e = array[n] #element with index n oddl.append(e) #add the element in the list oddl n += 1 #increase index by 1 elif n % 2 == 0 or n == 0: #if the index is zero or even 'skip' continue return oddl #return the list with elements that were in odd position array = [25, 6, 99, 74, 20, 101] print(range_list(array)) print(odd_index(array)) # Option 2 after watching the pseudoce video def odd_GMIT(array): oddG = [] while i <= len(array): for i == 1: oddG.append(i) i +=2 return oddG # Option 3 by Dominic Carr (Lecturer - Algorithmics Module) def odd_indices(input): output = [] for i in range(len(input)): if (i % 2) != 0: output.append(input[i]) return output print(odd_indices([1, 2, 3, 4, 5]))
true
ea07e7f7353344e90bbc9e4b0ccdff5ebc22a87f
npradaschnor/algorithms_module
/merge.py
561
4.1875
4
#recursive function that returns a merged list (1 element of str1 + 1 element of str2...and so on) def merge(str1,str2): if len(str1) == 0: #if the number of element in the str1 is zero, return str2 return str2 elif len(str2) == 0: # if the number of element in the str2 is zero, return str1 return str1 else: return str1[0] + str2[0] + merge(str1[1:],str2[1:]) #first element of str1 + first element of str2 + function calling itself to continue the pattern of element str1 + str2 to result in a merged list print(merge('dmnc', 'oii'))
true
7ca02e4f2af417d3a67f16cd90e3f87c722515c2
Necron9x11/udemy_pythonWorkbook100Exercises
/ex-20/ex-20.py
1,065
4.15625
4
#!/usr/bin/env python3 # # Python Workbook - 100 Exercises # Exercise # NN # # Points Value: NN # # Author: Daniel Raphael # # --------------------------------------------------------------------------------------------------------------------- # # Question: Calculate the sum of all dictionary values. # # d = {"a": 1, "b": 2, "c": 3} # # Expected output: # # 6 # # --------------------------------------------------------------------------------------------------------------------- d = {"a": 1, "b": 2, "c": 3} sum_x=0 for key in d.keys(): sum_x = sum_x + d[key] print(sum_x) # I got loops on the brain this morning... Instructors solution is way more Pythonic. # print([sum(x)for x in d.keys]) # Instructor's Solution # # Exercise for reference: # # Calculate the sum of all dictionary values. # # d = {"a": 1, "b": 2, "c": 3} # # Answer: # # d = {"a": 1, "b": 2, "c": 3} # print(sum(d.values())) # # Explanation: # # d.values() returns a list-like dict_values object while the sum function calculates the sum of the dict_values items.
true
7db32d46a6e1435dd916719ac8093b32206e4688
hfu3/text-mining
/Session12/anagrams.py
945
4.375
4
""" 1. read the file, save the words into a list 2. (option 1) count letters for each word 'rumeer' -> 6 'reemur' - 6 'kenzi' -> 5 (option2) sort the word 'rumeer' -> 'eemrru' sig 'reemur' - 'eemrru' sig 'kenzi' -> 'ekinz' sig create empty list for each signature expected: ['rumeer', 'reemur'] ['kenzi'] 4. create another dict, to store the data like {2[[/]]} """ def reads_file(): def save_words_2_list(): """ will return list of words """ for lines in f: def list_to_dict(words): """ words: a list of all the words reuturns a dictionary """ def print_anagrams(word_dict, n_words_in_anagrams = 1): """ prints all the anagrams with more than n words """ def create_another_dict(): def prints_anagram_by_number(words_dict): """ create def main(): words_list = reads_file word_dict = list_to_dict(word_list) #ex- 2 print_anagrams(word_dict, 2) if __name == '__main__": main()
true
54861c9c20c34fb60f1507432dec0e7db836758a
kalebinn/python-bootcamp
/Week-1/Day 3/linear_search.py
1,164
4.25
4
# TODO: Write a function that takes a integer and a list as the input. # the function should return the index of where the integer was found # on the list def search(x, list): """ this function returns the index of where the element x was found on the list. \tparam : x - the element you're searching for \tparam : list - the list you're searching through \treturns : the index of where the element was found (if applicable) """ for index in range(0,len(list)): if list[index] == x: return index def find_max(list): """ this function returns the maximum element in the list \tparam : list - a list of numerical elements \treturns : the maximum value in the list """ max = list[0] for element in list: if element >= max: max = element return max def find_min(list): """ this function returns the minimum element in the list \tparam : list - a list of numerical elements \treturns : the minimum value in the list """ min = list[0] for element in list: if element <= min: min = element return min
true
c9f4678ea364b027e5577856fe95ac2fd07c23e0
kalebinn/python-bootcamp
/Week-1/Day 1/4-loops.py
265
4.1875
4
counter = 0 while counter <= 0: print(counter) counter += 1 # range(start, stop, increment) print("using three inputs to range()") for number in range(0,5,1): print(number) print("using one input to range()") for number in range(5): print(number)
true
e05b380f577208e1df340765ae6a0232b7c5b7f4
Katezch/Python_Fundamentals
/python_fundamentals-master/02_basic_datatypes/2_strings/02_07_replace.py
382
4.34375
4
''' Write a script that takes a string of words and a symbol from the user. Replace all occurrences of the first letter with the symbol. For example: String input: more python programming please Symbol input: # Result: #ore python progra##ing please ''' s = input(" please input words here: ") symbol = input("please enter a symbol: ") res = s.replace(s[0], symbol) print(res)
true
8b8af177b6a6b2af1f96d5d9c75d7b166f1e15ab
Katezch/Python_Fundamentals
/python_fundamentals-master/07_classes_objects_methods/07_01_car.py
852
4.4375
4
''' Write a class to model a car. The class should: 1. Set the attributes model, year, and max_speed in the __init__() method. 2. Have a method that increases the max_speed of the car by 5 when called. 3. Have a method that prints the details of the car. Create at least two different objects of this Car class and demonstrate changing the objects attributes. ''' class Car(): def __init__(self, model, year, max_speed): self.model = model self.year = year self.max_speed = max_speed def __str__(self): return f"This is a {self.year} {self.model} car that has a maximum speed of {self.max_speed}" def increase_speed(self): self.max_speed += 5 car1 = Car("BMW", 2021, 50) car2 = Car("TSL", 2020, 60) print(car1) print(car2) car1.increase_speed() car2.increase_speed() print(car1) print(car2)
true
14d06fa26fb51aecf4a59fa232e410742d8c0487
nietiadi/svm4r
/old/proving.py
1,023
4.125
4
#!/usr/bin/python3 """ using ctl-rp to prove all proofs and give the answer, which is either 'sat' or 'unsat' """ import itertools import csv def proving(num_of_propositions=2, with_empty_clause=False): """ create the csv file containing the results from ctl-rp """ if with_empty_clause: fname = 'data/proofs_with_empty_clause_for_'+\ str(num_of_propositions)+'_propositions.csv' else: fname = 'data/proofs_without_empty_clause_for_'+\ str(num_of_propositions)+'_propositions.csv' fname = 'test.dat' with open(fname) as csvfile: csvin = csv.reader(csvfile) for row in csvin: #print(', '.join(row)) print(row) """ rows = list() y = 0 for x in itertools.product(range(0,2), repeat=num_of_clauses): #print(y, x) one_row = list(x); one_row.insert(0, y); rows.append(one_row); y+=1 #print(rows) with open(fname, 'wt') as fout: csvout = csv.writer(fout) csvout.writerows(rows) """ #main proving(2, False); #proving(2, True);
true
caa45bf56cd1b83f43c9ee05ebd9c618b74f8527
rtejaswi/python
/rev_str_loop.py
794
4.34375
4
'''str = "Python" reversedString=[] index = len(str) # calculate length of string and save in index while index > 0: reversedString += str[ index - 1 ] # save the value of str[index-1] in reverseString index = index - 1 # decrement index print(reversedString) # reversed string''' '''str = 'Python' #initial string reversed=''.join(reversed(str)) # .join() method merges all of the characters resulting from the reversed iteration into a new string print(reversed) #print the reversed string''' # Python code to reverse a string # using loop '''def reverse(s): str = "" for i in s: str = i + str return str s = "Python" print ("The original string is : ",end="") print (s) print ("The reversed string(using loops) is : ",end="") print (reverse(s))'''
true
6c1b6b9a6c235826ace320eae96868b1a754a05d
gregorybutterfly/examples
/Decorators/1-python-decorator-example.py
886
4.46875
4
#!/usr/bin/python """ A very simple example of how to use decorators to add additional functionality to your functions. """ def greeting_message_decorator(f): """ This decorator will take a func with all its contents and wrap it around WRAP func. This will create additional functionality to the 'greeting_message' func by printing messages.""" def wrap(*args, **kwargs): """ Here we can print *aregs and **kwargs and manipulate them """ print('>> Decorate before executing "greeting_message" function') func = f(*args, **kwargs) print('>> Decorate after executing "greeting_message" function') return func return wrap @greeting_message_decorator def greeting_message(name): """ This function will be decorated by 'greeting_message_decorator' before execution """ print('My name is ' + name) greeting_message('Adam')
true
3f78094152b4c5759fa4776296a4dd47e48d4b61
sam676/PythonPracticeProblems
/Robin/desperateForTP.py
1,004
4.28125
4
""" You've just received intel that your local market has received a huge shipment of toilet paper! In desperate need, you rush out to the store. Upon arrival, you discover that there is an enormously large line of people waiting to get in to the store. You step into the queue and start to wait. While you wait, you being to think about data structures and come up with a challenge to keep you busy. Your mission: create a queue data structure. Remember, queues are FIFO - first in first out - in nature. Your queue should be a class that has the methods "add" and "remove". Adding to the queue should store an element until it is removed. """ class queue(): def __init__(self): self.items = [] def add(self, item): self.items.insert(0,item) def remove(self): return self.items.pop() def size(self): return len(self.items) newQueue = queue() newQueue.add(35) newQueue.add(10) print(newQueue.size()) newQueue.remove() print(newQueue.size())
true
269910439e357f1e3e9b1576e08dc319918b9406
sam676/PythonPracticeProblems
/Robin/reverseMessage.py
1,083
4.21875
4
""" Today's question You are a newbie detective investigating a murder scene in the boardroom at the Macrosoft Corp. While searching for clues, you discover a red notebook. Inside of the notebook are long journal entries with inverted messages. At that moment, you remembered from your profiler father’s advice that you could stand in front of the mirror to see the messages. However, you have not slept for 3 days in a row...and haven't showered either. Because you really don't want to see your face, you decide that you would rather build an app that can take in a message string and return the reversed message for you. Now you just need to come up with a function to build your app - and don't take the shortcut using the "reverse" method ;)Please reverse this message found in the spooky journal: .uoy fo lla naht ynapmoc retteb a ekam nac I .ynapmoc siht ta OEC eht eb ot evresed I loopsstringsmedium """ def reverseMessage(message): return(message[::-1]) print(reverseMessage(".uoy fo lla naht ynapmoc retteb a ekam nac I .ynapmoc siht ta OEC eht eb ot evresed I"))
true