Any reason to use "while 1, do something, break" in Python?

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:
    # 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

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]:
        # 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
+4
source share
2 answers

, goto Python. while 1: - , continue - goto.

, , . , , while True:, while .

+7

, need > room && keys == True continue, while break. , (, ).

+1

Source: https://habr.com/ru/post/1624025/


All Articles