有什么理由在Python中使用“while1,do something,break”?

2024-04-27 04:41:03 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python库SymPy中,我试图理解^{}中的函数partitions()

开始是这样的:

^{1}$

我对下面的while循环感到困惑,因为它看起来毫无意义。如果我去掉while 1:和{}这应该没有什么区别。然而,我希望发展同情心的人知道他们在做什么,不会犯很简单的错误。所以这有什么意义,我看不出来吗?在

^{pr2}$

为了便于学习,我简化了整个函数,my_partitions(n)给出了与partitions(n)相同的结果。在

def my_partitions(n):
    ms = {n: 1}
    keys = [n]
    yield ms

    while keys != [1]:
        # Reuse any 1's.
        if keys[-1] == 1:
            del keys[-1]
            reuse = ms.pop(1)
        else:
            reuse = 0

        # Let i be the smallest key larger than 1.  Reuse one instance of i.
        i = keys[-1]
        ms[i] -= 1
        reuse += i
        if ms[i] == 0:
            del keys[-1], ms[i]

        # Break the remainder into pieces of size i-1.
        i -= 1
        q, r = divmod(reuse, i)
        ms[i] = q
        keys.append(i)
        if r:
            ms[r] = 1
            keys.append(r)

        yield ms

Tags: ofthe函数ifmykeysmssympy
2条回答

这是一个将goto引入Python的肮脏的黑客行为。while 1:行是标签,continue语句是goto。在

如果可以避免的话,请不要写那样的代码。如果必须这样做,至少要使其while True:,因为{}的参数通常是一个布尔值。在

need > room && keys == True的情况下,转到continue,它重新启动while循环,而不是{}。这看起来很难看,但在这种情况下是必要的(当然应该有其他选择)。在

相关问题 更多 >