Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def power_set(set):
- """
- Given a set (list with no duplicates), returns a list of all the subsets.
- """
- size = len(set)
- # start with empty set
- result = [[]]
- for i in range(size):
- pivot = [set[i]]
- # generate all possible subsets with each individual element
- # using helper recursive function
- gen_subsets(result, pivot, set[i+1:])
- return result
- def gen_subsets(result, base, remainder):
- """
- Given base set and remainder set, generates and appends to result all possible
- subsets (including base) containing base and any of the elements in remainder.
- """
- # Have to append a copy of base, otherwise black magic will happen.
- result.append(base[:])
- # If remainder set is empty, no more subsets. Return.
- if len(remainder) == 0:
- return
- for i in range(len(remainder)):
- # recursive backtracking: add an element from remainder to base, generate subsets
- # and afterwards discard that element
- base.append(remainder[i])
- gen_subsets(result, base, remainder[i+1:])
- base.pop()
- return
- hello = [1,2,3]
- print(power_set(hello))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement