blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1ce6ad0a83e82ade475c75c40d9cf5c8fb4cac43
ellen-yan/self-learning
/LearnPythonHardWay/ex5.py
1,363
4.34375
4
my_name = 'Ellen X. Yan' my_age = 23 # not a lie my_height = 65 # inches my_weight = 135 # lbs my_eyes = 'Brown' my_teeth = 'White' my_hair = 'Black' print "Let's talk about %s." % my_name print "She's %d inches tall." % my_height print "She's %d pounds heavy." % my_weight print "Actually that's not too heavy." print "She's got %s eyes and %s hair." % (my_eyes, my_hair) print "His teeth are usually %s depending on the coffee." % my_teeth # this line is tricky print "If I add %d, %d, and %d I get %d." % ( my_age, my_height, my_weight, my_age + my_height + my_weight) print "I just want to print %%" print "This prints no matter what: %r, %r" % (my_name, my_age) # '%s', '%d', and '%r' are "formatters". They tell Python to take the variable # on the right and put it in to replace the %s with its value # List of Python formatters: # %c: character # %s: string conversion via str() prior to formatting # %i: signed decimal integer # %d: signed decimal integer # %u: unsigned decimal integer # %o: octal integer # %x: hexadecimal integer (lowercase letters) # %X: hexadecimal integer (UPPERcase letters) # %e: exponential notation (with lowercase 'e') # %E: exponential notation (with UPPERcase 'E') # %f: floating point real number # %g: the shorter of %f and %e # %G: the shorter of %f and %E # %r: print the raw data (i.e. everything); useful for debugging
true
a6f237792aef743e05e0e1d0f81e510b0926bdec
nsimsofmordor/PythonProjects
/Projects/PythonPractice.org/p2_odd_or_even.py
481
4.40625
4
# Ask the user for a number. # Depending on whether the number is even or odd, print out an appropriate message to the user. # If the number is a multiple of 4, print out a different message. # Ask for a positive number number = int(input("Enter a positive number: ")) while number < 0: number = int(input("Enter a positive number: ")) # print out if odd or even if number % 4 == 0: print("Multiple of 4") elif number % 2 == 0: print("Even") else: print("Odd")
true
ee6fcba43821b771900c0ced8ca27003e6085fd0
nsimsofmordor/PythonProjects
/Projects/PythonPractice.org/p6_sting_lists.py
287
4.53125
5
# Ask the user for a string and print out whether this string is a palindrome or not. my_str = str(input("Enter a string to check if it is a palindrome or not: ").lower()) rev_str = my_str[::-1].lower() if my_str == rev_str: print("Palindrome!") else: print("Not Palindrome!")
true
068905cbe2bea0582747af13f294ce98d8edf24f
nsimsofmordor/PythonProjects
/Projects/Python_Tutorials_Corey_Schafer/PPBT5 Dicts.py
1,064
4.375
4
# {Key:value} == {Identifier:Data} student = {'name': 'john', 'age': '27', 'courses': ['Math', 'Science']} print(f"student = {student}") print(f"student[name] = {student['name']}") print(f"student['courses'] = {student['courses']}\n") # print(student['Phone']) # throws a KeyError, sine that key doesn't exist print(student.get('phone', 'Not Found')) print() print("setting student[phone] = 555-5555") student['phone'] = '555-5555' print(student) print() print("results of student.update({'name': 'frank'})") student.update({'name': 'frank'}) print(student) print() print("deleting student['age']") del student['age'] print(student) print() print("printing the name...") name = student['name'] print(name) print("\nprinting the len of student") print(len(student)) print("\nprinting the student keys") print(student.keys()) print("\nprinting the student values") print(student.values()) print("\nprinting the student items") print(student.items()) print('\nprinting the key,value pairs') for key,value in student.items(): print (key, value)
true
14325d0779ae0aa4b96b89daddcaef7448493106
msossoman/coderin90
/calculator.py
1,165
4.125
4
def add (a, b): c = a + b print "The answer is: {0} + {1} = {2}".format(a, b, c) def subtract (a, b): c = a - b print "The answer is {0} - {1} = {2}".format(a, b, c) def multiply (a, b): c = a * b print "The answer is {0} * {1} = {2}".format(a, b, c) def divide (a, b): c = a / b print "The answer is {0} / {1} = {2}".format(a, b, c) def choice(): operation = int(raw_input("""Select operation: \n 1. Add\n 2. Subtract\n 3. Multiply\n 4. Divide\n Enter choice (1/2/3/4):""")) if operation == 1: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") add(float(a), float(b)) elif operation == 2: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") subtract(float(a), float(b)) elif operation == 3: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") multiply(float(a), float(b)) elif operation == 4: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") divide(float(a), float(b)) else: print "Please select a valid operation" choice() if __name__ == '__main__': choice()
true
1b26680c89752d77a1f78e231a9165c4a25a004c
Ashok-Mishra/python-samples
/python exercises/dek_program054.py
864
4.4375
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Define a class named Shape and its subclass Square. The Square class has # an init function which takes a length as argument. Both classes have a # area function which can print the area of the shape where Shape's area # is 0 by default. # Hints: # To override a method in super class, we can define a method with the # same name in the super class. class Shape(object): def area(self): return 0 class Square(Shape): def __init__(self, length): print 'calling init method' self.length = length def area(self): return self.length * self.length def main(): squareObj = Square(int(raw_input('Enter Length : '))) # squareObj = Square(int('5')) print 'Area of Square is : ', squareObj.area() if __name__ == '__main__': main()
true
40746a8b06658c8d7935e4238f69e17e1d7d9315
Ashok-Mishra/python-samples
/python exercises/dek_program068.py
970
4.40625
4
#!/usr/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # program068: # Please write a program using generator to print the even numbers between # 0 and n in comma separated form while n is input by console. # Example: # If the following n is given as input to the program: # 10 # Then, the output of the program should be: # 0,2,4,6,8,10 # Hints: # Use yield to produce the next value in generator. # In case of input data being supplied to the question, it should be # assumed to be a console input. def evenGenerator(endValue): eveniter = 0 while eveniter <= endValue: if eveniter % 2 == 0: yield eveniter eveniter += 1 def main(endValue): result = [] evenGen = evenGenerator(int(endValue)) for res in evenGen: result.append(str(res)) # print result print ",".join(result) if __name__ == '__main__': main(raw_input("Input endLimit: "))
true
e260d508fca7871b4955a4d44eded3503d532c18
Ashok-Mishra/python-samples
/python exercises/dek_program062.py
482
4.40625
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Write a program to read an ASCII string and to convert it to a unicode # string encoded by utf - 8. # Hints: # Use unicode() function to convert. def do(sentence): # print ord('as') unicodeString = unicode(sentence, "utf-8") print unicodeString def main(): sentence = 'this is a test' do(sentence) if __name__ == '__main__': main() # main(raw_input('Enter String :'))
true
047481cff2b6856af271cecf82fbeb71e1e68ad3
Ashok-Mishra/python-samples
/python exercises/dek_program071.py
571
4.40625
4
#!/usr/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # program071: # Please write a program which accepts basic mathematic expression from # console and print the evaluation result. # Example: # If the following string is given as input to the program: # 35+3 # Then, the output of the program should be: # 38 # Hints: # Use eval() to evaluate an expression. def main(expression): print eval(expression) if __name__ == '__main__': expression = raw_input("Enter expression: ") main(expression) # main('34+5')
true
d502383264e8d290050e3b1384916f7888c07677
Ashok-Mishra/python-samples
/python exercises/dek_program045.py
694
4.375
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Write a program which can filter even numbers in a list by using filter # function. The list is: # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. # Hints: # Use filter() to filter some elements in a list. # Use lambda to define anonymous functions. def do(start_number, end_number): list = [value for value in range(start_number, end_number + 1)] print 'list :', list result = filter(lambda number: number % 2 == 0, list) print 'Even Number From list :', result def main(): do(int(raw_input('Enter Starting Number :')), int(raw_input('Enter Ending Number :'))) if __name__ == '__main__': main()
true
714da2929f26a6b2788bad27279aec26de30f66b
Ashok-Mishra/python-samples
/python exercises/dek_program053.py
747
4.28125
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Define a class named Rectangle which can be constructed by a length and # width. The Rectangle class has a method which can compute the area. # Hints: # Use def methodName(self) to define a method. class Ractangle(object): def __init__(self, length, width): self.length = length self.width = width def areaOfRactangle(self): return self.length * self.width def main(): ractangleObj = Ractangle( int(raw_input('Enter Value for length of Ractangle :')), int(raw_input('Enter Value for Width of Ractangle :'))) print 'Area of Ractangle is : ', ractangleObj.areaOfRactangle() if __name__ == '__main__': main()
true
ef2f0b6305acf196994ca53109035688722d342e
Ashok-Mishra/python-samples
/python exercises/dek_program001.py
913
4.125
4
#!/user/bin/python # -*- coding: utf-8 -*- # Author : (DEK) Devendra Kavthekar # program001 : divisibleBy7not5 # Write a program which will find all such numbers which are divisible by 7 # but are not a multiple of 5, between 2000 and 3200 (both included). # The numbers obtained should be printed in a comma-separated sequence # on a single line. # Hints: # Consider use range(#begin, #end) method def divisibleBy7not5(startLimit, endLimit): result = [] for number in range(startLimit, endLimit + 1): # "endLimit + 1" bcoz limits too,should be included # print number if number % 7 == 0 and number % 5 != 0: result.append(number) return result def main(): print 'numbers divisible by 7 and not 5' print divisibleBy7not5(int(raw_input('Enter Value:')), int(raw_input('Enter Value:'))) if __name__ == '__main__': main() # checked
true
ae0fed29cb1b49c8deb8c0807df7f222c6aae61a
Ashok-Mishra/python-samples
/python exercises/dek_program008.py
722
4.28125
4
#!/user/bin/python # -*- coding: utf-8 -*- # Author : (DEK) Devendra Kavthekar # program008 : # Write a program that accepts a comma separated # sequence of words as input and prints the words # in a comma-separated sequence after sorting them alphabetically. # Suppose the following input is supplied to the program: # without,hello,bag,world # Then, the output should be: # bag,hello,without,world # Hints: # In case of input data being supplied to the question, it should be # assumed to be a console input. def main(): print "sample input ", 'without,hello,bag,world' str = raw_input('Enter : ') li1 = str.split(',') # print li1 li1.sort() print li1 if __name__ == '__main__': main() # checked
true
046bd214c938e63595f3d9fdeed82ecf1327b6b7
ayushtiwari7112001/Rolling-_dice
/Dice_Roll_Simulator.py
640
4.4375
4
#importing modual import random #range of the values of dice min_val = 1 max_val = 6 #to loop the rolling through user input roll_again = "yes" #loop while roll_again == "yes" or roll_again == "y": print("Roll the dices...") print("** The values are **") #generating and printing 1st random integer from 1 to 6 print(random.randint(min_val,max_val)) #generating and printing 2nd random integer from 1 to 6 print(random.randint(min_val, max_val)) #asking user to roll the dice again. Any input other than yes or y will terminate the loop roll_again=input("Roll the dices again (yes/no) or (y/n) ")
true
93278240e775bbba67da1572331d7a1d3cb279db
YeomeoR/codewars-python
/sum_of_cubes.py
656
4.25
4
# Write a function that takes a positive integer n, sums all the cubed values from 1 to n, and returns that sum. # Assume that the input n will always be a positive integer. # Examples: # sum_cubes(2) # > 9 # # sum of the cubes of 1 and 2 is 1 + 8 ### from cs50 video python, lecture 2 # def sum_cubes(n): # cubed = [] # i = 1 # while (i <= n): # cubed.append(i**3) # i+=1 # print(sum(cubed)) def sum_cubes(n): return sum(i**3 for i in range(0,n+1)) print(sum_cubes(1), 1) print(sum_cubes(2), 9) print(sum_cubes(3), 36) print(sum_cubes(4), 100) print(sum_cubes(10), 3025) print(sum_cubes(123), 58155876)
true
4f481dd9a6205e9979b2f9f17103dd3816a226ab
YeomeoR/codewars-python
/count_by_step.py
827
4.21875
4
# Implement a function named generateRange(min, max, step), which takes three arguments and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step. (min < max) # def generate_range(min, max, step): # listed = [] # rangey = range(min,max +1,step) # for n in rangey: # listed.append(n) # return listed def generate_range(min, max, step): return list(range(min, max + 1, step)) print(generate_range(1, 10, 1), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(generate_range(-10, 1, 1), [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1]) # print(generate_range(1, 15, 20), [1]) # print(generate_range(1, 7, 2), [1, 3, 5, 7]) # print(generate_range(0, 20, 3), [0, 3, 6, 9, 12, 15, 18])
true
3d40b4229c78f200c882547349bf5ad433a87908
goruma/CTI110
/P2HW1_PoundsKilograms_AdrianGorum.py
586
4.40625
4
# Program converts pounds value to kilograms for users. # 2-12-2019 # CTI-110 P2HW1 - Pounds to Kilograms Converter # Adrian Gorum # #Pseudocode #input pound amount > calculate pound amount divided by 2.2046 > display #conversion in kilograms #Get user input for pound amount. poundAmount = float(input('Enter the pound amount to be converted: ')) #Calculate the kilogram amount as pound amount / 2.2046. kilogramAmount = poundAmount / 2.2046 #Display the pound amount as kilograms. print('The pound amount converted to kilograms is: ', format(kilogramAmount, ',.3f'))
true
1ef83617a069d51eb924275376f133f4c323d375
goruma/CTI110
/P4HW4_Gorum.py
796
4.3125
4
# This programs draws a polygonal shape using nested for loops # 3-18-19 # P4HW4 - Nested Loops # Adrian Gorum # def main(): #Enable turtle graphics import turtle #Set screen variable window = turtle.Screen() #Set screen color window.bgcolor("red") #Pen Settings myPen = turtle.Turtle() myPen.shape("arrow") myPen.speed(10) myPen.pensize(8) myPen.color("yellow") #Nested loop to create square and then iterate the square 8 times at 45 degree angle for x in range(8): for y in range(4): #Create square shape myPen.forward(100) myPen.left(90) #Turn square 45 degrees to the left to start next iteration myPen.left(45) #Program Start main()
true
f3de93f96f4247c3bccba5f699eadd168e4439d0
vincent1879/Python
/MITCourse/ps1_Finance/PS1-1.py
844
4.125
4
#PS1-1.py balance = float(raw_input("Enter Balance:")) AnnualInterest = float(raw_input("Enter annual interest rate as decimal:")) MinMonthPayRate = float(raw_input("Enter minimum monthly payment rate as decimal:")) MonthInterest = float(AnnualInterest / 12.0) TotalPaid = 0 for month in range(1,13): print "Month", str(month) MinMonthPay = float(balance * MinMonthPayRate) print "Minimum monthly payment: $", str(round(MinMonthPay, 2)) InterestPaid = float(balance * MonthInterest) PrincipalPaid = float(MinMonthPay - InterestPaid) print "Principle paid:$", str(round(PrincipalPaid, 2)) TotalPaid += MinMonthPay balance = balance - PrincipalPaid print "Remaining balance: $", str(round(balance, 2)) print "RESULT:" print "Total amount paid:$", str(round(TotalPaid, 2)) print "Remaining balance:$", str(round(balance, 2))
true
b272382f80edeabc91c1a33ba847e34ebff32ac0
Holly-E/Matplotlib_Practice
/Dealing_with_files.py
1,051
4.125
4
# -*- coding: utf-8 -*- """ Spyder Editor Master Data Visualization with Python Course """ #open pre-existing file or create and open new file to write to # you can only write strings to txt files- must cast #'s to str( ) file = open('MyFile.txt', 'w') file.write('Hello') file.close() # can reuse file variable name after you close it. 'a' appends to file, vs 'w' which overwrites file file = open('MyFile.txt', 'a') file.write(' World') # \n makes a new line file.write('\n') file.write(str(123)) file.close() # open in reading mode file = open('MyFile.txt', 'r') # line = first line, if you call twice it will read the second line if there was one line = file.readline().split() print(line) line = file.readline() print(int(line) + 2) # .strip() to remove string .split() to make lists file.close() #The WITH method allows you to perfomr the same actions but without needing to close the file #The file is automatically closed outside the indentation with open('MyFile.txt', 'r') as file: line = file.readline() print(line)
true
39818a02bdab25b77dbfbc76cba087baecbd55d8
nibbletobits/nibbletobits
/python/day 6 in class.py
624
4.21875
4
# ******************************************** # Program Name: Day 5, in class # Programmer: Jordan P. Nolin # CSC-119: Summer 2021 # Date: June 21, 2021 # Purpose: A program to add the sum of all square roots # Modules used: # Input Variables: number() ect # Output: print statements, that output variable answer # ******************************************** def main(): myNumber = 1 stopNumber = 50 total = 0 while myNumber <= stopNumber: x = myNumber**2 total = total + x myNumber = myNumber + 1 print("the total is", total) main() input("press enter to end")
true
dd9873e3979fc3621a89d469d273f830371d757a
kingamal/OddOrEven
/main.py
500
4.1875
4
print('What number are you thinking?') number = int(input()) while number: if number >=1 and number <= 1000: if number % 2 != 0: print("That's an odd number! Have another?") number = int(input()) elif number % 2 == 0: print("That's an even number! Have another?") number = int(input()) else: print("Thanks for playing") else: print("That's a wrong number! Try it again") number = int(input())
true
d6a5f32aea3864aea415514dad886b81d434a8cc
sahilbnsll/Python
/Inheritence/Program01.py
949
4.25
4
# Basics of Inheritance class Employee: company= "Google Inc." def showDetails(self): print("This is a employee") class Programmer(Employee): language="Python" company= "Youtube" def getLanguage(self): print(f"The Language is {self.language}") def showDetails(self): print("This is Programmer Class.") e = Employee() e.showDetails() p = Programmer() p.showDetails() # Prints same content as e.showDetails because Programmer class doesn't have showDetails() so programmer class inherit showDetails() function from Base class Employee. print(p.company) # Prints "Google Inc." as Programmer class doesn't have company, so programmer class inherit company from Base class Employee. p.showDetails() # Prints "This is Programmer Class" as this time showDetails() is present in Programmer Class. print(p.company) # Prints "Youtube" as this time company is present in Programmer Class.
true
6e0f7759356bbfbf474fc5af93eb902e8a875661
sahilbnsll/Python
/Projects/Basic_Number_Game.py
406
4.15625
4
# Basic Number Game while(True): print("Press 'q' to quit.") num =input("Enter a Number: ") if num == 'q': break try: print("Trying...") num = int(num) if num >= 6: print("Your Entered Number is Greater than or equal to 6\n") except Exception as e: print(f"Your Input Resulted in an Error:{e}") print("Thanks For Playing.")
true
09a14e49b6bb2b7944bc5ec177586a40761ca6f7
kashifusmani/interview_prep
/fahecom/interview.py
2,489
4.125
4
""" Write Python code to find 3 words that occur together most often? Given input: There is the variable input that contains words separated by a space. The task is to find out the three words that occur together most often (order does not matter) input = "cats milk jump bill jump milk cats dog cats jump milk" """ from collections import defaultdict def algo(input, words_len=3): result = {} if len(input) < words_len: pass if len(input) == words_len: result = {make_key(input): 1} else: start = 0 while start+words_len < len(input): current_set = sorted(input[start:start+words_len]) our_key = make_key(current_set) if our_key in result: start += 1 continue else: result[our_key] = 1 print(current_set) inner_start = start + 1 while inner_start+words_len < len(input): observation_set = sorted(input[inner_start:inner_start+ words_len]) if current_set == observation_set: check(our_key, result) inner_start += 1 observation_set = sorted(input[inner_start:]) if current_set == observation_set: check(our_key, result) start += 1 return result def make_key(input): return ','.join(input) def check(our_key, result): if our_key in result: result[our_key] += 1 else: result[our_key] = 1 if __name__ == '__main__': input = "cats milk jump bill jump milk cats dog cats jump milk" print(algo(input.split(" "))) # Difference between tuple and list # What is a generator and why is it efficient # What is a decorator, how it works. # select player_id, min(event_date) as first_login from activity group by player_id order by player_id asc # with x as (select count(*) as total_logins, month-year(login_date) as month_year from logins group by month_year order by month_year asc), # with y as (select total_logins, month_year, row_number() as row), # select month_year, (b.total_logins - a.total_logins)/a.total_logins from # ( select total_logins, month_year, row from y) as a, ( select total_logins, month_year, row from y) as b where a.row + 1 = b.row # # with x as (select count(*) as num_direct_report, manager_id from employee group by manager_id where num_direct_report >=5) # select name from employee join x on employee.id=x.manager_id
true
b1da56330aaed2070bd2a2cf71e7905f800f11db
LaytonAvery/DigitalCraftsWeek1
/Day4/todolist.py
1,089
4.21875
4
choice = "" task = {} def add_task(choice): task = [{"title": name, "priority": priority}] task.append("") for key, value in task.append(""): print(key, value) # print(task) def delete_task(choice): del task def view_all(): for key, value in task.items(): print(key, value) choice = input(""" Welcome to your TODO app! Press 1 to 'Add Task'. Press 2 to 'Delete Task'. Press 3 to 'View All Tasks'. Press q to QUIT.""") print(choice) while True: choice = input(""" Welcome to your TODO app! Press 1 to 'Add Task'. Press 2 to 'Delete Task'. Press 3 to 'View All Tasks'. Press q to QUIT.""") print(choice) if choice == "1": name = input("Enter a task: ") priority = input("Enter task priority: ") add_task(choice) elif choice == "2": for items in task(): print(items) deletion = input("What would you like deleted? ") delete_task(choice) elif choice == "3": view_all() elif choice == "q": break
true
00aec8932d5749f9f5af478ebb9dbeff183a5c11
krizo/checkio
/quests/singleton.py
874
4.125
4
''' https://py.checkio.org/en/mission/capital-city/ You are an active traveler who have visited a lot of countries. The main city in the every country is its capital and each country can have only one capital city. So your task is to create the class Capital which has some special properties: the first created instance of this class will be unique and single, and all of the other instances should be the same as the very first one. Also you should add the name() method which returns the name of the capital. In this mission you should use the Singleton design pattern. ''' class Capital(object): __instance = None def __new__(cls, city): if Capital.__instance is None: Capital.__instance = object.__new__(cls) Capital.__instance.city = city return Capital.__instance def name(self): return self.city
true
2c4041af39e9c050adb9f1aa6352a6b9c25c8436
SwethaGullapalli/PythonTasks
/PrintFileNameHavingPy.py
866
4.375
4
#program to print the file extension having py """give input as list of file names iterate each file name in file names list declare one variable for holding file extension declare variables for index and dot index iterate each character in the file name increment the index by 1 if Character is equal to "." assign index to dot index if index is greater than or equal to dot index concatenate the character to file extension variable if .py== file extension variable print file name""" FileNameList = ["blue.py","black.txt","orange.log","red.py"] for FileName in FileNameList: FileExtension="" Index =0 DotIndex = -1 for Character in FileName: if Character == ".": DotIndex = Index if Index>=DotIndex and DotIndex!=-1: FileExtension=FileExtension+Character Index+=1 if".py" == FileExtension: print FileName
true
012065e8a85e1ac86c2e563e5df3d7feab87101a
Exodus76/aoc19
/day1.py
759
4.125
4
#day 1 part 1 #find the fuel required for a module, take its mass, divide by three, round down, and subtract 2 #part1 function def fuel_required(mass): if(mass < 0): return 0 else: return (mass/3 - 2) #part2 fucntion def total_fuel(mass): total = 0 while(fuel_required(mass) >= 0): total += fuel_required(mass) mass = fuel_required(mass) return total input_file = open('input.txt','r') total_fuel_1 = 0 total_fuel_requirement = 0 list_of_masses = input_file.readlines() for i in list_of_masses: total_fuel_1 += fuel_required(int(i)) print("part1 = " + str(total_fuel_1)) for i in list_of_masses: total_fuel_requirement += total_fuel(int(i)) print("part2 = " + str(total_fuel_requirement))
true
9eb137a3f310eeb8c6d006bfd72fce5e035e06b2
mansiagnihotrii/Data-Structures-in-python
/Linked List/4_linkedlist_partition.py
851
4.125
4
''' Given a linked list and an element , say 'x'. Divide the same list so that the left part of the list has all the elements less that 'x' and right part has all elements greater than or equal to 'x'. ''' #!/usr/bin/env python3 import linkedlist from linkedlist import LinkedList,Node def partition_list(head,element): start = head new = LinkedList() new.head = Node(start.data) start = start.next while start: if start.data >= element: linkedlist.insert_end(new.head,start.data) else: new.head = linkedlist.insert_beg(new.head,start.data) start = start.next return new.head list1 = LinkedList() head = linkedlist.create_list(list1) element = input("Enter partition element: ") if head is None: print("List is empty") else: new_head = partition_list(head,element) linkedlist.printlist(new_head)
true
c696a2980ffe52412000a0f0deda444cea00badf
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/strings/funny_string.py
1,059
4.34375
4
def funny_string(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/funny-string/problem In this challenge, you will determine whether a string is funny or not. To determine whether a string is funny, create a copy of the string in reverse e.g. abc -> cba. Iterating through each string, compare the absolute difference in the ascii values of the characters at positions 0 and 1, 1 and 2 and so on to the end. If the list of absolute differences is the same for both strings, they are funny. Determine whether a give string is funny. If it is, return Funny, otherwise return Not Funny. Args: s (str): String to check Returns: str: Returns "Funny" or "Not Funny" based on the results of the string """ for i in range(len(s)//2): if abs(ord(s[i]) - ord(s[i+1])) != abs(ord(s[len(s)-i-1]) - ord(s[len(s)-i-2])): return "Not Funny" return "Funny" if __name__ == "__main__": assert funny_string("acxz") == "Funny" assert funny_string("bcxz") == "Not Funny"
true
0562ecb6074ee2c8d62d863db65a1c5a5325fd66
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/strings/mars_exploration.py
919
4.34375
4
def mars_exploration(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/mars-exploration/problem Sami's spaceship crashed on Mars! She sends a series of SOS messages to Earth for help. Letters in some of the SOS messages are altered by cosmic radiation during transmission. Given the signal received by Earth as a string, s, determine how many letters of Sami's SOS have been changed by radiation. For example, Earth receives SOSTOT. Sami's original message was SOSSOS. Two of the message characters were changed in transit. Args: s (str): string to compare with SOS message (must be divisible by 3) Returns: int: the number of characters that differ between the message and "SOS" """ sos = int(len(s)/3) * "SOS" return sum(sos[i] != s[i] for i in range(len(s))) if __name__ == "__main__": assert mars_exploration("SOSSPSSQSSOR") == 3
true
ff2f6d4c31e79e2249438839b9e85049e4f2c4e0
kcc3/hackerrank-solutions
/python/python_functionals/validating_email_addresses_with_filter.py
1,146
4.15625
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/validate-list-of-email-address-with-filter/problem""" def fun(s): """Determine if the passed in email address is valid based on the following rules: It must have the username@websitename.extension format type. The username can only contain letters, digits, dashes and underscores [a-z], [A-Z], [0-9], [_-]. The website name can only have letters and digits [a-z][A-Z][0-9] The extension can only contain letters [a-z][A-Z]. The maximum length of the extension is 3. Args: s (str): Email address to check Returns: (bool): Whether email is valid or not """ if s.count("@") == 1: if s.count(".") == 1: user, domain = s.split("@") website, extension = domain.split(".") if user.replace("-", "").replace("_", "").isalnum(): if website.isalnum(): if extension.isalnum(): if len(extension) <= 3: return True return False if __name__ == "__main__": test = "itsallcrap" print(fun(test))
true
10a395af6ac6efa71d38074c2d88adff4665435e
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/bit_manipulation/maximizing_xor.py
932
4.3125
4
def maximizing_xor(l, r): """Hackerrank Problem: https://www.hackerrank.com/challenges/maximizing-xor/problem Given two integers, l and r, find the maximal value of a xor b, written a @ b, where a and b satisfy the following condition: l <= a <= b <= r Solve: We XOR the l and r bound and find the length of that integer in binary form. That gives us the binary from which we can create the highest value of a xor b, because that falls within l and r. Args: l (int): an integer, the lower bound inclusive r (int): an integer, the upper bound inclusive Returns: int: maximum value of the xor operations for all permutations of the integers from l to r inclusive """ xor = l ^ r xor_binary = "{0:b}".format(xor) return pow(2, len(xor_binary)) - 1 if __name__ == "__main__": print(maximizing_xor(10, 15)) print(maximizing_xor(11, 100))
true
6d15fcd0279049189d9a54c882f0b27a46034a59
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/the_grid_search.py
2,824
4.21875
4
def grid_search(g, p): """Hackerrank Problem: https://www.hackerrank.com/challenges/the-grid-search/problem Given a 2D array of digits or grid, try to find the occurrence of a given 2D pattern of digits. For example: Grid ---------- 1234567890 0987654321 1111111111 1111111111 2222222222 Pattern ------ 876543 111111 111111 The 2D pattern begins at the second row and the third column of the grid. The pattern is said to be present in the grid. Args: g (list): The grid to search, an array of strings p (list): The pattern to search for, an array of strings Returns: str: "YES" or "NO" depending on whether the pattern is found or not """ for i in range(len(g)-len(p)+1): # If we find a match for the first line, store the indices to search for match = [x for x in range(len(g[i])) if g[i].startswith(p[0], x)] if match: # Iterate through the list of indices where the first line of the pattern matched for j in match: found = True # Now see if the rest of the pattern matches within the same column / index for k in range(1, len(p)): if p[k] == g[i+k][j:j+len(p[k])]: continue else: found = False break if found: return "YES" return "NO" if __name__ == "__main__": g = ["7283455864", "6731158619", "8988242643", "3830589324", "2229505813", "5633845374", "6473530293", "7053106601", "0834282956", "4607924137"] p = ["9505", "3845", "3530"] assert grid_search(g, p) == "YES" g2 = ["7652157548860692421022503", "9283597467877865303553675", "4160389485250089289309493", "2583470721457150497569300", "3220130778636571709490905", "3588873017660047694725749", "9288991387848870159567061", "4840101673383478700737237", "8430916536880190158229898", "8986106490042260460547150", "2591460395957631878779378", "1816190871689680423501920", "0704047294563387014281341", "8544774664056811258209321", "9609294756392563447060526", "0170173859593369054590795", "6088985673796975810221577", "7738800757919472437622349", "5474120045253009653348388", "3930491401877849249410013", "1486477041403746396925337", "2955579022827592919878713", "2625547961868100985291514", "3673299809851325174555652", "4533398973801647859680907"] p2 = ["5250", "1457", "8636", "7660", "7848"] assert grid_search(g2, p2) == "YES" g3 = ["111111111111111", "111111111111111", "111111011111111", "111111111111111", "111111111111111"] p3 = ["11111", "11111", "11110"] assert grid_search(g3, p3) == "YES"
true
6eba8809d2c6d10aadc221ea78cf0d08d458d967
kcc3/hackerrank-solutions
/data_structures/python/stacks/maximum_element.py
1,176
4.34375
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/maximum-element/problem You have an empty sequence, and you will be given queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. """ # Enter your code here. Read input from STDIN. Print output to STDOUT # Setup the list which will act as our stack stack = [-1] # Read in the total number of commands num_commands = int(input()) # For each command, append, pop, or return the max value as specified. When we push to the stack, we can compare # with the current highest value so that the stack always has the max value at the tail of the list, and because when # we pop, we are removing the last added item, so it is either the last added value, or a copy of the last max value # when it was added for _ in range(num_commands): query = input().split(" ") if query[0] == "1": stack.append(max(int(query[1]), stack[-1])) elif query[0] == "2": stack.pop() elif query[0] == "3": print(stack[-1]) else: print("Unknown command")
true
54e29a17af6dfcb36c102bba527a588a533d29f3
kcc3/hackerrank-solutions
/python/built_ins/any_or_all.py
548
4.15625
4
""" Hackerrank Problem: https://www.hackerrank.com/challenges/any-or-all/problem Given a space separated list of integers, check to see if all the integers are positive, and if so, check if any integer is a palindromic integer. """ n = int(input()) ints = list(input().split(" ")) # Check to see if all integers in the list are positive if all(int(i) >= 0 for i in ints): # Check if any of the integers are a palindrome - where the digit number is the same if digits are reversed print(any(j == j[-1] for j in ints)) else: print(False)
true
048f4a1843a7cb34f846a62ff3cc70225a74c763
kcc3/hackerrank-solutions
/data_structures/python/stacks/balanced_brackets.py
2,594
4.40625
4
def is_balanced(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/balanced-brackets/problem A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ]. By this logic, we say a sequence of brackets is balanced if the following conditions are met: - It contains no unmatched brackets. - The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets. Given n strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO. Args: s (str): The string to compare Returns: (str): "YES" or "NO" based on whether the brackets in the string are balanced """ open_closed = {"(": ")", "[": "]", "{": "}"} balanced = [] for i in s: if i in open_closed.keys(): balanced.append(i) else: # If the stack is empty, we have a closed bracket without any corresponding open bracket so not balanced if len(balanced) == 0: return "NO" # Compare the brackets to see if they correspond, and if not, not balanced if i != open_closed[balanced.pop()]: return "NO" # If the stack is empty, every open bracket has been closed with a corresponding closed bracket if not balanced: return "YES" # If there's still something in the stack, then return NO because it's not balanced return "NO" if __name__ == "__main__": assert is_balanced("}}}") == "NO" assert is_balanced("{[()]}") == "YES" assert is_balanced("{[(])}") == "NO" assert is_balanced("{{[[(())]]}}") == "YES" assert is_balanced("{{([])}}") == "YES" assert is_balanced("{{)[](}}") == "NO" assert is_balanced("{(([])[])[]}") == "YES" assert is_balanced("{(([])[])[]]}") == "NO" assert is_balanced("{(([])[])[]}[]") == "YES"
true
93d2c4f2eb3485d73051a93cfa531070aa46a563
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/bigger_is_greater.py
1,021
4.28125
4
def bigger_is_greater(w): """Hackerrank Problem: https://www.hackerrank.com/challenges/bigger-is-greater/problem Given a word, create a new word by swapping some or all of its characters. This new word must meet two criteria: - It must be greater than the original word - It must be the smallest word that meets the first condition Args: w (str): The word to swap Returns: str: Return the next highest lexicographical word or "no answer" """ # Find non-increasing suffix arr = [c for c in w] i = len(arr) - 1 while i > 0 and arr[i - 1] >= arr[i]: i -= 1 if i <= 0: return "no answer" # Find successor to pivot j = len(arr) - 1 while arr[j] <= arr[i - 1]: j -= 1 arr[i - 1], arr[j] = arr[j], arr[i - 1] # Reverse suffix arr[i:] = arr[len(arr) - 1: i - 1: -1] return "".join(arr) if __name__ == "__main__": print(bigger_is_greater("zzzayybbaa")) print(bigger_is_greater("zyyxwwtrrnmlggfeb"))
true
49f4e08c38d8f2429e77d4af1d29e4010c381208
archeranimesh/pythonFundamentals
/code/pyworkshop/02_list/list_sort.py
556
4.21875
4
# Two ways to sort a list. lottery_numbers = [1, 3, 345, 123, 789, 12341] # 1st method does not modify the original list, # returns a shallow copy of original list. print("sorted list: ", sorted(lottery_numbers)) # reverse the list. print("reverse list: ", sorted(lottery_numbers, reverse=True)) x = sorted(lottery_numbers) # returns a list. print("x = ", x, "\ntypeof(x): ", type(x)) # In place list sorting. lottery_numbers.sort() print("list sort: ", lottery_numbers) # reverse lottery_numbers.reverse() print("list reverse: ", lottery_numbers)
true
63a6c50f451fd165eeff0b514a9c5e87b44b531d
michalecki/codewars
/sum_of_intervals.py
1,528
4.1875
4
''' Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4. List containing overlapping intervals: [ [1,4], [7, 10], [3, 5] ] The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4. ''' def sum_intervals(inp_arr): ''' :param array: array of intervals :return: sum of lengths of the intervals ''' # sort the intervals over the first digit inp_arr.sort() # loop and merge if overlap i = 0 while i < len(inp_arr) - 1: while inp_arr[i][1] >= inp_arr[i + 1][0]: inp_arr[i] = [inp_arr[i][0], max(inp_arr[i + 1][1], inp_arr[i][1])] del inp_arr[i + 1] if i == len(inp_arr) - 1: break i += 1 # calculate the sum total = sum([inp_arr[x][1] - inp_arr[x][0] for x in range(len(inp_arr))]) return total # testing sum_intervals([ [1, 2], [6, 10], [11, 15] ]) # \; // => 9 sum_intervals([ [1, 4], [7, 10], [3, 5] ]) # ; // => 7 sum_intervals([ [1, 5], [10, 20], [1, 6], [16, 19], [5, 11] ]) # ; // => 19
true
aa970b317af5316d42807008efbc5b41e8347486
michalecki/codewars
/sum_of_numbers.py
582
4.34375
4
def get_sum(a,b): ''' Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b. Note: a and b are not ordered! :param a: int :param b: int :return: int ''' if a == b: return a ab = [a, b] ab.sort() return sum(range(ab[0],ab[1]+1)) #testing print(get_sum(0,1)) # ok print(get_sum(4,4)) # ok print(get_sum(0,-1)) print(get_sum(-2,0)) print(get_sum(-3,-2)) print(get_sum(4,2)) print(get_sum(-3,5))#ok
true
a72af4074104f47c32f8714796c4a1f6948bc8d1
ShreyanGoswami/coding-contests
/Leetcode weekly contest 189/rearrange_words_in_sentence.py
860
4.25
4
''' Given a sentence text (A sentence is a string of space-separated words) in the following format: First letter is in upper case. Each word in text are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order. Return the new text following the format shown above. ''' class Solution: def arrangeWords(self, text: str) -> str: ''' Time complexity: O(nlogn) Space complexity: O(n*m) where n is the number of words and m is the maximum number of letters in a word ''' words = text.split() words[0] = words[0].lower() words.sort(key = lambda x: len(x)) words[0] = words[0].capitalize() return " ".join(x for x in words)
true
985bb44337d98dcf1b07803b84ae7417f48c0015
pragatij17/General-Coding
/Day 6/python/sum_of_numbers.py
256
4.25
4
# Write a program that asks the user for a number n and prints the sum of the numbers 1 to n. def sum_of_number(n): sum = 0 for i in range(1,n+1): sum =sum + i return sum n = int(input('Last digit of sum:')) print(sum_of_number(n))
true
dcf7913f53b7ea31ba263c2a26ecd5a52334846e
SaidRem/algorithms
/find_biggest_(recursion).py
404
4.21875
4
# Finds the biggest element using recursion def the_biggest(arr): # Base case if length of array equals 2 . if len(arr) == 2: return arr[0] if arr[0] > arr[1] else arr[1] # Recursion case. sub_max = the_biggest(arr[1:]) return arr[0] if arr[0] > sub_max else sub_max if __name__ == '__main__': arr = list(map(int, input().strip().split())) print(the_biggest(arr))
true
6af4513c000f0bf8ae449e915e146515187fed08
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab07-rock_paper_scissors.py
1,327
4.25
4
#lab07-rockpaperscissors.py import random user_input = 'yes' while user_input == 'yes': print('Let\'s play rock-paper-scissors!') print('The computer will ask the user for their choice of rock, paper or scissors, and then the computer will randomly make a selection.') #computer tell user how the game will work user = input ('rock, paper or scissors:') choices = ('rock', 'paper', 'scissors') #the user will have to choose one of these options computer = random.choice(choices) #the computer will select a random choice if user == computer: print('It\'s a tie') elif user == 'rock': if computer == 'paper': print('Computer wins, the computer chose paper') if computer =='scissors': print('Computer loses, the computer chose scissors' ) elif user == 'paper': if computer =='scissors': print('Computer wins, the computer chose scissors' ) if computer == 'rock': print('Computer loses, the computer chose rock') elif user == 'rock': if computer =='scissors': print('Computer loses, the computer chose scissors' ) if computer == 'rock': print('Computer wins, the computer chose rock') user = input('Would you like to play again?')
true
4885b4212545ee9f635fed82f045478503adc865
PdxCodeGuild/class_mudpuppy
/Reviewed/Brea/python/lab17/lab17_version2_checked.py
1,009
4.125
4
#Lab 17, Version 2 Anagram def split(word): return list(word) # good practice, but generally don't make a function # that calls a single function, especially one that's already well-known like list() def remove_spaces(str): new_str = '' for i in range(len(str)): if(str[i] != ' '): new_str += str[i] return new_str # I like that you did this the hard way (you learn more that way) # but you could just do str.replace('', ' ') # Also, don't use the parameter str, that overwrites a builtin function user_input1 = input("What is the first input you'd like to compare? : ") user_input1 = user_input1.lower() list_inp1 = split(remove_spaces(user_input1)) user_input2 = input("What is the second input to compare? : ") user_input2 = user_input2.lower() list_inp2 = split(remove_spaces(user_input2)) list_inp1.sort() list_inp2.sort() if list_inp1 == list_inp2: print("These two inputs are anagrams!") else: print("These two inputs are not anagrams!") # Nice!
true
37675d15d25aa51006258ff94564fbc04ff6e685
PdxCodeGuild/class_mudpuppy
/1 Python/class_demos/function-lecture/add-number-words-ultimate-solution.py
986
4.125
4
import operator def get_valid_input(): valid_input = False while not valid_input: num1 = input("Spell out a number with letters: ") if num1 in number_dict: return num1 else: print(f"{num1} is not supported. Try entering a different number: ") def reduce_list_to_value(fn, starting_value, values): accumulator = starting_value for val in values: accumulator = fn(accumulator, val) return accumulator def square_and_add(x,y): return x + y**2 number_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} numbers = [] for _ in range(4): inp = get_valid_input() numbers.append(number_dict[inp]) number_sum = reduce_list_to_value(operator.add, 0, numbers) product = reduce_list_to_value(operator.mul, 1, numbers) sum_squares = reduce_list_to_value(square_and_add, 0, numbers) print(f"The sum is {number_sum}, the product is {product}, the sum of squares is {sum_squares}")
true
096d0dc863ab7739debf8e8000545f4e7f7f3cda
PdxCodeGuild/class_mudpuppy
/Assignments/Devan/1 Python/labs/lab11-simple_calculator.py
1,098
4.21875
4
# Lab 11: Simple Calculator Version 3 def get_operator(op): return operators[op] def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y def eval(fn, n1, n2): return fn(n1, n2) operators = {'+': add, '-': subtract, '*': multiply, '/': divide} while True: try: operator = input('Enter your operator (+, -, *, /) or done: ') if operator == 'done': print('\nThanks for using the calculator.') break if operator not in operators: print('Not a vaild operator...') else: # todo: validate user entered number n1 = input('Enter the first number: ') if n1 is not int: print('Enter a vaild number. ') n2 = int(input('Enter the second number: ')) if n2 is not int: print('Enter a valid number. ') print(eval(get_operator(operator), int(n1), int(n2))) except KeyboardInterrupt: print('\nThank You') break
true
50962379cef04f28b24854aeeaccc11e9f673a9b
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/labs06.py
1,170
4.21875
4
# Lab 6: Password Generator """ Let's generate a password of length `n` using a `while` loop and `random.choice`, this will be a string of random characters. """ import random import string # string._file_ = random.choice('string.ascii_letters + string.punctuation + string.digits') # #print((string._file_)) # pass_num = input ("How many characters? ") # pass_num = int(pass_num) # out_num = '' # for piece in range(pass_num): # out_num = out_num + random.choice(string.ascii_letters + string.punctuation + string.digits) # print(out_num) string._file_ = random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation) pass_low = input("How many lowercase? ") pass_low = int(pass_low) pass_high = input("How many uppercase? ") pass_high = int(pass_high) pass_dig = input("How many numbers? ") pass_dig = int(pass_dig) out_num = '' for piece in range(pass_low): out_num = out_num + random.choice(string.ascii_lowercase) for piece in range(pass_high): out_num = out_num + random.choice(string.ascii_uppercase) for piece in range(pass_dig): out_num = out_num + random.choice(string.digits) print(out_num)
true
2874845c72626487f96500a7aac40ba91891870e
PdxCodeGuild/class_mudpuppy
/1 Python/solutions/lab09-v2.5.py
617
4.34375
4
# Supported unit types supported_units = ["ft", "mi", "m", "km"] # Ask the user for the unit they want unit = input("What unit do you want: ") # If an invalid unit is specified, alert the user and exit if unit not in supported_units: print("Please enter a valid unit! Options are ft, mi, m, km...") exit() # Get the amount of units amount = float(input("How many units: ")) # Check to see if the unit matches one we know if unit == "ft": print(amount * 0.3048) elif unit == "mi": print(amount * 1609.34) elif unit == "m": print(amount * 1 * 1 * 1) # Extra spicy elif unit == "km": print(amount * 1000)
true
7d22fbd58d09e95c2ab94e8adb567da9c3932b36
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/lab18.py
439
4.125
4
import string input_string = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] #change variable name #create an empty list for index in range(1,len(input_string)-1): left_side = input_string[index-1] middle = input_string[index] right_side = input_string[index + 1] if left_side < middle and right_side < middle: print(index) elif left_side > middle and right_side > middle: print(index)
true
91c7e627278fe3386b9db69c2bf8636072abbeaf
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/lab09-unit_converter.py
1,154
4.46875
4
""" Ask the user for the number of feet, and print out the equivalent distance in meters. Hint: 1 ft is 0.3048 m. So we can get the output in meters by multiplying the input distance by 0.3048. Below is some sample input/output. """ # import decimal # print("Enter number of feet ") # number_feet = float(input('')) # meters = 0.3048 # print(f" that equals {number_feet * meters} meters ") """ Allow the user to also enter the units. Then depending on the units, convert the distance into meters. The units we'll allow are feet, miles, meters, and kilometers. """ # import math # distance = 11 # user = input("Choose a unit: ") # unit_dict = { 'feet' : 0.3048, 'miles': 1609.3, 'meter': 1, 'kilometer': 1000 } # user_int = unit_dict[user] # conversion = user_int * distance # print(f"(The conversion is {conversion} ") """ Add support for yards, and inches. """ # import math # distance = 11 # user = input("Choose a unit: ") # unit_dict = { 'feet' : 0.3048, 'miles': 1609.3, 'meter': 1, 'kilometer': 1000, 'yard' : 0.9144, 'inch' : 0.254 } # user_int = unit_dict[user] # conversion = user_int * distance # print(f"(The conversion is {conversion} ")
true
c5d508427ca54175b9b640d81d451807aa07ac21
PdxCodeGuild/class_mudpuppy
/Assignments/Racheal/python/test.py
1,247
4.34375
4
import random #Twinkle, twinkle, little star, #How I wonder what you are! #Up above the world so high, #Like a diamond in the sky. # little = input("Enter adjective:") # wonder = input("Enter verb:") # world = input("Enter noun:") # high = input("Enter adjective:") # diamond = input("Enter noun:") # sky =input("Enter noun:") # print(f"twinkle, twinkle,{little} star, how I {wonder} what you are! Up above the {world} so {high} like a {diamond}in the {sky}. Twinkle twinkle little start, how I wonder what you are") # list1 = [] user_input = input('enter a plural noun, an adjective, a verb, a noun, and another adjective:' ) # list1 = user_input.append(user_input) # print(f"twinkle, twinkle,{little} star, how I {wonder} what you are! Up above the {world} so {high} like a {diamond}in the {sky}. Twinkle twinkle little start, how I wonder what you are") user_input_list = user_input.split() print(len(user_input_list)) print(f"twinkle, twinkle,{user_input_list[0]} star, how I {user_input_list[1]} what you are! Up above the {user_input_list[2]} so {user_input_list[3]} like a {user_input_list[4]}in the. Twinkle twinkle little start, how I wonder what you are") word = "" for i in range(): word += random.choice() print(word)
true
a8dd0814e6f3294f7c65ed85b0c49311589f6fb8
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab25-atm.py
2,171
4.15625
4
#lab25-atm.py class ATM: def __init__(self, balance=0, interest_rate=.01): self.balance = balance self.interest_rate = interest_rate self.transactions = [] def check_balance(self): '''returns the account balance''' print(f"Your balance is {self.balance}") return self.balance def deposit(self, amount): '''deposits the given amount in the account''' print(f"Your deposit is {amount}") self.balance += amount self.transactions.append(f'User deposited ${amount}') print(f"Your balance is {self.balance}") def check_withdrawal(self, amount): '''returns true if the withdrawn amount won't put the account in the negative''' if self.balance >= amount: return True else: return False def withdrawl(self, amount): '''withdraw(amount) withdraws the amount from the account and returns it''' if self.balance >= amount: self.balance -= amount print(f"Your balance is {self.balance}") self.transactions.append(f'User withdrew ${amount}') else: print("You do not have enough money") def print_transactions(self): print(f"Here is your list of transactions {self.transactions}") '''printing out the list of transactions''' def calc_interest(self): '''returns the amount of interest calculated on the account''' interest = self.balance * self.interest_rate print(f"Your balance is {interest}") my_atm = ATM(balance=100) while True: user_choice = input('Choose (d)eposit, (w)ithdrawl, (cb)alance, (h)istory, (q)uit: ') if 'd' == user_choice: amount = input(f'How much would you like to deposit?') my_atm.deposit(int(amount)) if 'w' == user_choice: amount = input(f'How much would you like to withdrawl?') my_atm.withdrawl(int(amount)) if 'cb' == user_choice: my_atm.check_balance() if 'h' == user_choice: my_atm.print_transactions() elif 'q' == user_choice: break print(f'Thank you, please come again!')
true
a35cffa0ab2b6c4424709cf8693ef70106688eb9
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Class Examples/Test_042120.py
1,464
4.1875
4
#Test Examples April 21st, 2020 #average numbers lab re-do # nums = [5, 0, 8, 3, 4, 1, 6] # running_sum = 0 # for num in nums: # running_sum = running_sum + num # print(running_sum) # aver = running_sum / len(nums) # print(f"The average of your numbers is {aver}.") #--------REPL Version of average numbers lab # nums = [] # running_sum = 0 # while True: # user_input = int(input("Enter a number (or, '0' for done) : ")) # if user_input == 0: # aver = running_sum / len(nums) # print(f"The average of your numbers is {aver}.") # break # nums.append(user_input) # running_sum += user_input # print(nums) #-----------class version of average numbers # class NumList: # def __init__(self): # self.nums = [] # def append(self, in_num): # self.nums.append(int(in_num)) # def average(self): # return sum(self.nums) / len(self.nums) # me = NumList() # while True: # user_input = input("Enter a number or 'done': ") # if user_input == 'done': # break # me.append(user_input) # print(me.nums) # print(me.average()) #--------------------- #Tic Tac Toe Tests board = [[' ', '|', ' ', '|', ' '], [' ', '|', ' ', '|', ' '], [' ', '|', ' ', '|', ' ']] board2 = [] # for inner_list in board: # board2.append(''.join(inner_list)) board2 = '\n'.join([''.join(inner_list) for inner_list in board]) print(board2)
true
750437c3c078315b3a3ee1981aa1173e2dfaeefe
charlotteviner/project
/land.py
1,632
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 28 17:37:12 2017 @author: charlotteviner Credit: Code written by Andrew Evans. Create elevation data for use in the project. Provided for background on how the artificial environment 'land' was created. Returns: land (list) -- List containing land elevation data. land (.txt) -- File containing data for the land elevation. """ import matplotlib import csv w = 100 # Set width to 100. h = 100 # Set height to 100. land = [] # Create empty list called 'land'. # Plot a 100 x 100 square. for y in range(0, h): # Cycle through coordinates (0, h) until h = 100. row = [] # Create empty list called 'row'. for x in range(0, w): row.append(0) # Append 0 to 'row' at (0, w) until w = 100. land.append(row) # Append each row created to the 'land' list. # Add relief to the 100 x 100 square. for y in range(0, h): # Cycle through coordinates (0, h) until h = 100. for x in range(0, w): # Cycle through (0, w) until w = 100. if (x + y) < w: # If (x + y) < w, then the coordinate will = x + y. land[y][x] = x + y else : # If not, the coordinate will = (w - x) + (h - y). land[y][x] = (w - x) + (h - y) # Plot 'land' on a graph. matplotlib.pyplot.ylim(0, h) # Limit of y axis. matplotlib.pyplot.xlim(0, w) # Limit of x axis. matplotlib.pyplot.imshow(land) print(land) # Create a new file 'land.txt' which contains the coordinate data. f = open('land.txt', 'w', newline='') writer = csv.writer(f, delimiter=',') for row in land: writer.writerow(row) f.close()
true
a13f132c3ac6e87e313570bcc86e470c096ae0b5
koushik-chandra-sarker/PythonLearn
/a_script/o_Built-in Functions.py
1,608
4.125
4
""" Python Built-in Functions: https://docs.python.org/3/library/functions.html or https://www.javatpoint.com/python-built-in-functions """ # abs() # abs() function is used to return the absolute value of a number. i = -12 print("Absolute value of -40 is:", abs(i)) # Output: Absolute value of -40 is: 12 # bin() # Convert an integer number to a binary string prefixed with “0b”. i = 5 print(bin(i)) # Output: 0b101 # sum() x = sum([2, 5, 3]) print(x) # Output: 10 x = sum((5, 5, 3)) print(x) # Output: 13 x = sum((5, 5, 3), 10) print(x) # Output: 23 x = sum((3 + 5j, 4 + 3j)) print(x) # Output: (7+8j) # pow() """ pow(x, y, z) x: It is a number, a base y: It is a number, an exponent. z (optional): It is a number and the modulus. """ print(pow(2, 3)) # Output: 8 print(pow(4, 2)) # Output: 16 print(pow(-4, 2)) # Output: 16 print(pow(-2, 3)) # Output: -8 # min() function is used to get the smallest element from the collection. s = min(123, 2, 5, 3, 6, 35) print(s) # Output: 2 s = min([10, 12], [12, 21], [13, 15]) print(s) # Output: 2[10, 12] s = min("Python", "Java", "Scala") print(s) # Output: java s = min([10, 12, 33], [12, 21, 55], [13, 15], key=len) print(s) # Output:[13,15] # max() function is used to get the highest element from the collection. s = max(123, 2, 5, 3, 6, 35) print(s) # Output: 123 s = max([10, 12], [12, 21], [13, 15]) print(s) # Output: [13, 15] s = max("Python", "Java", "Scala") print(s) # Output: scala s = max([10, 12, 33], [12, 21, 55, 9], [13, 15], key=len) print(s) # Output:[12, 21, 55, 9]
true
19c94192bbd45a17858bd0b0348a077042c144b7
gibsonn/MTH420teststudent
/Exceptions_FileIO/exceptions_fileIO.py
2,762
4.25
4
# exceptions_fileIO.py """Python Essentials: Exceptions and File Input/Output. <Name> <Class> <Date> """ from random import choice # Problem 1 def arithmagic(): """ Takes in user input to perform a magic trick and prints the result. Verifies the user's input at each step and raises a ValueError with an informative error message if any of the following occur: The first number step_1 is not a 3-digit number. The first number's first and last digits differ by less than $2$. The second number step_2 is not the reverse of the first number. The third number step_3 is not the positive difference of the first two numbers. The fourth number step_4 is not the reverse of the third number. """ step_1 = input("Enter a 3-digit number where the first and last " "digits differ by 2 or more: ") step_2 = input("Enter the reverse of the first number, obtained " "by reading it backwards: ") step_3 = input("Enter the positive difference of these numbers: ") step_4 = input("Enter the reverse of the previous result: ") print(str(step_3), "+", str(step_4), "= 1089 (ta-da!)") # Problem 2 def random_walk(max_iters=1e12): """ If the user raises a KeyboardInterrupt by pressing ctrl+c while the program is running, the function should catch the exception and print "Process interrupted at iteration $i$". If no KeyboardInterrupt is raised, print "Process completed". Return walk. """ walk = 0 directions = [1, -1] for i in range(int(max_iters)): walk += choice(directions) return walk # Problems 3 and 4: Write a 'ContentFilter' class. """Class for reading in file Attributes: filename (str): The name of the file contents (str): the contents of the file """ class ContentFilter(object): # Problem 3 def __init__(self, filename): """Read from the specified file. If the filename is invalid, prompt the user until a valid filename is given. """ # Problem 4 --------------------------------------------------------------- def check_mode(self, mode): """Raise a ValueError if the mode is invalid.""" def uniform(self, outfile, mode='w', case='upper'): """Write the data ot the outfile in uniform case.""" def reverse(self, outfile, mode='w', unit='word'): """Write the data to the outfile in reverse order.""" def transpose(self, outfile, mode='w'): """Write the transposed version of the data to the outfile.""" def __str__(self): """String representation: info about the contents of the file."""
true
69fe06f4d308eca042f3bf0c30f4a207d65473ac
Yu4n/Algorithms
/CLRS/insertion_sort.py
1,175
4.3125
4
# Loop invariant is that the subarray A[0 to i-1] is always sorted. def insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key # Driver code to test above def insertionSortRecursive(arr, n): # base case if n <= 1: return # Sort first n-1 elements insertionSortRecursive(arr, n - 1) '''Insert last element at its correct position in sorted array.''' key = arr[n - 1] j = n - 2 # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = key if __name__ == '__main__': arr = [12, 11, 13, 5, 6] insertionSort(arr) print(arr) arr2 = [6, 5, 4, 3, 2, 1, 0, -1] insertionSortRecursive(arr2, len(arr2)) print(arr2)
true
46fd209659f3dd4ca466d6ca7e7af8f23c661238
mverini94/PythonProjects
/DesignWithFunctions.py
2,401
4.65625
5
''' Author....: Matt Verini Assignment: HW05 Date......: 3/23/2020 Program...: Notes from Chapter 6 on Design With Functions ''' ''' Objectives for this Chapter 1.) Explain why functions are useful in structuring code in a program 2.) Employ a top-down design design to assign tasks to functions 3.) Define a recursive function 4.) Explain the use of the namespace in a program and exploit it effectively 5.) Define a function with required and optional parameters 6.) Use higher-order fuctions for mapping, filtering, and reducing - A function packages an algorithm in a chunk of code that you can call by name - A function can be called from anywhere in a program's code, including code within other functions - A function can receive data from its caller via arguments - When a function is called, any expression supplied as arguments are first evaluated - A function may have one or more return statements ''' def summation(lower, upper): result = 0 while lower <= upper: result += lower #result = result + lower lower += 1 #lower = lower + 1 print(result) summation(1, 4) ''' - An algorithm is a general method for solving a class of problems - The individual problems that make up a class of problems are known as problem instances - What are the problem instances of our summation algorithm? - Algorithms should be general enough to provide a solution to many problem instances - A function should provide a general method with systematic variations - Each function should perform a single coherent task - Such as how we just computed a summation ''' ''' TOP-DOWN Design starts with a global view of the entire problem and breaks the problem into smaller, more manageable subproblems - Process known as problem decomposition - As each subproblem is isolated, its solution is assigned to a function - As functions are developed to solve subproblems, the solution to the overall problem is gradually filled ot. - Process is also called STEPWISE REFINEMENT - STRUCTURE CHART - A diagram that shows the relationship among a program's functions and the passage of data between them. - Each box in the structure is labeled with a function name - The main function at the top is where the design begins - Lines connecting the boxes are labeled with data type names - Arrows indicate the flow of data between them '''
true
caaceae86ca5f9ac137756c98fccecba86b05c88
mverini94/PythonProjects
/__repr__example.py
540
4.34375
4
import datetime class Car: def __init__(self, color, mileage): self.color = color self.mileage = mileage def __repr__(self): return '__repr__ for Car' def __str__(self): return '__str__ for Car' myCar = Car('red', 37281) print(myCar) '{}'.format(myCar) print(str([myCar])) print(repr(myCar)) today = datetime.date.today() print() '''str is used for clear representation for someone to read''' print(str(today)) print() '''repr is used for debugging for developers''' print(repr(today))
true
2e0c3573ed6698fa45e56983fb5940dc57daeb94
odai1990/madlib-cli
/madlib_cli/madlib.py
2,673
4.3125
4
import re def print_wecome_mesage(): """ Print wilcome and explane the game and how to play it and waht the result Arguments: No Arguments Returns: No return just printing """ print('\n\n"Welcome To The Game" \n\n In this game you will been asked for enter several adjectives,nouns,numbers and names and collect these and put them in a funny paragraph.\n\n Be Ready ') def read_template(file_name): """ Reading file and return it to other function Arguments: n:string --- ptha file Returns: String of all countent of ifle """ try: with open(file_name) as file: content_text=file.read() except Exception: raise FileNotFoundError("missing.txt") return content_text def parse_template(content_text): """ Saprate text form each location will replace it inputs user Arguments: content_text:string --- test Returns: list contane stripted text and what we stripted in tuple """ all_changes=re.findall('{(.+?)}',content_text) all_text_stripted=re.sub("{(.+?)}", "{}",content_text) return all_text_stripted,tuple(all_changes) def read_from_user(input_user): """ Reaing inputs from user Arguments: input_user:string --- to let users knows waht he should insert Returns: string of waht user input """ return input(f'> Please Enter {input_user}: ') def merge(*args): """ put every thing toguther what user input and stripted text Arguments: args:list --- list of wat user input and stripted text Returns: return text merged with user inputs """ return args[0].format(*args[1]) def save(final_content): """ save the file to specifec location with final content Arguments: path:string --- the path where you whant to add final_content:string --- final text Returns: none/ just print result """ with open('assets/result.txt','w') as file: file.write(final_content) print(final_content) def start_game(): """ Strating the game and mangae the order of calling functions Arguments: none Returns: none """ print_wecome_mesage() content_of_file=parse_template(read_template('assets/sample.txt')) save(merge(content_of_file[0],map(read_from_user,content_of_file[1]))) def test_prompt(capsys, monkeypatch): monkeypatch.setattr('path.to.yourmodule.input', lambda: 'no') val = start_game() assert not val if __name__ == '__main__': start_game()
true
07cd0f2a3208e04dd0c34a501b68de19f692c35a
Temesgenswe/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
364
4.3125
4
#!/usr/bin/python3 """Module defines append_write() function""" def append_write(filename="", text=""): """Appends a string to a text file Return: the number of characters written Param: filename: name of text file text: string to append """ with open(filename, 'a', encoding="UTF8") as f: return f.write(str(text))
true
86e76c7aa9c052b23b404c05f57420750a5029b7
Temesgenswe/holbertonschool-higher_level_programming
/0x06-python-classes/103-magic_class.py
751
4.4375
4
#!/usr/bin/python3 import math class MagicClass: """Magic class that does the same as given bytecode (Circle)""" def __init__(self, radius=0): """Initialize radius Args: radius: radius of circle Raises: TypeError: If radius is not an int nor a float """ self.__radius = 0 if type(radius) is not int and type(radius) is not float: raise TypeError('radius must be a number') self.__radius = radius def area(self): """Returns the calculated area of circle""" return self.__radius ** 2 * math.pi def circumference(self): """Returns the calculated circumference of circle""" return 2 * math.pi * self.__radius
true
d3e203ffb4eac1ffe1bd1776de5f06220b81b6c1
LorenzoChavez/CodingBat-Exercises
/Warmup-1/sum_double.py
231
4.15625
4
# Given two int values, return their sum. Unless the two values are the same, then return double their sum. def sum_double(a, b): result = 0 if a == b: result = (a+b) * 2 else: result = a+b return result
true
7ce2d175697104c3df72fd437f9fe01fc0ed5053
alxanderapollo/HackerRank
/WarmUp/salesByMatchHR.py
1,435
4.3125
4
# There is a large pile of socks that must be paired by color. Given an array of integers # representing the color of each sock, determine how many pairs of socks with matching colors there are. # Example # There is one pair of color and one of color . There are three odd socks left, one of each color. # The number of pairs is . # Function Description # Complete the sockMerchant function in the editor below. # sockMerchant has the following parameter(s): # int n: the number of socks in the pile # int ar[n]: the colors of each sock # Returns # int: the number of pairs # Input Format # The first line contains an integer , the number of socks represented in . # The second line contains space-separated integers, , the colors of the socks in the pile. def sockMerchant(n, ar): mySet = set() #hold all the values will see count = 0 #everytime we a see a number we first check if it is already in the set #if it is delete the number for i in range(n): if ar[i] in mySet: mySet.remove(ar[i]) count+=1 else: mySet.add(ar[i]) return count #add one to the count #otherwise if we've never seen the number before add it to the set and continue #once we are done with the array #return the count n = 9 ar = [10,20 ,20, 10, 10, 30, 50, 10, 20] print(sockMerchant(n, ar))
true
3b38c1507501d451d741da0daa812a4f63152941
kushagra65/Python-CLock-Project
/ANALOG CLOCK.py
2,034
4.28125
4
#import the essential modules import time# importing the time module import turtle #importing the turtle module from the LOGO days #---------------------------------------------------------------- #creating the screen of the clock wn = turtle.Screen()#creating a screen wn.bgcolor("black")#setting the backgroung color wn.setup(width=600, height=600)#setting the size of the screen wn.title("analog clock @ kushagra verma") wn.tracer(0)#sets the animation time ,see in the while loop #--------------------------------------------------------------------------- #creating our drawing pen pen = turtle.Turtle()# create objects pen.hideturtle() pen.speed(0) # animation speed pen.pensize(5) # widht of the pens the pen is drawing def DrawC(h,m,s,pen):# creates min,hr,sec hands #drawing a clock face pen.penup() #means dont draw a line pen.goto(0, 210) pen.setheading(180)#pen facing to the left pen.color("orange")#color of the circle pen.pendown() pen.circle(210) #now drawing lines for the hours pen.penup() pen.goto(0, 0) pen.setheading(90) for _ in range(12): pen.fd(190) pen.pendown() pen.fd(20) pen.penup() pen.goto(0,0) pen.rt(30) # Drawing the hour hand pen.penup() pen.goto(0,0) pen.color("blue") pen.setheading(90) angle = (h / 12) * 360 pen.rt(angle) pen.pendown() pen.fd(100) #drawing the minite hand pen.penup() pen.goto(0,0) pen.color("gold") pen.setheading(90) angle=( m / 60 ) * 360 pen.rt(angle) pen.pendown() pen.fd(180) # Drawing the sec hand pen.penup() pen.goto(0,0) pen.color("yellow") pen.setheading(90) angle=( s / 60 ) * 360 pen.rt(angle) pen.pendown() pen.fd(50) while True: h=int(time.strftime("%I")) m=int(time.strftime("%M")) s=int(time.strftime("%S")) DrawC(h,m,s,pen) wn.update() time.sleep(1) pen.clear() #after exiting the loop a error will show ignore the error
true
e783154304256165ff443159d4181209454d2e08
kanishk333gupta/Elementary-Signals-in-continuous-and-discrete-time
/Exponential signal.py
1,765
4.34375
4
#EXPONENTIAL SIGNAL import numpy as np #Importing all definitions from the module and shortening as np import matplotlib.pyplot as mplot #Shortening as mplot ,an alias to call the library name ###CONTINUOUS x = np.linspace(-1, 2, 100) # 100 linearly spaced numbers from -1 to 2 xCT = np.exp(x) # Exponent function mplot.plot(x , xCT) # Plot a exponential signal mplot.xlabel('x') # Give X-axis label for the Exponential signal plot mplot.ylabel('exp(x)') # Give Y-axis label for the Exponential signal plot mplot.title('Exponential Signal in Continuous Time')#Give a title for the Exponential signal plot mplot.grid() # Showing grid mplot.show() # Display the Exponential signal ###DISCRETE #Defining a function to generate DISCRETE Exponential signal # Initializing exponential variable as an empty list # Using for loop in range # and entering new values in the list # Ends execution and return the exponential value def exp_DT(a, n): exp = [] for range in n: exp.append(np.exp(a*range)) return exp a = 2 # Input the value of constant n = np.arange(-1, 1, 0.1) #Returns an array with evenly spaced elements as per the interval(start,stop,step ) x = exp_DT(a, n) # Calling Exponential function mplot.stem(n, x) # Plot the stem plot for exponential wave mplot.xlabel('n') # Give X-axis label for the Exponential signal plot mplot.ylabel('x[n]') # Give Y-axis label for the Exponential signal plot mplot.title('Exponential Signal in Discrete Time') # Give a title for the exponential signal plot mplot.grid() # Showing grid mplot.show() # Display the exponential signal
true
26864be554f52e6a3dc2cee5455de74599228579
angellovc/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
355
4.15625
4
#!/usr/bin/python3 """ number_of_lines function module """ def number_of_lines(filename=""): """Get the numbers of lines into a text file Keyword Arguments: filename {str} -- [text file] """ with open(filename, mode="r", encoding="UTF8") as f: lines = 0 for line in f: lines += 1 return lines
true
687e728de6afc1a57f322db9204a20957055b25c
angellovc/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,770
4.125
4
#!/usr/bin/python3 """ Matrix_divided functions module """ def matrix_divided(matrix, div): """ Make a division of all the elements into the matrix by a div number returns a new result list Args: matrix: matrix of dividends, just floats or integers are allowed div: that's represent the divisor, you cannot use 0, because division by zero in imposible """ is_matrix = all(isinstance(element, list) for element in matrix) if is_matrix is False: # check if matrix is really a matrix errors("no_matrix_error") length = len(matrix[0]) # check the corrent length for row in matrix: if length != len(row): errors("len_error") for row in matrix: # check if the elements into the matrix are numbers if len(row) == 0: errors("no_number_error") for element in row: if type(element) not in [int, float]: errors("no_number_error") if div == 0: errors("zero_error") if type(div) not in [int, float]: errors("div_not_number") new_matrix = [] def division(dividend): return round((dividend / div), 2) for i in range(0, len(matrix)): # make the matrix division new_matrix.append(list(map(division, matrix[i]))) return new_matrix def errors(error): # errors list if error == "len_error": raise TypeError("Each row of the matrix must have the same size") if error in ["no_number_error", "no_matrix_error"]: raise TypeError("matrix must be a matrix (list of lists) \ of integers/floats") if error == "zero_error": raise ZeroDivisionError("division by zero") if error == "div_not_number": raise TypeError("div must be a number")
true
f0c1ca32d74b47203d48ebe82b5520069a1bdacc
angellovc/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
515
4.21875
4
#!/usr/bin/python3 """ read_lines module """ def read_lines(filename="", nb_lines=0): """read and print n number of lines into a text file Keyword Arguments: filename {str} -- [text file] (default: {""}) nb_lines {int} -- [n lines to read] (default: {0}) """ with open(filename, mode="r", encoding="UTF8") as f: lines = 0 for line in f: print(line, end="") lines += 1 if nb_lines > 0 and lines >= nb_lines: break
true
13ecec23ce620311c11f33da1ba3bba90cbd7fec
angellovc/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/100-print_tebahpla.py
241
4.4375
4
#!/usr/bin/python3 """ print the ascii alphabet in reverse using upper and lower characters""" for lower, upper in zip(range(122, 96, -2), range(89, 64, -2)): print("{}{}".format(chr(lower), chr(upper)), end='') # print ascii numbers
true
70a97b65e8cb2c963b0ae981b52ae5b191743d57
emmaAU/CSC280
/Random.py
575
4.125
4
#import random #print(random.random) import math print(math) a = int(input('enter coefficient for x**2 ')) b = int(input('enter b: ')) c = int(input('what is c?: ')) disc = b**2 - 4*a*c if disc > 0: root1 = -b + math.sqrt(disc) / 2*2 print(root1) root2 = -b - math.sqrt(disc) / 2*2 print(root2) elif disc == 0: root1 = root2 = -b / 2*2 else: print('no roots') product = 1 n = int(input('please enter a value you want to compute its factorial')) for i in range(2, n+1): product = product * i print('the factorial of', n, 'is, product')
true
57eb63f9f063deda592db8a58ebf420737f5f37c
etridenour/digitalCrafts
/classNotes/python/class7-2.py
2,516
4.3125
4
# class MyClass: # def SayHello(): # print("Hello there!") # MyClass.SayHello() class Person: def greet (self): #self points to object you are creating (ex. me, matt) print("Hello") me = Person() me.greet() matt = Person() matt.greet() # class MyClass: # Greeting = " " # lcass variable, available to all objects # def __init__(self): # print("Upon Initialization: Hello!") # def instance_method(self): #creates space to be filled in, self has to be there to let it know what to reference # print("Hello {0}".format(self.Greeting)) # def class_method(): # this is a class method because it doesn't have self # print("Hello {0}".format(self.Greeting)) # digitalCrafts = MyClass() # flatIrons = MyClass() # flatIrons.instance_method() # MyClass.Greeting = 'Eric' #set global variable equal to greeting, can change the name and will change in output # digitalCrafts.instance_method() # utAustin = MyClass() # utAustin.instance_method() # # digitalCrafts.instance_method() # # # MyClass.class_method() #calling a class method, this needs myClass before # # test.class_method() # class Person: # GlobalPerson = "Zelda" # global variable # def __init__ (self, name): # self.name = name #set instance variable # print(name) # def greet (self, friend): # instance method # print("Hello {} and {} and {}".format(self.name, friend, self.GlobalPerson)) # matt = Person('Fisher') # matt.greet("Travis") # person1 = Person('Hussein') # person1.greet("Skyler") # Person.GlobalPerson = 'Eric' # matt.greet('Travis') # person1.greet('Skyler') # class Person: # def __init__ (self, name): #constructor # self.name = name # self.count = 0 # def greet (self): # self._greet() # def _greet (self): # self.count += 1 # if self.count > 1: # print("Stop being so nice") # self.__reset_count() # else: # print("Hello", self.name) # def __reset_count(self): # self.count = 0 # matt = Person('Fisher') # matt.greet() #calling function # matt.greet() # matt.greet() # travis = Person('Ramos') #only prints hello ramos because it is it's own thing, even though went through same class # travis.greet() # class Animal: # def __init__ (self, name): # self.name = name # class Dog (Animal): #what you inherit goes in (), in this case animal # def woof (self): # print("Woof") # class Cat (Animal): # def meow (self): # print("Meow") super().__init__(power, health)
true
4f7ff64e0ec87b80e8689e8d484f9c0cefd3fbdf
ParkerCS/ch18-19-exceptions-and-recursions-aotoole55
/recursion_lab.py
1,152
4.78125
5
''' Using the turtle library, create a fractal pattern. You may use heading/forward/backward or goto and fill commands to draw your fractal. Ideas for your fractal pattern might include examples from the chapter. You can find many fractal examples online, but please make your fractal unique. Experiment with the variables to change the appearance and behavior. Give your fractal a depth of at least 5. Ensure the fractal is contained on the screen (at whatever size you set it). Have fun. (35pts) ''' import turtle color_list = ['red', 'yellow', 'orange', 'blue'] def circle(x, y, radius, iteration): my_turtle = turtle.Turtle() my_turtle.speed(0) my_turtle.showturtle() my_screen = turtle.Screen() #Color my_turtle.pencolor(color_list[iteration % (len(color_list[0:4]))]) my_screen.bgcolor('purple') #Drawing my_turtle.penup() my_turtle.setposition(x, y) my_turtle.pendown() my_turtle.circle(radius) #Recursion if radius <= 200 and radius > 1: radius = radius * 0.75 circle(25, -200, radius, iteration + 1) my_screen.exitonclick() circle(25, -200, 200, 0)
true
6efd603459989c8fa85b848c52d05a96a2ff8a74
peluza/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
719
4.5625
5
#!/usr/bin/python3 """3-say_my_name """ def say_my_name(first_name, last_name=""): """say_my_name Arguments: first_name {str} -- the value is the first_name Keyword Arguments: last_name {str} -- the value is the las_name (default: {""}) Raises: TypeError: first_name must be a string TypeError: last_name must be a string Returns: str -- My name is <first name> <last name> """ if type(first_name) is not str: raise TypeError("first_name must be a string") if type(last_name) is not str: raise TypeError("last_name must be a string") result = print("My name is {} {}".format(first_name, last_name)) return result
true
428fd8714cd7c2542af1000822bf90da9dd58847
linleysanders/algorithms
/Homework Week One (Average of Averages)/Linley Sanders Week One Homework.py
2,609
4.28125
4
# coding: utf-8 # # Lede Algorithms -- Assignment 1 # # In this assignment you will use a little algebra to figure out how to take the average of averages. # In[1]: import pandas as pd import matplotlib.pyplot as plt import requests get_ipython().run_line_magic('matplotlib', 'inline') # First, read in the titanic.csv data set. # In[2]: df = pd.read_csv("titanic.csv") df.head() # Compute the average survival rate (mean of the `survived` column) # In[3]: df['survived'].mean() # Now compute the average survival rates of the male and female 1st, 2nd, and 3rd class passengers (six groups in total) # In[31]: df.groupby(by='gender')['survived'].count() # In[32]: df.groupby(by='gender')['survived'].value_counts() # ## Male Survival Rate: 16.70% # ## Female Survival Rate: 66.30% # In[35]: 142/850 # In[34]: 307/463 # In[37]: df.groupby(by='pclass')['survived'].count() # In[36]: df.groupby(by='pclass')['survived'].value_counts() # ## First Class Survival Rate: 59.93% # ## Second Class Survival Rate: 42.5% # ## Third Class Survival Rate: 19.26% # In[38]: 193/322 # In[39]: 119/280 # In[40]: 137/711 # Compute the average of these six averages. Is it the same as the the overall average? # In[43]: #It's not the same as the overall average—it is higher (34.19+16.70+66.30+59.93+42.5+19.26)/(6) # How would you compute the overall average from the average of averages? Start with the formulas # # $$mean = \frac{\sum_{i=1}^N x_i}{N}$$ # # for the overall mean, where $x_i$ is data value $i$ and $N$ is the total number of values, and # # $$mean_k = \frac{\sum_{i=1}^{N_k} xk_i}{N_k}$$ # # is the mean of group $k$, where $xk_i$ is value $i$ of group $k$ and $N_k$ is the number of values in group $k$, and # # $$N = \sum_{i=1}^M N_k$$ # # relates the total number of values $N$ to the number of values in each of the $M$ groups. # # Your task is to derive a formula that computes $mean$ using only $mean_k$, the $N_k$, and $N$. Note: this question is not asking you to write code! Rather, you must answer two questions: # # - What is the correct formula? # - How can we derive this formula starting from the formulas above? # ## Answer / Response: # # The first formula is the calculation overall for mean. The second formula is the calculation for a group (a column), as the extra variable K. Big N is equal to the sum of the values, and Nk would give the total number of people in a column. I think the solution would be to take 1/6 of each percentage and # Now use this formula to calculate the overall mean. Does it match?
true
fbb3938b667cba8afe5144c023cacbd833028f03
crashtack/exercism
/python/clock/clock.py
1,144
4.34375
4
class Clock(object): """ A Clock class that ignores date """ def __init__(self, hours=0, minutes=0): """ Initialize the Clock object """ self.hours = hours % 24 self.minutes = minutes self.time_min = (self.hours * 60) + self.minutes self.time_min = self.time_min % 1440 def add(self, minute=0): """ Add minutes to the time and check for overflow """ self.time_min += minute self.time_min = self.time_min % 1440 return self.__str__() def __eq__(self, other): """ Check if time_min is equal """ if isinstance(other, self.__class__): return self.time_min == other.time_min else: return False def __ne__(self, other): """ Check if time_min is not equal """ return not self.__eq__(other) def __hash__(self): """ Return a hash of the time value """ return hash(self.time_min) def __str__(self): """ Returns the hh:mm time format """ return '{:02d}:{:02d}'.format( int(self.time_min / 60) % 24, self.time_min % 60 )
true
deb0106dadea39101d8c40357c3f41f9383a9937
GarryK97/Python
/Hashtable/Task5.py
2,715
4.4375
4
from Task3 import HashTable def read_file_removesp(file_name): """ Read a text file and convert it to a list of words without any special characters. :param file_name: File to read :return: the list of words """ f = open(file_name, 'rt', encoding='UTF8') file_list = [] for line in f: line = line.strip() # Remove whitespaces line = line.split(" ") # Split by words for i in range(len(line)): word_nosp = "" # String that will store word with no special character line[i] = line[i].lower() # Lower the word to make search easy for char in line[i]: # for each character in word, if char.isalpha(): # if the character is not special character (if it is alphabet), word_nosp += char # Add it to word_nosp if word_nosp != "": # To prevent adding white spaces and already existing words file_list.append(word_nosp) # Append the word with no special character f.close() return file_list book1 = read_file_removesp("Book1.txt") book2 = read_file_removesp("Book2.txt") book3 = read_file_removesp("Book3.txt") book_hashtable = HashTable(399989, 1091) # Making a hash table for books in [book1, book2, book3]: for word in books: try: count = book_hashtable[word] # if the word exists in hash table, count will store the value of it book_hashtable[word] = count + 1 # + 1 count except KeyError: book_hashtable[word] = 1 # If the word does not exist in hash table, it means a new word needs to be added # Making a non-duplicate words list words_list = [] for books in [book1, book2, book3]: for word in books: if word not in words_list: words_list.append(word) # Finding Maximum max_count = 0 max_word = "" for word in words_list: if book_hashtable[word] > max_count: # if word count > current maximum word count, max_count = book_hashtable[word] # Change to new max count and word max_word = word # Finding common, uncommon, rare words common_words = [] uncommon_words = [] rare_words = [] for word in words_list: # Zipf's law in simple python code if book_hashtable[word] > (max_count / 100): common_words.append(word) elif book_hashtable[word] > (max_count / 1000): uncommon_words.append(word) else: rare_words.append(word) print("Number of common words : " + str(len(common_words))) # Prints the result print("Number of uncommon words : " + str(len(uncommon_words))) print("Number of rare words : " + str(len(rare_words)))
true
606de1aa9e681af56f022880698088b3ea58904d
nidakhawar/PracticePythonExcercises
/AverageOfSubjects.py
510
4.1875
4
biology=float(input("Please input your Biology score:")) chemistry=float(input("Please input your Chemistry score:")) physics=float(input("Please input your Physics score:")) if biology<40: print("Fail") if chemistry<40: print("Fail") if physics<40: print("Fail") else: score=((biology+chemistry+physics)/3) if score >=70: print("first") elif score>=60: print("2.1") elif score>=50: print("pass") elif score>=40: print("pass") else: print("fail")
true
976cc8ab3327128b679d3d205e8c2dc1b2daae0b
zacharykaczor/Small-Programs
/odd_numbers.py
535
4.1875
4
# Based on https://www.youtube.com/watch?v=LkIK8f4yvOU. # The Difference of Two Squares. number = int(input("Please enter a positive odd number: ")) while number % 2 == 0 or number < 0: number = int(input( "Please enter a positive number: " if number < 0 else "Please enter an odd number: " )) root_2 = number // 2 root_1 = root_2 + 1 print(f"The roots are { root_1 } and { root_2 }.") print(f"The squares are { root_1 ** 2 } and { root_2 ** 2 }.") print(f"{ root_1 ** 2 } - { root_2 ** 2 } = { number }.")
true
bce8bf614aca3883f2ac618caa8f00bc32a5dd73
costacoz/python_design_patterns
/behavioral/iterator.py
1,296
4.5
4
# Iterators are built into Python. # It can be engaged, using 'iter(arg*)' function # arg* - can be list, tuple, dic, set and string. # Below is the example of using it. # fruits_tuple = {'apple', 'blueberry', 'cherry', 'pineapple'} # fruits_tuple = ('apple', 'blueberry', 'cherry', 'pineapple') # fruits_tuple = ['apple', 'blueberry', 'cherry', 'pineapple'] fruits_tuple = 'apples' fruits_iterator = iter(fruits_tuple) print(next(fruits_iterator)) print(next(fruits_iterator)) print(next(fruits_iterator)) print(fruits_iterator.__next__()) # Loop through an iterator fruits_tuple = ('apple', 'blueberry', 'cherry', 'pineapple') for f in fruits_tuple: print(f) # # To create an iterator manually we need to implement iter and next # in __iter__ we initialize iterator, same as in __init__, and return iterator class Iterator: def __iter__(self): self.a = 2 return self # must always return iterator object def __next__(self): if self.a < 10: x = self.a self.a += 1 return x else: raise StopIteration # to stop iterator in loop iterable_obj = Iterator() # iterator = iter(iterable_obj) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) for i in iterable_obj: print(i)
true
db6a67f488a152ccc2768d3d24728afb318f10de
CodecoolBP20172/pbwp-3rd-si-code-comprehension-kristofilles
/comprehension.py
2,101
4.3125
4
"""Its a bot what randomly choose a number between 1 and 20, and the user need to guess within 6 round what number was choosen by the bot.""" import random #import the random module guessesTaken = 0 #assign 0 to guessesTaken variable print('Hello! What is your name?') #print out this sentence myName = input() #assign a user input to myName variable number = random.randint(1, 20) #assign a randomly choosen integer(between 1 and 20) to number variable print('Well, ' + myName + ', I am thinking of a number between 1 and 20.') #printing out this sentence with the given name while guessesTaken < 6: #loop while the guessesTaken variable is less then 6 print('Take a guess.') #print out this sentence guess = input() #assign a user input to guess variable guess = int(guess) #making type conversion changing the value of the guess variable to integer from string guessesTaken += 1 #increasing the value of the guessesTaken by 1 if guess < number: #doing something if guess value is lower than number value print('Your guess is too low.') #if its true print out this sentence if guess > number: #doing something if the guess value is higher than the number value print('Your guess is too high.') #if its true print out this sentence if guess == number: #doing something if the guess value is equal with the number value break #if its true the loop is immediately stop if guess == number: #doing something if the guess value is equal with the number value guessesTaken = str(guessesTaken) #making type conversion changing the value of the guessesTaken variable to string from integer print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!') #print out how many try needed to the user to guess out if guess != number: #doing something if guess value is not equal with number value number = str(number) #making type conversion changing the value of the number variable to string from integer print('Nope. The number I was thinking of was ' + number) #print out the randomly choosen number
true
07bd3a329eafee4c2398a08943aeb985a282b6f2
onionmccabbage/pythonTrainingMar2021
/using_ternary.py
474
4.40625
4
# Python has one ternary operator # i.e. an operator that takes THREE parts # all other operators are binary, i.e. they take TWO parts # e.g. a = 1 or 3+2 # the ternary operator works like this # 'value if true' 'logical condition' 'value if false' x = 6 y = 5 print("x" if x>y else "y") # alternative syntax for the ternary operator nice = False personality = ("horrid", "lovely")[nice] # spot the index 0 or 1 print("My cat is {}".format(personality)) #
true
375b0579cdbe45e4a66d954f8d5e767f8ef70546
justEhmadSaeed/ai-course-tasks
/Python Assignment 1/Part 2/Task 5.py
261
4.28125
4
# Write a list comprehension which, from a list, generates a lowercased version of each string # that has length greater than five strings = ['Some string', 'Art', 'Music', 'Artifical Intelligence'] for x in strings: if len(x) > 5: print(x.lower())
true
f21b75948484cc34cea7d9d166dc47e72611749d
liadbiz/Leetcode-Solutions
/src/python/degree_of_array.py
1,373
4.15625
4
""" Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. Example 1: Input: [1, 2, 2, 3, 1] Output: 2 Explanation: The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2. Example 2: Input: [1,2,2,3,1,4,2] Output: 6 Note: nums.length will be between 1 and 50,000. nums[i] will be an integer between 0 and 49,999. """ class Solution: def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ import collections import operator fre_dict = collections.Counter(nums).most_common() max_fre = max(fre_dict, key = operator.itemgetter(1))[1] def fre_sub(i): return len(nums) - nums.index(i) - nums[::-1].index(i) return min(fre_sub(i[0]) for i in fre_dict if i[1] == max_fre) if __name__ == "__main__": nums1 = [1, 2, 2, 3, 1] nums2 = [1,2,2,3,1,4,2] print(Solution().findShortestSubArray(nums1)) print(Solution().findShortestSubArray(nums2))
true
bbeb124cd35e865c17ae7a9691022031b81ba553
jonahtjandra/sudoku-solver
/Sudoku.py
2,939
4.15625
4
class Sudoku: def __init__(self, board:'list[list]') -> None: if (len(board) != 9 or len(board[0]) != 9): raise "Expected a 9 by 9 board" self.board = board self.iterations = [] # for printing out the 2d list representation of the board def display(self, board:'list[list]'): if (len(board) != 9): print("Not a valid 9x9 sudoku board!") return x = 0 for i in range(len(board)+4): if (i==0 or i==4 or i==8 or i==12): print('-------------------------') continue y = 0 for j in range(len(board)+4): if (j == 0 or j==4 or j==8): print('|', end=' ') elif (j == 12): print('|') else: print(board[x][y], end=' ') y += 1 x += 1 # method to check if a certain number, n, is valid to be # place at a certain x and y coordinate in the board def isPossible(self, x:int, y:int, n:int) -> bool: if (x > 8 and y > 8 and n >= 0 and n <= 9): return False #horizontal check for i in range(9): if (self.board[x][i] == n and i != y): return False #vertical check for i in range(9): if (self.board[i][y] == n and i != x): return False #square check square_x = x // 3 square_y = y // 3 for i in range(3): for j in range(3): if (self.board[square_x * 3 + i][square_y * 3 + j] == n and x != square_x * 3 + i and y != square_y * 3 + j): return False #possible placement return True # Method to check if solution is correct def isSolution(self) -> bool: for i in range(9): for j in range(9): if (not(self.isPossible(self.board, i, j, self.board[i][j]))): return False return True # Method to find the next empty coordinate in the board # Returns false if there are no empty space left (solved) def nextEmpty(self, loc:list) -> bool: for i in range(9): for j in range(9): if (self.board[i][j] == '.'): loc[0] = i loc[1] = j return True return False # Method to solve the board # Returns false if board is not solveable def solve(self) -> bool: loc = [0,0] if (not self.nextEmpty(loc)): return True i = loc[0] j = loc[1] for n in range(1,10): if (self.isPossible(i, j, n)): self.board[i][j] = n self.display(self.board) if (self.solve()): return True self.board[i][j] = '.' return False
true
53da6c914c6b7139abf47e3b214b47725e93c50b
comalvirdi/CPE101
/LAB4/loops/cubesTable.py
1,518
4.3125
4
# CPE 101 Lab 4 # Name: def main(): table_size = get_table_size() while table_size != 0: first = get_first() increment = get_increment() show_table(table_size, first, increment) table_size = get_table_size() # Obtain a valid table size from the user def get_table_size(): size = int(input("Enter number of rows in table (0 to end): ")) while (size) < 0: print ("Size must be non-negative.") size = int(input("Enter number of rows in table (0 to end): ")) return size; # Obtain the first table entry from the user def get_first(): first = int(input("Enter the value of the first number in the table: ")) while (first) < 0: print ("First number must be non-negative.") first = int(input("Enter the value of the first number in the table: ")) return first; def get_increment(): increment = int(input("Enter the increment between rows: ")) while (increment) < 0: print ("Increment must be non-negative.") increment = int(input("Enter the increment between rows: ")) return increment; # Display the table of cubes def show_table(size, first, increment): print ("A cube table of size %d will appear here starting with %d." % (size, first)) print ("Number Cube") sum = 0 for num in range (first, first+ size * increment, increment): print ("{0:<7} {1:<4}" .format(num, num**3)) sum += num**3 print ("\nThe sum of cubes is:", sum, "\n") if __name__ == "__main__": main()
true
e9cb86ab9b68ed4b6f0c061f48629cb0eb270316
lguychard/loispy
/src/loispy/interpreter/procedure.py
2,279
4.28125
4
from environment import Environment class Procedure(object): """ Represents a loisp procedure. A procedure encapsulates a body (sequence of instructions) and a list of arguments. A procedure may be called: the body of the procedure is evaluated in the context of an environment, and given """ def __init__(self, env, args, body, name=""): """ @param Environment env @param list[str] args @param function body @param str name """ self.env = env self.args = args # Check now if the procedure has variable arguments self.numargs = -1 if len(args) >= 1 and "..." in args[-1] else len(self.args) if self.numargs == -1: self.numpositional = len(self.args) -1 self.positional = self.args[:self.numpositional] self.vararg = self.args[-1].replace("...", "") self.body = body self.name = name def __call__(self, *argvals): """ 'the procedure body for a compound procedure has already been analyzed, so there is no need to do further analysis. Instead, we just call the execution procedure for the body on the extended environment.' [ABELSON et al., 1996] """ call_env = Environment(self.pack_args(argvals), self.env) return self.body.__call__(call_env) def pack_args(self, argvals): """ Return a dict mapping argument names to argument values at call time. """ if self.numargs == -1: if len(argvals) <= self.numpositional: raise Exception("Wrong number of arguments for '%s' (%d)" % (self.name, len(argvals))) _vars = dict(zip(self.positional, argvals[:self.numpositional])) _vars.update({self.vararg : argvals[self.numpositional:]}) else: if len(argvals) != self.numargs: raise Exception("Wrong number of arguments for '%s' (%d)" % (self.name, len(argvals))) _vars = dict(zip(self.args, argvals)) return _vars def __str__(self): return "<Procedure %s>" % self.name if self.name else "<Procedure>" def __repr__(self): return self.__str__()
true
2fa3fbd312b86064da4f77d85dd226575de9dcaf
Heisenberg27074/Web-Scraping-with-Python3
/lists/maxmin.py
724
4.3125
4
#Rewrite the program that prompts the user for a list of #numbers and prints out the maximum and minimum of the numbers at #the end when the user enters “done”. Write the program to store the #numbers the user enters in a list and use the max() and min() functions to #compute the maximum and minimum numbers after the loop completes. lst=list() while(1): snum=input("Enter a number") if snum =='done': break try: num=float(snum) lst.append(num) except:print('Please enter a number not anything else!!!') if len(lst)<1:print("There are no items to compare inside list, please enter some data") else: print('Maximum:',max(lst)) print('Minimum',min(lst))
true
75a6883fb38db72e5775e46f6e94e49a3c4a9978
dimitardanailov/google-python-class
/python-dict-file.py
1,842
4.53125
5
# https://developers.google.com/edu/python/dict-files#dict-hash-table ## Can build up a dict by starting with the empty dict {} ## and storing key / value pairs into the dict like this: ## dict[key] = value-for-that-key dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' print dict ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'} # Simple lookup, returns 'alpha' print dict['a'] ## alpha # Put new key / value into dict dict['a'] = 6 print dict ## {'a': 6, 'o': 'omega', 'g': 'gamma'} print 'a' in dict ## True if 'z' in dict: print dict['z'] ## Avoid KeyError ## By default, iterating over a dict iterates over its keys ## Note that the keys are in a random order for key in dict: print key ## prints a g o ## Exactly the same as above for key in dict.keys(): print key ## Get the .keys list: print dict.keys() ## ['a', 'o', 'g'] ## Common case --loop over the keys in sorted order, ## accessing each key/value for key in sorted(dict.keys()): print key, dict[key] ## .items() is the dict expressed as (key, value) tuples print dict.items() ## [('a', 6), ('o', 'omega'), ('g', 'gamma')] ## This loops syntax accesses the whole dict by looping ## over the .items() tuple list, accessing one (key, value) ## pair on each iteration. for k, v in dict.items(): print k, ' > ', v ## a > 6 ## o > omega ## g > gamma ## Dic formatting hash = {} hash['word'] = 'garfield' hash['count'] = 42 # %d for int, %s for string s = 'I want %(count)d copies of %(word)s' % hash print s # I want 42 copies of garfield ## Del var = 6 del var # var no more! list = ['a', 'b', 'c', 'd'] del list[0] ## Delete first element del list[-2:] ## Delete last two elements print list ## ['b'] dict = { 'a': 1, 'b': 2, 'c': 3} del dict['b'] ## Delete 'b' entry print dict ## {'a': 1, 'c': 3}
true
c7668e86b91ed2fbcaa51d0d4811ae448d0f2a14
RobDBennett/DS-Unit-3-Sprint-1-Software-Engineering
/module4-software-testing-documentation-and-licensing/arithmetic.py
1,941
4.21875
4
#!/usr/bin/env python # Create a class SimpleOperations which takes two arguements: # 1. 'a' (an integer) # 2. 'b' (an integer) # Create methods for (a, b) which will: # 1. Add # 2. Subtract # 3. Multiply # 4. Divide # Create a child class Complex which will inherit from SimpleOperations # and take (a, b) as arguements (same as the former class). # Create methods for (a, b) which will perform: # 1. Exponentiation ('a' to the power of 'b') # 2. Nth Root ('b'th root of 'a') # Make sure each class/method includes a docstring # Make sure entire script conforms to PEP8 guidelines # Check your work by running the script class SimpleOperations: """A constructor for simple math. Parameters- :var a: int :var b: int """ def __init__(self, a, b) -> None: self.a = a self.b = b def add(self): return self.a + self.b def subtract(self): return self.a - self.b def multiply(self): return self.a * self.b def divide(self): if self.b == 0: return f'Cannot divide by zero!' else: return self.a / self.b class Complex(SimpleOperations): """A constructor for more complicated math. :var a: int :var b: int """ def __init__(self, a, b) -> None: super().__init__(a, b) def exponentiation(self): return self.a ** self.b def nth_root(self): return round((self.a ** (1.0 / self.b)), 4) if __name__ == "__main__": print(SimpleOperations(3, 2).add()) print('-------------------') print(SimpleOperations(3, 2).subtract()) print('-------------------') print(SimpleOperations(3, 2).multiply()) print('-------------------') print(SimpleOperations(3, 2).divide()) print('-------------------') print(Complex(3, 2).exponentiation()) print('-------------------') print(Complex(3, 2).nth_root()) print('-------------------')
true
8a60d618f47ce9917bf2c8021b2863585af07672
sreesindhu-sabbineni/python-hackerrank
/TextWrap.py
511
4.21875
4
#You are given a string s and width w. #Your task is to wrap the string into a paragraph of width w. import textwrap def wrap(string, max_width): splittedstring = [string[i:i+max_width] for i in range(0,len(string),max_width)] returnstring = "" for st in splittedstring: returnstring += st returnstring += '\n' return returnstring if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
true
25001af33ac7a663e5f20810c42d5cba3ac73242
AhmedElkhodary/Python-3-Programming-specialization
/1- Python Basics/FinalCourseAssignment/pro5.py
620
4.15625
4
#Provided is a list of data about a store’s inventory where each item #in the list represents the name of an item, how much is in stock, #and how much it costs. Print out each item in the list with the same #formatting, using the .format method (not string concatenation). #For example, the first print statment should read The store has 12 shoes, each for 29.99 USD. inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"] item =[] for inv in inventory: item = inv.split(", ") print("The store has {} {}, each for {} USD.".format(item[1], item[0], item[2]))
true
a53c2faa1c8da8d9f736720d2f653811898ea67a
AhmedElkhodary/Python-3-Programming-specialization
/1- Python Basics/Week4/pro3.py
256
4.3125
4
# For each character in the string already saved in # the variable str1, add each character to a list called chars. str1 = "I love python" # HINT: what's the accumulator? That should go here. chars = [] for ch in str1: chars.append(ch) print(chars)
true
a1b182cd04c27dc9c000923a627c7e6cb2a2ff3b
DiegoCol93/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
2,275
4.25
4
#!/usr/bin/python3 """ Module for storing the Square class. """ from models.rectangle import Rectangle from collections import OrderedDict class Square(Rectangle): """ Por Esta no poner esta documentacion me cague el cuadrado :C """ # __init__ | Private | method |-------------------------------------------| def __init__(self, size, x=0, y=0, id=None): """ __init__: Args: size(int): Size of the Square object. x(int): Value for the offset for display's x position. y(int): Value for the offset for display's y position. """ super().__init__(size, size, x, y, id) # __str__ | Private | method |--------------------------------------------| def __str__(self): """ Returns the string for the Rectangle object """ return "[Square] ({}) {}/{} - {}".format(self.id, self.x, self.y, self.width) # update | Public | method |----------------------------------------------| def update(self, *args, **kwargs): """ Updates all attributes of the Rectangle object. """ if bool(args) is True and args is not None: try: self.id = args[0] self.size = args[1] self.x = args[2] self.y = args[3] except Exception as e: pass else: for i in kwargs.keys(): if i in dir(self): setattr(self, i, kwargs[i]) # to_dictionary | Public | method |---------------------------------------| def to_dictionary(self): """ Returns the dictionary representation of a Square object. """ ret_dict = OrderedDict() ret_dict["id"] = self.id ret_dict["size"] = self.width ret_dict["x"] = self.x ret_dict["y"] = self.y return dict(ret_dict) # Set & Get __width | Public | method |------------------------------------ @property def size(self): """ Getter of the Rectangle's width value. """ return self.width @size.setter def size(self, number): """ Setter of the Rectangle's width value. """ self.width = number self.height = number
true
971187848e721a42aec82fb6aa5d13f881d84ff4
johnmwalters/dsp
/python/q8_parsing.py
1,242
4.40625
4
# The football.csv file contains the results from the English Premier League. # The colums labeled 'Goals and 'Goals Allowed' contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in 'for' and 'against' goals. import csv def read_data(data): with open(data) as csvfile: reader = csv.DictReader(csvfile) low_diff = 9999 club = '' for row in reader: print row['Team'], row['Games'], row['Wins'], row['Losses'], row['Draws'],row['Goals'], row['Goals Allowed'], row['Points'] goal_difference = int(row['Goals']) - int(row['Goals Allowed']) abs_goal_difference = abs(int(row['Goals']) - int(row['Goals Allowed'])) print abs_goal_difference if abs_goal_difference < low_diff: club = row['Team'] print club low_diff = abs_goal_difference else: low_diff = low_diff print club # COMPLETE THIS FUNCTION #def get_min_score_difference(self, parsed_data): # COMPLETE THIS FUNCTION #def get_team(self, index_value, parsed_data): # COMPLETE THIS FUNCTION read_data('football.csv')
true
499b850f68b05aceb843bcd4f6f94c9cb1077afc
thales-mro/python-cookbook
/2-strings/4-pattern-match-and-search.py
1,181
4.125
4
import re def date_match(date): if re.match(r'\d+/\d+/\d+', date): print('yes') else: print('no') def main(): text = 'yeah, but no, but yeah, but no, but yeah' print(text.find('no')) date1 = '02/01/2020' date2 = '02 Jan, 2020' date_match(date1) date_match(date2) print("For multiple uses, it is good to compile the regex") datepat = re.compile(r'\d+/\d+/\d+') if datepat.match(date1): print("yes") else: print("no") if datepat.match(date2): print("yes") else: print("no") text = "Today is 02/01/2020. In a week it will be 09/01/2020." print(datepat.findall(text)) print("Including capture groups (in parenthesis)") datepat = re.compile(r'(\d+)/(\d+)/(\d+)') m = datepat.match('26/09/1998') print(m) print(m.group(0), m.group(1), m.group(2), m.group(3), m.groups()) print(datepat.findall(text)) for month, day, year in datepat.findall(text): print('{}--{}--{}'.format(year, month, day)) print("With finditer:") for m in datepat.finditer(text): print(m.groups()) if __name__ == "__main__": main()
true
881166784fd6a82253a5b189f956582a7a8de5e0
firebirdrazer/CodingTests
/check_paren.py
1,952
4.40625
4
def check_bracket(Str): stack = [] #make a empty check stack while Str != "": #as long as the input is not empty tChar = Str[0] #extract the first character as the test character Str = Str[1:] #the rest characters would be the input in the next while loop if tChar == "(" or tChar == "{": #as the test character is a left-bracket "(" or "{" stack.append(tChar) #the character would be added into the stack elif tChar == ")" or tChar == "}": #if the test character is a right-bracket ")" or "}" if len(stack) == 0: #then we have to check the stack to see if there's a corresponding one return False #if no or empty, the string would be invalid else: #if yes, we can pop the corresponding character from the stack if tChar == ")" and stack[-1] == "(": stack.pop(-1) elif tChar == "}" and stack[-1] == "{": stack.pop(-1) else: return False if stack == []: #which means if the string is valid, the stack would be empty return True #after the process else: #if there's anything left after the process return False #the function would return False #main program Test=input() #input string print(check_bracket(Test)) #return True if the input has valid brackets
true