On Fri, Jan 8, 2021 at 11:31 AM Greg Ewing <greg.ew...@canterbury.ac.nz> wrote:
>
> Another way to approach this problem is using recursion, e.g.
>
> def find_combinations(items, n, comb, result):
>    if n == 0:
>      result.append(comb)
>    else:
>      for item in items:
>        find_combinations(items, n - 1, comb + [item], result)
>
> words = []
> find_combinations(['a', 'b', 'c'], 3, [], words)
> print(words)
>

True, but I'd much rather write it as a generator:

def permute(items, n):
    if not n:
        yield ""
        return
    # Optional performance enhancement:
    if n == 1: return (yield from items)
    for item in items:
        for rest in permute(items, n - 1):
            yield item + rest

words = list(permute("abc", 3))

I'm not sure how performance would go, but this is a lot cleaner.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to