pythoncombinationscombinatoricslexicographicinteger-partition

Generate restricted weak integer compositions (or partitions) of an integer n into k parts in Python


(Re-posting, as I did not get any response to my previous post)
I am trying to write a Python code to generate weak integer compositions (partitions) of a number 'n' into 'k' parts but with a MINIMUM and MAXIMUM value constraint on each partition (see example given below). Also, the partitions have to be generated in lexicographic order. I have found some related posts but have not been able to implement it. Any help will be appreciated.

Example:
Possible integer partitions for n=5 in k=3 parts:
[5,0,0], [4,1,0], [4,0,1], [3,2,0], [3,1,1], [3,0,2], ..., [0,0,5]
After imposing the constraint that each integer in the partition has a MINIMUM value 0 and a MAXIMUM value 3, I should get:
[3,2,0], [3,1,1], [3,0,2], ...so on, only.

Related posts:
Elegant Python code for Integer Partitioning
Generate lexicographic series efficiently in Python


Solution

  • This kind of problem is most straightforward to solve with a recursive generator function. To generate partitions of n into k parts, we can select the first part v, and then recursively partition n - v into k - 1 parts.

    You want earlier solutions to have larger numbers in the first position, so we'll choose v in descending order.

    def constrained_partitions(n, k, min_elem, max_elem):
        allowed = range(max_elem, min_elem-1, -1)
    
        def helper(n, k, t):
            if k == 0:
                if n == 0:
                    yield t
            elif k == 1:
                if n in allowed:
                    yield t + (n,)
            elif min_elem * k <= n <= max_elem * k:
                for v in allowed:
                    yield from helper(n - v, k - 1, t + (v,))
    
        return helper(n, k, ())
    

    Example:

    >>> for p in constrained_partitions(5, 3, 0, 3):
    ...     print(p)
    ... 
    (3, 2, 0)
    (3, 1, 1)
    (3, 0, 2)
    (2, 3, 0)
    (2, 2, 1)
    (2, 1, 2)
    (2, 0, 3)
    (1, 3, 1)
    (1, 2, 2)
    (1, 1, 3)
    (0, 3, 2)
    (0, 2, 3)