Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import itertools
- # composition devides n into all possible combinations k of ints that sum to n
- # inputs: k and n are of type 'int'
- # output: a set of tuples
- def compositions(k, n):
- if k <= 0:
- return set()
- if k ==1:
- return set((n,))
- it = itertools.combinations(range(1,n),k-1)
- tu=set()
- s=list()
- for i in it:
- s.append(i)
- sl= sorted(s)
- for i in sl:
- nl =list()
- nl.append(i[0])
- for t in range(1,k-1):
- nl.append(i[t]-i[t-1])
- nl.append(n-i[k-2])
- tu.add(tuple(nl))
- return tu
Add Comment
Please, Sign In to add comment