python - 改变问题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 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
如何检查硬币数量是否可用?当前输出为:
5$ x 1
2$ x 2
0.2$ x 1
0.1$ x 1
0.05$ x 1
0.02$ x 2
这是不正确的,因为我只有一枚 2 美元的硬币。我被困住了。
解决方案
只要确保您使用的数量不超过您拥有的数量:
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
推荐阅读
- file - 使用自定义数据类型创建 txt 文件
- vim - Vim delete word 有时会进入插入模式?
- sql-server - SQL Server 中的等效分区交换
- python - FFT:与示例的边界不同
- php - PHP 错误:当一切似乎都正确时,调用资源上的成员函数 query()
- python-3.x - 请求令牌时返回错误的范围
- python-3.x - 无法分配给 ErrorExpression
- elasticsearch - 具有动态最大值的 Kibana 仪表
- bots - 如何使 Gushup Web 小部件全屏并默认打开
- node.js - 在机器启动时使用 grunt 启动节点 js 应用程序