![](/img/trans.png)
[英]Make a comparison and print out what is not in the list, how can I do that?
[英]How can I make the output print out a list of numbers?
所以我想要做的是找到等於數字v: int
所需的 1 美元、2 美元、5 美元和 10 美元鈔票的總數v: int
,我有點卡在如何做到這一點上......這是到目前為止我的代碼..
def coinChange(v: int):
while x == 1 and x == 2 and x == 5 and x == 10:
if x + x + x + x == v:
return x
就像它肯定是錯誤的,所以我在這里做錯了什么,我應該怎么做才能解決它? 順便說一句,輸出應該是一個列表,所以就像......如果coinChange(38)
是輸入,輸出應該是[10,10,10,5,2,1]
什么是正確的代碼來確保我得到正確的輸出?
嘗試改用此代碼。
def change(amount):
money = ()
for coin in [10,5,2,1]:
num = amount/coin
money += (coin,) * num
amount -= coin * num
return money
您可以使用整數除法 ( //
) 和模數 ( %
) 運算來確定所需的每種面額的數量。
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
可以使用循環減少代碼:
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
兩種實現的結果將是相同的:
coinChange(38) # [10, 10, 10, 5, 2, 1]
最簡單的邏輯,你可以理解它確保從更大的開始,比如先檢查 10,然后是 5,然后是 2,然后是 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.