Guest User

Untitled

a guest
Aug 16th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. Getting the subsets of a set in Python
  2. def subsets(s):
  3. """Return a list of the subsets of s.
  4.  
  5. >>> subsets({True, False})
  6. [{False, True}, {False}, {True}, set()]
  7. >>> counts = {x for x in range(10)} # A set comprehension
  8. >>> subs = subsets(counts)
  9. >>> len(subs)
  10. 1024
  11. >>> counts in subs
  12. True
  13. >>> len(counts)
  14. 10
  15. """
  16. assert type(s) == set, str(s) + ' is not a set.'
  17. if not s:
  18. return [set()]
  19. element = s.pop()
  20. rest = subsets(s)
  21. s.add(element)
  22.  
  23. from itertools import chain, combinations
  24.  
  25. def powerset(iterable):
  26. "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
  27. s = list(iterable)
  28. return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
  29.  
  30. def subsets(s):
  31. return map(set, powerset(s))
  32.  
  33. >>> from itertools import combinations
  34. >>> s=set(range(10))
  35. >>> subs = [set(j) for i in range(len(s)) for j in combinations(s, i+1)]
  36. >>> len(subs)
  37. 1023
  38.  
  39. def powerset(elements):
  40. if len(elements) > 0:
  41. head = elements[0]
  42. for tail in powerset(elements[1:]):
  43. yield [head] + tail
  44. yield tail
  45. else:
  46. yield []
  47.  
  48. >>> s=set(range(10))
  49. >>> L=list(s)
  50. >>> subs = [{L[j] for j in range(len(L)) if 1<<j&i} for i in range(1,1<<len(L))]
  51. >>> s in subs
  52. True
  53. >>> set() in subs
  54. False
  55.  
  56. >>> from itertools import combinations
  57. >>> s=set([1,2,3])
  58. >>> sum(map(lambda r: list(combinations(s, r)), range(1, len(s)+1)), [])
  59. [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Add Comment
Please, Sign In to add comment