在Python库SymPy中,我试图理解
我对下面的while循环感到困惑,因为它看起来毫无意义。如果我去掉
sympy.utilities.iterables
中的partitions()
函数:
它开头是这样的:
def partitions(n, m=None, k=None, size=False):
"""Generate all partitions of integer n (>= 0).
我对下面的while循环感到困惑,因为它看起来毫无意义。如果我去掉
while 1:
和break
应该不会有任何影响。但是,我认为开发SymPy的人知道自己在做什么,并不会犯非常简单的错误。所以这个while循环有一些我没有看到的意义吗?while 1:
# Let i be the smallest key larger than 1. Reuse one instance of i.
i = keys[-1]
newcount = ms[i] = ms[i] - 1
reuse += i
if newcount == 0:
del keys[-1], ms[i]
room += 1
# Break the remainder into pieces of size i-1.
i -= 1
q, r = divmod(reuse, i)
need = q + bool(r)
if need > room:
if not keys:
return
continue
ms[i] = q
keys.append(i)
if r:
ms[r] = 1
keys.append(r)
break
出于学习目的,我简化了整个函数,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
my_partitions(n)
不仅仅是对partitions(n, m, k, size)
的清理。它只是为相同的n提供相同的结果。 - Watchduck