blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9fdc839e30c4eccbb829abfa30178545f2f3f7b3 | sheayork/02A-Control-Structures | /E02a-Control-Structures-master/main06.py | 719 | 4.5 | 4 | #!/usr/bin/env python3
import sys
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
print('Greetings!')
color = input("What is my favorite color? ")
if (color.lower().strip() == 'red'):
print('Correct!')
else:
print('Sorry, try again.')
##BEFORE: Same as before, but some people may put spaces in-between letter or right after typing something
## (I know I have a bad habit of doing the latter when it comes to typing papers). So basically the program
## will remove those spaces and change everything to lowercase letters to tell if the answer
## is right or not.
##AFTER: It didn't do it for spaces in-between letters, but otherwise I was correct. | true |
b93667bb58dfc610850d6ffa407ee418af6f44b0 | Mamedefmf/Python-Dev-Course-2021 | /magic_number/main.py | 1,233 | 4.15625 | 4 | import random
def ask_number (min, max):
number_int = 0
while number_int == 0:
number_str = input(f"What is the magic number ?\nType a number between {min} and {max} : ")
try:
number_int = int(number_str)
except:
print("INPUT ERROR: You need to type a valid number")
else:
if number_int < min or number_int > max:
print(f"INPUT ERROR: You must give a number between {min} and {max}")
number_int = 0
return number_int
MIN_NUMBER = 1
MAX_NUMBER = 10
MAGIC_NUMBER = random.randint(MIN_NUMBER, MAX_NUMBER)
NB_LIVES = 4
number = 0
lives = NB_LIVES
while not number == MAGIC_NUMBER and lives > 0:
print(f"You have {lives} attempts left")
number = ask_number(MIN_NUMBER, MAX_NUMBER)
if number > MAGIC_NUMBER:
print(f"{number} is greater than the Magic Number")
lives -= 1 # subtract 1 live
elif number < MAGIC_NUMBER:
print(f"{number} is lower than the Magic Number")
lives = lives - 1 # subtract 1 live
else:
print(f"You Won! the Magic Number is {MAGIC_NUMBER}\n Congratulations !!!")
if lives == 0:
print(f"You Lost!\nThe magic number was: {MAGIC_NUMBER}") | true |
2a2ae134cceba04732db0f61fb19f83221ca3f1d | pranavkaul/Coursera_Python_for_Everybody_Specialization | /Course-1-Programming for everybody-(Getting started with Python/Assignment_6.py | 999 | 4.3125 | 4 | #Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
#Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours.
#Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation.
#The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75).
#You should use input to read a string and float() to convert the string to a number.
#Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly.
#Do not name your variable sum or use the sum() function.
def computepay(h,r):
if h > 40:
total = (((1.5 * r) * (h-40)) + (40 * r))
else:
total = h * r
return total
hours = input('Hours')
h = float(hours)
rate = input('Rate')
r = float(rate)
total = computepay(h,r)
print ("Pay",total)
| true |
df4a4165ed70cee917e537eb19b1ed040703dbc7 | Craby4GitHub/CIS129 | /Mod 2 Pseudocode 2.py | 2,879 | 4.3125 | 4 | ########################################################################################################################
# William Crabtree #
# 27Feb17 #
# Purpose: To figure out what the user will do for a week long vaction based on certain perferances #
# and money avaiablity. #
########################################################################################################################
# Setting trip values
florence = 1500
staycation = 1400
camping = 240
visitingParents = 100
kayakinginLake = 100
print("Oh, you are going on a vacation? Lucky you!")
print("So we need to ask how much money you have to spend on this vacation")
totalMoney = int(input("What disposable income do you have for this trip? "))
print("Ok, now that we know how much you have, lets figure out what some of your perferences are.")
# Then we start asking questions
goingAbroad = input("What about going abroad? ")
if goingAbroad == "y":
if florence <= totalMoney:
print("Hey, you can go to Florence!")
print("Going to Florence will cost a total of", florence)
else:
print("You can't go abroad because it will cost", florence)
drivingLongDistance = input("Are you willing or capable of driving a long distance? ")
if drivingLongDistance == "y":
alone = input("Do you want to be alone? ")
if alone == "y":
if kayakinginLake <= totalMoney:
print("You can go Kayaking in a remote lake.")
print("That will only cost you gass money in the total of", kayakinginLake)
else:
print("You can't afford Kayaking in a lake becauseit costs", kayakinginLake)
if camping <= totalMoney:
print("You can go camping in a park.")
print("That will cost you a total of", camping)
else:
print("You can't go camping because it costs", camping)
if alone == "n":
if visitingParents <= totalMoney:
print("You can vist your parents, they miss you.")
print("The only thing you need to buy is gas with a total cost of", visitingParents)
else:
print("You can't visit your parents because it costs", visitingParents)
elif drivingLongDistance == "n":
if staycation <= totalMoney:
print("Hey, you can do a Staycation at a nearby resort.")
print("A Staycation will cost you a total of", staycation)
else:
print("You cant do a Staycation because it costs", staycation)
| true |
4b1ae200aa26d0259e03ec346abdb42c4671b26b | Craby4GitHub/CIS129 | /Final/Final.py | 2,265 | 4.1875 | 4 | ########################################################################################################################
# William Crabtree #
# 26Apr17 #
# Purpose: The magic Triangle! #
########################################################################################################################
# Create list to show user where their input goes
usersNum = ["First Entry", "Second Entry", "Third Entry"]
genNum = ['Empty', 'Empty', 'Empty']
# Define how the triangle prints out
def triangle():
# Basically, centering of the triangle so it always looks like a triangle
fourth = '({}) [{}] ({})'.format(genNum[0], usersNum[1], genNum[2])
second = '[{}]'.format(usersNum[2]).center(int(len(fourth)/2), ' ')
third = '[{}]'.format(usersNum[0]).center(int(len(fourth)/2), ' ')
first = '({})'.format(genNum[1]).center(int(len(second) + len(third)), ' ')
print(first)
print(second, end="")
print(third)
print(fourth)
def UserLoop():
# Loop three times
for i in range(3):
# Error Catch
try:
# Ask user for a number
number = int(input("Enter a number between -40 and 40: "))
# if users number is less than -40 or greater than 40, kick em out
if -40 <= number <= 40:
usersNum[i] = number
else:
print("Number was not in the correct range.")
print(len(usersNum))
exit()
except ValueError:
print("You did not enter a valid number.")
exit()
def Math():
# Get the total sum of numbers inputted and half it
totalSum = int(sum(usersNum))/2
# Subtract the sum from the opposite number and input that value into genNum
for generatedNumber in range(3):
genNum[generatedNumber] = totalSum - int(usersNum[generatedNumber])
print("Here is the triangle:")
triangle()
UserLoop()
Math()
print("Here is your final triangle.")
triangle()
| true |
f5f85d737006dc462254a2926d4d7db88db72cb6 | WarrenJames/LPTHWExercises | /exl9.py | 1,005 | 4.28125 | 4 | # Excercise 9: Printing, Printing, Printing
# variable "days" is equal to "Mon Tue Wed Thu Fri Sat Sun"
days = "Mon Tue Wed Thu Fri Sat Sun"
# variable "months" is Jan Feb Mar Apr May Jun Aug seperated by \n
# \n means words written next will be printed on new a line
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nAug"
# prints string of text "Here are the days: " and varible, days
print "Here are the days: ", days # prints as "Here are the days: Mon Tue Wed Thu Fri Sat Sun"
print "Here are the months: ", months
# prints as "Here are the months:
# Jan
# Feb
# Mar
# Apr
# Jun
# Aug
# prints """ triple double-quotes which is a long string capable of printing on multiple lines.
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5 , or 6.
"""
# prints as
# "There's something going on here.
# With the three double-quotes.
# We'll be able to type as much as we like.
# Even 4 lines if we want, or 5 , or 6."
| true |
e6f1bf912c575ed81b4b0631514ee67943a26f2f | WarrenJames/LPTHWExercises | /exl18.py | 1,977 | 4.875 | 5 | # Excercise 18: Names, Variables, Code, Functions
# Functions do three things:
# They name pieces of code the way variables name strings and numbers.
# They take arguments the way your scripts take argv
# Using 1 and 2 they let you make your own "mini-scripts" or "tiny commands"
# First we tell python we want to make a function using def for "define".
# On the same line as def we give the function a name. In this case we just
# called it print_two but it could also be "peanuts". It doens't matter,
# except that the function should have a short name that says what it does.
# without the asterisk, python will believe print_two accepts 1 variable.
# Tells python to take all the arguments to the function and then put them in
# args as a list. It's like agrv but for functions. not used too
# often unless specifically needed
## def print_two(*args):
## arg1, arg2 = args
## print "arg1: %r, arg2: %r" % (arg1, arg2)
# okay that *args is actually pointless
# define(function) name is print_two_again(arg1, arg2): <-- don't forget the ":"
# it tells what print_two_again consists of, which so happens to be printing
# "Senor: (raw modulo), El: (raw modulo)" % modulo is (arg1, arg2) or
# (James, Warren)
def print_two_again(arg1, arg2):
print "Senor: %r, El: %r" % (arg1, arg2)
# this just takes one argument
# define(function) print_one(variable arg1 which equals First): <-- consists of
# print "the: %raw modulo" raw modulo is arg1 which is "first"
def print_one(arg1):
print "the: %r" % arg1
# this one takes no arguments
# define print_none(): empty call expression consists of printing
# "I got nothin'."
def print_none():
print "I got nothin'."
## print_two("James","Warren")
# lines 43 to 45 all call functions
# calls print_two_again("James", "Warren") for arg1 and arg2
# calls print_one("First!") for arg1
# calls print_none() with no arguments
print_two_again("James","Warren")
print_one("First!")
print_none()
| true |
fd90e5312f0798ca3eb88c8139bdd2fe17786654 | SaloniSwagata/DSA | /Tree/balance.py | 1,147 | 4.15625 | 4 | # Calculate the height of a binary tree. Assuming root is at height 1
def heightTree(root):
if root is None:
return 0
leftH = heightTree(root.left)
rightH = heightTree(root.right)
H = max(leftH,rightH) # height of the tree will be the maximum of the heights of left subtree and right subtree
return H+1 # +1 for the contribution of root
# Check if tree is balanced or not
def BalanceTree(root):
if root is None:
return True
leftH = heightTree(root.left)
rightH = heightTree(root.right)
if abs(leftH-rightH)>1:
return False
isLeftBalance = BalanceTree(root.left)
isRightBalance = BalanceTree(root.right)
if isLeftBalance and isRightBalance:
return True
else:
return False
# Check if tree is balanced or not using single function
def isBalanced(root):
if root is None:
return 0,True
lh, leftisB = isBalanced(root.left)
rh, rightisB = isBalanced(root.right)
h = max(lh,rh)+1
if abs(lh-rh)>1:
return h,False
if leftisB and rightisB:
return h,True
else:
return h,False | true |
4af84efdf7b997185c340f2b69e7873d5b87df73 | SaloniSwagata/DSA | /Tree/BasicTree.py | 1,377 | 4.1875 | 4 | # Creating and printing a binary tree
# Creating a binary tree node
class BinaryTreeNode:
def __init__(self,data):
self.left = None
self.data = data
self.right = None
# Creating a tree by taking input tree wise (i.e, root - left subtree - right subtree)
# For None, the user enters -1
def FullTreeInput():
rootdata = int(input())
if rootdata==-1:
return None
root = BinaryTreeNode(rootdata)
leftChild = FullTreeInput()
rightChild = FullTreeInput()
root.left = leftChild
root.right = rightChild
return root
# Printing tree simple way
def printTree(root):
if root==None:
return
print(root.data)
printTree(root.left)
printTree(root.right)
# Detailed printing of tree
def printDetailedTree(root):
if root == None:
return
print(root.data, end=":")
if root.left != None:
print("L ",root.left.data, end=" ,")
if root.right!=None:
print("R ",root.right.data)
print()
printDetailedTree(root.left)
printDetailedTree(root.right)
# Counting the number of nodes in tree
def numnodes(root):
if root == None:
return 0
left = numnodes(root.left)
right= numnodes(root.right)
return 1+left+right
btn1 = BinaryTreeNode(2)
btn2 = BinaryTreeNode(3)
btn3 = BinaryTreeNode(4)
btn1.left = btn2
btn1.right = btn3 | true |
c868093ac8ba3e14bad9835728fcc45598e0dfd5 | SaloniSwagata/DSA | /Tree/levelOrder.py | 1,309 | 4.25 | 4 | # Taking input level order wise using queue
# Creating a binary tree node
class BinaryTreeNode:
def __init__(self,data):
self.left = None
self.data = data
self.right = None
import queue
# Taking Level Order Input
def levelInput():
rootData = int(input("Enter the root node data: "))
if rootData ==-1:
return None
root = BinaryTreeNode(rootData)
q = queue.Queue()
q.put(root)
while not(q.empty()):
current_node = q.get()
leftdata = int(input("Enter the left node data: "))
if leftdata!=-1:
leftnode = BinaryTreeNode(leftdata)
current_node.left = leftnode
q.put(leftnode)
rightdata = int(input("Enter the right node data: "))
if rightdata!=-1:
rightnode = BinaryTreeNode(rightdata)
current_node.right = rightnode
q.put(rightnode)
return root
# Level Order Output
def levelInput(root):
if root is None:
print("Empty tree")
else:
q = queue.Queue()
q.put(root)
while not(q.empty()):
current_node = q.get()
if current_node is not None:
print(current_node.data,end=" ")
q.put(current_node.left)
q.put(current_node.right) | true |
dbd90779db40037c1cdf29d85485c84b397405fc | Sudeep-K/hello-world | /Automating Tasks/Mad Libs.py | 1,445 | 4.5 | 4 | #! python
'''
Create a Mad Libs program that reads in text files and lets the user add
their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB
appears in the text file.
The program would find these occurrences and prompt the user to
replace them.
The results should be printed to the screen and saved to a new text file.
'''
import re
#textFile = input('Enter the name of path of your file:)')
#TODO: read the content of file
fileObject = open('F:\\python\\purre.txt')
text = fileObject.read()
fileObject.close()
#TODO: replace the occurences of word ADJECTIVE, NOUN, ADVERB, or VERB appearing in the text file.
adjective = input('Enter an adjective')
noun1 = input('Enter a noun')
verb = input('Enter a verb')
noun2 = input('Enter a noun')
#TODO: create regex to replace above occurences in text file
#replace occurence of adjective
text = re.sub(r'\b{}\b'.format('ADJECTIVE'), adjective, text)
#replace occurence of noun
text = re.sub(r'^(.*?)\b{}\b'.format('NOUN'), r'\1{}'.format(noun1), text)
#replace occurence of verb
text = re.sub(r'\b{}\b'.format('VERB'), verb, text)
#replace occurence of noun
text = re.sub(r'^(.*?)\b{}\b'.format('NOUN'), r'\1{}'.format(noun2), text)
#TODO: print result to the screen
print(text)
#TODO: save result to the file
fileObject = open('F:\\python\\textfile.txt', 'w')
fileObject.write(text)
fileObject.close()
input('Enter \'ENTER\' to exit (:')
| true |
e10c4cd35fce90bc44dbb4dd3ffaf75b13adcaa9 | harishvinukumar/Practice-repo | /Break the code.py | 1,503 | 4.28125 | 4 | import random
print('''\t\t\t\t\t\t\t\t### --- CODEBREAKER --- ###
\t\t\t\t\t1. The computer will think of 3 digit number that has no repeating digits.
\t\t\t\t\t2. You will then guess a 3 digit number
\t\t\t\t\t3. The computer will then give back clues, the possible clues are:
\t\t\t\t\tClose: You've guessed a correct number but in the wrong position
\t\t\t\t\tMatch: You've guessed a correct number in the correct position
\t\t\t\t\tNope: You haven't guess any of the numbers correctly
\t\t\t\t\t4. Based on these clues you will guess again until you break the code with a perfect match!''')
digits = list(range(10))
random.shuffle(digits)
list1 = digits[:3]
#print(list1)
string1 = ""
random.shuffle(list1)
for i in list1:
string1 = string1 + str(i)
# Another hint:
string2 = "123"
while string1 != string2:
guess = int(input("What is your guess?: "))
string2 = str(guess)
if string1[0] == string2[0]:
print("Match (in first position!)")
if string1[1] == string2[1]:
print("Match (in second position!)")
if string1[2] == string2[2]:
print("Match (in third position!)")
if (string2[0] in string1[1:]) or (string2[2] in string1[:2]) or (string2[1] == string1[0] or string2[1] == string1[2]):
print("Close")
if (string2[0] not in string1) and (string2[1] not in string1) and (string2[2] not in string1):
print("Nope")
if string1 == string2:
print("You Broke the Code! (Code: {})".format(string1))
break
| true |
97aa8452a4bab355d139eed764ebfd5f692ab06b | shaikzia/Classes | /yt1_cor_classes.py | 691 | 4.21875 | 4 | # Program from Youtube Videos - corey schafer
"""
Tut1 - Classes and Instances
"""
#Defining the class
class Employee:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
# Creating an instances of the class
emp1 = Employee('Muhammad', 'Faiz', 60000)
emp2 = Employee('Zairah', 'Shaik',50000)
emp3 = Employee('Muhammad', 'Saad',50000)
#Printing the email
print(emp1.email)
print(emp2.email)
print(emp3.email)
# Print the Full Name
print(emp1.fullname())
print(emp2.fullname())
print(emp3.fullname()) | true |
4e592149e3f98f2d428bb5a37dd85431ad7be763 | Deepkumarbhakat/Python-Repo | /factorial.py | 206 | 4.25 | 4 | #Write a program to find the factorial value of any number entered through the keyboard
n=5
fact=1
for i in range(0,n,-1):
if i==1 or i==0:
fact=fact*1
else:
fact=fact*i
print(fact) | true |
27cd32606dddc864ce68c35f824a533e1467419d | Deepkumarbhakat/Python-Repo | /function3.py | 243 | 4.28125 | 4 | # Write a Python function to multiply all the numbers in a list.
# Sample List : (8, 2, 3, -1, 7)
# Expected Output : -336
def multiple(list):
mul = 1
for i in list:
mul =mul * i
print(mul)
list=[8,2,3,-1,7]
multiple(list) | true |
3a98e9a55e3217f3f4faa76b71ab08a75adf1d8e | Deepkumarbhakat/Python-Repo | /function9.py | 434 | 4.25 | 4 | # Write a Python function that takes a number as a parameter and check the number is prime or not.
# Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors
# other than 1 and itself.
def prime(num):
for i in range(2,num//2):
if num % i == 0:
print("not prime")
break
else:
print("prime")
num=int(input("enter any number : "))
prime(num) | true |
63507dcd1e550687bbc7d6108211bd15cf2164af | Deepkumarbhakat/Python-Repo | /string15.py | 282 | 4.15625 | 4 | # Write a Python program that accepts a comma separated sequence of words as input
# and prints the unique words in sorted form (alphanumerically).
# Sample Words : red, white, black, red, green, black
# Expected Result : black, green, red, white,red
st=("input:"," , ")
print(st)
| true |
5ed7472af54b4e92e4f8b8160dbdfa42fc8a0c7b | deepabalan/byte-of-python | /functions/function_varargs.py | 720 | 4.15625 | 4 |
# When we declare a starred parameter such as *param, then all the
# positional arguments from that point till the end are collected as
# a tuple called 'param'.
# Similarly, when we declare a double-starred parameter such as **param,
# then all the keyword arguments from that point till end are collected
# as a dictionary called 'param'.
def total(a=5, *numbers, **phonebook):
print ('a', a)
# iterate through all the items in tuple
for single_item in numbers:
print('single_item', single_item)
# iterate through all the items in dictionary
for first_part, second_part in phonebook.items():
print(first_part, second_part)
total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560)
| true |
e2f198706079a03d282121a9959c8e913229d07c | hazydazyart/OSU | /CS344/Homework2/Problem4.py | 959 | 4.15625 | 4 | #Megan Conley
#conleyme@onid.oregonstate.edu
#CS344-400
#Homework 2
import os
import sys
import getopt
import math
#Function to check if a number is prime
#Arguments: int
#Return: boolean
#Notes: a much improved function to find primes using the sieve, this time using the
#square root hint from Homework 1.
def isPrime(input):
for i in range (2, int(math.sqrt(input))+1):
if (input % i) == 0:
return False
return True
#Function which finds and prints nth prime
#Arguments: passed from command line
#Return: none
def findPrime(argv):
count = 0
val = 2
if len(sys.argv) != 2:
print 'Usage: python Problem4.py <number>'
sys.exit(2)
userInput = int(sys.argv[1])
#Loops until the number of primes founds reaches the user's input upper bound and prints it
while count < userInput:
if isPrime(val):
count += 1
if count == userInput:
print 'The ' + str(userInput) + 'th prime is ' + str(val)
val += 1
if __name__ == '__main__':
findPrime(sys.argv[1:])
| true |
a5b0bcd93668247dbaeaa869de1e1f136aa32f28 | emilyscarroll/MadLibs-in-Python | /MadLibs.py | 593 | 4.21875 | 4 | # Story: There once was a very (adjective) (animal) who lived in (city). He loved to eat (type of candy).
#1) print welcome
#2) ask for input for each blank
#3) print story
print("Hello, and welcome to MadLibs! Please enter the following words to complete your story.")
adj = input("Enter an adjective: ")
animal = input("Enter a type of animal: ")
city = input( "Enter the name of a city: ")
candy = input("Enter a type of candy: ")
\n
print("Thank you! Your story is:")
\n
print("There once was a very " + adj + " " + animal + " who lived in " + city + ". He loved to eat " + candy + ".")
| true |
4f82dfb7a6b951b9a5fed1546d0743adb4109fbd | kkeller90/Python-Files | /newton.py | 335 | 4.375 | 4 | # newtons method
# compute square root of 2
def main():
print("This program evaluates the square root of 2 using Newton's Method")
root = 2
x = eval(input("Enter number of iterations: "))
for i in range(x):
root = root - (root**2 - 2)/(2*root)
print(root)
main()
| true |
bb83df21cb7dc89440d61876288bfd6bafce994d | ZzzwyPIN/python_work | /chapter9/Demo9_2.py | 1,137 | 4.28125 | 4 | class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year)+' '+self.make+' '+self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading)+" miles on it.")
def updat_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
if miles >= 0:
self.odometer_reading += miles
else:
print("You can't roll back the odometer!")
# ~ my_new_car = Car('audi','a4','2016')
# ~ print(my_new_car.get_descriptive_name())
# ~ my_new_car.read_odometer()
# ~ my_new_car.odometer_reading = 23
# ~ my_new_car.read_odometer()
# ~ my_new_car.updat_odometer(80)
# ~ my_new_car.read_odometer()
# ~ my_new_car.increment_odometer(100)
# ~ my_new_car.read_odometer()
# ~ my_new_car.updat_odometer(38)
# ~ my_new_car.increment_odometer(-1)
| true |
eac160ec897eed706fd6924ef2c55bef93159034 | AlirieGray/Tweet-Generator | /qu.py | 1,052 | 4.21875 | 4 | from linkedlist import LinkedList
from linkedlist import Node
class Queue(LinkedList):
def __init__(self, iterable=None):
super().__init__(iterable)
def enqueue(self, item):
"""Add an object to the end of the Queue."""
self.append(item)
def dequeue(self):
"""Remove and return the object at the beginning of the Queue."""
if self.is_empty():
raise IndexError("Cannot dequeue from empty queue")
temp = self.head.data
self.head = self.head.next
return temp
def peek(self):
if self.is_empty():
raise IndexError("Cannot peek from empty queue")
return self.head.data
def toTuple(self):
q_list = []
current = self.head
while current:
q_list.append(current.data)
current = current.next
return tuple(q_list)
if __name__ == '__main__':
q = Queue(["Hello", "world,", "I", "am", "a", "queue!"])
print(q.toTuple())
while not q.is_empty():
print(q.dequeue())
| true |
09a979bccf9cce42b1fa77cf88cf8fa889037879 | michaelworkspace/AdventOfCode2020 | /day01.py | 1,277 | 4.40625 | 4 | from typing import List
def find_product(inputs: List[int]) -> int:
"""Given a list of integers, if the sum of two element is 2020, return it's product."""
# This is the classic Two Sum problem
# This is not good solution because it is O(n^2)
# for x in INPUTS:
# for y in INPUTS:
# if x + y == 2020:
# ans = x * y
# return ans
# This is the optimal solution because its time complexity is O(n)
needs = {2020 - x for x in inputs}
for num in inputs:
if num in needs:
ans = num * (2020-num)
return ans
"""--- PART 2 --- """
def find_product_part2(inputs: List[int]) -> int:
"""Given a list of integers, if the sum of three element is 2020, return it's product."""
n = len(inputs)
# This is the classic Three Sum problem
# Naive run time is O(n^3) cube which is not very efficient
for i in range(n):
for j in range(i+1, n):
for k in range(j+1, n):
if inputs[i] + inputs[j] + inputs[k] == 2020:
ans = inputs[i] * inputs[j] * inputs[k]
return ans
with open("Inputs/day01.txt") as f:
inputs = [int(line.strip()) for line in f]
print(find_product(inputs))
print(find_product_part2(inputs))
| true |
0ad185da2701617e9580000faad35f2c31df8c9a | YasmineCodes/Interview-Prep | /recursion.py | 2,641 | 4.3125 | 4 | # Write a function fib, that finds the nth fibonacci number
def fib(n):
assert n >= 0 and int(n) == n, "n must be a positive integer"
if n == 1:
return 0
elif n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
print("The 4th fibonacci number is: ", fib(4)) # 2
print("The 10th fibonacci number is: ", fib(10)) # 34
# Write a recursive function to find the sum all the digits in a positive number n
# For example: the number 223 shoudl return 7
def sum_digits(n):
# Constraint
assert n >= 0 and int(n) == n, "n must be a positive int"
# Base case
if n < 10:
return n
else:
# recursion case
return n % 10 + sum_digits(int(n/10))
print("The sum of digits in the number 100 is: ", sum_digits(100)) # 1
print("The sum of digits in the number 112 is: ", sum_digits(11234)) # 11
print("The sum of digits in the number 23 is: ", sum_digits(23)) # 5
# Write recursive function that finds the Greates Common Denominator using Euclidean Algorithm (https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm)
def gcd(n1, n2):
assert int(n1) == n1 and int(n2) == n2, 'numbers must be integers'
a = max(n1, n2)
b = min(n1, n2)
if a < 0:
a = a*-1
if b < 0:
b = b*-1
if a % b == 0:
return b
else:
return gcd(b, a % b)
print("The GCD for 8 and 12 is: ", gcd(8, 12))
print("The GCD for 10 and 85 is: ", gcd(20, 85))
print("The GCD for 48 and 18 is: ", gcd(48, 18))
# Write a function that uses recursion to find the binary representation of a number
def binary(n):
if n == 0:
return ""
else:
return binary(int(n/2)) + str(n % 2)
print("The binary representation of 10 is: ", binary(10)) # 1010
print("The binary representation of 13 is: ", binary(13)) # 1101
def binary2(n):
if int(n/2) == 0:
return n % 2
else:
return n % 2 + 10*binary2(int(n/2))
print("Using binary2: The binary representation of 10 is: ", binary2(10)) # 1010
print("Using binary2: The binary representation of 13 is: ", binary2(13)) # 1101
# Write a recursive function called power that returns the base raised to the exponent
# 2, 4 : 2 * power(2, 3)
# 2 * power(2, 2)
# 2 * power(2, 1)
#2* power(2, 0)
# 1
def power(base, exponent):
if exponent == 0:
return 1
else:
return base * power(base, exponent-1)
print("3 raised to the power of 0 is : ", power(3, 0)) # 1
print("2 raised to the power of 2 is : ", power(2, 2)) # 4
print("5 raised to the power of 4 is : ", power(2, 4)) # 625
| true |
aa92573b123c0f334eca8304adae5b1410f108e5 | Xia-Sam/hello-world | /rock paper scissors game against computer.py | 1,714 | 4.3125 | 4 | import random
rand_num=random.randint(1,3)
if rand_num==1:
com_side="rock"
elif rand_num==2:
com_side="paper"
else:
com_side="scissors"
i=0
while i<5:
print("You can input 'stop' at anytime to stop the game but nothing else is allowed.")
user_side=input("Please input your choice (R P S stands for rock paper scissors respectively):")
if user_side=="R" or user_side=="P" or user_side=="S":
if user_side=="R":
if rand_num==1:
print(" Game is a tie. Try again. 5 more chances")
elif rand_num==2:
print("Computer win. You lose. ")
i+=1
print(5-i," chances left.")
else:
print("You win. You can continue playing.")
elif user_side=="P":
if rand_num==2:
print(" Game is a tie. Try again. 5 more chances")
elif rand_num==1:
print("You win. You can continue playing.")
else:
print("Computer win. You lose. ")
i += 1
print(5 - i, " chances left.")
else:
if rand_num==1:
print("Computer win. You lose. ")
i += 1
print(5 - i, " chances left.")
elif rand_num==2:
print("You win. You can continue playing.")
else:
print(" Game is a tie. Try again. 5 more chances")
elif user_side=="stop":
break
else:
print("You can only input R, S or P!! ")
print("Try again. You only have 5 chances totally. ")
i+=1
print(5-i," chances left")
print("Game over. Thank you for playing my game.")
| true |
55ae7ae4ad64c690800e9d2a9d37684eb3069bb9 | andkoc001/pands-problem-set | /06-secondstring.py | 1,379 | 4.15625 | 4 | # Title: Second Strig
# Description: Solution to problem 6 - program that takes a user input string and outputs every second word.
# Context: Programming and Scripting, GMIT, 2019
# Author: Andrzej Kocielski
# Email: G00376291@gmit.ie
# Date of creation: 10-03-2019
# Last update: 10-03-2019
###
# Prompt for the user; definition of a new variable "sentence" for the user's input
# Intermediate test of the program - predefined sentence
# sentence = "1abc 2def 3geh 4ijk 5lkm 6nop 7rst 8uwz"
sentence = input("Please enter a sentence: ")
# Intermediate test of the program - prints out the user's input
# print(type(sentence))
# print(sentence)
# Calls method split method in order to split the user input into single words, separated by a space
sentence.split()
# Assignment of number of words in the sentence to variable n
n = len(sentence.split())
# Intermediate test of the program - shows number of words in the sentence
# print(n)
# Joining the words by contanation - pre-definintion of empty (for now) variable, which will be subsequently updated as the program runs
result_line = ""
# Prints out odd words from the sentence
for i in range(n):
# Separation of odd and even words
if i % 2 == 0:
# this was original command that returned words in separate lines
# print(sentence.split()[i])
result_line += (sentence.split()[i]) + " "
print(result_line)
| true |
3cc0fcee11a7eea3411f26afebac5fea6eebd6b1 | BlackJimmy/SYSU_QFTI | /mateig.py | 427 | 4.15625 | 4 | #this example shows how to compute eigen values of a matrix
from numpy import *
#initialize the matrix
n = 5
a = zeros( (n, n) )
for i in range(n):
a[i][i] = i
if(i>0):
a[i][i-1] = -1
a[i-1][i] = -1
#print the matrix
print "The matrix is:"
for i in range(n):
print a[i]
#compute the eigen values of the matrix
(eigvalues, eigvectors) = linalg.eig(a)
print "Its eigen values are:"
print eigvalues
| true |
d7d9550e9acb11727564ba122a9427139f47a5e3 | ode2020/bubble_sort.py | /bubble.py | 388 | 4.1875 | 4 | def bubble_sort(numbers):
for i in range (len(numbers) - 1, 0, -1):
for j in range (i):
if numbers[j] > numbers[j+1]:
temp = numbers[j]
numbers[j] = numbers[j+1]
numbers[j+1] = temp
print(numbers)
numbers = [5, 3, 8, 6, 7, 2]
bubble_sort(numbers)
print(numbers)
print("The code executed successfully")
| true |
aa83f5258b80e1c403a25d30aeb96f2a8125ec73 | ravalrupalj/BrainTeasers | /Edabit/Day 3.3.py | 459 | 4.125 | 4 | #Get Word Count
#Create a function that takes a string and returns the word count. The string will be a sentence.
#Examples
#count_words("Just an example here move along") ➞ 6
#count_words("This is a test") ➞ 4
#count_words("What an easy task, right") ➞ 5
def count_words(txt):
t = txt.split()
return len(t)
print(count_words("Just an example here move along"))
print(count_words("This is a test"))
print(count_words("What an easy task, right")) | true |
9975f7dc75b81bbbe7cfdcd701f2e09335a3ce54 | ravalrupalj/BrainTeasers | /Edabit/Emptying_the_values.py | 1,532 | 4.4375 | 4 | #Emptying the Values
#Given a list of values, return a list with each value replaced with the empty value of the same type.
#More explicitly:
#Replace integers (e.g. 1, 3), whose type is int, with 0
#Replace floats (e.g. 3.14, 2.17), whose type is float, with 0.0
#Replace strings (e.g. "abcde", "x"), whose type is str, with ""
#Replace booleans (True, False), whose type is bool, with False
#Replace lists (e.g. [1, "a", 5], [[4]]), whose type is list, with []
#Replace tuples (e.g. (1,9,0), (2,)), whose type is tuple, with ()
#Replace sets (e.g. {0,"a"}, {"b"}), whose type is set, with set()
#Caution: Python interprets {} as the empty dictionary, not the empty set.
#None, whose type is NoneType, is preserved as None
#Notes
#None has the special NoneType all for itself.
def empty_values(lst):
l=[]
for i in lst:
if type(i)==int:
l.append(0)
elif type(i)==float:
l.append(0.0)
elif type(i)==str:
l.append('')
elif type(i)==bool:
l.append(False)
elif type(i)==list:
l.append([])
elif type(i)==tuple:
l.append(())
elif type(i)==set:
l.append(set())
else:
l.append(None)
return l
print(empty_values([1, 2, 3]) )
#➞ [0, 0, 0]
print(empty_values([7, 3.14, "cat"]) )
#➞ [0, 0.0, ""]
print(empty_values([[1, 2, 3], (1,2,3), {1,2,3}]) )
#➞ [[], (), set()]
print(empty_values([[7, 3.14, "cat"]]))
#➞ [[]]
print(empty_values([None]) )
#➞ [None]
| true |
60a84a613c12d723ba5d141e657989f33930ab74 | ravalrupalj/BrainTeasers | /Edabit/Powerful_Numbers.py | 615 | 4.1875 | 4 | #Powerful Numbers
#Given a positive number x:
#p = (p1, p2, …)
# Set of *prime* factors of x
#If the square of every item in p is also a factor of x, then x is said to be a powerful number.
#Create a function that takes a number and returns True if it's powerful, False if it's not.
def is_powerful(num):
i=1
l=[]
while i<=num:
if num%i==0:
l.append(i)
i=i+1
return l
print(is_powerful(36))
#➞ True
# p = (2, 3) (prime factors of 36)
# 2^2 = 4 (factor of 36)
# 3^2 = 9 (factor of 36)
print(is_powerful(27))
#➞ True
print(is_powerful(674))
#➞ False
#Notes
#N/A | true |
4dd2faade46f718a07aeba94270ea71ff90b5996 | ravalrupalj/BrainTeasers | /Edabit/Is_the_Number_Symmetrical.py | 462 | 4.4375 | 4 | #Create a function that takes a number as an argument and returns True or False depending on whether the number is symmetrical or not. A number is symmetrical when it is the same as its reverse.
def is_symmetrical(num):
t=str(num)
return t==t[::-1]
print(is_symmetrical(7227) )
#➞ True
print(is_symmetrical(12567) )
#➞ False
print(is_symmetrical(44444444))
#➞ True
print(is_symmetrical(9939) )
#➞ False
print(is_symmetrical(1112111) )
#➞ True | true |
885a0a3ce15dbf2504dd24ce14552a4e245b3790 | ravalrupalj/BrainTeasers | /Edabit/Big_Countries.py | 1,652 | 4.53125 | 5 | #Big Countries
#A country can be said as being big if it is:
#Big in terms of population.
#Big in terms of area.
#Add to the Country class so that it contains the attribute is_big. Set it to True if either criterea are met:
#Population is greater than 250 million.
#Area is larger than 3 million square km.
#Also, create a method which compares a country's population density to another country object. Return a string in the following format:
#{country} has a {smaller / larger} population density than {other_country}
class Country:
def __init__(self, name, population, area):
self.name = name
self.population = population
self.area = area
# implement self.is_big
self.is_big = self.population > 250000000 or self.area > 3000000
def compare_pd(self, other):
# code
this_density = self.population / self.area
other_density = other.population / other.area
if this_density > other_density:
s_or_l = 'larger'
else:
s_or_l = 'smaller'
return self.name + ' has a ' + s_or_l + ' population density than ' + other.name
australia = Country("Australia", 23545500, 7692024)
andorra = Country("Andorra", 76098, 468)
print(australia.is_big )
#➞ True
print(andorra.is_big )
#➞ False
andorra.compare_pd(australia)
#➞ "Andorra has a larger population density than Australia"
#Notes
#Population density is calculated by diving the population by the area.
#Area is given in square km.
#The input will be in the format (name_of_country, population, size_in_km2), where name_of_country is a string and the other two inputs are integers. | true |
a22a66ffd651519956fc0f1ea0eb087a4146e8dd | ravalrupalj/BrainTeasers | /Edabit/Loves_Me_Loves_Me.py | 1,034 | 4.25 | 4 | #Loves Me, Loves Me Not...
#"Loves me, loves me not" is a traditional game in which a person plucks off all the petals of a flower one by one, saying the phrase "Loves me" and "Loves me not" when determining whether the one that they love, loves them back.
#Given a number of petals, return a string which repeats the phrases "Loves me" and "Loves me not" for every alternating petal, and return the last phrase in all caps. Remember to put a comma and space between phrases.
def loves_me(num):
l=['Loves me','Loves me not']
final_l=[]
add=l[0]
for i in range(0,num):
final_l.append(add)
if final_l[-1]==l[0]:
add=l[1]
else:
add=l[0]
final_l[-1]=final_l[-1].upper()
return ', '.join(final_l)
print(loves_me(3))
#➞ "Loves me, Loves me not, LOVES ME"
print(loves_me(6) )
#➞ "Loves me, Loves me not, Loves me, Loves me not, Loves me, LOVES ME NOT"
print(loves_me(1))
#➞ "LOVES ME"
#Notes
#Remember to return a string.
#he first phrase is always "Loves me". | true |
13b3a8a4d538ca1404902f5cc9d0d4cb5380f231 | ravalrupalj/BrainTeasers | /Edabit/sum_of_even_numbers.py | 698 | 4.1875 | 4 | #Give Me the Even Numbers
#Create a function that takes two parameters (start, stop), and returns the sum of all even numbers in the range.
#sum_even_nums_in_range(10, 20) ➞ 90
# 10, 12, 14, 16, 18, 20
#sum_even_nums_in_range(51, 150) ➞ 5050
#sum_even_nums_in_range(63, 97) ➞ 1360
#Remember that the start and stop values are inclusive.
def sum_even_nums_in_range(start, stop):
count=0
for i in range(start,stop+1):
if i%2==0:
count=count+i
return count
#return sum(i for i in range(start, stop+1) if not i%2)
print(sum_even_nums_in_range(10, 20) )
# 10, 12, 14, 16, 18, 20
print(sum_even_nums_in_range(51, 150) )
print(sum_even_nums_in_range(63, 97) ) | true |
7801a9735e3d51e4399ee8297d719d86eb44bc58 | ravalrupalj/BrainTeasers | /Edabit/Recursion_Array_Sum.py | 440 | 4.15625 | 4 | #Recursion: Array Sum
#Write a function that finds the sum of a list. Make your function recursive.
#Return 0 for an empty list.
#Check the Resources tab for info on recursion.
def sum_recursively(lst):
if len(lst)==0:
return 0
return lst[0]+sum_recursively(lst[1:])
print(sum_recursively([1, 2, 3, 4]))
#➞ 10
print(sum_recursively([1, 2]) )
#➞ 3
print(sum_recursively([1]) )
#➞ 1
print(sum_recursively([]) )
#➞ 0
| true |
207c144e096524b8de5e6d9ca11ce5cb4969d8e1 | ravalrupalj/BrainTeasers | /Edabit/Letters_Only.py | 496 | 4.25 | 4 | #Letters Only
#Write a function that removes any non-letters from a string, returning a well-known film title.
#See the Resources section for more information on Python string methods.
def letters_only(string):
l=[]
for i in string:
if i.isupper() or i.islower():
l.append(i)
return ''.join(l)
print(letters_only("R!=:~0o0./c&}9k`60=y") )
#➞ "Rocky"
print(letters_only("^,]%4B|@56a![0{2m>b1&4i4"))
#➞ "Bambi"
print(letters_only("^U)6$22>8p).") )
#➞ "Up"
| true |
4fad5f1ab4362dbc1119d1f72a85d6c91abdfa8f | ravalrupalj/BrainTeasers | /Edabit/The_Fibonacci.py | 368 | 4.3125 | 4 | #The Fibonacci Number
#Create a function that, given a number, returns the corresponding Fibonacci number.
#The first number in the sequence starts at 1 (not 0).
def fibonacci(num):
a=0
b=1
for i in range(1,num+1):
c=a+b
a=b
b=c
return c
print(fibonacci(3) )
#➞ 3
print(fibonacci(7))
#➞ 21
print(fibonacci(12))
#➞ 233
| true |
5182829f043490134cb86a3962b07a791e7ae0cb | ravalrupalj/BrainTeasers | /Edabit/How_many.py | 601 | 4.15625 | 4 | #How Many "Prime Numbers" Are There?
#Create a function that finds how many prime numbers there are, up to the given integer.
def prime_numbers(num):
count=0
i=1
while num:
i=i+1
for j in range(2,i+1):
if j>num:
return count
elif i%j==0 and i!=j:
break
elif i==j:
count=count+1
break
print(prime_numbers(10))
#➞ 4
# 2, 3, 5 and 7
print(prime_numbers(20))
#➞ 8
# 2, 3, 5, 7, 11, 13, 17 and 19
print(prime_numbers(30))
#➞ 10
# 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29
| true |
f07bfd91788707f608a580b702f3905be2bf201b | ravalrupalj/BrainTeasers | /Edabit/One_Button_Messagin.py | 650 | 4.28125 | 4 | # One Button Messaging Device
# Imagine a messaging device with only one button. For the letter A, you press the button one time, for E, you press it five times, for G, it's pressed seven times, etc, etc.
# Write a function that takes a string (the message) and returns the total number of times the button is pressed.
# Ignore spaces.
def how_many_times(msg):
if len(msg)==0:
return 0
current=msg[0]
rest_of_string = msg[1:]
char_int=ord(current)-96
return char_int+how_many_times(rest_of_string)
print(how_many_times("abde"))
# ➞ 12
print(how_many_times("azy"))
# ➞ 52
print(how_many_times("qudusayo"))
# ➞ 123
| true |
d9acdd4825dfd641d4eac7dd92d15b428b0e07f0 | ravalrupalj/BrainTeasers | /Edabit/Iterated_Square_Root.py | 597 | 4.5 | 4 | #Iterated Square Root
#The iterated square root of a number is the number of times the square root function must be applied to bring the number strictly under 2.
#Given an integer, return its iterated square root. Return "invalid" if it is negative.
#Idea for iterated square root by Richard Spence.
import math
def i_sqrt(n):
if n < 0: return 'invalid'
count = 0
while n >= 2:
n **= 0.5
count += 1
return count
print(i_sqrt(1))
#➞ 0
print(i_sqrt(2))
#➞ 1
print(i_sqrt(7))
#➞ 2
print(i_sqrt(27))
#➞ 3
print(i_sqrt(256))
#➞ 4
print(i_sqrt(-1) )
#➞ "invalid"
| true |
edb6aaff5ead34484d01799aef3df830208b574c | ravalrupalj/BrainTeasers | /Edabit/Identical Characters.py | 460 | 4.125 | 4 | #Check if a String Contains only Identical Characters
#Write a function that returns True if all characters in a string are identical and False otherwise.
#Examples
#is_identical("aaaaaa") ➞ True
#is_identical("aabaaa") ➞ False
#is_identical("ccccca") ➞ False
#is_identical("kk") ➞ True
def is_identical(s):
return len(set(s))==1
print(is_identical("aaaaaa"))
print(is_identical("aabaaa") )
print(is_identical("ccccca"))
print(is_identical("kk")) | true |
da002bf4a8ece0c60f4103e5cbc92f641d27f573 | ravalrupalj/BrainTeasers | /Edabit/Stand_in_line.py | 674 | 4.21875 | 4 | #Write a function that takes a list and a number as arguments. Add the number to the end of the list, then remove the first element of the list. The function should then return the updated list.
#For an empty list input, return: "No list has been selected"
def next_in_line(lst, num):
if len(lst)>0:
t=lst.pop(0)
r=lst.append(num)
return lst
else:
return 'No list has been selected'
print(next_in_line([5, 6, 7, 8, 9], 1))
#➞ [6, 7, 8, 9, 1]
print(next_in_line([7, 6, 3, 23, 17], 10))
#➞ [6, 3, 23, 17, 10]
print(next_in_line([1, 10, 20, 42 ], 6))
#➞ [10, 20, 42, 6]
print(next_in_line([], 6))
#➞ "No list has been selected"
| true |
b5255591c5a67f15767deee268a1972ca61497cd | ravalrupalj/BrainTeasers | /Edabit/Emphasise_the_Words.py | 617 | 4.21875 | 4 | #Emphasise the Words
#The challenge is to recreate the functionality of the title() method into a function called emphasise(). The title() method capitalises the first letter of every word.
#You won't run into any issues when dealing with numbers in strings.
#Please don't use the title() method directly :(
def emphasise(string):
r=''
for i in string.split():
t=(i[0].upper())+(i[1:].lower())+' '
r=r+t
return r.rstrip()
print(emphasise("hello world"))
#➞ "Hello World"
print(emphasise("GOOD MORNING") )
#➞ "Good Morning"
print(emphasise("99 red balloons!"))
#➞ "99 Red Balloons!"
| true |
6eceebf49b976ec2b757eee0c7907f2845c65afd | ravalrupalj/BrainTeasers | /Edabit/Is_String_Order.py | 405 | 4.25 | 4 | #Is the String in Order?
#Create a function that takes a string and returns True or False, depending on whether the characters are in order or not.
#You don't have to handle empty strings.
def is_in_order(txt):
t=''.join(sorted(txt))
return t==txt
print(is_in_order("abc"))
#➞ True
print(is_in_order("edabit"))
#➞ False
print(is_in_order("123"))
#➞ True
print(is_in_order("xyzz"))
#➞ True
| true |
56bf743185fc87230c9cb8d0199232d393757809 | ravalrupalj/BrainTeasers | /Edabit/Day 2.5.py | 793 | 4.53125 | 5 | #He tells you that if you multiply the height for the square of the radius and multiply the result for the mathematical constant π (Pi), you will obtain the total volume of the pizza. Implement a function that returns the volume of the pizza as a whole number, rounding it to the nearest integer (and rounding up for numbers with .5 as decimal part).
#vol_pizza(1, 1) ➞ 3
# (radius² x height x π) = 3.14159... rounded to the nearest integer.
#vol_pizza(7, 2) ➞ 308
#vol_pizza(10, 2.5) ➞ 785
import math
def vol_pizza(radius, height):
t=(radius ** 2) * height *math.pi
y=round(t,1)
return round(y)
print(vol_pizza(1, 1)) # (radius² x height x π) = 3.14159... rounded to the nearest integer.
print(vol_pizza(7, 2))
print(vol_pizza(10, 2.5))
print(vol_pizza(15, 1.3))
| true |
d9d1a7dbd41fea7d00f7299ae6708fc46e21d42d | ravalrupalj/BrainTeasers | /Edabit/Day 4.4.py | 510 | 4.46875 | 4 | #Is It a Triangle?
#Create a function that takes three numbers as arguments and returns True if it's a triangle and False if not.
#is_triangle(2, 3, 4) ➞ True
#is_triangle(3, 4, 5) ➞ True
#is_triangle(4, 3, 8) ➞ False
#Notes
#a, b and, c are the side lengths of the triangles.
#Test input will always be three positive numbers.
def is_triangle(a, b, c):
return a+b>c and a+c>b and b+c>a
print(is_triangle(2, 3, 4))
print(is_triangle(3, 4, 5))
print(is_triangle(4, 3, 8))
print(is_triangle(2, 9, 5)) | true |
a055bcd166678d801d9f2467347d9dfcd0e49254 | ravalrupalj/BrainTeasers | /Edabit/Count_and_Identify.py | 832 | 4.25 | 4 | #Count and Identify Data Types
#Given a function that accepts unlimited arguments, check and count how many data types are in those arguments. Finally return the total in a list.
#List order is:
#[int, str, bool, list, tuple, dictionary]
def count_datatypes(*args):
lst=[type(i) for i in args]
return [lst.count(i) for i in (int, str, bool, list, tuple, dict)]
print(count_datatypes(1, 45, "Hi", False) )
#➞ [2, 1, 1, 0, 0, 0]
print(count_datatypes([10, 20], ("t", "Ok"), 2, 3, 1) )
#➞ [3, 0, 0, 1, 1, 0]
print(count_datatypes("Hello", "Bye", True, True, False, {"1": "One", "2": "Two"}, [1, 3], {"Brayan": 18}, 25, 23) )
#➞ [2, 2, 3, 1, 0, 2]
print(count_datatypes(4, 21, ("ES", "EN"), ("a", "b"), False, [1, 2, 3], [4, 5, 6]) )
#➞ [2, 0, 1, 2, 2, 0]
#Notes
#If no arguments are given, return [0, 0, 0, 0, 0, 0] | true |
fde94a7ba52fa1663a992ac28467e42cda866a9b | ravalrupalj/BrainTeasers | /Edabit/Lexicorgraphically First_last.py | 762 | 4.15625 | 4 | #Lexicographically First and Last
#Write a function that returns the lexicographically first and lexicographically last rearrangements of a string. Output the results in the following manner:
#first_and_last(string) ➞ [first, last]
#Lexicographically first: the permutation of the string that would appear first in the English dictionary (if the word existed).
#Lexicographically last: the permutation of the string that would appear last in the English dictionary (if the word existed).
def first_and_last(s):
t=sorted(s)
e=''.join(t)
r=e[::-1]
p=e,r
return list(p)
print(first_and_last("marmite"))
#➞ ["aeimmrt", "trmmiea"]
print(first_and_last("bench"))
#➞ ["bcehn", "nhecb"]
print(first_and_last("scoop"))
#➞ ["coops", "spooc"]
| true |
5c503edd8d4241b5e674e0f88b5c0edbe0888235 | ravalrupalj/BrainTeasers | /Edabit/Explosion_Intensity.py | 1,312 | 4.3125 | 4 | #Explosion Intensity
#Given an number, return a string of the word "Boom", which varies in the following ways:
#The string should include n number of "o"s, unless n is below 2 (in that case, return "boom").
#If n is evenly divisible by 2, add an exclamation mark to the end.
#If n is evenly divisible by 5, return the string in ALL CAPS.
#The example below should help clarify these instructions.
def boom_intensity(n):
if n<2:
return 'boom'
elif n%2==0 and n%5==0:
return 'B'+'O'*n+'M'+'!'
elif n%2==0:
return 'B'+('o'*n)+'m'+'!'
elif n%5==0:
return 'B' + ('O' * n) + 'M'
else:
return 'B'+('o'*n)+'m'
print(boom_intensity(4) )
#➞ "Boooom!"
# There are 4 "o"s and 4 is divisible by 2 (exclamation mark included)
print(boom_intensity(1) )
#➞ "boom"
# 1 is lower than 2, so we return "boom"
print(boom_intensity(5) )
#➞ "BOOOOOM"
# There are 5 "o"s and 5 is divisible by 5 (all caps)
print(boom_intensity(10) )
#➞ "BOOOOOOOOOOM!"
# There are 10 "o"s and 10 is divisible by 2 and 5 (all caps and exclamation mark included)
#Notes
#A number which is evenly divisible by 2 and 5 will have both effects applied (see example #4).
#"Boom" will always start with a capital "B", except when n is less than 2, then return a minature explosion as "boom". | true |
bc123a73adc60347bc2e8195581e6d556b27c329 | ravalrupalj/BrainTeasers | /Edabit/Check_if_an_array.py | 869 | 4.28125 | 4 | #Check if an array is sorted and rotated
#Given a list of distinct integers, create a function that checks if the list is sorted and rotated clockwise. If so, return "YES"; otherwise return "NO".
def check(lst):
posi = sorted(lst)
for i in range(0,len(lst)-1):
first=posi.pop(0)
posi.append(first)
if posi==lst:
return "YES"
return 'NO'
print(check([3, 4, 5, 1, 2]))
#➞ "YES"
# The above array is sorted and rotated.
# Sorted array: [1, 2, 3, 4, 5].
# Rotating this sorted array clockwise
# by 3 positions, we get: [3, 4, 5, 1, 2].
print(check([1, 2, 3]))
#➞ "NO"
# The above array is sorted but not rotated.
print(check([7, 9, 11, 12, 5]) )
#➞ "YES"
# The above array is sorted and rotated.
# Sorted array: [5, 7, 9, 11, 12].
# Rotating this sorted array clockwise
# by 4 positions, we get: [7, 9, 11, 12, 5]. | true |
a3b5f7ffe220bd211b6fde53c99b9bcb086dbf39 | ravalrupalj/BrainTeasers | /Edabit/Reverse_the_odd.py | 656 | 4.4375 | 4 | #Reverse the Odd Length Words
#Given a string, reverse all the words which have odd length. The even length words are not changed.
def reverse_odd(string):
new_lst=string.split()
s=''
for i in new_lst:
if len(i)%2!=0:
t=i[::-1]
s=s+t+' '
else:
s=s+i+' '
return s.strip()
print(reverse_odd("Bananas"))
#➞ "sananaB"
print(reverse_odd("One two three four"))
#➞ "enO owt eerht four"
print(reverse_odd("Make sure uoy only esrever sdrow of ddo length"))
#➞ "Make sure you only reverse words of odd length"
#Notes
#There is exactly one space between each word and no punctuation is used. | true |
8124f901f1650f94c89bdae1eaf3f837925effde | ravalrupalj/BrainTeasers | /Edabit/Balancing_Scales.py | 944 | 4.5 | 4 | #Balancing Scales
#Given a list with an odd number of elements, return whether the scale will tip "left" or "right" based on the sum of the numbers. The scale will tip on the direction of the largest total. If both sides are equal, return "balanced".
#The middle element will always be "I" so you can just ignore it.
#Assume the numbers all represent the same unit.
#Both sides will have the same number of elements.
#There are no such things as negative weights in both real life and the tests!
def scale_tip(lst):
t=len(lst)//2
l= sum(lst[0:t])
r=sum(lst[t+1:])
if l>r:
return 'left'
elif l<r:
return 'right'
else:
return 'balanced'
print(scale_tip([0, 0, "I", 1, 1]))
#➞ "right"
# 0 < 2 so it will tip right
print(scale_tip([1, 2, 3, "I", 4, 0, 0]))
#➞ "left"
# 6 > 4 so it will tip left
print(scale_tip([5, 5, 5, 0, "I", 10, 2, 2, 1]))
#➞ "balanced"
# 15 = 15 so it will stay balanced
| true |
d183ee49cc90ee2ede5a0d6383404edd9f08a4a8 | nicolaespinu/LightHouse_Python | /spinic/Day14.py | 1,572 | 4.15625 | 4 | # Challenge
# Dot's neighbour said that he only likes wine from Stellenbosch, Bordeaux, and the Okanagan Valley,
# and that the sulfates can't be that high. The problem is, Dot can't really afford to spend tons
# of money on the wine. Dot's conditions for searching for wine are:
#
# Sulfates cannot be higher than 0.6.
# The price has to be less than $20.
# Use the above conditions to filter the data for questions 2 and 3 below.
#
# Questions:
#
# 1. Where is Stellenbosch, anyway? How many wines from Stellenbosch are there in the entire dataset?
# 2. After filtering with the 2 conditions, what is the average price of wine from the Bordeaux region?
# 3. After filtering with the 2 conditions, what is the least expensive wine that's of the highest quality
# from the Okanagan Valley?
#
# Stretch Question:
# What is the average price of wine from Stellenbosch, according to the entire unfiltered dataset?
# Note: Check the dataset to see if there are missing values; if there are, fill in missing values with the mean.
import pandas as pd
df = pd.read_csv('winequality-red_2.csv')
df = df.drop(columns = ['Unnamed: 0'])
df.head()
print('Q1 of wines from Stellenbosch:',df[df['region'].str.contains('Stellenbosch')].shape[0])
filterDF = df[(df['sulphates']<=0.6) & (df['price']<20)]
print("Q2 avg price of wines from Bordeaux: ",filterDF[filterDF['region']=='Bordeaux']['price'].mean())
print(filterDF[filterDF['region'].str.contains('Okanagan Valley')].sort_values(['quality','price'],ascending=[False,True]))
# 1. 35 Wines
# 2 .$11.30
# 3. Wine 1025 | true |
afdf0666b5d24b145a7fee65bf489fd01c4baa8c | OaklandPeters/til | /til/python/copy_semantics.py | 1,348 | 4.21875 | 4 | # Copy Semantics
# -------------------------
# Copy vs deep-copy, and what they do
# In short: copy is a pointer, and deep-copy is an entirely seperate data structure.
# BUT.... this behavior is inconsistent, because of the way that attribute
# setters work in Python.
# Thus, mutations of attributes is not shared with copies, but mutations
# of items IS shared.
# See example #1 VS #2
import copy
# Example #1
# Item mutation DOES change copies, but not deep copies
original = ["one", "two", ["three", "333"]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
assert (original == shallow)
assert (original == deep)
assert (shallow == deep)
original[2][0] = "four"
assert (original == shallow)
assert (original != deep)
assert (shallow != deep)
# Example #2
# Attribute mutation does not change copies, nor deep copies
class Person:
def __init__(self, name):
self.name = name
def __repr__(self):
return "{0}({1})".format(self.__class__.__name__, self.name)
def __eq__(self, other):
return self.name == other.name
original = Person("Ulysses")
shallow = copy.copy(original)
deep = copy.deepcopy(original)
assert (original == shallow)
assert (original == deep)
assert (shallow == deep)
original.name = "Grant"
assert (original != shallow)
assert (original != deep)
assert (shallow == deep)
| true |
761768971347ca71abb29fcbbaccf6ef92d4df86 | Varobinson/python101 | /tip-calculator.py | 998 | 4.28125 | 4 | #Prompt the user for two things:
#The total bill amount
#The level of service, which can be one of the following:
# good, fair, or bad
#Calculate the tip amount and the total amount(bill amount + tip amount).
# The tip percentage based on the level of service is based on:
#good -> 20%
#fair -> 15%
# bad -> 10%
try:
#Ask user for total bill amount
total_bill = int(input('What was your total? '))
#convert total to float
#prompt user for service quality
service = input('What was the service bad, fair, or good? ')
#adding split feature
#promt user for split amount
split = input('How many people will be paying? ')
except:
print('error')
#convert split to int
split = int(split)
tip = ()
service = service.lower()
if service == 'bad':
tip = total_bill * 0.1
elif service == 'fair':
tip = total_bill * 0.15
elif service == 'good':
tip = total_bill * 0.2
else:
print("Cant't help you! ")
#added split to total
total = total_bill + tip / split
print(total)
| true |
94bdd2d96de22c8911e7c22e46405558785fc25e | chhikara0007/intro-to-programming | /s2-code-your-own-quiz/my_code.py | 1,211 | 4.46875 | 4 | # Investigating adding and appending to lists
# If you run the following four lines of codes, what are list1 and list2?
list1 = [1,2,3,4]
list2 = [1,2,3,4]
list1 = list1 + [5]
list2.append(5)
# to check, you can print them out using the print statements below.
print list1
print list2
# What is the difference between these two pieces of code?
def proc(mylist):
mylist = mylist + [6]
def proc2(mylist):
mylist.append(6)
# Can you explain the results given by the four print statements below? Remove
# the hashes # and run the code to check.
print list1
proc(list1)
print list1
print list2
proc2(list2)
print list2
# Python has a special assignment syntax: +=. Here is an example:
list3 = [1,2,3,4]
list3 += [5]
# Does this behave like list1 = list1 + [5] or list2.append(5)? Write a
# procedure, proc3 similar to proc and proc2, but for +=. When you've done
# that check your conclusion using the print-procedure call-print code as
# above.
def proc3(mylist):
mylist += [5]
print list3
proc3(list3)
print list3
print list1
print list2
print list3
# What happens when you try:
list1 = list1 + [7,8,9]
list2.append([7,8,9])
list3 += [7,8,9]
print list1
print list2
print list3 | true |
592e186d9725f23f98eaf990116de6c572757063 | Lobo2008/LeetCode | /581_Shortest_Unsorted_ContinuousSubarray.py | 1,749 | 4.25 | 4 | """
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Note:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.
"""
class Solution:
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
"""
把数组看成折线图,折线图应该是上升或者平行的
两个指针head 和tail,同时从两边开始,当head指针的路劲下降的时候,找到了start,当tail指针的路径上坡了,找到了end,end-start就是长度
"""
if len(nums) <= 1: return 0
sortnums = sorted(nums)
head, tail = 0, len(nums)-1
headFind, tailFind = False, False
while head <= tail:
headRs = nums[head] ^ sortnums[head] == 0
tailRs = nums[tail] ^ sortnums[tail] == 0
if not headRs and not tailRs: return tail - head + 1
if headRs: #等于0的时候要继续比下一个
head += 1
if tailRs:
tail -= 1
return 0
so = Solution()
nums = [2, 6, 4, 8, 10, 9, 15]#5
# nums = [10,9,8,7,6,5]
# nums = [] #0
# nums = [1] #0
# nums = [1,10] #0
# nums = [10,1] #2
# nums = [2,1,3,4,5] #2
nums = [2,3,4,5,1] #5
print(so.findUnsortedSubarray(nums))
| true |
eff175292e48ca133ae5ca276a679821ebae0712 | soumilshah1995/Data-Structure-and-Algorithm-and-Meta-class | /DataStructure/Deque/DEQChallenge.py | 1,505 | 4.15625 | 4 | """
DEQUE Abstract Data Type
DEQUE = Double ended Queue
High level its combination of stack and queue
you can insert item from front and back
You can remove items from front and back
we can use a list for this example. we will use methods
>----- addfront
>----- add rear
>----- remove front
>----- remove rear
we want to check Size, isempty
QUEUE - FIFO
STACK - LIFO
DEQUE - can use both LIFO or FIFO
any items you can store in list can be stored in DEQUE
Most common Questions is Palindrone
using DEQUE Datastructure
"""
class Deque(object):
def __init__(self):
self.items = []
def add_front(self, item):
self.items.insert(0, item)
def add_rear(self, item):
self.items.append(item)
def remove_front(self):
return self.items.pop(0)
def remove_rear(self):
return self.items.pop()
def size(self):
return len(self.items)
def isempty(self):
if(self.items) == []:
return True
else:
return False
def peek_front(self):
return self.items[0]
def peek_rear(self):
return self.items[-1]
def main(data):
deque = Deque()
for character in data:
deque.add_rear(character)
while deque.size() >= 2:
front_item = deque.remove_front()
rear_item = deque.remove_rear()
if rear_item != front_item:
return False
return True
if __name__ == "__main__":
print(main("nitin"))
print(main("car")) | true |
b777cc4d1682a6a3c1e5a450c282062c4a0514da | jrobind/python-playground | /games/guessing_game.py | 755 | 4.21875 | 4 | # Random number CLI game - to run, input a number to CLI, and a random number between
# zero and the one provided will be generated. The user must guess the correct number.
import random
base_num = raw_input('Please input a number: ')
def get_guess(base_num, repeat):
if (repeat == True):
return raw_input('Wrong! Guess again: ')
else:
return raw_input('Please guess a number between 0 and ' + base_num + '. ')
if (base_num == ''):
print('Please provide a number: ')
else:
random_num = random.randint(0, int(base_num))
guess = int(get_guess(base_num, False))
# use a while loop
while (random_num != guess):
guess = int(get_guess(base_num, True))
print('Well done! You guessed correct.')
| true |
e88333ce7bd95d7fb73a07247079ae4f5cb12d11 | graciofilipe/differential_equations | /udacity_cs222/final_problems/geo_stat_orb.py | 2,907 | 4.375 | 4 | # PROBLEM 3
#
# A rocket orbits the earth at an altitude of 200 km, not firing its engine. When
# it crosses the negative part of the x-axis for the first time, it turns on its
# engine to increase its speed by the amount given in the variable called boost and
# then releases a satellite. This satellite will ascend to the radius of
# geostationary orbit. Once that altitude is reached, the satellite briefly fires
# its own engine to to enter geostationary orbit. First, find the radius and speed
# of the initial circular orbit. Then make the the rocket fire its engine at the
# proper time. Lastly, enter the value of boost that will send the satellite
# into geostationary orbit.
#
import math
import numpy as np
from scipy.integrate import solve_ivp
# These are used to keep track of the data we want to plot
h_array = []
error_array = []
period = 24. * 3600. # s
earth_mass = 5.97e24 # kg
earth_radius = 6.378e6 # m (at equator)
gravitational_constant = 6.67e-11 # m3 / kg s2
total_time = 9. * 3600. # s
marker_time = 0.25 * 3600. # s
# Task 1: Use Section 2.2 and 2.3 to determine the speed of the inital circular orbit.
initial_radius = earth_radius + 200*1000
initial_speed = np.sqrt(earth_mass*gravitational_constant/initial_radius)
final_radius = 42164e3
boost_time = initial_radius*math.pi/initial_speed
# Task 3: Which is the appropriate value for the boost in velocity? 2.453, 24.53, 245.3 or 2453. m/s?
# Change boost to the correct value.
boost = 245.3 # m / s
ic = [initial_radius, 0, 0, initial_speed]
def x_prime(t, x):
vector_to_earth = -np.array([x[0], x[1]]) # earth located at origin
a = gravitational_constant * earth_mass / np.linalg.norm(vector_to_earth) ** 3 * vector_to_earth
speed_x, speed_y = x[2], x[3]
vec = [speed_x, speed_y, a[0], a[1]]
return vec
def integrate_until(ti, tf, ic, x_prime_fun):
tval = np.linspace(ti, tf, 111)
sol = solve_ivp(x_prime_fun,
t_span=(ti, tf),
t_eval=tval,
y0=ic,
vectorized=False,
rtol=1e-6,
atol=1e-6)
return sol
ic1 = [initial_radius, 0, 0, initial_speed]
sol1 = integrate_until(ti=0, tf=boost_time , ic=ic1, x_prime_fun=x_prime)
ic2 = sol1.y[:, 110]
v = ic2[2], ic2[3]
new_v = v + boost * np.array(v/np.linalg.norm(v))
ic2[2], ic2[3] = new_v[0], new_v[1]
sol2 = integrate_until(ti=boost_time , tf=total_time, ic=ic2, x_prime_fun=x_prime)
import plotly.graph_objs as go
from plotly.offline import plot
data = [go.Scatter(x=[earth_radius*math.cos(i) for i in np.linspace(0, 2*math.pi, 10000)],
y=[earth_radius*math.sin(i) for i in np.linspace(0, 2*math.pi, 10000)],
name='earth'),
go.Scatter(x=sol1.y[0], y=sol1.y[1], name='pre boost'),
go.Scatter(x=sol2.y[0], y=sol2.y[1], name='post boost')]
plot(data)
| true |
75c14cfafe64264b72186017643b6c3b3dacb42f | Malak-Abdallah/Intro_to_python | /main.py | 866 | 4.3125 | 4 | # comments are written in this way!
# codes written here are solutions for solving problems from Hacker Rank.
# -------------------------------------------
# Jenan Queen
if __name__ == '__main__':
print("Hello there!! \nThis code to practise some basics in python. \n ")
str = "Hello world"
print(str[2:])
# TASK 1:
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
# 1<= n <= 100
print("Enter an integer greater then zero and less or equal 100 ")
n = int(input().strip())
if (n % 2) != 0:
print("Weird")
elif n % 2 == 0:
if n in range(2, 6) or n > 20:
print("Not Weird")
else:
print("Weird")
| true |
01f42ded2480038227e1d492193c9a1dbb3395bf | Chih-YunW/Leap-Year | /leapYear_y.py | 410 | 4.1875 | 4 | while True:
try:
year = int(input("Enter a year: "))
except ValueError:
print("Input is invalid. Please enter an integer input(year)")
continue
break
if (year%4) != 0:
print(str(year) + " is not a leap year.")
else:
if(year%100) != 0:
print(str(year) + " is a leap year.")
else:
if(year%400) == 0:
print(str(year) + " is a leap year.")
else:
print(str(year) + " is not a leap year.")
| true |
999579d8777c53f7ab91ebdcc13b5c76689f7411 | ayushmohanty24/python | /asign7.2.py | 682 | 4.1875 | 4 | """
Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values
"""
fname = input("Enter file name: ")
try:
fh = open(fname)
except:
print("File doesn't exist")
quit()
total=0
count=0
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
count=count+1
finding=line.find(':')
number=line[finding+1:].strip()
num=float(number)
total=total+num
average=total/count
print("Average spam confidence:",average)
| true |
adfa2df9495c4631f0d660714a2d130bfedd9072 | jni/interactive-prog-python | /guess-the-number.py | 2,010 | 4.15625 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
def initialize_game():
global secret_number, rangemax, guesses_remaining, guesses_label
rangemax = 100
guesses_remaining = 7
new_game()
# helper function to start and restart the game
def new_game():
global secret_number, rangemax, guesses_remaining, guesses_label
secret_number = random.randrange(rangemax)
if rangemax == 100:
guesses_remaining = 7
else:
guesses_remaining = 10
# define event handlers for control panel
def range100():
global rangemax
rangemax = 100
new_game()
print 'The secret number is now in [0, 100).'
def range1000():
global rangemax
rangemax = 1000
new_game()
print 'The secret number is now in [0, 1000).'
def input_guess(guess):
global secret_number, guesses_remaining, guesses_label
guess = int(guess)
print 'Your guess was %i' % guess
guesses_remaining -= 1
guesses_label.set_text('Guesses remaining: %i' % guesses_remaining)
if guess < secret_number:
print '... and it was too low.'
elif guess > secret_number:
print '... and it was too high.'
else:
print '... and BOOM. You got it.'
new_game()
if guesses_remaining == 0:
print 'You ran out of guesses! Starting a new game.'
print '(The secret number was %i.)' % secret_number
new_game()
# create frame
initialize_game()
frame = simplegui.create_frame('Guess the number', 200, 200)
# register event handlers for control elements and start frame
frame.add_input('Enter guess:', input_guess, 50)
frame.add_button('New game in [0, 100)', range100, 100)
frame.add_button('New game in [0, 1000)', range1000, 100)
guesses_label = frame.add_label('Guesses remaining: %i' %
guesses_remaining)
# call new_game
new_game()
frame.start()
| true |
5fd5b964582057ac930249378e9b944ac1b31bc0 | raghav1674/graph-Algos-In-Python | /Recursion/05/StairCaseTraversal.py | 393 | 4.15625 | 4 |
def max_ways_to_reach_staircase_end(staircase_height, max_step, current_step=1):
if staircase_height == 0 or current_step == 0:
return 1
elif staircase_height >= current_step:
return max_ways_to_reach_staircase_end(
staircase_height-current_step, max_step, current_step-1) + staircase_height//current_step
print(max_ways_to_reach_staircase_end(10, 2))
| true |
a4a7c7db2d8fbfb5649f831e832190e719c499c6 | phos-tou-kosmou/python_portfolio | /euler_project/multiples_of_three_and_five.py | 1,459 | 4.34375 | 4 | def what_are_n():
storage = []
container = 0
while container != -1:
container = int(input("Enter a number in which you would like to find multiples of: "))
if container == -1: break
if type(container) is int and container not in storage:
storage.append(container)
elif container in storage:
print("You have already entered this number, please enter all positive unique integer values")
else:
print("You must enter a valid integer that is postive")
return storage
def __main__():
# what_are_n() will return an array of integers
main_storage = what_are_n()
# next we will take a user input for what number they would
# like to find the summation of all multiples from storage
n = int(input("What number would you like to find the multiples of? : "))
final_arr = []
'''This will loop through n and enter a second for loop that will check
the mod of each element in final_arr. We are able to break once finding
an element because duplicates would skew the outcome. Once one number mods
n, then any other mod that equals 0 is arbitrary to that i'''
for i in range(0,n):
for j, fac in enumerate(main_storage):
if i % fac == 0:
final_arr.append(i)
break
final = sum(final_arr)
print(final)
if __name__ == "__main__":
pass
__main__() | true |
eec09d1b8c6506de84400410771fcdeb6fe73f73 | StephenTanksley/hackerrank-grind-list | /problem-solving/extra_long_factorials.py | 950 | 4.5625 | 5 | """
The factorial of the integer n, written n!, is defined as:
n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1
Calculate and print the factorial of a given integer.
Complete the extraLongFactorials function in the editor below. It should print the result and return.
extraLongFactorials has the following parameter(s):
n: an integer
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the extraLongFactorials function below.
# Memoization here isn't strictly necessary, but I wanted to practice writing out a memoization feature.
def memo(f):
table = {}
def helper(x):
if x not in table:
table[x] = f(x)
return table[x]
return helper
@memo
def extraLongFactorials(n):
product = 1
for i in range(1, n+1):
product *= i
print(product)
if __name__ == '__main__':
n = int(input())
extraLongFactorials(n)
| true |
aad85067c090c60b6095d335c6b9a0863dd76311 | dpolevodin/Euler-s-project | /task#4.py | 820 | 4.15625 | 4 | #A palindromic number reads the same both ways.
#The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
num_list = []
result = []
# Create a list with elements multiplied by each other
for i in range(100,1000):
for j in range(100,1000):
num_list.append(i * j)
word_list_str = map(str, num_list)
# Find palindrom in list and add it in new list
for element in word_list_str:
element_reverse = ''.join(reversed(element))
if element == element_reverse:
result.append(element_reverse)
# Sort list to find max value in palindromic numbers
fin_result = list(map(int, result))
fin_result.sort()
# Print max palindromic number
print('Max palindrom is: ', fin_result[-1])
| true |
41b6ee22ddfb9f6ad0d6dc18d0ec4e5bf1e0bb43 | anagharumade/Back-to-Basics | /BinarySearch.py | 827 | 4.125 | 4 | def BinarySearch(arr, search):
high = len(arr)
low = 0
index = ((high - low)//2)
for i in range(len(arr)):
if search > arr[index]:
low = index
index = index + ((high - low)//2)
if i == (len(arr)-1):
print("Number is not present in the input array.")
else:
pass
elif search < arr[index]:
high = index
index = (high - low)//2
if i == (len(arr)-1):
print("Number is not present in the input array.")
else:
pass
else:
if arr[index] == search:
print("Number found at position: ", index)
break
if __name__ == "__main__":
arr = [1,2,3,4,5,6,7,8,9,12]
BinarySearch(arr, 7)
| true |
3967fad907d30a59282306b168bfd3fa032bfaa9 | mootfowl/dp_pdxcodeguild | /python assignments/lab10_unit_converter_v3.py | 1,466 | 4.34375 | 4 | '''
v3 Allow the user to also enter the units.
Then depending on the units, convert the distance into meters.
The units we'll allow are inches, feet, yards, miles, meters, and kilometers.
'''
def number_crunch():
selected_unit = input("Pick a unit of measurement: inches, feet, yards, miles, meters, or kilometers. > ")
selected_number = float(input("And now pick a number. > "))
if selected_unit == 'inches':
conversion = selected_number * 0.0254
print(f"{selected_number} {selected_unit} is equal to {conversion} meters.")
number_crunch()
elif selected_unit == 'feet':
conversion = selected_number * 0.3048
print(f"{selected_number} {selected_unit} is equal to {conversion} meters.")
number_crunch()
elif selected_unit == 'yards':
conversion = selected_number * 0.9144
number_crunch()
elif selected_unit == 'miles':
conversion = selected_number * 1609.34
print(f"{selected_number} {selected_unit} is equal to {conversion} meters.")
number_crunch()
elif selected_unit == 'meters':
conversion = selected_number
print(f"{selected_number} {selected_unit} is equal to {conversion} meters. DUH.")
number_crunch()
elif selected_unit == 'kilometers':
conversion = selected_number / 1000
print(f"{selected_number} {selected_unit} is equal to {conversion} meters.")
number_crunch()
number_crunch()
| true |
d900cef1d0915808b0b213a6339636bf2dd3dcd2 | mootfowl/dp_pdxcodeguild | /python assignments/lab15_ROT_cipher_v1.py | 971 | 4.15625 | 4 | '''
LAB15: Write a program that decrypts a message encoded with ROT13 on each character starting with 'a',
and displays it to the user in the terminal.
'''
# DP note to self: if a = 1, ROT13 a = n (ie, 13 letters after a)
# First, let's create a function that encrypts a word with ROT13...
alphabet = 'abcdefghijklmnopqrstuvwxyz '
key = 'nopqrstuvwxyzabcdefghijklm '
def encrypt(word):
encrypted = ''
for letter in word:
index = alphabet.find(letter) # returns the alphabet index of the corresponding letter
encrypted += (key[index]) # prints the rot13 letter that correlates to the alphabet index
return encrypted
def decrypt(encrypted_word):
decrypted = ''
for letter in encrypted_word:
index = key.find(letter)
decrypted += (alphabet[index])
return decrypted
secret_sauce = input("Type in a word > ")
print(encrypt(secret_sauce))
not_so_secret_sauce = input("Type in an encrypted word > ")
print(decrypt(not_so_secret_sauce))
| true |
858422c01e9d9390216773f08065f38a124cb579 | monicaneill/PythonNumberGuessingGame | /guessinggame.py | 1,724 | 4.46875 | 4 | #Greetings
print("Hi there! Welcome to Monica's first coding project, 'The Python Number Guessing Game'!")
print("Let's see if you can guess the number in fewer steps than the computer openent. Let's begin!")
#Computer Function
def computerGuess(lowval, highval, randnum, count=0):
if highval >= lowval:
guess = lowval + (highval - lowval) // 2
# If guess is in the middle, it is found
if guess == randnum:
return count
#If 'guess' is greater than the number it must be
#found in the lower half of the set of numbers
#between the lower value and the guess.
elif guess > randnum:
count = count + 1
return computerGuess(lowval, guess-1, randnum, count)
#The number must be in the upper set of numbers
#between the guess and the upper value
else:
count + 1
return computerGuess(guess + 1, highval, randnum, count)
else:
#Number not found
return -1
#End of function
#Generate a random number between 1 and 100
import random
randnum = random.randint(1,101)
count = 0
guess = -99
while (guess != randnum):
#Get the user's guess
guess = (int) (input("Enter your guess between 1 and 100:"))
if guess < randnum:
print("You need to guess higher")
elif guess > randnum:
print("Not quite! Try guessing lower")
else:
print("Congratulations! You guessed right!")
break
count = count + 1
#End of while loop
print("You took " + str(count) + " steps to guess the number")
print("The computer guessed it in " + str(computerGuess(0,100, randnum)) + " steps") | true |
0e5c69430dcddf93721e19e55a54d131394ca452 | montoyamoraga/nyu-itp | /reading-and-writing-electronic-text/classes/class_02/cat.py | 2,211 | 4.125 | 4 | # import sys library
import sys
# this is a foor loop
#stdin refers to the lines that are input to the program
#typical python styling is indenting with four spaces
for line in sys.stdin:
#strip() removes whitespace at the end of the line
#strip() is a method of a line object
line = line.strip()
if "you" in line:
#print prints to the console
print line
# python follows the pemdas order of precedence
## stands for parenthesis, exponents, multiplication, addition, substraction
#this is a string variable
tofu = "delicious"
#this is for printing it to the screen
#notice that this it doesn't include quotes
print tofu
#to check the length of the string, use len()
print len("ok thx bye")
#operator in has two arguments, one to the left and one to the right
#it returns True if the string on the left can be found on the one to the right
#and False otherwise
print "foo" in "buffoon"
print "foo" in "reginald"
#strings have the method startswith that returns True or False
#if the string on the argument is found on the original string
#it is case-sensitive
print "tofu".startswith("to")
print "tofu".startswith("soy")
#ther is an analog method called endswith, to check for endings
print "tofu".endswith("fu")
print "tofu".endswith("soy")
#the find() method looks for a string inside of another string
#it returns the position in the string where it found the first match
#return -1 if nothing is found
print "tofu".find("u")
print "tofu".find("x")
#the lower() method evaluates to lowercase and upper() to uppercase
#they don't change the original value, they return the evaluated value
#most python functionalities don't affect the original one
#there is also titlecase, with method title()
print "tofu is awesome".lower()
print "tofu is awesome".upper()
print "tofu is awesome".title()
# the strip() method removes at beginning and end
print " t o f u yeah ".strip()
#the replace method replaces the first argument for the second argument
#in the original string,
print "what up, this is weird weird oh no".replace("i", "o");
#string indexing
#you can access subsets of the strings with [i:j]
#where i and j stand from ith to (j-1)th character
| true |
47c9f72baa7577f726046a80f338e40fd199bb61 | montoyamoraga/nyu-itp | /reading-and-writing-electronic-text/assignments/assignment_04/this.py | 2,031 | 4.1875 | 4 | #assignment 04
#for class reading and writing electronic text
#at nyu itp taught by allison parrish
#by aaron montoya-moraga
#february 2017
#the digital cut-up, part 2. write a program that reads in and creatively re-arranges the content of several source texts. what is the unit of your cut-up technique? (the word, the line, the character? something else?) how does your procedure relate (if at all) to your choice of source text? feel free to build on your assignment from last week. your program must make use of at least one set or dictionary. choose one text that you created with your program to read in class.
#my program takes two texts, lyrics for two different songs (javiera plana's invisible and flaming lips' bad days) and remixes them taking different random words from each of them, producing
#import sys, random and string module
from os import system
import random
import string
# read files
text01 = open("./text_original_01.txt").read()
text02 = open("./text_original_02.txt").read()
#split the texts in lists with all of the words
list01 = text01.split()
list02 = text02.split()
#construct a set of every word in the texts
set01 = set()
set02 = set()
for word in list01:
set01.add(word)
for word in list02:
set02.add(word)
#construct a dictionary with words as keys and number of times in values
dict01 = dict()
dict02 = dict()
for word in list01:
if word in dict01:
dict01[word] += 1
else:
dict01[word] = 1
for word in list02:
if word in dict02:
dict02[word] += 1
else:
dict02[word] = 1
for i in range(10):
#empty string for the current line
currentLine = ""
#make a random decision
decision = random.randint(1,2)
if decision == 1:
word = random.choice(dict01.keys())
for i in range(dict01[word]):
currentLine = currentLine + word + " "
elif decision == 2:
word = random.choice(dict02.keys())
for i in range(dict02[word]):
currentLine = currentLine + word + " "
print currentLine
| true |
e7f50e19dbf531b0af4ae651759d714278aac06b | ribeiroale/rita | /rita/example.py | 498 | 4.21875 | 4 | def add(x: float, y: float) -> float:
"""Returns the sum of two numbers."""
return x + y
def subtract(x: float, y: float) -> float:
"""Returns the subtraction of two numbers."""
return x - y
def multiply(x: float, y: float) -> float:
"""Returns the multiplication of two numbers."""
return x * y
def divide(x: float, y: float) -> float:
"""Returns the division of two numbers."""
if y == 0:
raise ValueError("Can not divide by zero!")
return x / y
| true |
299cc5fc729fef69fea8e96cd5e72344a1aa3e12 | voyeg3r/dotfaster | /algorithm/python/getage.py | 1,075 | 4.375 | 4 | #!/usr/bin/env python3
# # -*- coding: UTF-8 -*-"
# ------------------------------------------------
# Creation Date: 01-03-2017
# Last Change: 2018 jun 01 20:00
# this script aim: Programming in Python pg 37
# author: sergio luiz araujo silva
# site: http://vivaotux.blogspot.com
# twitter: @voyeg3r
# ------------------------------------------------
"""
One frequent need when writing interactive console applications is to obtain
an integer from the user. Here is a function that does just that:
This function takes one argument, msg . Inside the while loop the user is prompt-
ed to enter an integer. If they enter something invalid a ValueError exception
will be raised, the error message will be printed, and the loop will repeat. Once
a valid integer is entered, it is returned to the caller. Here is how we would
call it:
"""
def get_int(msg):
while True:
try:
i = int(input(msg))
return i
except ValueError as err:
print(err)
age = get_int("Enter your age ")
print("Your age is", age)
| true |
d9eddfd175dd379bd8453f908a0d8c5abeef7a29 | bbullek/ProgrammingPractice | /bfs.py | 1,536 | 4.1875 | 4 | ''' Breadth first traversal for binary tree '''
# First, create a Queue class which will hold nodes to be visited
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
return self.queue.pop(0)
def isEmpty(self):
return len(self.queue) == 0
# Define a Node class that holds references to L/R children, value, and 'visited' boolean
class Node:
def __init__(self, value = None):
self.value = value
self.left = None
self.right = None
self.visited = False
# Define a Binary Tree class full of nodes
class BinTree:
def __init__(self):
self.root = None
# Now the BFS algorithm
def BFS(root):
if root is None: # Edge case where we're passed a null ref
return
queue = Queue() # Initialize queue
root.visited = True
queue.enqueue(root)
while queue.isEmpty() == False:
v = queue.dequeue() # Some node containing a value
print(v.value)
# for all vertices adjacent to v...
if v.left is not None and v.left.visited == False:
v.left.visited = True
queue.enqueue(v.left)
if v.right is not None and v.right.visited == False:
v.right.visited = True
queue.enqueue(v.right)
# The main function where everything comes together
def main():
tree = BinTree()
# Populate the tree with nodes
tree.root = Node(50)
tree.root.left = Node(20)
tree.root.right = Node(30)
tree.root.left.left = Node(10)
tree.root.left.right = Node(5)
tree.root.right.left = Node(3)
# Perform BFS to visit the nodes of this tree
BFS(tree.root)
main() | true |
17f30d9b41e3bac84534424877c3fc81791ef755 | jibachhydv/bloomED | /level1.py | 498 | 4.15625 | 4 | # Get the Number whose index is to be returned
while True:
try:
num = int(input("Get Integer: "))
break
except ValueError:
print("Your Input is not integer")
# List of Number
numbers = [3,6,5,8]
# Function that return index of input number
def returnIndex(listNum, num):
for i in range(len(listNum)):
if listNum[i] == num:
return i
return -1
# Run the Function
print(f"Index of {num} in {numbers} is {returnIndex(numbers, num)}") | true |
fca406d84960938a40a1d2216983f2c07efa374e | Suraj-S-Patil/Python_Programs | /Simple_Intrst.py | 246 | 4.125 | 4 | #Program to calculate Simple Interest
print("Enter the principal amount, rate and time period: ")
princ=int(input())
rate=float(input())
time=float(input())
si=(princ*rate*time)/100
print(f"The simple interest for given data is: {si}.")
| true |
d552de01cad51b019587300e6cf5b7cbc5d3122f | Cherol08/finance-calculator | /finance_calculators.py | 2,713 | 4.40625 | 4 | import math
#program will ask user if they want to calculate total investment or loan amount
option = """ Choose either 'investment' or 'bond' from the menu below to proceed:\n
Investment - to calculate the amount of interest you'll earn on interest
Bond - to calculate the amount you'll have to pay on a home loan\n """
print(option)
choice = input("Enter option:\t").lower() # lower method used to convert input to lowercase characters
# while loop used if user doesn't enter either of the 2 options specified, program will keep asking
# user to enter correct option. if user does enter either option
#break statement will discontinue the loop and continue with the next statement
while (choice != "investment") and (choice != "bond"):
print("Invalid option.\n")
choice = input("Enter option:\t").lower()
if (choice == "investment") or (choice == "bond"):
break
# if user chooses investment, program will ask user to enter the following values:
# P- principal investment amount, r - interest rate, t - time planned to invest in years
# and the type of interest they'd like to use. The conditional statement executed if user chooses investment,
# will calculate user's investment depending on the type of interest user chooses.
# A- total investment amount with interest. Each outcome is rounded off to 2 decimal places
if choice == "investment":
P = float(input("Enter amount to deposit:\t"))
r = float(input("Enter the percentage of interest rate:\t"))
t = int(input("Enter number of years planned to invest:\t"))
interest = input("Simple or compound interest:\t").lower()
if interest == "simple":
A = round(P*(1+r*t), 2) #simple interest formula
print(f"\nThe total amount of your investment with simple interest is R{A}")
elif interest == "compound":
A = round(P*math.pow((1+r), t), 2) #compund interest formula
print(f"\nThe total amount of your investment with compound interest is R{A}")
# if user chooses bond, program will ask user for the following values:
# p-present value amount, i-interest rate, n -number of months to repay bond
# x - the total bond repayment per month
#the final answer is rounded of to two decimal places and displayed
elif choice == "bond":
bond = True
p = float(input("Enter present value of the house:\t"))
i = float(input("Enter the percentage of interest rate:\t"))
if i:
i = i/12 #interest in the bond formula is divided by 12
n = int(input("Enter period planned to repay the bond(in months):\t"))
x = round((i*p)/(1 - math.pow((1+i), -n)), 2) #bond formula
print(f"\nThe total bond repayment is R{x} per month")
| true |
462321abc830736f71325221f81c4f5075dd46fb | amithjkamath/codesamples | /python/lpthw/ex21.py | 847 | 4.15625 | 4 | # This exercise introduces 'return' from functions, and hence daisy-chaining them.
# Amith, 01/11
def add(a, b):
print "Adding %d + %d" % (a,b)
return a + b
def subtract(a, b):
print "Subtracting %d - %d" % (a,b)
return a - b
def multiply(a,b):
print "Multiplying %d * %d" % (a,b)
return a*b
def divide(a,b):
print "Dividing %d / %d" % (a,b)
return a/b
print "Let's do some math with just functions!"
age = add(30,5)
height = subtract(78,4)
weight = multiply(90,2)
iq = divide(100,2)
# Example of how "string %x" % variable is combined with "string", variable, "string again" ...
print "Age: %d, Height: %d, Weight:" % (age, height), weight, ", IQ: %d" % iq
print "Here's a puzzle"
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, " Can you do it by hand?"
| true |
923177e67d9afe32c3bcc738a8726234c5d08ad2 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex6.py | 758 | 4.5 | 4 | # Strings and Text
# This script demonstrates the function of %s, %r operators.
x = "There are %d types of people." % 10
binary = "binary" # saves the string as a variable
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not) # inserting variables ()
# here's where we print out our variables ^^^
print x
print y
print "I said: %r." % x # prints
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
# % hilarious becomes the missing variable for joke_evaluation
print joke_evaluation % hilarious
# more assigning strings to variables. will be used later
w = "This is the left side of..."
e = "a string with a right side"
# below is where we print the obove variables (w, e)
print w + e
| true |
568c69be02b59df5d2c531bb707be680fc5efa77 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex29.py | 1,080 | 4.65625 | 5 | # What If
# The if statements, used in conjunction with the > , < operators will print
# the following text if True.
# In other words, ( if x is True: print "a short story" )
# Indentation is needed for syntax purpouses. if you do not indent you will get
# "IndentationError: expected an indented block".
# If you do not create a colon after the new block of code is declared,
# you will get a SyntaxError: invalid syntax.
people = 20
cats = 30
dogs = 15
if people < cats and 1 == 1: # Prints first
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs and "test" != "testing": # Prints second
print "The world is dry!"
dogs += 5 # "increment by" operator. This is the same as 15 + 5 = 20
if people >= dogs: # Prints third
print "People are greater than or equal to dogs."
if people <= dogs: # Prints fourth
print "People are less than or equal to dogs."
if (not people != dogs): # Prints fifth
print "People are dogs."
| true |
46554c75d2000a673d11d628b5921831bec87b74 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex15.py | 944 | 4.25 | 4 | # Reading Files
# this file is designed to open and read a given file as plain text
# provide ex15.py with an argument (file) and it will read it to you
# then it will as for the filename again, you can also give it a different file.
from sys import argv
# here is how we can give an additional argument when trying to run the script (insert read file)
script, filename = argv
# line 8 doesnt actually open the file to the user. this is under the hood.
txt = open(filename)
# line 11 is how we actually read the file to the user. but first you must open it.
print "Here's your file %r:" % filename
print txt.read()
# here is where we ask for the filename again and assign it to a variable (file_again)
print "Type the filename again:"
file_again = raw_input("> ")
# here is how we open the new file in the directory
txt_again = open(file_again)
# here is how we actually print or read() the second file txt_again.read()
print txt_again.read()
| true |
2ca7c4e31ad857f80567942a0934d9399a6da033 | zoeyangyy/algo | /exponent.py | 600 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Time : 2018/8/16 下午10:27
# @Author : Zoe
# @File : exponent.py
# @Description :
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
result = base
if exponent == 0:
return 1
elif exponent > 0:
for i in range(exponent-1):
result *= base
return result
else:
for i in range(-exponent-1):
result *= base
return 1/result
c = Solution()
print(c.Power(2,-3)) | true |
36d281d594ec06a38a84980ca15a5087ccb2436a | connor-giles/Blackjack | /hand.py | 847 | 4.125 | 4 | """This script holds the definition of the Hand class"""
import deck
class Hand:
def __init__(self):
self.cards = [] # A list of the current cards in the user's hand
self.hand_value = 0 # The actual value of the user's hand
self.num_aces = 0 # Keeps track of the number of aces that the user has
def __len__(self):
return len(self.cards)
def add_card(self, new_card):
self.cards.append(new_card)
self.hand_value += deck.values[new_card.rank]
if new_card.rank == 'Ace':
self.num_aces += 1
def adjust_for_ace(self):
# If the users hand value is greater than 21 but the user still has an ace, you need to re-adjust the hand value
while self.hand_value > 21 and self.num_aces:
self.hand_value -= 10
self.num_aces -= 1
| true |
6b16f67a76c4951b641d252d40a1931552381975 | by46/geek | /codewars/4kyu/52e864d1ffb6ac25db00017f.py | 2,083 | 4.1875 | 4 | """Infix to Postfix Converter
https://www.codewars.com/kata/infix-to-postfix-converter/train/python
https://www.codewars.com/kata/52e864d1ffb6ac25db00017f
Construct a function that, when given a string containing an expression in infix notation,
will return an identical expression in postfix notation.
The operators used will be +, -, *, /, and ^ with standard precedence rules and
left-associativity of all operators but ^.
The operands will be single-digit integers between 0 and 9, inclusive.
Parentheses may be included in the input, and are guaranteed to be in correct pairs.
to_postfix("2+7*5") # Should return "275*+"
to_postfix("3*3/(7+1)") # Should return "33*71+/"
to_postfix("5+(6-2)*9+3^(7-1)") # Should return "562-9*+371-^+"
c++ to_postfix("2+7*5") # Should return "275*+" to_postfix("3*3/(7+1)")
# Should return "33*71+/" to_postfix("5+(6-2)*9+3^(7-1)") # Should return "562-9*+371-^+"
You may read more about postfix notation, also called Reverse Polish notation,
here: http://en.wikipedia.org/wiki/Reverse_Polish_notation
"""
ORDERS = {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
'^': 3,
'(': 0,
')': 4
}
def to_postfix(infix):
"""Convert infix to postfix
>>> to_postfix("2+7*5")
'275*+'
>>> to_postfix("3*3/(7+1)")
'33*71+/'
>>> to_postfix("5+(6-2)*9+3^(7-1)")
'562-9*+371-^+'
>>> to_postfix("(5-4-1)+9/5/2-7/1/7")
'54-1-95/2/+71/7/-'
"""
stack = []
result = []
for c in infix:
if c.isdigit():
result.append(c)
elif c == '(':
stack.append(c)
elif c == ')':
while stack[-1] != '(':
result.append(stack.pop())
stack.pop()
else:
while stack and ORDERS[stack[-1]] >= ORDERS[c]:
result.append(stack.pop())
stack.append(c)
if stack:
result.extend(reversed(stack))
return ''.join(result)
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
81cfaff6e7ed2ac0be013d2439592c4fb8868e63 | apugithub/Python_Self | /negetive_num_check.py | 355 | 4.15625 | 4 |
# Negetive number check
def check(num):
return True if (num<0) else False
print(check(-2))
### The function does check and return the negatives from a list
lst = [4,-5,4, -3, 23, -254]
def neg(lst):
return [num for num in lst if num <0]
# or the above statement can be written as= return sum([num < 0 for num in nums])
print(neg(lst)) | true |
8f27badfdef2487c0eb87e659fac64210faa1646 | gaylonalfano/Python-3-Bootcamp | /card.py | 767 | 4.125 | 4 | # Card class from deck of cards exercise. Using for unit testing section
# Tests: __init__ and __repr__ functions
from random import shuffle
class Card:
available_suits = ("Hearts", "Diamonds", "Clubs", "Spades")
available_values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
def __init__(self, suit, value):
if suit not in Card.available_suits:
raise ValueError # (f"{suit} is not a valid suit.")
elif str(value) not in Card.available_values:
raise ValueError # (f"{value} is not a valid value.")
else:
self.suit = suit
self.value = value
def __repr__(self):
return "{} of {}".format(self.value, self.suit) # f"{self.value} of {self.suit}" | true |
6bcb51fae80c295f98d6004344c5ffec1028f602 | gaylonalfano/Python-3-Bootcamp | /infinite_generators_get_multiples.py | 649 | 4.21875 | 4 | # def get_multiples(number=1, count=10):
# for i in range(1, count+1):
# yield number*i
#
# evens = get_multiples(2, 3)
# print(next(evens))
# print(next(evens))
# print(next(evens))
# print(next(evens))
# GET_UNLIMITED_MULTIPLES EXERCISE:
def get_unlimited_multiples(number=1):
next_num = number
while True:
yield next_num
next_num += number
# Student's example with *
# def get_unlimited_multiples(num=1):
# next_num = 1
# while True:
# yield num*next_num
# next_num += 1
fours = get_unlimited_multiples(4)
print(next(fours))
print(next(fours))
print(next(fours))
print(next(fours)) | true |
c68446d2fa042a3c279654f3937c16d632bf2420 | gaylonalfano/Python-3-Bootcamp | /decorators_logging_wraps_metadata.py | 2,667 | 4.40625 | 4 | """
Typical syntax:
def my_decorator(fn):
def wrapper(*args, **kwargs):
# do stuff with fn(*args, **kwargs)
pass
return wrapper
Another tutorial example: https://www.youtube.com/watch?v=swU3c34d2NQ
from functools import wraps
import logging
logging.basicConfig(filename='example.log', level=logging.INFO)
def logger(func):
@wraps(func)
def log_func(*args):
logging.info(f"Running {func.__name__} with arguments {args}")
print(func(*args))
return log_func
@logger # With Decorator
def add(x, y):
return x+y
@logger # With Decorator
def sub(x, y):
return x-y
# WITH DECORATOR??? Not sure with add since it's built-in...
add(3, 3)
add(4, 5)
sub(10, 5)
sub(20, 10)
# WITHOUT DECORATOR:
add_logger = logger(add)
sub_logger = logger(sub)
add_logger(3, 3) # 6
add_logger(4, 5) # 9
sub_logger(10, 5) # 5
sub_logger(20, 10) # 10
# **NEXT** Open the file example.log to see log results
"""
# USING WRAPS TO PRESERVE METADATA - LOGGING FUNCTION DATA
# def log_function_data(fn):
# def wrapper(*args, **kwargs):
# """I'm a WRAPPER function""" # This is the doc string __doc__
# print(f"You are about to call {fn.__name__}")
# print(f"Here's the documentation: {fn.__doc__}")
# return fn(*args, **kwargs)
# return wrapper
#
# @log_function_data
# def add(x,y):
# """Adds two numbers together."""
# return x+y
#
# print(add(10, 30)) # PROBLEM WITH ADD FUNCTION!
# print(add.__doc__) # ALL referring to WRAPPER instead! NOT GOOD!
# print(add.__name__)
# help(add)
'''
SOLUTION - Module called functools with WRAPS FUNCTION!
wraps is simply a function we use to wrap around our wrapper function.
It ensures that the metadata of the functions that get decorated are
not lost by the decorator. So, for example, if you decorate @ add or len,
you won't lose the original metadata for those functions.
from functools import wraps
# wraps preserves a function's metadata
# when it is decorated!
def my_decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# do some stuff with fn(*args, **kwargs)
pass
return wrapper
'''
from functools import wraps
def log_function_data(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
"""I'm a WRAPPER function""" # This is the docstring __doc__
print(f"You are about to call {fn.__name__}")
print(f"Here's the documentation: {fn.__doc__}")
return fn(*args, **kwargs)
return wrapper
@log_function_data
def add(x,y):
"""Adds two numbers together."""
return x+y
print(add(10, 30))
print(add.__doc__)
print(add.__name__)
help(add)
| true |
0fa247aef355f85a8a00d44357933f418038c91d | gaylonalfano/Python-3-Bootcamp | /debugging_pdb.py | 1,790 | 4.1875 | 4 | '''
Python Debugger (pdb) -- To set breakpoints in our code we can use pdb by inserting this line:
def function(params):
import pdb; pdb.set_trace() - Usually added/imported like this inside a function
*Rest of code*
Usually placed right before something starts breaking. Allows you to see a preview of what happens before/after.
Pdb Commands:
l (list)
n (next line)
a all values
p (print)
c (continue - finishes debugging by running the rest of the code)
NOTE - If you have parameters/variable names that are any of these above COMMANDS,
then you need to type: "p [variable name]" to print the value of that var. Ex. p c #
'''
# import pdb
#
#
# first = 'First'
# second = 'Second'
# pdb.set_trace()
# result = first + second
# third = 'Third'
# result += third
# print(result)
# def add_numbers(a, b, c, d):
# import pdb; pdb.set_trace()
#
# return a + b + c + d
#
# add_numbers(1, 2, 3, 4)
# DIVIDE() - two params num1, num2. If you don't pass the correct amount of args
# it should say "Please provided two integers or floats". If num2 == 0, should
# raise a ZeroDivisionError, so return string "Please do not divide by zero"
def divide(num1, num2):
try:
return num1/num2
except TypeError:
print("Please provide two integers or floats")
except ZeroDivisionError:
print("Please do not divide by zero")
# def divide2(num1):
# import pdb; pdb.set_trace()
# if type(num1) != int or type(num1) != float:
# raise TypeError("Please provide two integers or floats")
# # elif num2 == 0:
# # raise ZeroDivisionError("Please do not divide by zero")
# else:
# print(num1)
# divide(4, 2)
# divide([], "1")
# divide(1, 0)
# divide2('1', '2')
# divide2(4, '1')
# divide2([], 0)
divide2(5) | true |
9c309fa1bc6df7bf3d6e6b7ed047df45eb670316 | gaylonalfano/Python-3-Bootcamp | /sorted.py | 1,583 | 4.5625 | 5 | '''
sorted - Returns a new sorted LIST from the items in iterable (tuple, list, dict, str, etc.)
You can also pass it a reverse=True argument.
Key difference between sorted and .sort() is that .sort() is a list-only method and returns the
sorted list in-place. sorted() accepts any type of iterable. Good for sorted on a key in dictionaries, etc.
'''
more_numbers = [6, 1, 8, 2]
sorted(more_numbers) # [1, 2, 6, 8]
print(more_numbers)
print(sorted(more_numbers, reverse=True))
sorted((2, 1, 45, 23, 99))
users = [
{'username': 'samuel', 'tweets': ['I love cake', 'I love pie']},
{'username': 'katie', 'tweets': ["I love my cat"], "color": "purple"},
{'username': 'jeff', 'tweets': []},
{'username': 'bob123', 'tweets': [], "num": 10, "color": "green"},
{'username': 'doggo_luvr', 'tweets': ["dogs are the best"]},
{'username': 'guitar_gal', 'tweets': []}
]
# sorted(users) # Error message. Need to specify on what you want to sort on
print(sorted(users, key=len)) # default is ascending
print(sorted(users, key=lambda user: user['username'])) # 'bob123', 'doggo_luvr', etc.
# Sort based off of who has the most tweets
print(sorted(users, key=lambda user: len(user['tweets']), reverse=True)) # Ascending default. 0 tweets > 2 tweets
# List of songs w/ playcount. How to sort based on playcount?
songs = [
{'title': 'happy birthday', 'playcount': 1},
{'title': 'Survive', 'playcount': 6},
{'title': 'YMCA', 'playcount': 99},
{'title': 'Toxic', 'playcount': 31}
]
print(sorted(songs, key=lambda song: song['playcount'], reverse=True)) | true |
a5668f587fe9b9b26b70afd0e7bf97bc317c35b3 | gaylonalfano/Python-3-Bootcamp | /polymorphism_OOP.py | 1,806 | 4.3125 | 4 | '''
POLYMORPHISM - A key principle in OOP is the idea of polymorphism - an object can take
on many (poly) forms (morph). Here are two important practical applications:
1. Polymorphism & Inheritance - The same class method works in a similar way for different classes
Cat.speak() # meow
Dog.speak() # woof
Human.speak() # Yo
A common implementation of this is to have a method in a base (or parent) class that is
overridden by a subclass. This is called METHOD OVERRIDING. If other people on a team
want to write their own subclass methods, this is useful.
class Animal:
def speak(self):
raise NotImplementedError("Subclass needs to implement this method")
class Dog(Animal):
def speak(self):
return "woof"
class Cat(Animal):
def speak(self):
return "meow"
class Fish(Animal):
pass
d = Dog()
print(d.speak())
f = Fish()
print(f.speak()) # NotImplementedError: Subclass needs to implement this method - need a speak()
2. Special Methods (__dunder__ methods, etc) - The same operation works for different kinds of objects:
sample_list = [1, 2, 3]
sample_tuple = (1, 2, 3)
sample_string = "awesome"
len(sample_list)
len(sample_tuple)
len(sample_string)
8 + 2 = 10
"8" + "2" = "82"
Python classes have special (aka "magic") methods that are dunders. These methods with special
names that give instructions to Python for how to deal with objects.
'''
class Animal:
def speak(self):
raise NotImplementedError("Subclass needs to implement this method")
class Dog(Animal):
def speak(self):
return "woof"
class Cat(Animal):
def speak(self):
return "meow"
class Fish(Animal):
pass
d = Dog()
print(d.speak())
f = Fish()
print(f.speak()) # NotImplementedError: Subclass needs to implement this method - need a speak() | true |
79c42425fad9a2049934a8208d0b8cf9ca9b0a08 | gaylonalfano/Python-3-Bootcamp | /custom_for_loop_iterator_iterable.py | 1,648 | 4.4375 | 4 | # Custom For Loop
'''
ITERATOR - An object that can be iterated upon. An object which returns data,
ONE element at a time when next() is called on it. Think of it as anything we can
run a for loop on, but behind the scenes there's a method called next() working.
ITERABLE - An object which will return an ITERATOR when iter() is called on it.
IMPORTANT: A list is also just an iterable. The list is actually never directly
looped over. What actually happens is the for loop calls iter("HELLO"), which
returns the iterator that is then the loop will call next() on that iterator
over and over again until it hits the end!
UNDERSTAND THE ITER() AND NEXT() METHODS
ITER() - Returns an iterator object.
NEXT() - When next() is called on an iterator, the iterator returns the next ITEM.
It keeps doing so until it raises a StopIteration error. It's actually using a
try/except block until it reaches the end and raises the StopIteration error.
'''
def my_for(iterable, func):
iterator = iter(iterable)
while True:
# Need to add in try/except block to stop error from displaying to user
try:
# Would be nice to add some functionality to it (sum, mul, etc.) other than just print
# print(next(iterator))
i = next(iterator)
func(i)
except StopIteration:
# print("End of loop")
break
# else: Another syntax is to do the func() call in the else statement
# func(i)
def square(x):
print(x**2) # If you only use RETURN, then it won't PRINT
#my_for("hello")
my_for([1, 2, 3, 4], square) # 1, 4, 9, 16
my_for('lol', print)
| true |
2e9cde6ddaf45706eb646ec7404d22a851430e3f | gaylonalfano/Python-3-Bootcamp | /dundermethods_namemangling.py | 1,096 | 4.5 | 4 | # _name - Simply a convention. Supposed to be "private" and not used outside of the class
# __name - Name Mangling. Python will mangle/change the name of that attribute. Ex. p._Person__lol to find it
# Used for INHERITANCE. Python mangles the name and puts the class name in there for inheritance purposes.
# Think of hierarchy (Person > [Teacher, Cop, Coach, Student, etc.]). Teacher could also have self._Teacher__lol
# __name__ - Don't go around making your own __dunder__ methods
class Person:
def __init__(self):
self._secret = 'hi!'
self.name = 'Tony'
self.__msg = "I like turtles"
self.__lol = "hahahaha"
# In other programming languages to make private do:
# private self._secret = "hi!"
# def doorman(self, guess):
# if guess == self._secret:
# let them in
p = Person()
print(p.name)
print(p._secret)
# print(p.__msg) # AttributeError: 'Person' object has no attribute '__msg'
print(dir(p)) # list ['_Person__msg', '_Person_lol', '__class__', '__delattr__', ...]
print(p._Person__msg)
print(p._Person__lol) | true |
15dbca45f3fbb904d3f747d4f165e7dbca46c684 | XavierKoen/cp1404_practicals | /prac_01/loops.py | 924 | 4.5 | 4 | """
Programs to display different kinds of lists (numerical and other).
"""
#Basic list of odd numbers between 1 and 20 (inclusive).
for i in range(1, 21, 2):
print(i, end=' ')
print()
#Section a: List counting in 10s from 0 to 100.
for i in range(0, 101, 10):
print(i, end=' ')
print()
#Section b: List counting down from 20 to 1.
for i in range(1, 21):
j = 21 - i
print(j, end=' ')
print()
#Section c: Print number of stars (*) desired on one line.
number_of_stars = int(input("Number of stars: "))
for i in range(1, number_of_stars + 1):
print("*",end="")
print()
#Section d: Print desired number of lines of stars (*) with increasing number of stars in each line.
# Beginning with one and finishing with desired number.
number_of_stars = int(input("Number of stars: "))
for i in range(1, number_of_stars + 1):
for j in range(1, i + 1):
print("*",end="")
print()
print() | true |
e1e5bdeab07475e95a766701d6feb6e14fe83494 | XavierKoen/cp1404_practicals | /prac_02/password_checker.py | 2,067 | 4.53125 | 5 | """
CP1404/CP5632 - Practical
Password checker code
"""
MIN_LENGTH = 2
MAX_LENGTH = 6
SPECIAL_CHARS_REQUIRED = False
SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]<>?{}|\\"
def main():
"""Program to get and check a user's password."""
print("Please enter a valid password")
print("Your password must be between {} and {} characters, and contain:".format(MIN_LENGTH, MAX_LENGTH,))
print("\t1 or more uppercase characters")
print("\t1 or more lowercase characters")
print("\t1 or more numbers")
if SPECIAL_CHARS_REQUIRED:
print("\tand 1 or more special characters: {}".format(SPECIAL_CHARACTERS))
password = input("> ")
while not is_valid_password(password):
print("Invalid password!")
password = input("> ")
print("Your {}-character password is valid: {}".format(len(password), password))
def is_valid_password(password):
"""Determine if the provided password is valid."""
# Establish counter variables.
count_lower = 0
count_upper = 0
count_digit = 0
count_special = 0
# If length is wrong, return False.
if MIN_LENGTH <= len(password) <= MAX_LENGTH:
# Count each character using str methods.
for char in password:
count_lower = count_lower + int(char.islower())
count_upper = count_upper + int(char.isupper())
count_digit = count_digit + int(char.isdigit())
# Return False if any are zero.
if count_lower == 0 or count_upper == 0 or count_digit == 0:
return False
else:
# Count special characters from SPECIAL_CHARACTERS string if required.
# Return False if count_special is zero.
if SPECIAL_CHARS_REQUIRED:
for char in password:
count_special = count_special + int(char in SPECIAL_CHARACTERS)
if count_special == 0:
return False
else:
return False
# If we get here (without returning False), then the password must be valid.
return True
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.