Advertisement
Guest User

Untitled

a guest
Apr 30th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4.  
  5. def compositions(l, init=None):
  6.  
  7. # Use init argument or start an empty list (for the first list)
  8. init = init or []
  9.  
  10. yield init
  11.  
  12. # Recursion break condition, when there is no more combinations to make
  13. if len(l) == 0:
  14. return
  15.  
  16. # Iterate through the remaining elements
  17. for i, v in enumerate(l):
  18.  
  19. # Add the element to the list, and create new
  20. # combinations with the remaining elements
  21. for ret in compositions(l[i+1:], init + [v]):
  22. # replace with "yield from" on Python 3
  23. yield ret
  24.  
  25. print(compositions([1, 2, 3]))
  26.  
  27. # So, in the first call, it will yield the empty list []
  28. # and will iterate through [1, 2, 3, 4]
  29. #
  30. # In the first iteration (element 1), it will add the
  31. # element to the list and call the function with the
  32. # remaining elements:
  33. #
  34. # for ret in compositions([2, 3, 4], [1]):
  35. #
  36. # In this second call, it will yield the list with
  37. # an single element [1] and will iterate through
  38. # [2, 3, 4]
  39. #
  40. # In the first iteration (element 2), it will add the
  41. # element to the list and call the function with the
  42. # remaining elements:
  43. #
  44. # for ret in compositions([3, 4], [1, 2]):
  45. #
  46. # And so on...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement