Python Generating All Nondecreasing Sequences
I am having trouble finding a way to do this in a Pythonic way. I assume I can use itertools somehow because I've done something similar before but can't remember what I did. I am
Solution 1:
You can do this using itertools.combinations_with_replacement
:
>>>L, N = 3,3>>>cc = combinations_with_replacement(range(1, N+1), L)>>>for c in cc: print(c)
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 2, 2)
(1, 2, 3)
(1, 3, 3)
(2, 2, 2)
(2, 2, 3)
(2, 3, 3)
(3, 3, 3)
This works because c_w_r preserves the order of the input, and since we're passing a nondecreasing sequence in, we only get nondecreasing tuples out.
(It's easy to convert to lists if you really need those as opposed to tuples.)
Post a Comment for "Python Generating All Nondecreasing Sequences"