Rounding in Python - python

Hi everyone I am currently doing a school project and even my teacher is stumped. In Canada the penny has been removed so now all purchases are rounded to either 0 or 5. For example 5.53 would become 5.55 and 5.52 would become 5.50. I am trying to get my program to round like this, but I can't figure out how. I know how to round to decimal places, but I don't know how to round to specifics like this. Any help would be appreciated!
Here is my code. The project is about making a program that a cashier would use in a coffee shop.
order = ['coffee', 'tea', 'hashbrown','jelly','cream','chocolate','glazed','sandwich','bagel','cookie','pannini']
quantity = ['0','0','0','0','0','0','0','0','0','0','0']
# coffee = $1
# Tea = $1.30
# hashbrown = $1.25
# all donuts = $1.50
# sandwich = $2.50
# bagel = $2
# cookie = $0.50
# pannini = $4
cashier = 1
total = 0
while cashier == 1:
print "What did the customer order?"
ordered = input ()
while ordered > 10 or ordered < 0:
print "Do you want to input a valid order?"
ordered = input ()
print "How many are being ordered?"
quantityorder = input ()
quantity[ordered] = quantityorder
print "Ordered",quantityorder,"",order[ordered],"!"
if ordered == 0:
ordered = 1.0
elif ordered == 1:
ordered = 1.30
elif ordered == 2:
ordered = 1.25
elif ordered == 3 or ordered == 4 or ordered == 5 or ordered == 6:
ordered = 1.50
elif ordered == 7:
ordered = 2.50
elif ordered == 8:
ordered = 2
elif ordered == 9:
ordered = 0.50
else:
ordered = 4.0
price = ordered * quantityorder
total = total + price
print "Anything else?"
cashier = input () #If the user inputs 1 then they can input another order if they didn't put in 1 then the program assumes that it is the end of a customers order
print "Your total is $", total * 1.13,"!"
total = total * 1.13
print
print "How much money was given?"
print
money = input ()* 1.0
while money < total:
print "Please input a valid number!"
money = input ()
print "The change should be $",money - total,"!"

This tortured me until I solved it. One rule I set for myself was NOT to use a case-by-case switch on modulo 5, but to use builtin functions. Nice puzzle. wim's "double it, round, then halve it" comment was close.
def nickelround(n):
N = int(n)
print "%0.2f" % (N + round((n - N) * 20) * 0.05)

In [42]:
x=0.57
int(x/0.05)*0.05
Out[42]:
0.55

Usually in these programming problems you're explicitly asked to solve for how to "make change", not just provide the total amount of change due (which is trivial). So you can just in-line the pennies correction into that function:
def make_change(bal):
bal = bal + .02 #correction for no pennies
currency = [20,10,5,1,.25,.1,.05]
change = {}
for unit in currency:
change[unit] = int(bal // unit)
bal %= unit
return change
This particular form returns a dict of change denominations and their corresponding counts.

As you already hinted, use the Decimal class (module decimal). Replace all floats in your code with decimal constructors like Decimal('13.52').
Now the function you want to use is 'quantize'.
You use it like that:
Decimal('1.63').quantize(Decimal('0.5'), rounding=ROUND_HALF_DOWN)
The parameter Decimal('0.5') indicates that you want to round to the halves.
UPDATE:
As the OP wanted to round to the units of 0.05, he must obviously use:
Decimal('1.63').quantize(Decimal('0.05'), rounding=ROUND_HALF_DOWN)

I'm going to be old-school and say, convert your number into a list of values with a null or some kind of tag to represent the decimal.
The make a variable to hold your rounded number and add each value from 1000s or whatever, to 100s, 10s and 1s. (You are looping of course).
Once your loop hits the tag, depending on how far you want to round, (this should be a parameter for your function) throw in a conditional to represent how you want to round ie. 5 means round up, 4 round down (this is another parameter). Then add the final value(s) and return your newly rounded number.
Step 2: Fire your teacher because this is an unbelievably easy problem.
Bare in mind, anyone who knows c or has worked with memory assignment should find this question a breeze.

You could use something as simple as this to round your numbers to a given base:
def round_func(x, base=0.05):
return round(base*round(float(x)/base), 2)
And since you want only 2 decimal places, you can just round it to 2 decimals. The inner round function is to round the given number as per the base, which is 0.05 in your case.

Do you know, how to use own functions?
Add this function to your code:
def nickelround(m):
return round(m/0.05,0)*0.05
and use it:
print "The change should be $", nickelround(money - total),"!"

Related

Ask user to enter a positive integer n and use this number to calculate the sum of series up to n term

Ask user to enter a positive integer n and use this number to calculate the sum of series up to n term. (20 pts)
Test case:
if n = 2 the series will become 3 + 33 = 36
if n = 5 the series will become 3 + 33 + 333 + 3333 + 33333 = 37035
The trick is to think about the number of times each digits place is added.
For instance, at n=5, you are adding the 3 in the units place 5 times, but adding the 3 in the ten thousands place only once. Because of this, it is appropriate to start the for loop at 5 and decrement as we add everything up together.
n = input("Please enter a number. ")
total = 0
for i in range(int(n),0,-1):
total += 3*i*(10**(int(n)-i))
print(total)
I am using math.pow to go to the next place (i.e. 1, 10, 100, etc.). I do int(n)-i because I want to start at 0 and go up to n for this exponent.
Output:
Please enter a number. 5
37035.0
Edit: I changed syntax to use Python's syntax for exponents instead of math.pow
You can use a recursive function that adds a 3 at the end using 10x + 3:
def function3(seed):
if(seed==1):
return 3
else:
return (10*f3(seed-1))+3
seed = int(input('integer please: '));
print(function3(seed))
We could also build a string which could be regarded as cheating if we're talking about a function.
Here is an alternative definition for the function:
def function3(seed):
s = ""
for i in range(0,seed):
s+="3"
return s

How to create a shopping cart calculator

I am writing a program which takes one input (a number of product) and gives one output (price of the product):
Drink: $2.25
6-pack: $10
25% discount if more than $20
((Sorry if my code is really bad I'm a newbie))
print( "How many drinks do you want?" )
drinks = input( "Enter number: ")
total = int(drinks)
single = 2.25
six = 10
single * 6 = six
if total > 20:
total * 0.75
print( "That will be a total of: ", total, "dollars")
I'm confused how to make it so that, after I have changed the input value to an int, how can I separate and calculate it based on my pricing criteria. Please help?
I assume you're looking for something like this. Hope it helps! I tried to keep your variable names the same so it would make some kind of sense to you. The line I commented out is an error.
drinks = input("How many drinks do you want?")
drinks = int(drinks)
total = 0
single = 2.25
six = 10
sixPacks = drinks // 6
singles = drinks % 6
# single * 6 = six
total += six * sixPacks
total += single * singles
if total > 20:
total *= 0.75
print( "That will be a total of: {} dollars".format(round(total, 2)))
Okay so let's break it down logically.
You first take in the input number of drinks the person wants. You're assigning it to total right away, when you should actually assign it to a variable that holds the number of drinks.
You should then multiply the number of drinks by the cost per drink. You also need to check if the number of drinks are a multiple of 6 so that you can price them by the six pack.
Once you have calculated this check if the total < 20.
Since this is a homework problem. I will encourage you to try to solve it with this approach.

Coin Change Maker Python Program

I am in a beginner programming course. We must do an exercise where we make a change maker program. The input has to be between 0-99 and must be represented in quarters, dimes, nickles, and pennies when the input is divided down between the four. I wrote a code that involved loops and whiles, but he wants something more easy and a smaller code. He gave me this as a way of helping me along:
c=int(input('Please enter an amount between 0-99:'))
print(c//25)
print(c%25)
He told us that this was basically all we needed and just needed to add in the dimes, nickles, and pennies. I try it multiple ways with the dimes, nickles, and pennies, but I cannot get the output right. Whenever I enter '99', I get 3 for quarters, 2 for dimes, 1 for nickles, and 0 for pennies. If anyone would be able to help me, that would be wonderful!
I'm now sure about what you want to achieve. Using the modulo operator you could easily find out how many quarters, dimes, nickles and pennies.
Let's just say you input 99.
c=int(input('Please enter an amount between 0-99:'))
print(c//25, "quarters")
c = c%25
print(c//10, "dimes")
c = c%10
print(c//5, "nickles")
c = c%5
print(c//1, "pennies")
this would print out:
3 quarters
2 dimes
0 nickles
4 pennies
n = int(input("Enter a number between 0-99"))
q = n // 25
n %= 25
d = n // 10
n %= 10
ni = n // 5
n %= 5
c = n % 5
print(str(q) +" " + str(d) +" " + str(ni) + " " + str(c))
I hope this helps? Something like this but don't just copy it. Everytime you divide by 25 10 5 you must lose that part because it's already counted.At the end print what ever you want :).
The actual trick is knowing that because each coin is worth at least twice of the next smaller denomination, you can use a greedy algorithm. The rest is just implementation detail.
Here's a slightly DRY'er (but possibly, uh, more confusing) implementation. All I'm really doing differently is using a list to store my results, and taking advantage of tuple unpacking and divmod. Also, this is a little easier to extend in the future: All I need to do to support $1 bills is to change coins to [100, 25, 10, 5, 1]. And so on.
coins = [25,10,5,1] #values of possible coins, in descending order
results = [0]*len(coins) #doing this and not appends to make tuple unpacking work
initial_change = int(input('Change to make: ')) #use raw_input for python2
remaining_change = initial_change
for index, coin in enumerate(coins):
results[index], remaining_change = divmod(remaining_change, coin)
print("In order to make change for %d cents:" % initial_change)
for amount, coin in zip(results, coins):
print(" %d %d cent piece(s)" % (amount, coin))
Gives you:
Change to make: 99
In order to make change for 99 cents:
3 25 cent piece(s)
2 10 cent piece(s)
0 5 cent piece(s)
4 1 cent piece(s)
"""
Change Machine - Made by A.S Gallery
This program shows the use of modulus and integral division to find the quarters, nickels, dimes, pennies of the user change !!
Have Fun Exploring !!!
"""
#def variables
user_amount = float(input("Enter the amount paid : "))
user_price = float(input("Enter the price : "))
# What is the change ?? (change calculation)
user_owe = user_amount - user_price
u = float(user_owe)
print "Change owed : " + str(u)
"""
Calculation Program (the real change machine !!)
"""
# Variables for Calculating Each Coin !!
calculate_quarters = u//.25
# Using the built-in round function in Python !!
round(calculate_quarters)
print "Quarters : " + str(calculate_quarters)
u = u%0.25
calculate_dime = u//.10
round(calculate_dime)
print "Dime : " + str(calculate_dime)
u = u%0.10
calculate_nickels = u//.05
round(calculate_nickels)
print "Nickels : " + str(calculate_nickels)
u = u%0.5
calculate_pennies = u//.01
round(calculate_pennies)
print "Pennies : " + str(calculate_pennies
Code for the change machine works 100%, its for CodeHs Python
This is probably one of the easier ways to approach this, however, it can also
be done with less repetition with a while loop
cents = int(input("Input how much money (in cents) you have, and I will tell
you how much that is is quarters, dimes, nickels, and pennies. "))
quarters = cents//25
quarters_2 = quarters*25
dime = (cents-quarters_2)//10
dime_2 = dime*10
nickels = (cents-dime_2-quarters_2)//5
nickels_2 = nickels*5
pennies = (cents-dime_2-quarters_2-nickels_2)

python to calculate percent of cars over the speed limit

I'm trying to calculate the percent of cars that go over the speed limit using this code, except there are errors in the second loop and I'm not sure how to use a loop to increment the amount of cars over the speed limit. My end goal is to print out the percent of cars that go above the speed limit. I'm new to programming so any tips or help would be appreciated, thanks :-)
numCars = int(input("Enter the number of cars: "))
carSpeeds = []
for i in range(numCars):
speed = int(input("Enter the car speed: "))
carSpeeds.append(speed)
carsAboveLimit = 0
speedLimit = int(input("Enter the speed limit: "))
if speed > speedLimit
carsAboveLimit =+ 1
i = i +1
percent = int(carsAboveLimit)/len(carSpeeds)
print("The percentage of cars over the speed limit is", percent)
You're doing an euclidian division. The type of carsAboveLimit is int, and it's the same thing for len(carSpeeds).
If you want to get the percent, just multiply by a floating number (typically 1.) like this :
percent = 1. * int(carsAboveLimit)/len(carSpeeds)
The major issues are
You are missing a colon at the end of the if statement
The if statement is only execute once, you didn't put it in a loop
You could change the if statement to:
for car_speed in carSpeeds:
if car_speed > speedLimit:
carsAboveLimit += 1
What this does is go through each item in the list. Each time the value of car_speed becomes the next item in the list.
The division is an integer division, so you won't get a decimal
You need to multiply by 100 to get a percent
Instead specify a float and multiply by 100:
percent = 100 * float(carsAboveLimit)/len(carSpeeds)
If you don't format the final string you will get many trailing digits
You should try it without formating first to see what I mean, then you could change it to:
print "The percentage of cars over the speed limit is %0.2f%%" % percent
Other things
Note that the usual convention for variable in Python is to use underscores instead of camelCase. That is, try to use: speed_limit instead of speedLimit.
You don't need the i variable. My guess is you were trying to have a counter to keep track of the loop maybe? Either way it isn't necessary.
Good luck!
You are missing a colon after if speed > speedLimit
carsAboveLimit is already an int; you do not need to cast it so again.
=+ is not an operator; += is
For a percentage you need to multiply by 100. ie
pct = 100. * carsAboveLimit / len(carSpeeds)
I would suggest writing it like
def get_int(prompt):
while True: # repeat until we get an integer
try:
return int(input(prompt))
except ValueError:
# that wasn't an integer! Try again.
pass
def get_speeds():
while True:
speed = get_int("Enter a car speed (or 0 to exit): ")
if speed == 0:
break
yield speed
def main():
# get list of car speeds
car_speeds = list(get_speeds())
# get number of speeders
limit = get_int("What's the speed limit? ")
num_speeders = sum(1 for speed in car_speeds if speed > limit)
# show % of speeders
pct = 100. * num_speeders / len(car_speeds)
print("{:0.1f} % of them are speeding!".format(pct))
main()
The problem you are facing is one a) casting of float to be able to have a fractional part, since int/int -> int and int/float -> float.
>>> 1/2
0
>>> 1/float(2)
0.5
and b) of proper formatting of the result to be displayed as a percentage value (assuming you want 2 decimal digits):
>>> '%0.2f%%' % (1/float(2))
'0.50%'
Reference to the 2 points mentioned above you can find here and here.
Your code would be complete as follows (including some minor details as other users have mentioned -- colon at if block, increment operator, etc). Note the for loop that was missing in your code but was mentioned:
numCars = int(input("Enter the number of cars: "))
carSpeeds = []
for i in range(numCars):
speed = int(input("Enter the car speed: "))
carSpeeds.append(speed)
carsAboveLimit = 0
speedLimit = int(input("Enter the speed limit: "))
for speed in carSpeeds:
if speed > speedLimit:
carsAboveLimit += 1
i += i
percent = int(carsAboveLimit)/float(len(carSpeeds))
print("The percentage of cars over the speed limit is %0.2f%%" % percent)
With output:
Enter the number of cars: 3
Enter the car speed: 1
Enter the car speed: 2
Enter the car speed: 3
Enter the speed limit: 2
The percentage of cars over the speed limit is 0.33%

Writing python code to calculate a Geometric progression

Im new to programming and python. I need help with coding a geometric progression thats supposed to calculate the progression 1,2,4,8,16... Heres what I have so far:
def work_calc (days_worked, n):
temp=int(1)
if days_worked<2:
print (1)
else:
while temp <= days_worked:
pay1 = (temp**2)
pay = int(0)
pay += pay1
temp +=1
print ('your pay for ',temp-1,'is', pay1)
main()
Right now it gives me this output: 1, 4, 9, 16, 25
i need : 1,2,4,8,16,32...
im writing code that basically should do this:
Example:
Enter a number: 5
your value 1 is: 1
your value 2 is : 2
your value 3 is : 4
your value 4 is : 8
your value 5 is : 16
your total is: 31
Thanks in advance for your help and guidance!
P.S: Im like a dumb blonde sometimes(mostly) when it comes to programming, so thanks for your patience..
As I said, looks like you need powers of 2:
def work_calc (days_worked, n):
for temp in range(days_worked):
print ('your pay for ', temp + 1, 'is', 2 ** temp)
if you want to print strings (not tuples as you're doing now):
def work_calc (days_worked):
for temp in range(days_worked):
print 'your pay for {} is {}'.format(temp + 1, 2 ** temp)
>>> work_calc(5)
your pay for 1 is 1
your pay for 2 is 2
your pay for 3 is 4
your pay for 4 is 8
your pay for 5 is 16
Just to note - your code is calculating squares of temp, not powers of 2 that's why is not working
I understand this is probably overkill for what you are looking to do and you've been given great advice in the other answers in how to solve your problem but to introduce some other features of python here are some other approaches:
List comprehension:
def work_calc(days):
powers_of_two = [2**x for x in range(days)]
for i, n in enumerate(powers_of_two):
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(sum(powers_of_two)))
This is compact and neat but would hold the whole list of 2^n in memory, for small n this is not a problem but for large could be expensive. Generator expressions are very similar to list comprehensions but defer calculation until iterated over.
def work_calc(days):
powers_of_two = (2**x for x in range(days))
total = 0
for i, n in enumerate(powers_of_two):
total += n
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(total))
Had to move the total to a rolling calculation and it still calculates 2**n each time, a generator function would avoid power calculation:
import itertools
def powers_of_two():
n = 1
while True:
yield n
n *= 2
def work_calc(days):
total = 0
for i, n in enumerate(itertools.islice(powers_of_two(), days)):
total += n
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(total))
As I said overkill, but hopefully introduces some of the other features of python.
Is this a homework question? (insufficient rep to comment)
In the sequence 1,2,4,8,16,32 each term is double the previous term.
So, you can keep a record of the previous term and double it to get the next one.
As others have mentioned, this is the same as as calculating 2^n (not, as I previously stated, n^2) , where n is the number of terms.
print ('your pay for 1 is' 1)
prevpay = 1
while temp <= days_worked:
pay1 = prevpay*2
pay = int(0)
pay += pay1
temp +=1
prevpay = pay1
print ('your pay for ',temp-1,'is', pay1)
That is all too complicated. Try always to keep things as simple as possible and especially, keep your code readable:
def main():
i = int(input("how many times should I double the value? "))
j = int(input("which value do you want to be doubled? "))
double_value(i,j)
def double_value(times,value):
for i in range(times):
i += 1
value = value + value
print(f"{i} --- {value:,}")
main()
Hope I could help.

Categories