首页 > 解决方案 > 改变问题python,如何创建边界?

问题描述

我对更改算法有疑问。我的代码如下所示:

def algorithm():
denominations = [5, 2, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01]
numbers_of_denominations = [2, 1, 10, 10, 20, 10, 20, 50]
change = 9.39
i = 0
while(change > 0):
    if(change >= denominations[i]):
        number_of_coins = int((change / denominations[i]))
        change = round(change - denominations[i] * number_of_coins, 2)

        print(denominations[i], "x", number_of_coins)
    i += 1

它确实给了我正确的答案,但问题是如果我的硬币数量有限怎么办?我不知道如何实现硬币的界限。例如,如果我有:

如何检查硬币数量是否可用?当前输出为:

5$ x 1
2$ x 2
0.2$ x 1
0.1$ x 1
0.05$ x 1
0.02$ x 2

这是不正确的,因为我只有一枚 2 美元的硬币。我被困住了。

标签: pythonalgorithmcurrency

解决方案


只要确保您使用的数量不超过您拥有的数量:

number_of_coins = min(numbers_of_denominations[i], int((change / denominations[i])))

这将为您min(1, 2)提供 2 美元的硬币,这只允许您使用拥有的硬币:

5 x 1
2 x 1
0.5 x 4
0.2 x 1
0.1 x 1
0.05 x 1
0.02 x 2

请注意,如果您没有足够的硬币来支付全部金额,则可能会导致超出范围的错误而无需进一步更改:

denominations = [5, 2, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01]
numbers_of_denominations = [2, 1, 10, 10, 20, 10, 20, 50]
change = 100
i = 0
while(change > 0):
    # Check if we've run out of money.

    if i >= len(denominations):
        print("No change left, need", change)
        break;

    if(change >= denominations[i]):
        number_of_coins = min(numbers_of_denominations[i], int((change / denominations[i])))
        change = round(change - denominations[i] * number_of_coins, 2)

        print(denominations[i], "x", number_of_coins)
    i += 1

由此可见:

5 x 2
2 x 1
0.5 x 10
0.2 x 10
0.1 x 20
0.05 x 10
0.02 x 20
0.01 x 50
No change left, need 77.6

推荐阅读