贪心算法Python - 代码命中无限循环

时间:2017-12-21 02:51:41

标签: python python-3.x algorithm infinite-loop greedy

我正在尝试在python 3中编写一个贪心算法。

前提是将用户所欠的更改作为输入,并尽可能少地给他们提供硬币。

可用硬币是:宿舍(0.25);硬币(0.1);镍(0.05);和便士(0.01)。

我的代码目前无限循环,我不知道自己做错了什么。

任何人都可以通过以下代码查看我的错误吗?

代码:

validacion = False
pennies = 0.01
nickels = 0.05
dimes = 0.1
quarters = 0.25
coinCounter = 0
penniesCounter = 0
nickelsCounter = 0
dimesCounters = 0
quartersCounter = 0 
cambio = False

while validacion is False:
    changeOwed = float(input("Change owed: "))
    if changeOwed > 0:
        validacion = True
    else:
        validacion = False
while cambio is False:
    if changeOwed > dimes and changeOwed <= quarters:
        coinCounter += 1
        quartersCounter += 1
        changeOwed -= quarters
        if changeOwed == 0.0:
            cambio = True
    elif changeOwed > nickels and changeOwed <= dimes:
        coinCounter += 1
        nickelsCounter += 1
        changeOwed -= nickels
        if changeOwed == 0.0:
            cambio = True
    elif changeOwed > pennies and changeOwed <= nickels:
        coinCounter += 1
        dimesCounters += 1
        changeOwed -= dimes
        if changeOwed == 0.0:
            cambio = True
    else:
        coinCounter += 1
        penniesCounter += 1
        changeOwed -= pennies
        if changeOwed == 0.0:
            cambio = True

print(coinCounter)

2 个答案:

答案 0 :(得分:0)

按照苛刻的ossifrage的建议,将你的作业改为:

BottomNavigationView

等等。然后使用整数美分测试您的代码,而不是IEEE-754二进制FP美元。

答案 1 :(得分:0)

让我们说你欠变0.46。所以你应该给: 1季度,2角钱和1美分:

>>> 0.46 - 0.25 - 0.1 - 0.1 -0.01
8.673617379884035e-18

正如你所看到的,它不是0.计算机以二进制形式处理,并非所有小数部分都能很好地转换为二进制。 简短的解决方案是将所有乘以100并处理整数:

>>> 46 - 25 - 10 - 10 -1
0

对于输入,你可以像这样乘以:

changeOwed = int(round(changeOwed * 100)) # 0.58*100 == 57.99999999

下一个问题是如果你的欠款少于四分之一,你可以给出四分之一的条件。它应该是:

if changeOwed >= quarters:
    # the quarter process
elif changeOwed >= dimes:
    # the dime process
#etc...

而不是做while cambio == False,这样做更有意义:

while changeOwed >= pennies: # the smallest coin you can give out
祝你好运!