Python Integer Partitioning with given k partitions

前端 未结 3 1983
灰色年华
灰色年华 2020-11-30 01:45

I\'m trying to find or develop Integer Partitioning code for Python.

FYI, Integer Partitioning is representing a given integer n as a sum of integers smaller than n.

3条回答
  •  离开以前
    2020-11-30 02:08

    First I want to thanks everyone for their contribution. I arrived here needing an algorithm for generating integer partitions with the following details :

    Generate partitions of a number into EXACTLY k parts but also having MINIMUM and MAXIMUM constraints.

    Therefore, I modified the code of "Snakes and Coffee" to accommodate these new requirements:

    def partition_min_max(n,k,l, m):
    '''n is the integer to partition, k is the length of partitions, 
    l is the min partition element size, m is the max partition element size '''
    if k < 1:
        raise StopIteration
    if k == 1:
        if n <= m and n>=l :
            yield (n,)
        raise StopIteration
    for i in range(l,m+1):
        for result in partition_min_max(n-i,k-1,i,m):                
            yield result+(i,)
    
    
    >>> x = list(partition_min_max(20 ,3, 3, 10 ))
    >>> print(x)
    >>> [(10, 7, 3), (9, 8, 3), (10, 6, 4), (9, 7, 4), (8, 8, 4), (10, 5, 5), (9, 6, 5), (8, 7, 5), (8, 6, 6), (7, 7, 6)]
    

提交回复
热议问题