简体   繁体   中英

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

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?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM