13
votes

In Python2 I could use

def subsets(mySet):
    return reduce(lambda z, x: z + [y + [x] for y in z], mySet, [[]])

to find all subsets of mySet. Python 3 has removed reduce.

What would be an equally concise rewrite of this for Python3?

2
reduce() is still there -- it was moved to functools. - Sven Marnach
@SvenMarnach: Ah, thanks. Is there a non-reduce() version? - Randomblue
Not quite a one-liner, but the itertools docs have a powerset implementation. - AdamKG
It's not written as a 1-liner, but could be munged into one: chain.from_iterable(combinations(list(iterable), r) for r in range(len(list(iterable))+1)) - Adam Parkin
@AdamParkin: Thanks. Where does chain come from? - Randomblue

2 Answers

14
votes

Here's a list of several possible implementations of the power set (the set of all subsets) algorithm in Python. Some are recursive, some are iterative, some of them don't use reduce. Plenty of options to choose from!

5
votes

The function reduce() can always be reaplaced by a for loop. Here's a Python implementation of reduce():

def reduce(function, iterable, start=None):
    iterator = iter(iterable)
    if start is None:
        start = next(iterator)
    for x in iterator:
        start = function(start, x)
    return start

(In contrast to Python's built-in version of reduce(), this version does not allow to pass in None as start parameter.)

Special-casing this code with the parameters you passed to reduce() gives

def subsets(my_set):
    result = [[]]
    for x in my_set:
        result = result + [y + [x] for y in result]
    return result