Reputation: 468
I have the following code I am trying to understand as I am new to Python. I understand that the code computes the powerset but the line subsetlist = [ subset + [item] for subset in result]
is a little hard to understand. How can I break this compounded line to simple for loop for understanding.
def powerset(x):
result = [[]]
for item in x:
subsetlist = [ subset + [item] for subset in result]
result.extend(subsetlist)
return result
This is what I have tried to make it simpler but it does not seem to work. My IDLE just gets stuck and does not print anything.
def powerset(x):
result = [[]]
for item in x:
for subset in result:
result.append(item)
print(result)
Upvotes: 1
Views: 861
Reputation: 226256
You were very close. Just move the empty list creation inside the second loop.
def powerset(x):
result = [[]]
for item in x:
subsetlist = []
for subset in result:
subsetlist.append(subset + [item])
result.extend(subsetlist)
return result
>>> powerset('abc')
[[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
Upvotes: 2