Advertisement
Guest User

Untitled

a guest
May 27th, 2015
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. def power_set(set):
  2. """
  3. Given a set (list with no duplicates), returns a list of all the subsets.
  4. """
  5. size = len(set)
  6. # start with empty set
  7. result = [[]]
  8. for i in range(size):
  9. pivot = [set[i]]
  10. # generate all possible subsets with each individual element
  11. # using helper recursive function
  12. gen_subsets(result, pivot, set[i+1:])
  13. return result
  14.  
  15. def gen_subsets(result, base, remainder):
  16. """
  17. Given base set and remainder set, generates and appends to result all possible
  18. subsets (including base) containing base and any of the elements in remainder.
  19. """
  20. # Have to append a copy of base, otherwise black magic will happen.
  21. result.append(base[:])
  22. # If remainder set is empty, no more subsets. Return.
  23. if len(remainder) == 0:
  24. return
  25.  
  26. for i in range(len(remainder)):
  27. # recursive backtracking: add an element from remainder to base, generate subsets
  28. # and afterwards discard that element
  29. base.append(remainder[i])
  30. gen_subsets(result, base, remainder[i+1:])
  31. base.pop()
  32.  
  33. return
  34.  
  35. hello = [1,2,3]
  36. print(power_set(hello))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement