Guest User

Untitled

a guest
Jul 17th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.58 KB | None | 0 0
  1. import itertools
  2. # composition devides n into all possible combinations k of ints that sum to n
  3. # inputs: k and n are of type 'int'
  4. # output: a set of tuples
  5. def compositions(k, n):
  6.  
  7. if k <= 0:
  8. return set()
  9. if k ==1:
  10. return set((n,))
  11. it = itertools.combinations(range(1,n),k-1)
  12. tu=set()
  13. s=list()
  14. for i in it:
  15. s.append(i)
  16. sl= sorted(s)
  17. for i in sl:
  18. nl =list()
  19. nl.append(i[0])
  20. for t in range(1,k-1):
  21. nl.append(i[t]-i[t-1])
  22. nl.append(n-i[k-2])
  23. tu.add(tuple(nl))
  24. return tu
Add Comment
Please, Sign In to add comment