Python - 两个迭代循环没有吐出所有正确的答案

时间:2012-01-09 08:08:52

标签: python loops iteration

有谁能告诉我这段代码有什么问题。它应该列出一些块的组合(6,9,20件),用于许多掘金。但是,有些解决方案尚未计算出来。

def boxes_nuggets(nuggets):

    if nuggets < 6: print "there are no sizes for less than 6 nuggets"
    else:
        for numSmall in range(0, nuggets/6+1):
            for numMed in range(0, nuggets/9+1):
                numLarge = (nuggets - 6 * numSmall - 9 * numMed)/20
                if nuggets == numLarge * 20 + numMed * 9 + numSmall * 6:
                    print numLarge, "large boxes", numMed, "medium boxes", numSmall, "small boxes"

                elif numLarge < 0: return None

2 个答案:

答案 0 :(得分:2)

我想你想把你的代码更改为:

if numLarge < 0:
    continue
if nuggets == numLarge * 20 + numMed * 9 + numSmall * 6:
    print ...

因此,删除elif numLarge < 0: return None并在打印前添加负数numLarge检查。

你遇到的问题是第一次numLarge变为负数,你返回,这会阻止其他可能的答案被发现。

def boxes_nuggets(nuggets):
    if nuggets < 6: print "there are no sizes for less than 6 nuggets"
    else:
        for numSmall in range(nuggets/6+1):
            for numMed in range(nuggets/9+1):
                numLarge = (nuggets - 6 * numSmall - 9 * numMed)/20
                if numLarge < 0: continue
                if nuggets == numLarge * 20 + numMed * 9 + numSmall * 6:
                    print numLarge, "large boxes", numMed, "medium boxes", numSmall, "small boxes"

答案 1 :(得分:0)

很好地利用嵌套循环来计算可能的组合。只需使用continue语句替换return语句即可删除错误。休息看起来很好。