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')
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 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
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')
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.
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)
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.