Search code examples
pythonrecursionpermutationbacktracking

Recursive permutation without loops or itertools


Searched the entire web for a solution, couldn't find anything.
Need some help figuring out the algorithm, getting all the permutations with repetitions.
I'm not allowed to use loops or any other helper libraries.

def func(num):
    # The solution 

The num, represents the number of each node length.

For example, if num=1, the solution would be ['a', 'b', 'c']
or if num=2, then ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'], etc

Thank you


Solution

  • You can use a recursive generator function:

    vals = ['a', 'b', 'c']
    def combos(d, n, c = ''):
       if len(c) == n:
           yield c
       else:
           def _range(x=0):
              if x < len(d):
                  yield from combos(d, n, c=c+d[x])
                  yield from _range(x+1)
           yield from _range()
    
    print([*combos(vals, 2)])
    

    Output:

    ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']