0

I have a recursive code to compute unique permutations. However, this gives me a segmentation fault (due to an exceeded stack limit). How do I convert it into an iterative code. I have followed online tutorials on converting recursive code to iterative, but my iterative code doesn't work.

class unique_element:
    def __init__(self,value,occurrences):
        self.value = value
        self.occurrences = occurrences

def perm_unique(elements):
    eset=set(elements)
    listunique = [unique_element(i,elements.count(i)) for i in eset]
    u=len(elements)
    return perm_unique_helper(listunique,[0]*u,u-1)

def perm_unique_helper(listunique,result_list,d):
    if d < 0:
        yield list(result_list)
    else:
        for i in listunique:
            if i.occurrences > 0:
                result_list[d]=i.value
                i.occurrences-=1
                for g in  perm_unique_helper(listunique,result_list,d-1):
                    print g
                    yield g
                i.occurrences += 1
  • 2
    Can you add a usage example? And why not use something like `set(itertools.permutations(elements))`? – Graipher Mar 21 '18 at 13:04
  • How about `multiset_permutations` from `sympy`. Check out [this answer](https://stackoverflow.com/a/40289807/4408538) for more info. – Joseph Wood Mar 21 '18 at 22:34

0 Answers0