Here is how I answered the question below. How would I solve this question better?
**
Define a procedure, stamps, which takes as its input a positive integer in pence and returns the number of 5p, 2p and 1p stamps (p is pence) required to make up that value. The return value should be a tuple of three numbers(that is, your return statement should be followed by the number of 5p, the number of 2p, and the number of 1p stamps). Your answer should use as few total stamps as possible by first using as many 5p stamps as possible, then 2 pence stamps and finally 1p stamps as needed to make up the total. (No fair for USians to just say use a "Forever" stamp and be done with it!)
**
Here is my solution
def stamps(i):
# Your code here
five = 0
two = 0
one = 0
while i > 0:
if i == 0:
break
if i >= 5:
five = five + 1
i = i - 5
if i == 0:
break
if i < 5 or i == 2:
two = two + 1
i = i - 2
if i == 0:
break
if i < 2 or i == 1:
one = one + 1
i = i - 1
return five,two,one
Here are the tests in the exercise
print stamps(8)
#>>> (1, 1, 1) # one 5p stamp, one 2p stamp and one 1p stamp
print stamps(5)
#>>> (1, 0, 0) # one 5p stamp, no 2p stamps and no 1p stamps
print stamps(29)
#>>> (5, 2, 0) # five 5p stamps, two 2p stamps and no 1p stamps
print stamps(0)
#>>> (0, 0, 0) # no 5p stamps, no 2p stamps and no 1p stamps
I would use modulo and remainder operations:
def modulo_and_remainder(a, b):
return a//b, a %b
def stamps(a):
five, rem = modulo_and_remainder(a, 5)
two, one = modulo_and_remainder(rem, 2)
return five, two, one
Alternatively (didn't even know this) you can use builtin divmod:
def stamps(a):
five, rem = divmod(a, 5)
two, one = divmod(rem, 2)
return five, two, one