[Python] Permutations, iterator, recursion and double loop

Discussão em 'Python' iniciado por Stack, Abril 22, 2025.

  1. Stack

    Stack Membro Participativo

    Here is a function that iterates over permutations of letters in a string:

    def permutations(items):
    for x in _permutations_rec('', items, len(items)):
    yield x

    def _permutations_rec(current, items, n):
    if len(current) == n:
    yield current
    else:
    for item, other_items in pick_item(items):
    for next_ in _permutations_rec(current+item, other_items, n):
    yield next_

    def pick_item(items):
    for i, item in enumerate(items):
    yield item, items[:i] + items[i+1:]

    # print permutations
    for x in permutations('abc'):
    print x


    In _permutations_rec in else part, I have two loops. In the first one I pick the next item that I append to the current string. The second loop iterates the next partial results and yields them. So, the second for is only to handle the iterator for the recursive call and "bubble-up" its results. I have found this pattern frequently when yielding results from recursive calls, e.g. when working with backtracking.

    Question:

    Is there an idiomatic, elegant way to use only one loop there, instead of two? Although I know there is nothing wrong there with those two loops, maybe there is some iterator kung-fu that would allow me to use only one (the simpler, the better).

    Edit:

    • I know itertools.permutations, my permutations is just a toy example

    Continue reading...

Compartilhe esta Página