Search code examples
pythonpython-3.xpython-itertools

After using combinations with replacement, how to remove tuples with combinations that I don't want


I'm trying to get a list of lists (or tuples) which follows a pattern something like this:

[1,1,1,2]
[1,1,2,2]
[1,2,2,2]
[1,2,2,3]
[1,2,3,3]
[1,2,3,4]

Using itertools.combinations_with_replacement I've gotten close, but I end up with lists which jump values for example:

[1,1,1,3]
or
[2,2,2,3]

I don't want this. I always want to start at 1, and increase until the list is filled, and then increase to the next value.

If I'm using itertools, then is there a way to remove the lists that I don't want?


Solution

  • Instead of using combinations, I would generate the pattern directly.

    Create a list of 1's with the desired length and iterate backward, changing the list accordingly.

    def generate_increment(n):
        lst = [1] * n
        result = []
        for k in range(n-1):
            lst[-1] += 1
            result.append(lst[:])
            for i in range(len(lst)-2, k, -1):
                a, b = lst[i], lst[i+1]
                if a != b:
                    lst[i] = b
                    result.append(lst[:])
        return result
    
    >>print(*generate_increment(4), sep='\n')
    
    [1, 1, 1, 2]
    [1, 1, 2, 2]
    [1, 2, 2, 2]
    [1, 2, 2, 3]
    [1, 2, 3, 3]
    [1, 2, 3, 4]