Finding change for a number - python

I'm a beginner and I was given a project. What I have written down right now works for every number besides the one I need 83 where it says I don't need nickel when I do. I tried doing different operations but that messes the math up with the other numbers. If you could help that would be great.
total = int(input("Enter change [0...99]: "))
half = total // 50
quarter = total % 50 // 25
dimes = total % 25 // 10
nickels = total % 10 // 5
pennies = total % 5 // 1
print(half, "half (ves)")
print(quarter, "Quarter (s)")
print(dimes, "Dime (s)")
print(nickels, "Nickel (s)")
print(pennies, "penny (s)")

You should update total after each coin:
half = total // 50
total = total % 50
# ...
This is because not all the coins are dividers of all the preceding coins. E.g. removing 25 from an amount changes its divisibility by 10, so total % 10 is not the same amount as remainder_after_dimes (if you had an odd number of quarters).
This could be done in a single step, using divmod:
half, total = divmod(total, 50)
quarter, total = divmod(total, 25)
dimes, total = divmod(total, 10)
nickels, total = divmod(total, 5)
pennies, total = divmod(total, 1)

Related

I want to round off to the nearest half hour meaning that If I arrive at 11:15 and leave 11:50, car will still be charged for one half an hour not two

I want to round off to the nearest half hour meaning that If I arrive at 11:15 and leave 11:50, car will still be charged for one half an hour not two. I have tried for the last couple of hours to fix it but I cant seem to know what to do (I recently started learning programming)
import math
PARKING_COST = 1.75
TAX_RATE = 1.13
startHour = eval(input('Input the hour when you entered the parking lot(in 24h time please, no leading zeroes):'))
startMinute = input('Input the minute when you entered the parking lot: ')
endHour = eval(input('Input the hour when you exited the parking lot(in 24h time please, no leading zeroes): '))
endMinute = input('Input the hour when you exited the parking lot: ')
minutesPassed = (60*endHour + int(endMinute))-(60*startHour + int(startMinute))
k=1
if minutesPassed<=(15*k):
k+=1
halfHoursPassed=math.floor(float(minutesPassed)/30)
else:
halfHoursPassed=math.ceil(float(minutesPassed)/30)
subtotal = halfHoursPassed * 1.75
total = subtotal * 1.13
print('*******')
print('Parkinglot')
print('Your time in was',str(startHour)+':'+ startMinute)
print('Your time out was',str(endHour)+':'+ endMinute)
print('You spent','%.0f' %halfHoursPassed,'half hours at our garages')
print('Your subtotal was $' + '%.2f' %subtotal)
print('Your total was $' + '%.2f' %total)
print('Thank you for your stay')
print('*******')
So with full_halves = int(minutesPassed / 30) you can get the "full" 30 minute periods. Then using modulo operator % you get the remainer: remaining = minutesPassed % 30. Now, if this remainer is greater than 15, you should add another full half, otherwise you use the full_halves as is.
The modulo operator % gives back the remainder after floor division //. That is to say that 7 // 3 == 2, 7 % 3 == 1. Indeed these two are mutually defined such that (x // k) * k + (x % k) == x.
You should consider taking the modulo of your minutesPassed and 30 to see where the partial-half-hour lies, then comparing that with 15 to judge whether or not to round up or down.
halfHoursPassed = minutesPassed // 30
if minutesPassed % 30 >= 15:
halfHoursPassed += 1
You can somewhat simplify this by using the builtin divmod, which gives both // and % at once.
halfHoursPassed, partialHalfHour = divmod(minutesPassed, 30)
if partialHalfHour >= 15:
halfHoursPassed += 1

Python Prediction for organism population growth

The inputs would be:
The initial number of organisms
The rate of growth (a real number greater than 1)
The number of hours it takes to achieve this rate
A number of hours during which the population grows
I have:
Population = int(input("The initial number of organisms: " ))
RateOfGrowth = int(input("The rate of growth (a real number > 0): " ))
HrToAchieve = int(input("The number of hours it takes to achieve this rate: " ))
Input_Hrs = int(input("Enter the total hours of growth: " ))
NewGrowth = 0
Passes = Input_Hrs/HrToAchieve
while Passes > 0:
NewGrowth = (Population * RateOfGrowth)-Population
Population += NewGrowth
Passes -= 1
print("The total population is", Population )
New at loops and not sure how I'm missing a pass
partially working with input 10,2,2,6 providing correct answer of 80
But when using 100 organisms with growth rate of 5 over 2 hrs over 25 hrs total, I get 7000 NOT
24414062500 which would be proper.
You can do that in one line and Im assuming if the growth rate of x is there in y hours and there are less than y hours left, then there wont be any growth whatsoever.
import math
ORG = int(input("The initial number of organisms: " ))
GR = int(input("The rate of growth (a real number > 0): " ))
GR_Hr = int(input("The number of hours it takes to achieve this rate: " ))
PG_Hr = int(input("Enter the total hours of growth: " ))
Growth = ORG * int(math.pow(GR, PG_Hr//GR_Hr)) # or Growth = ORG * int(GR ** (PG_Hr // GR_Hr))
EDIT USING LOOPS
Growth_using_loops = ORG
loop_counter = PG_Hr//GR_Hr # double slash // returns a integer instead of float
for i in range(loop_counter):
Growth_using_loops = Growth_using_loops * GR
print(Growth)
print(Growth_using_loops)
Output :
The initial number of organisms: 100
The rate of growth (a real number > 0): 5
The number of hours it takes to achieve this rate: 2
Enter the total hours of growth: 25
24414062500
24414062500

Coin Change Problem (but with minimum number of coins)

So I'm new to coding and I got an assignment where I needed to make a program that would give change for amounts less than a dollar in quarters, dimes, nickels, and cents. However, the assignment wanted the program to print the minimum number of coins needed (for example, if I inputted 58 cents then the output should be "2 quarters, 1 nickel, and 3 pennies" instead of "2 quarters, 0 dimes, 1 nickel, and 3 pennies". Essentially, if there is none of a certain coin, then the program shouldn't print it). I've been stuck on figuring out how to make it so that the program doesn't print any coin that isn't necessary.
This is what I have as of now:
amount = int(input( "Enter amount (1-99): " ))
twentyfive = amount // 25
ten = amount % 25 // 10
five = amount % 25 % 10 // 5
one = amount % 25 % 10 % 5 //1
print(twentyfive, "quarters", ten, "dimes", five, "nickels", one, "pennies")
Build the message dynamically, including only coins with a nonzero count.
messages = []
if quarters:
messages.append(f"{quarters} quarters")
if dimes:
messages.append(f"{dimes} dimes")
if nickels:
messages.append(f"{nickels} nickels")
if pennies:
messages.append(f"{pennies} pennies")
# print out all message parts, joined together with commas
print(", ".join(messages))
You'll need a bit more logic if you want to display "and" before the last coin amount.
Or use re:
import re
amount = int(input("Enter amount (1-99): "))
twentyfive = amount // 25
ten = amount % 25 // 10
five = amount % 25 % 10 // 5
one = amount % 25 % 10 % 5 //1
s = f"{twentyfive}, quarters, {ten}, dimes, {five}, nickels, {one}, pennies"
print(re.sub('0, \w+, ', '', s))
Output:
Enter amount (1-99): 58
2, quarters, 1, nickels, 3, pennies
You're solving the problem of printing a list with these requirements:
more than three items should be separated by ', '
the final item should be preceded by and, if there's more than 1 item
Examples:
['1 dime', '2 quarters'] : '1 dime and 2 quarters'
['3 nickels'] : '3 nickels'
['1 dime', '2 quarters', '3 nickels'] : '1 dime, 2 quarters, and 3 nickels'
def nice_list(items):
return ', '.join(items[:-1] + [('and ' if len(items) > 1 else '') + items[-1]])
Another problem you're solving is that you want to print a number with a noun, with the noun followed by an 's' if the number is not 1. But, annoyingly, if the noun ends in 'y', you want to replace it with 'ies'
Examples:
'0 dimes'
'1 nickel'
'5 quarters'
'3 pennies'
def number_noun(number, noun):
if number == 1 or not noun:
result = noun
else:
result = noun + 's' if noun[-1] != 'y' else noun[:-1] + 'ies'
return f'{number} {result}'
But you also want to avoid printing anything coin you need 0 of.
So:
amount = int(input( "Enter amount (1-99): " ))
coins = [
(amount // 25, 'quarter'),
(amount % 25 // 10, 'dime'),
(amount % 25 % 10 // 5, 'nickel'),
(amount % 25 % 10 % 5 //1, 'penny')
]
print(nice_list([number_noun(c, name) for c, name in coins]))
If you, like myself, don't like that the numbers of coins are now in the same list as the names of the coins:
amount = int(input( "Enter amount (1-99): " ))
coins = [
amount // 25,
amount % 25 // 10,
amount % 25 % 10 // 5,
amount % 25 % 10 % 5 //1
]
name = ['quarter', 'dime', 'nickel', 'penny']
print(nice_list([number_noun(c, name) for c, name in zip(coins, names)]))
I think the other answerers have inferred stricter requirements than your assignment probably has. Your sample output has commas and the word "and", so they have written code to produce output in exactly that format. I think they have made this more complicated than it needs to be, using lists, loops, slicing, and regexes for what is meant to be a beginner-level problem.
Since you said "I'm new to coding and I got an assignment", it seems unlikely that your task specifically requires that you have to produce output in such a strict format - and if it did, this should be mentioned in the question. Based on your description of the assignment, here is what I think a beginner would be expected to write:
if twentyfive > 0:
print(twentyfive, 'quarters')
if ten > 0:
print(ten, 'dimes')
if five > 0:
print(five, 'nickels')
if one > 0:
print(one, 'pennies')

Calculate a total from numbers produced by a for loop (running total)

My assignment is to calculate how much money a person would get if his salary started at 1 cent per day and doubled every day.
days = int(input("How many days will you work for pennies a day?"))
total_amount = ((2 ** (days - 1)) / 100)
print("Days Worked | Amount Earned That Day")
for num in range(days):
total_amount = format((2 ** (num) / 100), ',.2f')
print(num + 1, "|", "$", total_amount)
If I enter 15 for days, I can see the salary on each day, but I need the total amount earned over the 15 days.
I need the total amount earned over the 15 days
As a standard for loop example you want summation over each iteration. To achieve this, you initialize variable (total_accumulated in this case) with 0 and then add to this variable each intermediate result from each iteration, after loop is complete you print out final accumulated result like so (minimal editing of your original code):
days = int(input("How many days will you work for pennies a day?"))
total_amount = ((2 ** (days - 1)) / 100)
total_accumulated = 0
print("Days Worked | Amount Earned That Day")
for num in range(days):
current_pay = (2 ** (num) / 100)
total_accumulated += current_pay
total_amount = format(current_pay, ',.2f')
print(num + 1, "|", "$", total_amount)
print("Total accumulated:", str(total_accumulated))
As noted in comment to your question by #NiVeR this can be calculated directly, and this answer is aimed only at example with loops since this looks like classic case of exercise.
Keep track of today salary and previous day salary. previous to calculate today salary and today salary to calculate total
init_sal = .01
total = 0
today_sal = 0
days = int(input("How many days will you work for pennies a day?"))
for x in range(1, days+1):
if x == 1:
today_sal = init_sal
prev_sal = today_sal
else:
today_sal = prev_sal * 2
prev_sal = today_sal
total += today_sal
print ('$', today_sal)
print (total)

Python function: Find Change from purchase amount [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back.
Would it be best to set up a dictionary?
Gee, you mean this isn't problem 2b in every programming course any more? Eh, probably not, they don't seem to teach people how to make change any more either. (Or maybe they do: is this a homework assignment?)
If you find someone over about 50 and have them make change for you, it works like this. Say you have a check for $3.52 and you hand the cashier a twnty. They'll make change by saying "three fifty-two" then
count back three pennies, saying "three, four, five" (3.55)
count back 2 nickels, (3.60, 3.65)
count back a dime (3.75)
a quarter (4 dollars)
a dollar bill (five dollars)
a $5 bill (ten dollars)
a $10 bill (twenty.)
That's at heart a recursive process: you count back the current denomination until the current amount plus the next denomination comes out even. Then move up to the next denomination.
You can, of course, do it iteratively, as above.
This is probably pretty fast - just a few operations per denomination:
def change(amount):
money = ()
for coin in [25,10,5,1]
num = amount/coin
money += (coin,) * num
amount -= coin * num
return money
Your best bet is to probably have a sorted dictionary of coin sizes, and then loop through them checking if your change is greater than the value, add that coin and subtract the value, otherwise move along to the next row in the dictionary.
Eg
Coins = [50, 25, 10, 5, 2, 1]
ChangeDue = 87
CoinsReturned = []
For I in coins:
While I >= ChangeDue:
CoinsReturned.add(I)
ChangeDue = ChangeDue - I
Forgive my lousy python syntax there. Hope that's enough to go on.
This problem could be solved pretty easy with integer partitions from number theory. I wrote a recursive function that takes a number and a list of partitions and returns the number of possible combinations that would make up the given number.
http://sandboxrichard.blogspot.com/2009/03/integer-partitions-and-wiki-smarts.html
It's not exactly what you want, but it could be easily modified to get your result.
The above soloution working.
amount=int(input("Please enter amount in pence"))
coins = [50, 25, 10, 5, 2, 1]
coinsReturned = []
for i in coins:
while amount >=i:
coinsReturned.append(i)
amount = amount - i
print(coinsReturned)
Alternatively a solution can reached by using the floor and mod functions.
amount = int(input( "Please enter amount in pence" ))
# math floor of 50
fifty = amount // 50
# mod of 50 and floor of 20
twenty = amount % 50 // 20
# mod of 50 and 20 and floor of 10
ten = amount % 50 % 20 // 10
# mod of 50 , 20 and 10 and floor of 5
five = amount % 50 % 20 % 10 // 5
# mod of 50 , 20 , 10 and 5 and floor of 2
two = amount % 50 % 20 % 10 % 5 // 2
# mod of 50 , 20 , 10 , 5 and 2 and floor of 1
one = amount % 50 % 20 % 10 % 5 % 2 //1
print("50p>>> " , fifty , " 20p>>> " , twenty , " 10p>>> " , ten , " 5p>>> " , five , " 2p>>> " , two , " 1p>>> " , one )
Or another solution
amount=int(input("Please enter the change to be given"))
endAmount=amount
coins=[50,25,10,5,2,1]
listOfCoins=["fifty" ,"twenty five", "ten", "five", "two" , "one"]
change = []
for coin in coins:
holdingAmount=amount
amount=amount//coin
change.append(amount)
amount=holdingAmount%coin
print("The minimum coinage to return from " ,endAmount, "p is as follows")
for i in range(len(coins)):
print("There's " , change[i] ,"....", listOfCoins[i] , "pence pieces in your change" )
I have an improve solution from above solutions
coins=[]
cost = float(input('Input the cost: '))
give = float(input('Tipe Amount given: '))
change = (give - cost)
change2 = change-int(change)
change2 = round(change2,2)*100
coin = [50,25,10,5,1]
for c in coin:
while change2>=c:
coins.append(c)
change2 = change2-c
half=coins.count(50)
qua = coins.count(25)
dime=coins.count(10)
ni=coins.count(5)
pen=coins.count(1)
dolars = int(change)
if half !=0 or qua != 0 or dime!=0 or ni!=0 or pen!=0:
print ('The change of', round(give,2), 'is:',change, 'like \n-dolas:',dolars,'\n-halfs:',half,'\n-quarters:',qua,'\n-dime:',dime,'\n-nickels:',ni,'\n-pennies:',pen)
else:
print ('The change from', round(give,2), 'is:',change,'and no coins')

Categories