So what I'm trying to do is find the total number of 1 dollar, 2 dollar, 5 dollar and 10 dollar bills needed to equal a number v: int
and i'm kinda stuck on how to do it...
Here is my code so far..
def coinChange(v: int):
while x == 1 and x == 2 and x == 5 and x == 10:
if x x x x == v:
return x
Like its definitely wrong, so what am I doing wrong here and what should I do to fix it? Btw, the output should be a list, so like... if coinChange(38)
is the input, the output should be [10,10,10,5,2,1]
What is the right code to make sure I get the right output?
CodePudding user response:
Try using this code instead.
def change(amount):
money = ()
for coin in [10,5,2,1]:
num = amount/coin
money = (coin,) * num
amount -= coin * num
return money
CodePudding user response:
Easiest logic and you can understand it make sure to start with greater like check 10 first then 5 and then 2 and then 1
def coinChange(x):
coins = []
while x != 0:
if x >= 10:
x = x - 10
coins.append(10)
elif x >= 5:
x = x - 5
coins.append(5)
elif x >= 2:
x = x - 2
coins.append(2)
elif x >= 1:
x = x - 1
coins.append(1)
print(coins)
coinChange(38)
CodePudding user response:
You can use integer division (//
) and modulus (%
) operations to determine the number of each denomination required.
def coinChange(v: int):
tens = v // 10
remainder = v % 10
fives = remainder // 5
remainder = remainder % 5
twos = remainder // 2
ones = remainder % 2
coins = [10 for n in range(tens)]
coins = [5 for n in range(fives)]
coins = [2 for n in range(twos)]
coins = [1 for n in range(ones)]
return coins
The code can be reduced using a loop:
def coinChange(v: int):
coins = [10, 5, 2, 1]
change = []
for c in coins:
change = [c for n in range(v // c)]
v = v % c
return change
The result for both implementations will be the same:
coinChange(38) # [10, 10, 10, 5, 2, 1]