简体   繁体   中英

Generating subsets of a permutation in Python but not all permutations

I have a list L = [1,2,3] and I want to calculate the product of all combinations, but only once -- that is:

null # that is, no elements of the list are multiplied
1
2
3
1 * 2
1 * 3
2 * 3
1 * 2 * 3

I've seen a number of posts talking about using itertools , permutations and combinations, but these return results including [1,2,3] , [2,1,3] , [3,2,1] , etc, which is not what I'm after. (I'm using Python 3 if that is useful to know)

NB Very aware that this could be failure of my search skills, and I just don't know the precise term that I'm looking for.

What you want are all subsets. It turns out itertools recipes offer a neat way to generate the powerset of an iterable.

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

Example

from functools import reduce
from operator import mul

for values in powerset([1, 2, 3]):
    print(' * '.join([str(x) for x in values]),
          '=',
          reduce(mul, values, 1))

Output

 = 1
1 = 1
2 = 2
3 = 3
1 * 2 = 2
1 * 3 = 3
2 * 3 = 6
1 * 2 * 3 = 6

You want the powerset of your set. itertools has an example of how to find it.

https://docs.python.org/2/library/itertools.html

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