blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
350a83984b3caf17099ade37124fac67b08f6cab
Jeremalloch/edX-6.00.1x
/Week 2/Credit card debt 2.py
878
4.25
4
#balance - the outstanding balance on the credit card #annualInterestRate - annual interest rate as a decimal #monthlyPaymentRate - minimum monthly payment rate as a decimal #Month: 1 #Minimum monthly payment: 96.0 #Remaining balance: 4784.0 #balance = 4213 #annualInterestRate = 0.2 #monthlyPaymentRate = 0.04 minimumPaymentTotal=0 for month in range(1,13): minimumPayment=round(balance*monthlyPaymentRate,2) unpaidBalance=balance-minimumPayment interest=round((annualInterestRate/12)*unpaidBalance,2) balance=unpaidBalance+interest print('Month: ' + str(month)) print('Minimum monthly payment: '+ str(minimumPayment)) print('Remaining balance: ' + str(balance)) minimumPaymentTotal+=minimumPayment remamingBalance=balance print('Total paid: '+str(minimumPaymentTotal)) print('Remaining balance: '+ str(remamingBalance))
true
7876bbb52fea9a7cce825001ec66dbb730307eca
richard-yap/Lets_learn_Python3
/module_11_file_ops.py
880
4.21875
4
#------------------------------File operations--------------------------------- f = open("file.txt", "r") #reading a File # "w" write File # "a" append file #teacher example: f = open("test.txt", "w") # write or overwrite it for i in range(10): f.write("This is line {}\n".format(i + 1)) #must write \n if not the text will keep going and going # you have to do this in order to view the file as the file is still in yr RAM, do this #and it will go to the hardisk f.close() # do it this way if you dw to forget to f.close() with open("test.csv", "a") as f # this is to add more things to the file (appending) for i in range(10): f.write("This is line {}\n".format(i + 1)) #if you want csv change it to .csv #getting uniquue words # save an article into article.txt first f = open("article.txt), "r") texr = f.read() len(set(text.split()))
true
b7cb25e3ad93ba04ec69d0d9e9b5764af206917e
fmeccanici/thesis_workspace
/gui/nodes/tutorials/getting_started.py
1,210
4.125
4
## https://techwithtim.net/tutorials/pyqt5-tutorial/basic-gui-application/ from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel import sys class MyWindow(QMainWindow): def __init__(self): super(MyWindow,self).__init__() self.initUI() def initUI(self): self.setGeometry(200,200,300,300) # sets the windows x, y, width, height self.setWindowTitle("My first window!") # setting the window titl self.label = QLabel(self) self.label.setText("my first label") self.label.move(50, 50) # x, y from top left hand corner. self.b1 = QtWidgets.QPushButton(self) self.b1.setText("click me") self.b1.move(100,100) # to move the button self.b1.clicked.connect(self.button_clicked) # inside main function def button_clicked(self): print("clicked") # we will just print clicked when the button is pressed self.label.setText("you pressed the button") self.update() def update(self): self.label.adjustSize() def window(): app = QApplication(sys.argv) win = MyWindow() win.show() sys.exit(app.exec_()) window()
true
2ebe3ca2166f2c0d23723d7b470649a980589bf8
pacefico/crackingcoding
/hackerrank/python/stacks_balanced_brackets.py
1,397
4.375
4
""" 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 (). url: https://www.hackerrank.com/challenges/ctci-balanced-brackets """ import re def is_matched(expression): open_brackets = ["[", "{", "("] close_brackets = ["]", "}", ")"] stack = [] for item in expression: if item in open_brackets: stack.append(item) else: if len(stack) == 0 or stack.pop() != open_brackets[close_brackets.index(item)]: return False return True if len(stack) == 0 else False def original_tests(): t = int(input().strip()) for a0 in range(t): expression = input().strip() if is_matched(expression) == True: print("YES") else: print("NO") def my_tests(): def case0(): return "{[()]}" def case1(): return "{[(])}" def case2(): return "{{[[(())]]}}" def case3(): return "{{[[(())]]}}[" assert is_matched(case0()) == True assert is_matched(case1()) == False assert is_matched(case2()) == True assert is_matched(case3()) == False my_tests()
true
404d0bb546bbdde263fecebafd3cbc2d692d8539
leasoussan/DIpython
/week5/w5d2/w5d2xp/w5d2xp.py
2,891
4.5
4
# # Exercise 1 : Pets # # Consider this code # class Pets(): # def __init__(self, animals): # self.animals = animals # def walk(self): # for animal in self.animals: # print(animal.walk()) # class Cat(): # is_lazy = True # def __init__(self, name, age): # self.name = name # self.age = age # def walk(self): # return f'{self.name} is just walking around' # def __repr__(self): # return self.name # # to get the name in representing # class Bengal(Cat): # def sing(self, sounds): # return f'{sounds}' # class Chartreux(Cat): # def sing(self, sounds): # return f'{sounds}' # class Persian(Cat): # def speak(self, sounds): # return f'{sounds}' # # # # # # Add another cat breed # # # Create a list of all of the pets (create 3 cat instances from the above) # # my_cats = [] # # # Instantiate the Pet class with all your cats. Use the variable my_pets # # # Output all of the cats walking using the my_pets instance # # cat1 = Bengal("Jojo",12) # # cat2 = Chartreux("Liri",6) # # cat3 = Persian("loan",3) # my_cats = [Bengal("Jojo",12), Chartreux("Liri",6), Persian("loan",3)] # # they inherit form Cat - creat 3 object from 3 a subclass of the class cat # my_pets = Pets(my_cats) # my_pets.walk() # # # # # # Exercise 2 : Dogs # Create a class named Dog with the attributes name, age, weight # Implement the following methods for the class: # bark: returns a string of “ barks”. # run_speed: returns the dogs running speed (weight/age *10). # fight : gets parameter of other_dog, # returns string of which dog won the fight between them, # whichever has a higher run_speedweight* should win. class Dog(): def __init__(self, name, age, weight): self.name = name self.age = age self.weight = weight def bark(self): print("Barks") def run_speed(self): return ((self.weight/self.age) * 10 ) def fight(self, other_dog): if (self.run_speed() * self.weight) > (other_dog.run_speed()* other_dog.weight): return f"{self.name} won the battle" return f"{other_dog.name} wont the battle" d1 = Dog("Jojo", 12, 12) d2 = Dog("Riri", 9, 16) d3 =Dog("Fifi", 4, 2) # Create 3 dogs and use some of your methods # TRY WITH CALL # class Dog(): # def __call__(self, name, age, weight): # self.name = name # self.age = age # self.weight = weight # def bark(self): # print("Barks") # def run_speed(self): # return ((self.weight/self.age) * 10 ) # def fight(self, other_dog): # other_dog = Dog() # if (self.run_speed * self.weight) > other_dog: # return f"{self.name} won the battle" # return f"{other_dog.name} wont the battle"
true
a149fd11632bbeca1fe86340029eec23e55cdb1a
leasoussan/DIpython
/week4/w4d3/w4d3xpninja.py
1,665
4.15625
4
# Don’t forget to push on Github # Exercise 1: List Of Integers - Randoms # !! This is the continuation of the Exercise Week4Day2/Exercise 2 XP NINJA !! # 2. Instead of asking the user for 10 integers, generate 10 random integers yourself. Make sure that these random integers lie between -100 and 100. # 3. Instead of always generating 10 integers, let the amount of integers also be random! Generate a random positive integer no smaller than 50. # 4. Go back and check all of your output! Does your code work correctly for a list of unknown length, or does it only work correctly for a list that has 10 items in it? # 5. # Exercise 2: Authentication CLI - Login: # Create a menu using a while loop and user input (see week 4 day 2 exercise xp7) # Create a dictionary that contains users: each key will represent a username, and each value will represent that users’ password. Start this dictionary with 3 users & passwords # Add a menu option to exit # Add a menu option called login: when a user selects login, take 2 inputs from him and check if they match up with any users in our dictionary # Print a message on if they logged in successfully or not # If successful try and store the username in a variable called logged_in so we can track it later # Exercise 3: Authentication CLI - Signup: # Continues authentication CLI - login # Add another option of signup to our menu: # Take input for username and make sure it doesn’t exist as a key in our dictionary, keep asking the user for a valid username as long as it is required # Take input for a password (do you want to add criteria to password strength? How would you go about implementing that?)
true
4f96e87e1178254694b5e1beafafe6599d25dc97
Ehotuwe/Py111-praktika1
/Tasks/a3_check_brackets.py
951
4.3125
4
def check_brackets(brackets_row: str) -> bool: """ Check whether input string is a valid bracket sequence Valid examples: "", "()", "()()(()())", invalid: "(", ")", ")(" :param brackets_row: input string to be checked :return: True if valid, False otherwise """ brackets_row = list (brackets_row) a = ')' b = '(' check = True if len(brackets_row) % 2: check = False else: while len (brackets_row) and check: if brackets_row[0] == b and brackets_row[1] == a: brackets_row.pop(0) brackets_row.pop(0) elif brackets_row[-1] == a and brackets_row[-2] == b: brackets_row.pop(-1) brackets_row.pop(-1) elif brackets_row[0] == b and brackets_row[-1] == a: brackets_row.pop(0) brackets_row.pop(-1) else: check = False return check
true
b781edf2a60aca47feb2a0800a8f3e2c8c27a2de
dkaimekin/webdev_2021
/lab9/Informatics_4/e.py
220
4.46875
4
number = int(input("Insert number: ")) def find_power_of_two(number): temp = 1 power = 0 while temp < number: temp *= 2 power += 1 return power print(find_power_of_two(number))
true
ef068651162e5a8954b8a0a9880c4810245f0d6e
hemanth430/DefaultWeb
/myexp21.py
1,462
4.40625
4
#sentence = "All good things come to those who wait" def break_words(stuff): """This funciton will break up words for us.""" words = stuff.split(' ') return words #This is used to split sentence into words , ouput = ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait'] def sort_words(words): """Sorts the words""" return sorted(words) #This is used to sort words , ['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who'] def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print word #Used to print the first word after popping it off , All def print_last_word(words): """Prints the last word after popping it off""" word = words.pop(-1) print word #Used to print the last word after popping it off , wait def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) #Takes a full sentence and return the sorted words def print_first_and_last(sentence): """Prints the first and last words of the sentence""" words = break_words(sentence) print_first_word(words) print_last_word(words) #returns the first and last word of the sentece def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words) #prints the first and last word of the sorted sentence
true
d09a68f92d09bcac8a5fedeb0455aa125d17921f
adonispuente/Intro-Python-I
/src/14_cal.py
2,500
4.53125
5
""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py [month] [year]` and does the following: - If the user doesn't specify any input, your program should print the calendar for the current month. The 'datetime' module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. Note: the user should provide argument input (in the initial call to run the file) and not prompted input. Also, the brackets around year are to denote that the argument is optional, as this is a common convention in documentation. This would mean that from the command line you would call `python3 14_cal.py 4 2015` to print out a calendar for April in 2015, but if you omit either the year or both values, it should use today’s date to get the month and year. """ import sys import calendar from datetime import datetime # bring in current day and time today = datetime.now() # print(today) # count the number of sys.argv arguments num_args = len(sys.argv) # print(num_args) # store the sys.argv arguments in an array arguments = sys.argv # print(arguments) # print(calendar.month) # - if no input # print the calendar for the current month if num_args == 1: print(calendar.month(today.year, today.month)) print(today) # - elif one input # assume the additional argument is the month and print that month for current year elif num_args == 2: month_num = int(sys.argv[1]) print(calendar.month(today.year, month_num)) # - elif two inputs # the fist will be the month, 2nd will be the year. We'll use those for the calendar. elif num_args == 3: month_num = int(sys.argv[1]) year_num = int(sys.argv[2]) print(calendar.month(year_num, month_num)) # - else more than 2 inputs # send error message else: # print a usage statement print( "Please provide numerical dates in the following format: 14_cal.py [month] [year]") # exit the program sys.exit(1)
true
afa43852fca155cd5aaad6d2bb91a02cbe4fd2e3
dnguyen289/Python
/nguyen_dana_payment.py
752
4.375
4
# Variables and Calculations 2 # Dana Nguyen June 22 2016 # Part 1: Monthly interest Rate Calculator # Calculate monthly payments on a loan # Variables: p = initial amount # Variables: r = monthly interest rate # Variables: n = number of months # Print, properly labeled the monthly payment ( m ) from math import pow inital = input('Enter the initial amount on a loan: $' ) rate = input('Enter the monthly interest rate (in decimal form): ' ) months = input ('Enter the number of months of the loan: ' ) p = float(inital) r = float(rate) n = int(months) top = r * pow(1+r , n) bottom = pow (1+r, n) - 1 fraction = top / bottom payment = p * fraction m = format(payment , '7.2f') print('Monthly payment: $' , m )
true
e4e9f100067fc2b5dd8a1feb50deccd35c3a0614
CatherineBose/DOJO-Python-Fundametals
/mul_sum_average_Range.py
716
4.59375
5
# Multiples # Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise. # Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000. # Sum List # Create a program that prints the sum of all the values in the list: a = [1, 2, 5, 10, 255, 3] # Average List # Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3] #multiples A for count in range(1, 1001, 2): print count #multiples B for count in range(5,1000001,5): print count #sum list my_numbers = [1, 2, 5, 10, 255, 3] sum = 0 for i in my_numbers: sum += i print sum #average list print sum/len(my_numbers)
true
c3d7ed0322ad497f78590ab3c6d770e9571b7718
Shubh0520/Day_2_Training
/Dict_1.py
405
4.28125
4
""" Write a Python program to sort (ascending and descending) a dictionary by value. """ import operator dict_data = {3: 4, 2: 3, 5: 6, 0: 1} print(f"Dictionary defined is {dict_data}") ascend = sorted(dict_data.items()) print(f"Sorted Dictionary in ascending order is: {ascend}") descend = sorted(dict_data.items(), reverse=True) print(f"Sorted Dictionary in Descending order is: {descend}")
true
f3115da63107ac4ada00fe11e58270a621d4c312
Infra1515/edX-MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python---May-August-2017
/midterm_exam + extra problems/print_without_vowels.py
425
4.3125
4
def print_without_vowels(s): ''' s: the string to convert Finds a version of s without vowels and whose characters appear in the same order they appear in s. Prints this version of s. Does not return anything ''' vowels = 'aeiou' no_vowels = [] for letter in list(s): if letter not in vowels and letter not in vowels.upper(): no_vowels.append(letter) print(''.join(no_vowels))
true
235ac2bf53b66b2df9d10a07bdfe0ccc66181a97
rajal123/pythonProjectgh
/LabExercise/q7.py
897
4.40625
4
''' you live 4 miles from university. The bus drives at 25mph but spends 2 minutes at each of the 10 stops on the way. How long will the bus journey take? Alternatively,you could run to university.you jog the first mile at 7mph;then run the next two at 15mph;before jogging the last at 7mph again.Will this be quicker or slower than the bus?''' living_miles_apart = 4 drives_velocity = 25 time_taken = ((living_miles_apart/drives_velocity) * 60) # 2 minutes in each stop time_spends = 20 total_time = time_taken + time_spends print(f"Total time taken by bus is {total_time}") jog_one = ((1/7)*60) jog_two = ((2/15)*60) jog_three = ((1/7)*60) total_walk_time = jog_one + jog_two + jog_three print(f"time taken by running is {total_walk_time}") if(total_time > total_walk_time): print("taking bus is slower than running") else: print("taking bus is quicker than running")
true
56b5482b39acc25c53af9dde98302db19a5106b2
TAMU-IEEE/programming-101-workshop
/Workshop 2/decisions_2.py
676
4.4375
4
'''Gets a number from the user, and prints “yes” if that number is divisible by 4 or 7, and “no” otherwise. Test Suite: inputs: outputs: domain: -7 "yes" Negative factors 1 "no" Positive integers, nonfactors 0 "no" Zero (border case) 4 "yes" Positive integers, factors of 4 7 "yes" Positive integers, factors of 7 28 "yes" Positive integers, factors of both (border case) ''' # Get input from the user number = int(input("Enter a number to check:")) # Conditionals if number % 7 == 0: print("yes, because it is divisible by 7") elif number % 4 == 0: print("yes,because it is divisible by 4") else: print("no, it is not divisible by either 4 or 7")
true
7b580887c8858cc36fa63eed979dedabb981e5f4
TAMU-IEEE/programming-101-workshop
/Workshop 3/funcs_2.py
589
4.3125
4
'''Write a function that returns two given strings in alphabetical order. Test suite: input: output: domain: "hi", "man" "hi man" ordered "zz", "aa" "aa zz" unordered ''' # think about how we compare characters and their hidden ascii value! def alphabetizeMe(string1, string2): for i in range(0, len(string1)): if string1[i] < string2[i]: return '{0} {1}'.format(string1, string2) elif string2[i] < string1[i]: return '{0} {1}'.format(string2, string1) # it's possible that there is a more elegant solution print(alphabetizeMe('rocks', 'oneal'))
true
e5f75a207712c3866750c0e4ff1392054d9a990e
ShriPunta/Python-Learnings
/Python Basics/Phunctions.py
1,507
4.1875
4
#Each Function named with keyword 'def' def firstFuncEver(x,y,z): sum=x+y+z return sum #Scope of Variable is defined by where its declaration in the program #Higher (higher from start of program) declarations means greater scope of variable #if you give value in the function start, it is the default value def secFuncEver(x,y=2,z=1): return firstFuncEver(x,y,z+6) for x in range(0,10): print("Add ", x,"them",secFuncEver(x,y=45), " ") print(secFuncEver(x)) print('\n') #This gives Flexibility, it means whatever number of variables there are #they will be taken in an array format def flexi_Param(*args): sum = 2 print(args) print(type(args)) for n in args: sum+=n return sum print(flexi_Param(1)) print(flexi_Param(1,2,4)) flexi=[9,8,7] def Flexi_Args(add1,add2,add3): print(add1,add2,add3) sum1=add1+add2+add3 return sum1 #Flexi is sent as a an array itself, and taken up 1 by 1 #The number of elements should perfectly match number of parameters #Called UnPacking of Arguments Flexi_Args(*flexi) import Collecshuns Collecshuns.modu() #Using Unpacking of variables #We can use this unpacking if we do not know the variables #What it does is, it stores the first number in 'first' and last number in 'last' #All the middle numbers are stored in 'middle' def Flexi_Args(grades): first, *middle, last = grades avg = sum(middle)/len(middle) print(avg) Flexi_Args([1,2,3,4,5,6,7,8,9]) Flexi_Args([200,1,1,1,1,1,1,1,200])
true
47c450984b7263d1072fd232397d3c6645b3edc0
Basileus1990/Receipt
/ShopAssistant.py
2,435
4.15625
4
import Main from ChosenProducts import ChosenProduct # class meant to check which and how many products you want to buy. then he displays a receipt def ask_for_products(): list_of_chosen_products = [] while True: Main.clear_console(True) chosenNumber = chose_product() if chosenNumber == 0: break howMany = chose_how_many() if howMany == 0: continue list_of_chosen_products.append(ChosenProduct(Main.selectedProducts[chosenNumber - 1], howMany)) write_receipt(list_of_chosen_products) def chose_product(): while True: print('\n' + ('#'*61)) print('Which product do you want to buy? Chose a number from above. If no more of them write \"0\"') try: chosenNumber = int(input()) if chosenNumber < 0 or chosenNumber > Main.selectedProducts.__len__(): raise Exception except(Exception): Main.clear_console(False) print('You wrote a wrong number!!! Please try again (: Hit enter to continue') input() Main.clear_console(True) continue break return chosenNumber def chose_how_many(): while True: print('How much of it you want to buy? Write 0 to go back') try: howMany = int(input()) if howMany < 0: raise Exception except(Exception): Main.clear_console(False) print('You wrote a wrong number!!! Please try again (: Hit enter to continue') input() Main.clear_console(True) continue break return howMany def write_receipt(list_of_chosen_products): Main.clear_console(False) if list_of_chosen_products.__len__() == 0: print('You didn\'t chose any product!') return print('You bought those products:') for i in list_of_chosen_products: print(i.product.name + ' in amount of ' + i.amountOfProduct.__str__() + ' Total cost equals: ' + (float(i.amountOfProduct) * float(i.product.price)).__str__()) # calculates sum cost of every product total_cost = 0.0 for i in list_of_chosen_products: total_cost += float(i.amountOfProduct) * float(i.product.price) print('In total you will have to pay: ' + total_cost.__str__())
true
1d86e2c7234b1659cfb9ec11c3421f8e6f9333fb
SAN06311521/compilation-of-python-programs
/my prog/sum_of_digits.py
259
4.21875
4
num = int(input("enter the number whose sum of digits is to be calculated: ")) def SumDigits(n): if n==0: return 0 else: return n % 10 + SumDigits(int(n/10)) print("the sum of the digits is : ") print(SumDigits(num))
true
a7fca4dd7d6e51fa67c3e22770a6a7b9cbb24fb3
SAN06311521/compilation-of-python-programs
/my prog/leap_yr.py
439
4.1875
4
print("This program is used to determine weather the entered year is a leap year or not.") yr = int(input("Enter the year to be checked: ")) if (yr%4) == 0 : if (yr%100) == 0 : if (yr%400) == 0 : print("{} is a leap year.".format(yr)) else: print("{} is not a leap year.".format(yr)) else: print("{} is a leap year.".format(yr)) else: print("{} is not a leap year.".format(yr))
true
9012204f8bde854d3d50139ded69bb038aa58f66
SAN06311521/compilation-of-python-programs
/my prog/class_circle.py
475
4.375
4
# used to find out circumference and area of circle class circle(): def __init__(self,r): self.radius = r def area(self): return self.radius*self.radius*3.14 def circumference(self): return 2*3.14*self.radius rad = int(input("Enter the radius of the circle: ")) NewCircle = circle(rad) print("The area of the circle is: ") print(NewCircle.area()) print("The circumference of the circle is: ") print(NewCircle.circumference())
true
0089887361f63ff82bfb55468aa678374c562513
Drabblesaur/PythonPrograms
/CIS_41A_TakeHome_Assignments/CIS_41A_UNIT_B_TAKEHOME_SCRIPT2.py
2,090
4.125
4
''' Johnny To CIS 41A Fall 2019 Unit B take-home assignment ''' # SCRIPT 2 ''' Use three named "constants" for the following: small beads with a price of 9.20 dollars per box medium beads with a price of 8.52 dollars per box large beads with a price of 7.98 dollars per box ''' SMALL_BEADS_PRICE = 9.20 MED_BEADS_PRICE = 8.52 LARGE_BEADS_PRICE = 7.98 # Ask the user how many boxes of small beads, how many boxes of medium beads, and how many large beads they need # (use the int Built-in Function to convert these values to int). smallBeads = int(input("How many Small Beads? :")) medBeads = int(input("How many Medium Beads? :")) largeBeads = int(input("How many Large Beads? :")) # Calculation smallTotal = round((smallBeads*SMALL_BEADS_PRICE),2) medTotal = round((medBeads*MED_BEADS_PRICE),2) largeTotal = round((largeBeads*LARGE_BEADS_PRICE),2) finalTotal = round((smallTotal + medTotal + largeTotal),2) # Print the invoice print("SIZE QTY COST PER BOX TOTALS") print(f"Small {str(smallBeads).rjust(3)} {str(SMALL_BEADS_PRICE).rjust(5)} {str(smallTotal).rjust(6)}") print(f"Medium {str(medBeads).rjust(3)} {str(MED_BEADS_PRICE).rjust(5)} {str(medTotal).rjust(6)}") print(f"Large {str(largeBeads).rjust(3)} {str(LARGE_BEADS_PRICE).rjust(5)} {str(largeTotal).rjust(6)}") print(f"TOTAL {str(finalTotal).rjust(10)}") ''' Execution Results: TEST 1 How many Small Beads? :10 How many Medium Beads? :9 How many Large Beads? :8 SIZE QTY COST PER BOX TOTALS Small 10 9.2 92.0 Medium 9 8.52 76.68 Large 8 7.98 63.84 TOTAL 232.52 TEST 2 How many Small Beads? :5 How many Medium Beads? :10 How many Large Beads? :15 SIZE QTY COST PER BOX TOTALS Small 5 9.2 46.0 Medium 10 8.52 85.2 Large 15 7.98 119.7 TOTAL 250.9 '''
true
e430729e07dc10717ef0be62f96ab9ac9278670b
dylanbrams/Classnotes
/practice/change/pig_latin.py
2,056
4.40625
4
''' Pig Latin: put input words into pig latin. ''' VOWELS = 'aeiouy' PUNCTUATION = '.,-;:\"\'&!\/? ' def find_consonant(word_in): """ :param word_in: :return: >>> find_consonant("Green") 2 >>> find_consonant("orange") 0 >>> find_consonant("streetlight") 3 >>> find_consonant("aardvark") 0 >>> find_consonant("a") 0 """ vowel_place = 0 current_iteration = 0 for current_letter in word_in: if current_letter in VOWELS: vowel_place = current_iteration break else: current_iteration += 1 return vowel_place def to_pig_latin(word, vowel_place): """ Inputs a string to make pig latin, along with where in the word the vowel is. Returns the word in pig latin. :param word: :param vowel_place: :return: """ word_out = '' if vowel_place == 0: word_out = word + 'way' elif vowel_place != None: word_out = (word[vowel_place:] + word[:vowel_place] + 'ay') else: word_out = None return word_out def match_format(word_to_match, word_to_modify): """ Matches punctuation and capitalization from one word to another. :param word_to_match: :param word_to_modify: :return: """ if word_to_match[-1] in PUNCTUATION: word_to_modify += word_to_match[-1] if word_to_match[0].isupper(): word_to_modify = word_to_modify.capitalize() return word_to_modify def main(): input_string = input ('Please enter a word to put into pig latin: ') output_string = input_string.lower().strip(PUNCTUATION) vowel_place = find_consonant(input_string) if vowel_place > len(output_string): print("Invalid word.") output_string = to_pig_latin(output_string, vowel_place) final_string = match_format(input_string, output_string) print (input_string + " in Pig Latin is " + final_string) if __name__ == '__main__': main() # import doctest # doctest.testmod(extraglobs={'t': ConversionClass()})
true
7a9a7a54b79ad81ce6c7e1dcacb1e51de53f3043
sshashan/PythonABC
/factorial.py
491
4.375
4
print("Factorial program") num1= int(input("Enter the number for which you want to see the factorial: ")) value=1 num =num1 while(num > 1): value=value*num num =num - 1 print("Factorial of "+str(num1)+" is: " ,value) def factorial(n): return 1 if(n==1 or n==0) else n * factorial(n-1) print(factorial(num1)) def fact(x): if (x == 0): return 1 else: return x * fact(x-1) print(fact(num1))
true
d337fc0ae229454fb657c1830189c31bb12d2f2e
sshashan/PythonABC
/Person_dict.py
353
4.25
4
print("This program gets the property of a person") person={"name":"Sujay Shashank","age":30,"phone":7744812925,"gender":"Male","address":"Mana tropicale"} print("What information you want??") key= input("Enter the property (name,age,phone,gender,address):").lower() result=person.get(key,"Info what you are looking for is not present") print(result)
true
d86c1fbb67e71e269e118cc9a6565456c57cd39c
sshashan/PythonABC
/calculator.py
713
4.34375
4
print("Calculator for Addition/Deletion/Multiplication/Subtraction") print("Select the operation type") print("1.Addition") print("2.Subtraction") print("3.Multiplication") print("4.Division") user_opt=int(input("Enter your operation number: ")) num1= int(input("Enter the first number :")) num2= int(input("Enter your second number:")) if (user_opt==1): print("Sum of two numbers are: ",num1+num2) elif (user_opt==2): print("Subtraction of two numbers are:", num1-num2) elif (user_opt==3): print("Multiplication of two numbers are :",num1*num2) elif (user_opt==4): print("Division of two numbers are: ",num1/num2) else: print("Enter a valid option")
true
afde2cea346697fc1f75f8427d574514d9941d76
greenfox-zerda-lasers/gaborbencsik
/week-03/day-2/38.py
259
4.125
4
numbers = [7, 5, 8, -1, 2] # Write a function that returns the minimal element # in a list (your own min function) def find_min(list): mini = list[0] for x in list: if x < mini: mini = x return mini print find_min(numbers)
true
051d2effa49713986d3bc82a296ceb18f3b825ef
greenfox-zerda-lasers/gaborbencsik
/week-04/day-3/09.py
618
4.25
4
#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 # create a 300x300 canvas. # create a square drawing function that takes 1 parameter: # the square size # and draws a square of that size to the center of the canvas. # draw 3 squares with that function. from tkinter import * root = Tk() size = 300 canvas = Canvas(root, width=size, height=size) canvas.pack() def square_drawing(x): canvas.create_rectangle(size/2 - x/2, size/2 - x/2, size/2 + x/2, size/2 + x/2, fill="green") print (size/2-x) print (size/2) square_drawing(120) square_drawing(50) square_drawing(20) root.mainloop()
true
730dabc7497180a3b6314421119d89d7735e2684
greenfox-zerda-lasers/gaborbencsik
/week-04/day-4/04-n_power.py
337
4.1875
4
#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 # 4. Given base and n that are both 1 or more, compute recursively (no loops) # the value of base to the n power, so powerN(3, 2) is 9 (3 squared). def powerN(base,n): if n < 1: return 1 else: return base * powerN(base,(n-1)) print (powerN(3,1))
true
d585e697fde25956f65403c02cfd5d10bc04b530
greenfox-zerda-lasers/gaborbencsik
/week-03/day-2/37.py
296
4.1875
4
numbers = [3, 4, 5, 6, 7] # write a function that filters the odd numbers # from a list and returns a new list consisting # only the evens def filter(list): new_list = [] for x in list: if x % 2 == 0: new_list.append(x) return new_list print filter(numbers)
true
5ec9098bbeaa87dd56a064b55169d4c24569277e
m1ghtfr3e/Number-Guess-Game
/Number_guess_game_3trials_FINE.py
853
4.3125
4
"""Guess number game""" import random attempt = 0 print(""" I have a number in mind between 1 and 10. Do you want to guess it? You have 3 tries! Enjoy :) """) letsstart = input("Do you want to start? (yes/no): ") if letsstart == 'yes': print("Let's start") else: print("Ok, see you :) ") computernumber = random.randrange(10) print("I think of a number between 0 and 10") while attempt < 3: guess = int(input("What is your guess?: ")) attempt = attempt + 1 if guess == computernumber: break elif guess <= computernumber: print("My number is bigger than yours") elif guess >= computernumber: print("My number is smaller than yours") if guess == computernumber: print("Nice, you got it! :-)") if guess != computernumber: print("try it again ;-) ")
true
10fabfbedc56aa8401cbe038bd69b8d0938d48f3
mahimadubey/leetcode-python
/maximum_subarray/solution2.py
675
4.15625
4
""" Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. """ class Solution: # @param A, a list of integers # @return an integer def maxSubArray(self, A): if not A: return 0 res = A[0] cur_sum = A[0] n = len(A) for i in range(1, n): cur_sum = max(cur_sum + A[i], A[i]) res = max(res, cur_sum) # If negative sum is not allowed, add the following line: # if res < 0: return 0 return res
true
dcbe94018816bda8efcd8e5b702eb328c136d52f
binhyc11/MIT-course-6.0001
/Finger exercise 4.1.1.py
409
4.15625
4
# Write a function isIn that accepts two strings as arguments and # returns True if either string occurs anywhere in the other, and False otherwise. # Hint: you might want to use the built-in str operation in. def isIn (x, y): if x in y or y in x: return True else: return False x = input ('Enter a string: ') y = input ('Enter a string: ') z = isIn (x, y) print (z)
true
0727891d7bb90fcf5cdf57f35826dc033db1047c
Yogini824/NameError
/PartA_q3.py
2,401
4.53125
5
'''The game is that the computer "thinks" about a number and we have to guess it. On every guess, the computer will tell us if our guess was smaller or bigger than the hidden number. The game ends when we find the number.Also Define no of attemps took to find this hidden number.(Hidden number lies between 0 - 100)''' import random # importing random file to generate a random number def guess(n): # defining a function to guess hidden number c=1 # taken variable to count the number of chances a=0 # taken a variable for reference to check thet user guessed the number while c<=5: # As there are 5 chances to guess while loop runs for 5 times k=int(input("Guess a number: ")) # taken a variable to guess a number if(k==n): # if guessed number is equal to hidden number print("Hidden number is",H,",You have won the game in",c,"chances") # printing that user has guessed the number a=1 # making the variable for reference to 1 to know that number has been guessed break # after guessing there is no need for while so break it elif(c!=5): # if the count not equal to 5 if(k<n): # and if guessed number lessthan hiddden print("Hidden number is greater, Guess again") # print hidden is greater else: # if not print("Hidden number is lesser, Guess again") # print hidden is lesser c+=1 # counting the chances adding 1 if(a==0): # if reference variable is 0 then user havent guessed the number print("Sorry, Your chances are over") # printing chances are over H= random.randint(0,100) # taken a variable to store random number generated by randint in range of 0-100 guess(H) # calling the function to guess the number
true
ceaf43928789e3a45e0d54d0b9bf756506f5a251
Yogini824/NameError
/PartB_q3.py
1,082
4.15625
4
'''Develop a Python Program which prints factorial of a given number (Number should be User defined)''' def factorial(n): # calling function to calculate factorial of given number if n<0: # checking if n is positive or not print("Enter a positive number") # if negative print to entner positive number elif n==0: # checking whether n is 0 or not return 1 # if 0 return 1 as the factorial of 0 is 1 else: # if n is positive return factorial(n-1)*n # return the multiplication of calling the function(recursion) to 1 less to n and n n=int(input("Enter a number : ")) # taking the input of a number for which we need factorial k=factorial(n) # taking a variable and calling function and the returned value from the function is assigned to variable print("Factorial of",n,"is",k) # printing the factorial of given number
true
a139f9e0778fbd1d1fb3754cdcbd02bd308c5cc9
pagsamo/google-tech-dev-guide
/leetcode/google/tagged/medium/inorder_binary_tree_traversal.py
886
4.1875
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: """ Time complexity: O(N) since visit exactly N nodes once. Space complexity: O(N) for skew binary tree; O(log N) for balance binary tree. Space due to recursive depth stack space Runtime: 32 ms, faster than 92.54% of Python3 online submissions for Binary Tree Inorder Traversal. """ def values(node: TreeNode, nums: List[int]) -> List[int]: if not node: return nums values(node.left, nums) nums.append(node.val) values(node.right, nums) return nums return values(root, [])
true
20f07ae9d39e0b191f52d4cc155a94493d1525b6
pagsamo/google-tech-dev-guide
/leetcode/recursion/reverse_string.py
419
4.15625
4
from typing import List def reverse_string(s:List[str]) -> None: """ To practice use of recursion """ def helper(start, end): if start < end: s[start], s[end] = s[end], s[start] helper(start + 1, end - 1) print("before", s) n = len(s) if n > 1: helper(0, n - 1) print("after", s) if __name__ == "__main__": reverse_string(["h", "e", "l", "l", "o"])
true
3231ef6292673615fafdfb53aa733d57ffc3c61b
pagsamo/google-tech-dev-guide
/70_question/dynamic_programming/water_area.py
1,119
4.1875
4
""" Water Area You are given an array of integers. Each non-zero integer represents the height of a pillar of width 1. Imagine water being poured over all of the pillars and return the surface area of the water trapped between the pillars viewed from the front. Note that spilled water should be ignored. Sample input: [0, 8, 0, 0, 5, 0, 0, 10, 0, 0, 1, 1, 0, 3] Sample output: 48. """ def waterArea(heights, debug=False): n = len(heights) left_max = [0] * n right_max = [0] * n i = 1 while i < n: # Compute the max to the left/right of index i left_max[i] = max(heights[:i]) right_max[n-1-i] = max(heights[n - i:]) i += 1 area = 0 for l, r, pillar in zip(left_max, right_max, heights): min_height = min(l, r) if pillar < min_height: area += min_height - pillar if debug: print(heights) print(left_max) print(right_max) print("The water area for {} is {}".format(heights, area)) return area if __name__ == "__main__": x = [0, 8, 0, 0, 5, 0, 0, 10, 0, 0, 1, 1, 0, 3] waterArea(x)
true
4983f02c95329f98637ab43444ee4bf4e2da8346
sresis/practice-problems
/CTCI/chapter-1/string-rotation.py
799
4.125
4
# O(N) import unittest def is_substring(string, substring): """Checks if it is a substring of a string.""" return substring in string def string_rotation(str1, str2): """Checks if str2 is a rotation of str1 using only one call of is_substring.""" if len(str1) == len(str2): return is_substring(str1+str1, str2) return False print(is_substring('football', 'ball')) class Test(unittest.TestCase): '''Test Cases''' data = [ ('waterbottle', 'erbottlewat', True), ('foo', 'bar', False), ('foo', 'foofoo', False) ] def test_string_rotation(self): for [s1, s2, expected] in self.data: actual = string_rotation(s1, s2) self.assertEqual(actual, expected) if __name__ == "__main__": unittest.main()
true
23114beb0d00f2b55d54c4c9390c41d6c89dc70e
sresis/practice-problems
/recursion-practice/q6.py
553
4.25
4
""" Write a recursive function that takes in a list and flattens it. For example: in: [1, 2, 3] out: [1, 2, 3] in: [1, [1, 2], 2, [3]] out: [1, 1, 2, 2, 3] """ def flatten_list(lst, result=None): ## if length of item is > 1, flatten it result = result or [] for el in lst: if type(el) is list: flatten(el, result) else: result.append(el) return result if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. RIGHT ON!\n")
true
dbd89843d85f927c8fb764183a2516d10863b26f
KyrillMetalnikov/A01081000_1510_V2
/lab07/exceptions.py
1,761
4.375
4
import doctest """Demonstrate proper exception protocol.""" def heron(number) -> float: """ Find the square root of a number. A function that uses heron's theorem to find the square root of a number. :param number: A positive number (float or integer) :precondition: number must be positive. :postcondition: A close estimate of the square root will be found :return: A close estimate of the square root as a float. >>> heron(9) 3.0 >>> heron(5.5) 2.345207879911715 """ try: if number < 0: number / 0 except ZeroDivisionError: print("Error: The number provided must be positive!") return -1 square_root_guess = number # arbitrary value for the heron formula for _ in range(0, 1000): # arbitrary amount of runs that get it close enough square_root_guess = (square_root_guess + (number / square_root_guess)) / 2 return square_root_guess def findAnEven(input_list: list) -> int: """ Return the first even number in input_list :param input_list: a list of integers :precondition: input_list must be a list of integers :postcondition: return the first even number in input_list :raise ValueError: if input_list does not contain an even number :return: first even number in input_list >>> findAnEven([1, 3, 5, 6, 8, 9]) 6 >>> findAnEven([2]) 2 """ even_number = [] for value in input_list: if value % 2 == 0: even_number.append(value) break if len(even_number) == 0: raise ValueError("input_list must contain an even number!") return even_number[0] def main(): heron(-1) doctest.testmod() if __name__ == "__main__": main()
true
6962206a6b3052cb75d5887eefc836a25b73df7e
KyrillMetalnikov/A01081000_1510_V2
/lab02/base_conversion.py
1,924
4.40625
4
""" Convert various numbers from base 10 to another base """ def base_conversion(): """ Convert a base 10 number to another base up to 4 digits. A user inputs a base between 2-9 then the program converts the input into an integer and displays the max number possible for the conversion. The user then inputs a number within allowed parameters which gets converted then the resulting conversion is displayed to the user. """ base = int(input("What base (2-9) do you want to convert to?")) # inputted base converts to int and is then stored print("The max value allowed is ", max_value(base)) number_base_10 = int(input("Please input the base 10 integer you wish to convert")) # inputted num is stored as int print(base_converter(number_base_10, base)) def max_value(base): """ Find the max possible value in a base conversion. Function uses an algorithm find the maximum value the conversion can hold when moving from base 10 using 4 digits :param base: the base being converted to: type integer :return: returns the max value the base can be converted to assuming there's 4 digits """ return base ** 4 - 1 def base_converter(number_base_10, base): """ Convert a number from base 10 to target base. Function uses an algorithm to convert a number from base 10 to a target base up to 4 digits :param number_base_10: the number in base 10 being converted: type integer :param base: the target base being converted to: type base :return: returns the 4 digits the base 10 number was converted to """ num0 = number_base_10 // base digit0 = str(number_base_10 % base) num1 = num0 // base digit1 = str(num0 % base) num2 = num1 // base digit2 = str(num1 % base) digit3 = str(num2 % base) return digit3 + digit2 + digit1 + digit0 if __name__ == "__main__": base_conversion()
true
b0bdc1aef3cbdb35b9d6745ef02046a1449d389a
nandansn/pythonlab
/Learning/tutorials/chapters/operators/bitwise.py
477
4.3125
4
# Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name. x = input("enter number x:") y = input("enter number y:") x = int(x) y = int(y) print("bitwise {} and {}".format(x,y), x & y) print("bitwise {} or {}".format(x,y), x | y) print("bitwise not of {} ".format(x), ~x) print("bitwise {} xor {}".format(x,y), x ^ y) print("bitwise right shift".format(x), x >> 2) print("bitwise left shift".format(x), x << 2)
true
83e8412a46c0f05b0d7c37a92f90bd768ddb073f
nandansn/pythonlab
/Learning/tutorials/chapters/operators/comparison.py
556
4.125
4
x = input("enter number x:") y = input("enter number y:") x = int(x) y = int(y) #check equal print("check {} and {} are equal".format(x,y),x == y) #check not equal print("check {} and {} are not equal".format(x,y),x != y) #check less than print("check {} is less than {} ".format(x,y),x <y) #check greater than print("check {} is greater than {} ".format(x,y),x > y) #check less than or equal print("check {} less than or equal to {}".format(x,y),x <= y) #check greater than equal print("check {} greater than or equal to {} ".format(x,y),x >= y)
true
a15aa28ac9f40f41a1b9c49ba70254c10d224139
nandansn/pythonlab
/durgasoft/chapter35/dict.py
797
4.25
4
''' update dictionary, ''' d = {101:'durga',102:'shiva'} d[103] = 'kumar' #if key not there, new value will be added. d[101]='nanda' #if key already available, new value will be updated. print(d) ' how to delete elements from the dictionary ' del d[101] # if the key present, then the key and value will be removed print(d) try: del d[101] except KeyError as key: print('key {} not available in {}'.format(key,d)) d.clear() ' to clear all the key/value pairs in dict' print(d) d.update({101:'abc'}) try: del d # this object is available for garbage collection. except NameError as name: print ('{} is not defined'.format(name)) 'how to speciy multiple values for the key' a={} a[100]=['nanda','kumar','k'] print(a)
true
b002c745c7813fb63f8ab1b327697342df62cbd7
nandansn/pythonlab
/durgasoft/chapter47/random-example.py
427
4.15625
4
from random import * for i in range(10): print(random()) for i in range(10): print(randint(i,567)) # generat the int value, inclusive of start and end. for i in range(10): print(uniform(i,10)) #generate the float value, within the range. not inclusive of start and end values. for i in range(10): print('random numbers') print(randrange(1,11,3)) # generate the random number with step value
true
89bad08e5b41e99386f42b0913f5434a4f6e9845
nandansn/pythonlab
/Learning/tutorials/chapters/operators/identity.py
331
4.28125
4
# is and is not are the identity operators in Python. # They are used to check if two values (or variables) are located on the same part of the memory. x ="hello" y ="hello" print("x is y", x is y) y = "Hello" print("x is y", x is y) print(" x is not y", x is not y) x = [1,2,3] y = [1,2,3] print("x is not y", x is not y)
true
12fe67f6785b89a35ace0769e2733d45660b6b23
nandansn/pythonlab
/durgasoft/chapter33/functions_of_tuple.py
395
4.34375
4
''' functions of tuple: ''' 'len()' t = tuple(input('enter tuple:')) print(t) print(len(t)) 'count occurence of the elelement' print(t.count('1')) '''sorting: natural sorting order ''' t=(4,3,2,1) print(sorted(t)) print(tuple(sorted(t))) print(tuple(sorted(t,reverse=True))) 'min and max method to find in the tuple...' print(max(t)) print(min(t))
true
581ad96b03b49138a25783d9cacd4bb132984259
nandansn/pythonlab
/durgasoft/chapter13/shiftoperators.py
272
4.53125
5
print(""" shift operators how it works""") print (1 << 2) # Rotate left most 2 bits to the right most. print ( 10 >> 2) # Rotate right most 2 bits to the left most. # for positive numbers left most bit is 0 # for negative numbers right most bit is 1 print (-10 >> 2)
true
9ff4380dbf6e147c1ed42a320aa4fc16a123b92c
nandansn/pythonlab
/durgasoft/chapter35/functions-in-dict.py
1,274
4.5
4
'function: to create empty dict' d = dict() 'function: to create dict, by using list of tuples' d= dict([(100,'nanda'),(200,'kumar'),(300,'nivrithi'),(400,'valar')]) print(d) '''functions: dict() list of tuples, set of tuples, tuple of tuples. ''' 'fucntion:length of dict' print(len(d)) print(d.get(100)) print(d.get(101)) # if key not present, then none will be returned. print(d.get(101,'No value')) # o/p will be 'No value' 'to remove the value of the corresponding key' print(d.pop(100)) # returns the value print(d) d.popitem() # key will be chosen randaomly, and corresponding key/value removed and value returned. print(d) 'to get the keys in the dictionary, returned is not list object. it is dict_keys' print(d.keys()) 'to get only the values, returned is type of dict_values' print(d.values()) 'to get the items(key,value), returned type is dict_items' print(d.items()) for k,v in d.items() : print('key:{}, value:{}'.format(k,v)) d1= d.copy() print(d1) ''' if key already avaliable, return the existing value for the key, if the key unavailable, add the value for that key.return the newly added value. ''' print(d.setdefault('109','nanda') ) print(d.setdefault('200','jkl')) print(d)
true
12ce3055d8595e5e0be0910da1498e92cad8256e
nandansn/pythonlab
/durgasoft/chapter15/read-data.py
256
4.3125
4
print("""We have input function to read data from the console. The data will be in str type we need to do type conversion.""") dataFromConsole = input("Enter data:") print("type of input is:", type(dataFromConsole)) print(type(int(dataFromConsole)))
true
d667e5a3f4185900a22a751283b9346b5af2613d
aalabi/learningpy
/addition.py
233
4.1875
4
# add up the numbers num1 = input("Enter first number ") num2 = input("Enter second number ") # sum up the numbers summation = num1 + num2 # display the summation print("The sum of {0} and {1} is {2}".format(num1, num2, summation))
true
aa478143bf9f657b6938650e8d174dcb016d5f39
Yvonnekatama/control-flow
/conditionals.py
875
4.125
4
# if else age=25 if age >= 30: print('pass') else: print('still young') # ternary operator temperature=30 read="It's warm today" if temperature >= 35 else "Wear light clothes" print(read) # if elif else name='Katama' if name=='Yvonne': print('my name') elif name=='Katama': print("That's my sur name") elif name=='Muelani': print("That's my nick name") else: print("I do'nt know who that is") # logical operators and chained conditionals user='Student' logged_in=False if user=='Student' and logged_in == False: print('Student page') else: print('Admin page,password required') user='Student' logged_in=True if not logged_in: print('Please log in') else: print('Key in user password') user='Admin' logged_in=True if user=='Admin' or logged_in== True: print('Admin page') else: print('Student page,password required')
true
a4509cc29dfe24626d1f60e8c067b8078d039f75
syurskyi/Math_by_Coding
/Programming Numerical Methods in Python/2. Roots of High-Degree Equations/2.1 PNMP_2_01.py.py
287
4.15625
4
''' Method: Simple Iterations (for-loop) ''' x = 0 for iteration in range(1,101): xnew = (2*x**2 + 3)/5 if abs(xnew - x) < 0.000001: break x = xnew print('The root : %0.5f' % xnew) print('The number of iterations : %d' % iteration)
true
995c5e8d0ebb7a3012580a18c3bc14fcc15b187b
koheron2/pyp-w1-gw-language-detector
/language_detector/main.py
1,194
4.25
4
# -*- coding: utf-8 -*- """This is the entry point of the program.""" from collections import Counter def detect_language(text, languages): words_appearing = 0 selected_language = None """Returns the detected language of given text.""" for language in languages: words = len([word for word in language['common_words'] if word in text]) if words > words_appearing: words_appearing = words selected_language = language['name'] return selected_language def most_common_word(text): words = text.split() counted_words = Counter(words) most_common = counted_words.most_common(1)[0][0] return most_common def percentage_of_language(text, languages): words = text.split() percent_dict = {} percentages = "" #return percentage of each language for language in languages: lang_words = [word for word in language['common_words'] if word in text] percentage = 100 * len(lang_words)/len(words) percent_dict[language['name']] = "%.2f" % percentage for key, val in percent_dict.items(): percentages += key + ": "+val+"\n" return percentages
true
690170d51cd1f93932925e019f01d1f7dd90712e
gladysmae08/project-euler
/problem19.py
1,430
4.375
4
# counting sundays ''' You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? ''' month_days = { 'jan' : 31, 'feb' : 28, 'mar' : 31, 'apr' : 30, 'may' : 31, 'jun' : 30, 'jul' : 31, 'aug' : 31, 'sep' : 30, 'oct' : 31, 'nov' : 30, 'dec' : 31 } month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 366%7 = 2; 1 jan 1901 = wed year = 1901 sunday_count = 0 day_count = 1 is_sunday = lambda x : (x % 7 == 6) while (year < 2001): for month in month_lengths: if month == 28 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): month += 1 day_count += month if is_sunday(day_count): sunday_count += 1 year += 1 if is_sunday(day_count): sunday_count -= 1 print(sunday_count)
true
c9f7b46835e56102fd280a80f992b6b2a5d76cd3
shubhamrocks888/linked_list
/create_loop_or_length_loop.py
1,198
4.125
4
class node: def __init__(self,data=None): self.data = data self.next = None class linked_list: def __init__(self): self.head = None def push(self,data): new_node = node(data) new_node.next = self.head self.head = new_node # Function to create a loop in the # Linked List. This function creates # a loop by connnecting the last node # to n^th node of the linked list, # (counting first node as 1) def create_loop(self,n): loop_node = self.head for _ in range(1,n): loop_node = loop_node.next end_node = self.head while end_node.next: end_node = end_node.next end_node.next = loop_node def length(self): cur_node = self.head l = [] while cur_node: if cur_node in l: print (len(l)-l.index(cur_node)) return l.append(cur_node) cur_node = cur_node.next print ("loop not exists") li = linked_list() li.push(1) li.push(2) li.push(3) li.push(4) li.create_loop(4) ## Create a loop for testing ##li.head.next.next.next.next = li.head li.length()
true
5e82215b548f332f5f56d1270345d01d38db1c80
Explorerqxy/review_practice
/025.py
1,049
4.28125
4
def PrintMatrixClockwisely(numbers, columns, rows): if numbers == None or columns <= 0 or rows <= 0: return start = 0 while columns > start * 2 and rows > start * 2: PrintMatrixInCircle(numbers, columns, rows, start) start += 1 def PrintMatrixInCircle(numbers, columns, rows, start): endX = columns -1 - start endY = rows - 1 - start #从左到右打印一行 for i in range(start, endX+1): number = numbers[start][i] printNumber(number) #从上到下打印一列 if start < endY: for i in range(start+1, endY+1): number = numbers[i][endX] #从右到左打印一行 if start < endX and start < endY: for i in range(endX-1, start-1, -1): number = numbers[endY][i] printNumber(number) #从下到上打印一列 if start < endX and start < endY -1: for i in range(endY-1, start, -1): number = numbers[i][start] printNumber(number) def printNumber(number): print(number)
true
47a42cfced82ca19f33265c6d5752766e7163756
mariocpinto/0009_MOOC_Python_Data_Structures
/Exercises/Week_03/assignment_7_1.py
502
4.6875
5
# 7.1 Write a program that prompts for a file name, # then opens that file and reads through the file, # and print the contents of the file in upper case. # Use the file words.txt to produce the output below. # You can download the sample data at http://www.pythonlearn.com/code/words.txt file_name = input('Enter Filename: ') try: file_handle = open(file_name,'r') except: print('Error opening file.') exit() for line in file_handle : line = line.rstrip() print(line.upper())
true
55a730379685d64d717df81c1306430f6c6c5255
brash99/phys441
/nmfp/Cpp/cpsc217/area_triangle_sides.py
775
4.25
4
#!/usr/bin/env python import math s1 = input('Enter the first side of the triangle: ') s2 = input('Enter the second side of the triangle: ') s3 = input('Enter the third side of the triangle: ') while True: try: s1r = float(s1) s2r = float(s2) s3r = float(s3) if s1r<=0 or s2r<=0 or s3r<=0: print ("The side lengths must be greater than zero!!") break s = (s1r+s2r+s3r)/2.0 term = area = math.sqrt(s*(s-s1r)*(s-s2r)*(s-s3r)) print ("The area of a triangle with side lengths, %.3f, %.3f, and %.3f is %.3f." % (s1r,s2r,s3r,area)) break except ValueError: print("The values must be real numbers!!") break print('Exiting ... bye!')
true
c8216213d129bd12d845771e8a87f7b06eeb11fa
brash99/phys441
/digits.py
783
4.21875
4
digits = [str(i) for i in range(10)] + [chr(ord('a') + i) for i in range(26)] # List of digits: 0-9, a-f num_digits = int(input("Enter the number of digits: ")) # User input for the number of digits possible_numbers = [] # List to store the possible numbers def generate_numbers(digit_idx, number): if digit_idx == num_digits: possible_numbers.append(number) return for digit in digits: if digit_idx == 0 and digit == '0': continue # Exclude leading zero generate_numbers(digit_idx + 1, number + digit) generate_numbers(0, '') # Print the list of possible numbers #for number in possible_numbers: # print(number) print ("length = ", len(possible_numbers)) print ("predicted length = ",35*36**(num_digits-1))
true
4ccceec7ce99deb87c2465b14de535a4108100f7
brash99/phys441
/JupyterNotebooks/DataScience/linear_regression.py
1,380
4.34375
4
import numpy as np from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt # create some data # # N.B. In linear regression, there is a SINGLE y-value for each data point, but there # may be MULTIPLE x-values, corresponding to the multiple factors that might affect the # experiment, i.e. y = b_1 * x_1 + b_2 * x_2 + b_3 * x_3 + ..... # Therefore, the x data is a TWO DIMENSIONAL array ... the columns correspond to the different # variables (x_1, x_2, x_3, ...), and the rows correspond to the values of those variables # for each data point. # # Data is y = x with some noise x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).reshape((-1, 1)) y = np.array([1.1, 2.1, 2.9, 3.9, 5.1, 5.9, 6.9, 8.05, 9.1, 9.7]) print(x) print(y) # Linear Regression Model from scikit-learn model = LinearRegression() model.fit(x, y) r_sq = model.score(x, y) print(f"Correlation coefficient R^2: {r_sq}") print(f"intercept: {model.intercept_}") # beta_0 print(f"slope: {model.coef_}") # beta1, beta2, beta3, etc. x_low = min(x) x_high = max(x) x_pred = np.linspace(x_low, x_high, 100) y_pred = model.predict(x_pred) # print (y_pred) # Plotting! plt.plot(x, y, 'o', label='Data') plt.plot(x_pred, y_pred, 'r-', label="Linear Regression Fit") plt.title("Basic Linear Regression") plt.xlabel("X") plt.ylabel("Y") plt.legend() plt.show()
true
b3fc68dceb1f57d89daa42ec09c214fe0807897c
mbarbour0/Practice
/Another Rock Paper Scissors Game.py
1,481
4.15625
4
# Yet another game of Rock Paper Scissors import os import random from time import sleep options = {"R": "Rock", "P": "Paper", "S": "Scissors"} def clear_screen(): """Clear screen between games""" if os.name == 'nt': os.system('cls') else: os.system('clear') def play_game(): """General function to call game play""" clear_screen() user_choice = input("Please enter 'R' for Rock, 'P' for Paper, or 'S' for Scissors\n>>> ").upper() if user_choice in list(options.keys()): print("You have selected {}.".format(options[user_choice])) else: print("Please select a valid option") exit() print("The computer is now selecting...") sleep(1) computer_choice = random.choice(list(options.keys())) print("The computer has selected {}.".format(options[computer_choice])) sleep(1) decide_winner(user_choice, computer_choice) def decide_winner(user_choice, computer_choice): """Function call to decide winner of the game""" if user_choice == "P" and computer_choice == "R": print("You win") elif user_choice == "R" and computer_choice == "S": print("You win") elif user_choice == "S" and computer_choice == "P": print("You win") elif user_choice == computer_choice: print("You tied") else: print("You lost") while __name__ == "__main__": play_game() quit_game = input("Continue? [Yn]\n>>> ").lower() if quit_game == 'n': break
true
dcb6d89fedc9ab9c2cd884a73904cf27633ba719
shraysidubey/pythonScripts
/Stack_using_LinkedList.py
1,634
4.21875
4
#Stack using the LinkedList. class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def appendHaed(self,new_data): new_node = Node(new_data) #create the new node 370__--> head new_node.next = self.head self.head = new_node #New_node Link to head def deleteHead(self): if self.head is None: print("Head is not in the LinkedList") return self.head = self.head.next def isEmpty(self): if self.head is None: return True else: return False def printList(self): temp = self.head while(temp!= None): print(str(temp.data) + "-->", end = " ") temp = temp.next return print() class Stack: def __init__(self): self.list = LinkedList() def push(self, item): self.list.appendHaed(item) return self.list def pop(self): if self.list.isEmpty(): print("Stack is empty") else: self.list.deleteHead() def printStack(self): self.list.printList() L = Stack() print("-------") L.push("1") L.printStack() print("-------") L.push("w") L.printStack() print("-------") L.push("r") L.printStack() print("-------") L.push("j") L.printStack() print("-------") L.push("t") L.printStack() print("-------") L.pop() L.printStack() print("-------") L.pop() L.printStack() L.pop() L.printStack() #print(L.list.head.data)
true
f0e18b65f8e66a9255a9dc7d110b775f916b6ff4
nvcoden/working-out-problems
/py_2409_1.py
744
4.21875
4
''' Question 1 Create methods for the Calculator class that can do the following: 1. Add two numbers. 2. Subtract two numbers. 3. Multiply two numbers. 4. Divide two numbers. Sample Output :- calculator = Calculator() calculator.add(10, 5) ➞ 15 calculator.subtract(10, 5) ➞ 5 calculator.multiply(10, 5) ➞ 50 calculator.divide(10, 5) ➞ 2 ''' class Calculator: def add(i,j): return i+j def subtract(i,j): return i-j def multiply(i,j): return i*j def divide(i,j): return i/j i = int(input("Enter the First no\n")) j = int(input("Enter the Second no\n")) print(Calculator.add(i,j)) print(Calculator.subtract(i,j)) print(Calculator.multiply(i,j)) print(Calculator.divide(i,j))
true
e853965a25662783b57054c0bf75a09a9ebe3615
rajjoan/PythonSamples
/Chapter 13/function7.py
215
4.25
4
def evenorodd(number): if number % 2 == 0: print("The number is even") else: print("this number is odd") n=int(input("Enter a number to finf even or odd : ")) evenorodd(n)
true
5bcf95b1954ac33b4698863f3900d466a6805539
angelblue05/Exercises
/codeacademy/python/while.py
1,298
4.21875
4
num = 1 while num < 11: # Fill in the condition # Print num squared print num * num # Increment num (make sure to do this!) num += 1 # another example choice = raw_input('Enjoying the course? (y/n)') while choice != "y" and choice != "n": # Fill in the condition (before the colon) choice = raw_input("Sorry, I didn't catch that. Enter again: ") # another example count = 0 while count < 10: # Add a colon print count # Increment count count += 1 # another example count = 0 while True: print count count += 1 if count >= 10: break # another example import random print "Lucky Numbers! 3 numbers will be generated." print "If one of them is a '5', you lose!" count = 0 while count < 3: num = random.randint(1, 6) print num if num == 5: print "Sorry, you lose!" break count += 1 else: print "You win!" # another example - guessing game from random import randint # Generates a number from 1 through 10 inclusive random_number = randint(1, 10) guesses_left = 3 # Start your game! while guesses_left > 0: guess = int(raw_input("Your guess: ")) if guess == random_number: print "You win!" break guesses_left -= 1 else: print "You lose."
true
98c0a56d846d180558421ee8ad664466349e85fd
Gaoliu19910601/python3
/tutorial2_revamp/tut4_boolean_cond.py
1,418
4.1875
4
print('') print('-----------------BOOLEAN AND CONDITION-----------------------') print('') language = 'Java' # If the language is python then it is a true condition and would print # the first condition and so forth for the next. However if everything # is False there would be no match if language is 'Python': print('Condition was true') elif language is 'Java': print('Yes, Language is Java') else: print('No match') user = 'Admin' logged_in = False # Use of 'or' means that one of them should be true to print the first statement # Use of 'and' means both should be true to print the first statement if user is 'Admin' or logged_in: print("He's working") else: print("He's in Reeperbahn") # Use of 'not' means the opposite of true or false but to first statement, the condition # should always be true if not logged_in: print('Please log in') else: print('Welcome') # Be always careful when using the 'is' condition instead of '==' a = [1,2,3] b = [1,2,3] b2 = a print(id(a)) print(id(b)) print(id(b2)) print(a is b) # two different objects print(a == b) # but have same value print(a is b2) # two same objects print(id(a) == id(b2)) # same as 'is' condition # False values: # False # None # numeric 0 # Empty string {}, [], '' # Everything else would give true values condition = None if condition: print('Evaluated to true') else: print('Evaluated to false')
true
e4771801e9edfa915000c7522e092b4447189169
Gaoliu19910601/python3
/tutorial2_revamp/tut5_loops.py
525
4.15625
4
nums = [1, 2, 3, 4, 5] # The for loop with an if condition along with a continue statement for num in nums: if num == 3: print('Found it!') continue print(num) print('') # Nested For loop for letter in 'abc': for num in nums: print(num,letter) print('') for i in range(1, 11): print(i) print('') # If the while loop is run as 'True' instead of 'x < 10' then # it would be infinite x = 0 while x < 10: if x==5: print('Found !') break print(x) x += 1
true
47de4cf8b2e8ac30e5ed01605a5fc48f0c784224
AakashKB/5_python_projects_for_beginners
/magic_8_ball.py
670
4.125
4
import random #List of possible answer the 8 ball can choose from potential_answers = ['yes','no','maybe','try again later', 'you wish','100% yes','no freaking way'] print("Welcome to the Magic 8 Ball") #Infinite loop to keep the game running forever while True: #Asks user for input, no need to store it input("Ask a yes or no question > ") #Choose a random number between 0 and the length of the answers list rand_num = random.randrange(len(potential_answers)) #Use random number as index to pick a response from the answers list response = potential_answers[rand_num] print(response)
true
c1f77aca918cb0b177d9f42a314ff9186c4cb051
rdegraw/numbers-py
/fibonacci.py
423
4.25
4
#---------------------------------------- # # Fibonacci number to the nth position # #---------------------------------------- position = int( raw_input( "Please enter the number of Fibonacci values you would like to print: " )) sequence = [0] while len(sequence) < position: # F(n) = F(n-1) + F(n-2) if len(sequence) == 1: sequence.append(1) else: sequence.append( sequence[-2] + sequence[-1]) print sequence
true
4d0987b5fca0c8342c604f9e18cec3493dbea869
limchiahau/ringgit
/ringgit.py
2,001
4.15625
4
from num2words import num2words import locale locale.setlocale(locale.LC_ALL,'') def to_decimal(number): ''' to_decimal returns the given number as a string with groupped by thousands with 2 decimal places. number is a number Usage: to_decimal(1) -> "1.00" to_decimal(1000) -> "1,000.00" ''' return locale.currency(number,symbol=False,grouping=True) def to_ringgit_word(amount): ''' to_ringgit_word return the amount of ringgit as text. The text will be formatted in title case. amount is a number Usage: to_ringgit_word(1100) -> "Ringgit Malaysia One Thousand One Hundred Only" ''' text = num2words(amount) without_comma = text.replace(',', '') title_case = without_comma.title() return 'Ringgit Malaysia ' + title_case + ' Only' def to_ringgit(amount): ''' to_ringgit returns the amount as a ringgit string. amount is a number Usage: to_ringgit(100) -> "RM100.00" ''' amount_str = to_decimal(amount) return f'RM{amount_str}' def format_ringgit(format, amount): ''' Format ringgit returns a string that is formatted using the format string and amount passed into the function. There are 2 variables usable in the format string. 1. @amount This represents the amount as ringgit in number format "RM100.00" 2. @text This represents the amount of ringgit in text format "RINGGIT MALAYSIA ONE HUNDRED ONLY" format is a string amount is a number Usage: format_ringgit("@text\n\t(@amount)", 100) returns: Ringgit Malaysia One Hundred Only (RM100.00) ''' with_amount = format.replace('@amount', to_ringgit(amount)) with_text = with_amount.replace('@text', to_ringgit_word(amount)) return with_text if __name__ == "__main__": import sys amount = float(sys.argv[1]) amount_text = format_ringgit('@text\n\t(@amount)', amount) print(amount_text)
true
20f1dbf7f0016a9a37158b325682504e3ca3fae9
Idealistmatthew/MIT-6.0001-Coursework
/ps4/ps4a.py
2,185
4.375
4
# Problem Set 4A # Name: <your name here> # Collaborators: # Time Spent: x:xx def get_permutations(sequence): ''' Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Assume that it is a non-empty string. You MUST use recursion for this part. Non-recursive solutions will not be accepted. Returns: a list of all permutations of sequence Example: >>> get_permutations('abc') ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] Note: depending on your implementation, you may return the permutations in a different order than what is listed here. ''' ## Applying the base case if len(sequence) == 1: return sequence else: ## making a list out of the letters letter_list = list(sequence) ## storing the letter to be concatenated recursively concat_letter = letter_list[0] ## making a list to store the final permutations inductive_permutations = [] ## removing the frontmost letter from the list del letter_list[0] ## applying recursion on the function sub_permutations = get_permutations(letter_list) ## looping through the permutations obtained via recursion for permutation in sub_permutations: ## loop to add the concat_letter to every possible position within the permutation for i in range(len(permutation) + 1): ## making the permutation into a list of letters new_word_list = list(permutation) ## inserting the concat_letter into position i new_word_list.insert(i,concat_letter) ## join the list to form the permutation new_permutation = ''.join(new_word_list) ## append the permutation to the final list inductive_permutations.append(new_permutation) return inductive_permutations if __name__ == '__main__': #EXAMPLE example_input = 'abc' print('Input:', example_input) print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']) print('Actual Output:', get_permutations(example_input))
true
16865ccc69e24a0ab37cc8b9dfa4f1e3ec7dbfac
sd-karthik/karthik-repo
/Training/5.python/DAY2/fun_var_arguments.py
264
4.40625
4
# FILE : fun_var_arguments.py # Function : Factorial of a number using recursion def recur(num): if not num: return num*recur(num-1) else: return 1 num1 = input("Enter a number to find its Factorial\n") total = recur(num1 ) print "FACT(", num1,"):", total
true
c665108b6cf623aae18c528df3fda336d7ce0864
sd-karthik/karthik-repo
/Training/python/DAY1/FIbanacci.py
711
4.125
4
# Print Fibonacci series print "PRINTING FIBONACCI SERIES" print "Choose your choice\n1.\t Using Maximum limit" print "2.\t Using Number of elements to be prtinted" choice = input() ele = 1 ele2 = 0 # Printing Fibonacci the maximum limit if choice == 1 : limit = input("Enter the Maximum limit") if (ele < 1): print "invalid input" exit() else: while ele <= limit: print ele temp = ele2+ele ele2 = ele ele = temp elif choice == 2: num = input("Enter the count of FIbonacci numbers to print") count = 0 if num < 1 : print "Invalid input" exit() else: while count < num: print ele temp = ele2+ele ele2 = ele ele = temp count+=1 else: print "Invalid choice"
true
0124d1b39ff94f880401d0ece0b0ef7612e9a8cc
sd-karthik/karthik-repo
/Training/5.python/DAY5/map.py
536
4.4375
4
# FILE: map.py # Functions : Implementation of map # -> Map will apply the functionality of each elements# in a list and returns the each element def sqr(x): return x*x def mul(x): return x*3 items = [1,2,3,4,5] print "map: sqr:", map(sqr, items) # returns a list list1 = map(lambda x:x*x*x, items ) print "map:lambda x:x*x*x:", list1 items.append('ha') print "append 'ha': map:mul", map(mul, items) items.remove("ha") # returns one value print "remove 'ha': reduce: lambda x,y:x+y:",reduce(lambda x,y:x+y, items,5)
true
329a3366d612789862c773edaded12703b68da32
wwymak/algorithm-exercises
/integrator.py
1,718
4.6875
5
""" Create a class of Integrator which numerically integrates the function f(x)=x^2 * e^−x * sin(x). You need to provide the class with the minimum value xMin, maximum value xMax and the number of steps N for integration. Then the integration process should be carried out accroding to the below information. Suppose that S=∫(xMin to xMax)f(x)dx ≈ ∑(from i = 0 to N−1)0f(xi)Δx Δx=(xMax−xMin)/(N−1) xi=xMin+iΔx. The class is composed of three methods: _init_, integrate and show: 1. The method of _init_ should initialize the xMin, xMax, N and other related parameters . 2. The method of integrate should perform the integration process with the given parameters. 3. The method of show should print on the screen the result of integration. The starter file has been attached. Fill the blank and run the code. Assign the parameters with value: xMin =1, xMax =3, N = 200. The result of integration of f(x) equals to (5 digital of accuracy): """ import numpy as np import math class Integrator: def __init__(self, xMin, xMax, N): self.xMin = xMin self.xMax = xMax self.N = N self.result = 0 def fx(self, x): return np.square(x) * np.exp(-x) * np.sin(x) def integrate(self): deltaX = (self.xMax - self.xMin) / (self.N ) for i in range(N): xcurr = self.xMin + i * deltaX; # print(xcurr, 'xcurr') temp = self.fx(xcurr) * deltaX # if N %20 == 0: # print(temp, self.result) self.result += temp def show(self): print(self.result) xMin =1.0 xMax =3.0 N = 199 examp = Integrator(xMin, xMax, N) examp.integrate() examp.show() # 0.76374
true
d79fbe4393091a929a8d1e645d17e73510275986
ryokugyu/machine-learning-models
/basic_CNN.py
1,692
4.1875
4
''' Implementing a simple Convolution Neural Network aka CNN Adapated from this article: https://towardsdatascience.com/building-a-convolutional-neural-network-cnn-in-keras-329fbbadc5f5 Dataset: MNIST ''' import tensorflow as tf from keras.dataset import mnist from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Dense, Conv2D, Flatten # downloading and splitting the dataset into test and train network (X_train, y_train), (X_test, y_test) = mnist.load_data() #checking the image shape print(X_train[0].shape) #reshaping data to fit model X_train = X_train.reshape(60000,28,28,1) X_test = X_test.reshape(10000,28,28,1) # one-hot encode target column #This means that a column will be created for each output category and a binary #variable is inputted for each category. For example, we saw that the first #image in the dataset is a 5. This means that the sixth number in our array #will have a 1 and the rest of the array will be filled with 0. y_train = to_categorical(y_train) y_test = to_categorical(y_test) # Check what we get from the to_categorical function print(y_train[0]) #Building the model layer by layer model = Sequential() #add model layers model.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28,28,1))) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(Flatten()) model.add(Dense(10, activation='softmax')) #Compiling the model takes three parameters: optimizer, loss and metrics. model.compile(optimizer='adam', loss='categorical_crossentropy') model.fit(X_train, y_train, validation_data=(X_test, y_test),epochs=3) #predict first 4 images in the test set model.predict(X_test[:4])
true
72cf8c17498315d97182bec675578d40e254633a
Chippa-Rohith/daily-code-problems
/daily problems pro solutions/problem4_sorting_window_range.py
835
4.1875
4
'''Hi, here's your problem today. This problem was recently asked by Twitter: Given a list of numbers, find the smallest window to sort such that the whole list will be sorted. If the list is already sorted return (0, 0). You can assume there will be no duplicate numbers. Example: Input: [2, 4, 7, 5, 6, 8, 9] Output: (2, 4) Explanation: Sorting the window (2, 4) which is [7, 5, 6] will also means that the whole list is sorted.''' def min_window_to_sort(nums): left=right=-1 max=float('-inf') for i in range(len(nums)): if max < nums[i]: max=nums[i] if nums[i]<max: right=i min=float('inf') for i in reversed(range(len(nums))): if min > nums[i]: min=nums[i] if nums[i]>min: left=i return (left,right) print(min_window_to_sort([2, 4, 7, 5, 6, 8, 9])) # (2, 4)
true
e3bfbdcefaa83965cf00323b9ed21e584d49a118
tdtshafer/euler
/problem-5.py
644
4.125
4
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ UPPER_LIMIT = 20 def main(): divisible_number = get_divisible_number() print("The smallest positive number divisible by all numbers 1-{} is {}".format(UPPER_LIMIT, divisible_number)) def get_divisible_number(): number = UPPER_LIMIT while not is_divisible(number): number += UPPER_LIMIT return number def is_divisible(number): for x in range(1,UPPER_LIMIT+1): if number % x != 0: return False return True main()
true
e12925a5059f4578698810992b1af350f525c099
rndmized/python_fundamentals
/problems/palindrome_test.py
632
4.53125
5
#Funtion will take a string, format it getting rid of spaces and converting all # characters to lower case, then it will reverse the string and compare it to # itself (not reversed) to chek if it matches or not. def is_palindrome(word): formated_word = str.lower(word.replace(" ","")) print(formated_word) #Using slices to reverse the word(using the step -1) reversed_word = formated_word[::-1] if formated_word == reversed_word: print('"',word,'"', "is a palindrome.") else: print(word, "is NOT a palindrome.") #Test sentence/word is_palindrome("A Santa dog lived as a devil God at NASA")
true
2c10cf1677039d7ddb669acf31f16cae1027d72d
bluelotus03/build-basic-calculator
/main.py
2,215
4.34375
4
# This is a basic calculator program built with python # It does not currently ensure numbers and operators are in the correct format when input, so if you want to enjoy the program, make sure you input numbers and operators that are allowed and at the right place <3 # ------------FUNCTIONS----------------------------------- # Welcome function def welcomeMsg(): print("\nHello! Welcome to our basic calculator with Python <3") print("\nCurrently, we support the following operations for 2 numbers at a time:\nAddition, Subtraction, Division, Multiplication") # Function to do the calculations def calculationTime(): # Takes user input for 2 numbers and an operator num1 = float(input("\n\nEnter a number: ")) operator = input("\nEnter the operation (+|-|/|*): ") num2 = float(input("\nEnter another number: ")) # Perform the correct operation based on user's input if operator == "+": result = (num1) + (num2) elif operator == "-": result = (num1) - (num2) elif operator == "/": result = (num1) / (num2) elif operator == "*": result = (num1) * (num2) # Print both numbers, the operator, and the result print("\n", num1, operator, num2, "=", result) # Ask the user to go again and return their answer def goAgainQ(): goAgain = input("\nWant to go again? (Y|N) ").lower() return goAgain # ------------MAIN PROGRAM----------------------------------- # By default when the program starts, set goAgain to y for yes goAgain = 'y' # Print the welcome message welcomeMsg() # While the user does not enter n for going again question while goAgain != 'n': # Call the function for calculations calculationTime() # At end of calculation results, ask user if they want to go again and assign the input returned to the yORn variable yORn = goAgainQ() # While user input is not 'y' or 'n,' tell them that's not valid input for this question and ask ask the question again while yORn !='y' and yORn !='n': print("\nSorry friend, that doesn't seem to be a Y or N") yORn = goAgainQ() # If user inputs 'n,' print goodbye msg and end program if yORn == 'n': print("\nIt was great having you here!\nHope to see you soon! 00\n") break
true
6789ade79015ec8d4fa7552882a90b21efe697de
rushabh95/practice-set
/1.py
306
4.1875
4
# Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a #tuple with those numbers. #Sample data : 3, 5, 7, 23 m=() n = [] i = 0 while i < 4: a = int(input("enter a number: ")) n.append(a) i+=1 print(n) m = tuple(n) print(m)
true
4ddda8da0be4ee303de96079c0ee4e247343836a
Jdicks4137/function
/functions.py
1,419
4.46875
4
# Josh Dickey 9/21/16 # This program solves quadratic equations def print_instructions(): """This gives the user instructions and information about the program""" print("This program will solve any quadratic equation. You will be asked to input the values for " "a, b, and c to allow the program to solve the equation.") def get_first_coefficient(): """This allows the user to input the values for a""" a = float(input("what is the value of a?")) return a def get_second_coefficient(): """This allows the user to input the values for b""" b = float(input("what is the value of b?")) return b def get_third_coefficient(): """This allows the user to input the values for c""" c = float(input("what is the value of c?")) return c def calculate_roots(a, b, c): """this is the formula the computer will calculate""" x = (-b + (b ** 2 - 4 * a * c) ** (1/2)) / (2 * a) y = (-b - (b ** 2 - 4 * a * c) ** (1/2)) / (2 * a) return x, y def main(): """this is the function that runs the entire program""" print_instructions() first_coefficient = get_first_coefficient() second_coefficient = get_second_coefficient() third_coefficient = get_third_coefficient() root1, root2 = calculate_roots(first_coefficient, second_coefficient, third_coefficient) print("the first root is:", root1, "and the second root is:", root2) main()
true
575de7537ae45b6d88a0b208999b95fd34dcb314
birkoff/data-structures-and-algorithms
/minswaps.py
1,856
4.40625
4
''' There are many different versions of quickSort that pick pivot in different ways. - Always pick first element as pivot. - Always pick last element as pivot (implemented below) - Pick a random element as pivot. - Pick median as pivot. ''' def find_pivot(a, strategy='middle'): if strategy and 'middle' == strategy: middle = int(len(a)/2) - 1 return middle # handle when value is too small or too big if a[middle] < if strategy and 'biggest' == strategy: biggest = None for i in range(len(a)): if biggest is None or a[i] > a[biggest]: biggest = i return biggest def partition(a, left, right): i_left = left # index of the smaller element if right >= len(a): return pivot = a[right] # Always pick last element as pivot for i_current in range(left, right): current = a[i_current] if current <= pivot: i_left = i_left + 1 a[i_left], a[i_current] = a[i_current], a[i_left] if (i_left + 1) < len(a): a[i_left+1], a[right] = a[right], a[i_left+1] return i_left + 1 def quicksort(a, left, right): if left < right and right < len(a): pi = partition(a, left, right) # Separately sort elements before # partition and after partition if pi is None: return quicksort(a, left, pi + 1) quicksort(a, pi + 1, right) # # pivot = find_pivot(a) # left = 0 # right = len(a) # # # for i_left in range(len(a)): # if a[i_left] > a[pivot]: # # return biggest def find_min_swaps(a): arr = a n = len(arr) quicksort(arr, 0, n-1) print("Sorted array is:") for i in range(n-1): print("%d" % arr[i]) a = [4, 3, 1, 2, 6, 9, 8, 7, 5] print(find_min_swaps(a))
true
4bc3fc901daf36615ffb6d76dc103c1fc56c9c69
alex-rantos/python-practice
/problems_solving/binaryTreeWidth.py
1,597
4.125
4
import collections """Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null. The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation. """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 indexDic = collections.defaultdict(list) def rightTraverse(node, index, depth): nonlocal indexDic if depth not in indexDic: indexDic[depth] = [index, index] else: indexDic[depth][0] = min(indexDic[depth][0], index) indexDic[depth][1] = max(indexDic[depth][1], index) #print(f'{depth} :: {node.val} -> {index}') nextIndex = index * 2 if node.left: rightTraverse(node.left, nextIndex - 1, depth + 1) if node.right: rightTraverse(node.right, nextIndex, depth + 1) rightTraverse(root, 1, 0) ans = 0 for depth in indexDic.keys(): ans = max(ans, indexDic[depth][1] - indexDic[depth][0] + 1) return ans
true
2991deeeb5aa13cc1a542f989111479f0b5680a8
alex-rantos/python-practice
/problems_solving/sortColors.py
1,248
4.21875
4
from typing import List """ Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. """ class Solution: def sortColors(self, nums: List[int]) -> List[int]: # O(n) solution cur = zeros = 0 twos = len(nums)-1 while (cur <= twos): if (nums[cur] == 0): nums[cur], nums[zeros] = nums[zeros], nums[cur] cur += 1 zeros += 1 elif nums[cur] == 1: cur += 1 else: nums[cur], nums[twos] = nums[twos], nums[cur] twos -= 1 def sortColorsN2(self, nums: List[int]) -> List[int]: # O(n^2) solution dic = { 0: [], 1: [], 2: [] } for i, c in enumerate(nums): dic[c].append(i) for i in range(len(nums)): if i < len(dic[0]): nums[i] = 0 elif i < len(dic[0])+len(dic[1]): nums[i] = 1 else: nums[i] = 2
true
4d8a8b1dc9e26df64db21565ae4f6ba97d9120fd
alex-rantos/python-practice
/problems_solving/hammingDIstance.py
529
4.15625
4
""" The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. """ class Solution: def hammingDistance(self, x: int, y: int) -> int: xorResult = x ^ y hd = 0 while xorResult > 0: hd += xorResult & 1 xorResult >>= 1 return hd def test(self): self.hammingDistance(1, 4) == 2 if __name__ == "__main__": sol = Solution() sol.test()
true
6fd1b9e364aa0650e4601f0973d79e8927c8759a
alex-rantos/python-practice
/problems_solving/remove_unnecessary_lists.py
906
4.375
4
""" Extracts all inner multi-level nested lists and returns them in a list. If an element is not a list return the element by itseft """ from itertools import chain # stackoverflow answer def remove_unnecessary_lists(nested_list): for item in nested_list: if not isinstance(item,list): yield item elif list(chain(*item)) == item: yield item else: yield from remove_unnecessary_lists(item) if __name__ == '__main__': my_nested_list = [['a', 'b', 'c', 'd'],['e', [["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]] l = [['a', 'b', 'c', 'd'],[["d","d","g"],[[["a"]]],[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]] #my_nested_list = [['a', 'b', 'c', 'd'],['e', ['r'], [["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]] flat_list = list(remove_unnecessary_lists(my_nested_list)) print(flat_list)
true
20bd0c0f04c09ad0bb8fa522b113e43c5a99c0db
shilihui1/Python_codes
/dict_forloop.py
565
4.40625
4
'''for loop in dictionary, using dictionary method a.items()''' a = {1: 'a', 2: 'b', 3: 'c', 4: 'd'} # items method for dictionary for key, value in a.items(): print(str(key) + "--" + str(value)) # keys method for dictionary for key in a.keys(): print(key) # values method for dictionary for value in a.values(): print(value) print("\nBEGIN: REPORT\n") # Iterate over the key-value pairs of kwargs for keys, values in a.items(): # Print out the keys and values, separated by a colon ':' print(str(keys) + ": " + values) print("\nEND REPORT")
true
e4960cabf2330beb1601b933756820e83b9f87f0
rickjiang1/python-automate-boring-stuff
/RegExp_Basic.py
915
4.375
4
#regular expression basics!! #this is the way of how to define a phonenumber ''' def isPhoneNumber(text): if len(text)!=12: print('This is more than 12 digit') return False for i in range(0,3): if not text[i].isdecimal(): return False #no area code if text[3]!='-': return False for i in range(4,7): if not text[i].isdecimal(): return False if text[7] !='-': return False #missing second dash for i in range(8,12): if not text[i].isdecimal(): return False return True print(isPhoneNumber('501-827-0039')) ''' #use regular expressions message='Call me 415-555-1011 tommorrow, or at 501-827-0039' foundNumber=False import re PhoneNUmberRe=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') #find one print(PhoneNUmberRe.search(message).group()) print('\n') #find all print(PhoneNUmberRe.findall(message))
true
fad659a950108ac733dc6821e1506181c21c7fe5
makaiolam/conditions-and-loops
/main.py
1,955
4.125
4
# first = input("what is your first name") # last = input("what is your last name") # print(f"you are {last}, {first}") #loops #----------------------------- # print(1) # print(2) # print(3) # print(4) # print(5) #while loop # while loop takes a boolean epxression (t/f) #boolean operations #--------------------- #comparision operators # x < 5 (less than) # x > 5 (greater than) # x <= 5 (less than or equal too) # x >= 5 (greater than or equal too) # x == 5(equal) # x != 5 (not equal to) #logical operatos # and # or # not # infinite loop, watch out for # counter = 0 # while(counter <= 5): # print(counter) # counter = counter + 1 # for loops # range(5) => 0,1,2,3,4. # counter = 0 # for counter in range(5): # print(counter + 1) #list of numbers numbers = [1,2,3,4,5] sum = 0 for counter in range(1,6): sum = sum + counter print(sum) #conditionals #---------------------- # definition if x then y # ex. if i go to school then i will learn # money = 5 # if money == 5: # print("i have 5 dollars") # elif money == 6: # print ("i have 6 dollars") # elif money == 7: # print ("i have 7 dollars") # else: # print("i have a different amount of money") # winter, fall, summer, spring # season = input ("what is the season? ") # if season == "winter": # print("go inside") # if season == "spring": # print("go outside and plant") # if season == "summer": # print("go and water plants") # if season == "fall" # print("start to pick the plants") # guess the number game import random computernumber = randomnumber (0-10) numberoftries = 5 win = false play = true while play == true: while numberoftries > 0: playnumber: input("enter a number between 0-10:") playernumber = int(playernumber) if playernumber > 10: print("bad number") else: if playernumber < "computernumber": print("number too low") else: if playernumber > computernumber: print("number too high")
true
d26cd8f44b032e6233a2aa5399b4623ce2b3cfaf
TL-Web30/CS35_IntroPython_GP
/day1/00_intro.py
1,407
4.25
4
# This is a comment # lets print a string # print("Hello, CS35!", "Some other text", "and theres more...") # variables # label = value # let const var (js) # int bool short (c) # first_name = "Tom" # # print("Hello CS35 and" , first_name) # num = 23.87 # # f strings # my_string = " this is a string tom" # print(my_string) # print(my_string.strip()) # print(len(my_string)) # print(len(my_string.strip())) # print(f"Hello CS35 and {first_name}.......") # print("something on a new line") # collections # create an empty list? Array # print(my_list) # create a list with numbers 1, 2, 3, 4, 5 # add an element 24 to lst1 # print(lst1) # # print all values in lst2 # print(lst2) # loop over the list using a for loop # while loop # List Comprehensions # Create a new list containing the squares of all values in 'numbers' numbers = [1, 2, 3, 4] squares = [] print(numbers) print(squares) # Filtering with a list comprehension evens = [] # create a new list of even numbers using the values of the numbers list as inputs print(evens) # create a new list containing only the names that start with 's' make sure they are capitalized (regardless of their original case) names = ["Sarah", "jorge", "sam", "frank", "bob", "sandy"] s_names = [] print(s_names) # Dictionaries # Create a new dictionary # empty # key value pairs # access an element via its key
true
166366c2f5457e02d5aee7dd44936a966ca17f56
tringhof/pythonprojects
/ex15.py
806
4.21875
4
#import argv from sys module from sys import argv #write the first argv argument into script, the second into filename script, filename = argv #try to open the file "filename" and save the file object into txt txt = open(filename) print "Here's your file %r: " %(filename) #use the read() command on that file object print txt.read() txt.close() print "Type the Filename again:" file_again = raw_input("> ") txt_again=open(file_again) print txt_again.read() txt.close() # close -- Closes the file. Like File->Save.. in your editor. # read -- Reads the contents of the file. You can assign the result to a variable. # readline -- Reads just one line of a text file. # truncate -- Empties the file. Watch out if you care about the file. # write('stuff') -- Writes "stuff" to the file.
true
3868ad37a26a7ca1b5799e155c5433200e5c98ff
bmilne-dev/cli-games
/hangman.py
2,259
4.40625
4
# a hangman program from scratch. from random import randint filename = "/home/pop/programming/python_files/word_list.txt" with open(filename) as f: words = f.read() word_list = words.split() # define a function to select the word def word_select(some_words): """choose a word for hangman from a word list""" some_word = some_words[randint(0, len(some_words) - 1)] return some_word # define a function to display the word using an external # list of previous guesses def display_word(some_word, my_guesses): """take the selected word and a list of user guesses and return a string that only shows previously guessed letters while replacing unknown letters with *""" hidden_list = [] for letter in some_word: if letter in my_guesses: hidden_list.append(letter) else: hidden_list.append('*') return ''.join(hidden_list) # define a function to receive the proper input # meaning, the user can only input valid char's and only 1 at a time def take_guess(): """accept user guesses and make sure they are the proper format""" user_guess = input("Take a guess!\n> ") while not user_guess.isalpha(): user_guess = input("\nAlpha-Numeric characters only!" "\nTake a guess!\n> ") while len(user_guess.strip()) > 1: user_guess = input("\nOne letter at a time please!" "\nTake a guess!\n> ") return user_guess # define a function to check if the guess is in the word def check_guess(user_guess, some_word, my_guesses): """see if user guessed correctly!""" if user_guess in some_word: return True else: return False word = word_select(word_list) guesses = [] n = 0 print(f"Welcome to hangman!") while True: if n == 6: print("Out of guesses!") print(f"The word was {word}!") break print(f"\nYou have {6 - n} guesses left") print("Your word:") print(display_word(word, guesses)) guess = take_guess() guesses.append(guess) display = display_word(word, guesses) if display == word: print(f"You got it!") break elif not check_guess(guess, word, guesses): n += 1
true
4b4a167aaefb2d6ccb840937f02b32a2fab0ae71
jamesledwith/Python
/PythonExercisesWk2/4PercentageFreeSpace.py
627
4.28125
4
#This program checks the percentage of disk space left and prints an apropiate response total_space = float(input("Enter total space: ")) amount_used = float(input("Enter amount used: ")) free_space_percent = 100 * (total_space - amount_used) / total_space; print(f"The percentage of free space is {free_space_percent:.1f}%") if amount_used > total_space: print("Input data is Invalid") elif total_space == amount_used: print("Warning: System full") elif 5 <= free_space_percent < 100: print("System has sufficient disk space") elif 0 <= free_space_percent < 5 : print("Warning, low disk space")
true
25f42be209ce937b382bd74243f2ce5a4df391c5
jamesledwith/Python
/PythonExercisesWk2/3MatchResults.py
472
4.125
4
#This program displays a match result of two teams hometeam_name = input("Home team name? ") hometeam_score = int(input("Home team score? ")) awayteam_name = input("Away team name? ") awayteam_score = int(input("Away team score? ")) if hometeam_score > awayteam_score: print("Winner: ",hometeam_name) elif awayteam_score > hometeam_score: print("Winner: ",awayteam_name) elif awayteam_score == hometeam_score: print("Draw") else: print("Invalid")
true
1de73cda72d4391293a1631173215ba74174d025
jamesledwith/Python
/PythonExercisesWk1/11VoltageToDC.py
327
4.40625
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 23 12:59:21 2020 @author: James """ import math print("This program calculates the Voltage in a DC Circuit") power = int(input("Enter the power: ")) resistance = int(input("Enter the resistance: ")) voltage = math.sqrt(power * resistance) print(f"Voltage is {voltage}")
true
e8cd3d172cba768564a53ad50340913e243ef8fa
hsalluri259/scripts
/python_scripts/odd_even.py
946
4.53125
5
#!/opt/app/python3/bin/python3.4 ''' Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: If the number is a multiple of 4, print out a different message. Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. ''' number = int(input("Enter a number:")) if number % 2 == 0 and number % 4 == 0: print("%d is divided by 4" % number) elif number % 2 == 0: print("%d is just Even" % number) else: print("%d is Odd" % number) num1 = int(input("Enter number1:")) num2 = int(input("Enter number2:")) if num1 % num2 == 0: print("%d is evenly divided by %d" % (num1,num2)) else: print("%d is not divided by %d" % (num1,num2))
true