在Python库SymPy中,我试图理解^{partitions()
:
开始是这样的:
^{1}$我对下面的while循环感到困惑,因为它看起来毫无意义。如果我去掉while 1:
和{
为了便于学习,我简化了整个函数,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
这是一个将goto引入Python的肮脏的黑客行为。
while 1:
行是标签,continue
语句是goto。在如果可以避免的话,请不要写那样的代码。如果必须这样做,至少要使其}的参数通常是一个布尔值。在
while True:
,因为{在}。这看起来很难看,但在这种情况下是必要的(当然应该有其他选择)。在
need > room && keys == True
的情况下,转到continue
,它重新启动while
循环,而不是{相关问题 更多 >
编程相关推荐