Implementing Powerset in Python
To implement the powerset algorithm in Python, we can use a recursive approach or an iterative approach. Here's an example of each:
Recursive Approach
def powerset(s):
"""
Returns the powerset of a given set s.
"""
if not s:
return [set()]
all_but_last = powerset(s[:-1])
last = s[-1]
return all_but_last + [x | {last} for x in all_but_last]
This function takes a set s
as input and returns its powerset. The function works by recursively generating the powerset of all but the last element, and then adding the last element to each of those subsets.
Here's an example usage:
>>> powerset({1, 2, 3})
[set(), {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]
Iterative Approach
def powerset(s):
"""
Returns the powerset of a given set s.
"""
powerset = [set()]
for elem in s:
powerset += [subset | {elem} for subset in powerset]
return powerset
This function also takes a set s
as input and returns its powerset. The function works by starting with the empty set, and then iteratively adding each element of the original set to the existing subsets.
Here's an example usage:
>>> powerset({1, 2, 3})
[set(), {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]
Both of these approaches have a time complexity of O(2^n), where n is the number of elements in the original set, as the powerset of a set with n elements contains 2^n elements.