In the SymPy Python library, I'm trying to understand a function partitions()in sympy.utilities.iterables:
It starts as follows:
def partitions(n, m=None, k=None, size=False):
"""Generate all partitions of integer n (>= 0).
I got confused in the next cycle because it looks pointless. If I remove while 1:and break, it does not matter. However, I expect that people who develop SymPy know what they are doing and are not making very simple mistakes. Does it make sense that I do not see?
while 1:
i = keys[-1]
newcount = ms[i] = ms[i] - 1
reuse += i
if newcount == 0:
del keys[-1], ms[i]
room += 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
For training purposes, I simplified the entire function, and my_partitions(n)gives the same results as partitions(n).
def my_partitions(n):
ms = {n: 1}
keys = [n]
yield ms
while keys != [1]:
if keys[-1] == 1:
del keys[-1]
reuse = ms.pop(1)
else:
reuse = 0
i = keys[-1]
ms[i] -= 1
reuse += i
if ms[i] == 0:
del keys[-1], ms[i]
i -= 1
q, r = divmod(reuse, i)
ms[i] = q
keys.append(i)
if r:
ms[r] = 1
keys.append(r)
yield ms
source
share