1

Just learning Python, so finding the answer for this hard to find as I'm not sure what to type in! I think the answer will use Itertools.

I have a list (of length L) with 1 starting number (could be any positive integer, n) and the rest zeros. EG L=4 n=3:

[3,0,0,0]

and I want all combinations that the 3 can be split into the spaces in the list. EG:

[[3,0,0,0],[2,1,0,0],[2,0,1,0],[2,0,0,1],[1,2,0,0],[1,0,2,0],[1,0,0,2],[1,1,1,0],[1,1,0,1],[1,0,1,1],[0,3,0,0],[0,2,1,0],[0,2,0,1],[0,1,2,0],[0,1,0,2],[0,1,1,1],[0,0,3,0],[0,0,2,1],[0,0,1,2],[0,0,0,3]]

Thanks for taking the time to read :)

C.Charlick
  • 21
  • 3
  • 3
    This is non-trivial, you should show some effort in solving this yourself instead of just asking for a solution outright – Idos Dec 13 '15 at 11:39
  • Try looking into generator expressions.. – Ahmed Shariff Dec 13 '15 at 11:41
  • It really has nothing to do with itertools, you just need to write an algorithm for that task. – Rafał Łużyński Dec 13 '15 at 11:51
  • First use [this function](http://stackoverflow.com/questions/10035752/elegant-python-code-for-integer-partitioning), then `m=4`, then `intermediate = {item + (0,)*(m-len(item)) for item in partition(3)}`, then `result = set(itertools.chain.from_iterable(itertools.permutations(item, m) for item in intermediate))`. Seems to give the result you're looking for. – TigerhawkT3 Dec 13 '15 at 12:15
  • @MartijnPieters - Going from combinations of sums of a number with a fill value to "general bars and stars" is some serious search-fu. I don't know how you found it, but Mark's answer there is exactly what's called for. :) – TigerhawkT3 Dec 13 '15 at 12:21
  • 1
    @TigerhawkT3: Reti43 found it, but could only flag. I confirmed the flag. – Martijn Pieters Dec 13 '15 at 12:22

0 Answers0