Reputation: 13
I am trying to create a function that returns a powerset (all subsets of a given tuple of numbers) in the form of a tuple of tuples.
I have followed code that I have found previously, but this returns the output as a list of lists rather than a tuple of tuples.
def subs(S):
if S == []:
return [[]]
x = subs(S[1:])
return x + [[S[0]] + y for y in x]
This correctly returns: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
for an input of subs([1,2,3])
However I am looking for the function to input a tuple and return a tuple of tuples, such that the output would be:
>>> print (subs((1,2,3))
((), (3), (2), (2, 3), (1), (1, 3), (1, 2), (1, 2, 3))
Any help would be appreciated, thanks.
Upvotes: 0
Views: 293
Reputation: 13069
The function for lists can be converted to use tuples instead. There is no direct equivalent of a list comprehension because the object needs to be mutable during the loop, but the result can be converted using tuple()
. Care is needed with the syntax for 1-element tuples, so some extra commas have to be inserted in a couple of places.
def subs(S):
if S == ():
return ((),)
x = subs(S[1:])
return x + tuple([(S[0],) + y for y in x])
Upvotes: 0
Reputation: 11893
mashing tuples together or making new tuples from old ones is a bit tricky because they are immutable. Here is a hint that may put you in the right direction, along with the tip about indexing in the other solution. You can use the "scatter" operator to unpack an existing tuple into pieces when making a new one as such:
In [12]: c = ((2,3),(4,),(99,0,8))
In [13]: d = (*c, (7,6,5))
In [14]: d
Out[14]: ((2, 3), (4,), (99, 0, 8), (7, 6, 5))
Upvotes: 0
Reputation: 5037
Here you go:
pip install more-itertools
from more_itertools import powerset
print(tuple([x for x in powerset( (1, 2, 3) )]))
Output:
((), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3))
Upvotes: 1