A set of 3 items has 8 subsets, including the empty set.
"""
List the subsets of a set.
A Python set can hold only hashable objects, but a Python set is not hashable.
Therefore a Python set cannot contain a Python set.
The subsets function is therefore forced to return a list instead of set.
A Python list can contain a list.
"""
import sys
def subsets(s):
"Return a list of the subsets of s."
assert type(s) == list
if not s: #if s is empty,
return [set()] #The empty set is the only subset of the empty set.
powerSet = []
for subset in subsets(s[1:]):
powerSet.append(subset)
powerSet.append(subset | {s[0]}) #union of two sets
return powerSet
s = [0, 1, 2] #or try s = [0, 1, 2, 3]
for i, subset in enumerate(subsets(s), start = 1):
print(i, subset)
sys.exit(0)
1 set()
2 {0}
3 {1}
4 {0, 1}
5 {2}
6 {0, 2}
7 {1, 2}
8 {0, 1, 2}
subsets
returns a
list.
Create this
list
with a
list
comprehension.
extras = [set(), {s[0]}]
return [subset | extra for subset in subsets(s[1:]) for extra in extras]
set
is not
hashable.
s = set() try: h = hash(s) except TypeError as error: print("A set is not hashable:", error) else: print("A set is hashable.")
A set is not hashable: unhashable type: 'set'