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.





It sounds like you want combinations, not permutations. Combinations don't count element order, permutations do.
– Carcigenicate
Aug 23 at 13:38





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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ