944,047 Members | Top Members by Rank

Ad:
  • Python Code Snippet
  • Views: 5308
  • Python RSS
0

Power Set List from Input List

by on May 14th, 2008
Returns the power set of the elements of a given list (even if some of those elements are also lists).
Python Code Snippet (Toggle Plain Text)
  1. # From another DaniWeb snippet
  2. def int2bin(n, count=24):
  3. """returns the binary of integer n, using count number of digits"""
  4. return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
  5.  
  6. # PowerSet of a List
  7. def PowerSet(orignal_list):
  8. list_size = len(orignal_list)
  9. num_sets = 2**list_size
  10. powerset = []
  11. # Don't include empty set
  12. for i in range(num_sets)[1:]:
  13. subset = []
  14. binary_digits = list(int2bin(i,list_size))
  15. list_indices = range(list_size)
  16. for (bit,index) in zip(binary_digits,list_indices):
  17. if bit == '1':
  18. subset.append(orignal_list[index])
  19. powerset.append(subset)
  20. return powerset
  21.  
  22. if __name__ == "__main__":
  23. print PowerSet([1,2,3])
Message:
Previous Thread in Python Forum Timeline: strange dictionary definition/object instance problem
Next Thread in Python Forum Timeline: To stop a loop





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC