Home > Enterprise >  How can I return a tuple with unique elements given a recursive function
How can I return a tuple with unique elements given a recursive function

Time:10-05

I have looked around in other posts and haven't been able to come to a solution for this. I have a function that needs to be recursively called using an itertools expression in order to return a tuple that has unique elements with it's order preserved.

for instance:

def function(list):
    return list and (list[0],)   function(some_itertools_expression)

given example: function([1, 7, 7, 9, 0, 1]) should return (1, 7, 9, 0)

I've tried using:

return list and (list[0],)   function(tuple([itertools.groupby(list)][:len(list)]))

but I end up running into RecursionError: maximum recursion depth exceeded. How can I solve this without getting the max recursion depth error?

CodePudding user response:

You can do this fairly easily, without needing recursion, by making a tuple via dictionary keys. The dict must have unique keys, and will preserve the order of the original input sequence.

>>> data = [1, 7, 7, 9, 0, 1]
>>> (*{}.fromkeys(data),)
(1, 7, 9, 0)

CodePudding user response:

If you must use a function from itertools in a recursive call, I would grab the first item of the sequence in each recursion and use itertools.filterfalse to filter items equal to the first from the sequence returned by a recursive call with the rest of the items:

from itertools import filterfalse

def unique(lst):
    if not lst:
        return ()
    first, *rest = lst
    return first, *filterfalse(lambda i: i == first, unique(rest))

print(unique([1, 7, 7, 9, 0, 1]))

This outputs:

(1, 7, 9, 0)

Demo: https://replit.com/@blhsing/WelloffPlainAutomaticparallelization

  • Related