【发布时间】:2019-12-13 19:54:58
【问题描述】:
我想知道是否有另一种方法来解决这个问题,而无需像我在这里所做的那样使用 3 个嵌套的 for 循环?我知道,如果要在足够大的列表上测试该方法,那么以这种方式嵌套循环很可能会导致很多问题。
问题来了:
from typing import List
def can_pay_with_three_coins(denoms: List[int], amount: int) -> bool:
"""Return True if and only if it is possible to form amount, which is a
number of cents, using exactly three coins, which can be of any of the
denominations in denoms.
>>> can_pay_with_three_coins([1, 5, 10, 25], 36)
True
>>> can_pay_with_three_coins([1, 5, 10, 25], 37)
False
"""
这是我的解决方案:
for i in range(len(denoms)):
one_coin = denoms[i]
for j in range(len(denoms)):
another_coin = denoms[j]
for k in range(len(denoms)):
last_coin = denoms[k]
if one_coin + another_coin + last_coin == amount:
return True
return False
我确信还有另一种方法可以解决这个问题,只是我真的想不出来。
感谢您的帮助!
【问题讨论】:
-
如果你已经测试过(1,5,10),下面的任何一个都不需要测试:(1,10,5),(5,1,10),(5 ,10,1)、(10,1,5) 或 (10,5,1)。
-
如果前两个硬币的总和已经超过金额,那么检查第三个硬币的任何内容都是没有意义的。
-
我完全忘记了这种可能性。谢谢!
标签: python performance