Generating subsets of a permutation in Python but not all permutations
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:
L = [1,2,3]
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)
itertools
[1,2,3]
[2,1,3]
[3,2,1]
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.
2 Answers
2
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))
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))
= 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.
itertools
https://docs.python.org/2/library/itertools.html
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It sounds like you want combinations, not permutations. Combinations don't count element order, permutations do.
– Carcigenicate
Aug 23 at 13:38