不同的成对加法迭代失败了Python

时间:2016-05-14 04:22:32

标签: python recursion iteration

此分配的目的是找到总和为数字n的最大数字数,以使这些数字是唯一的。例如,如果n = 8,我们从l = 1开始然后从n中减去1得到7然后尝试l = 2得到k = 5,但是我们停止因为这个数字的一​​些不同的总和是前面的成员名单。所以我正在尝试实现迭代方法。我已经尝试过递归方法,但是达到最大递归深度,因为n <= 10 ^ 9。我实际上在这里尝试一种递归方法来检查k的不同总和是否在列表中,但是这不起作用。对于n = 85的输入,其输出为[1,84],而正确的输出为[1,2,3,4,5,6,7,8,9,10,11,19]。我错过了什么?提前谢谢。

def optimalSummandsIter(n):
        '''
        The goal of this problem is to represent
        a given positive integer n as a sum of as many pairwise
        distinct positive integers as possible.
        In the first line, output the maximum number k such that n can be represented as a sum
        of k pairwise distinct positive integers. 
        In the second line, output k pairwise distinct positive integers
        that sum up to n (if there are many such representations, output any of them).
        Initially we have k = n and l = 1. 
        To solve a (k, l)-subproblem, we do the following. 
        If k ≤ 2l, we output just one summand k. 
        Otherwise we output l and then solve the subproblem (k − l, l + 1)
        '''
        summands = []
        k = n
        l = 1
        m = sum(summands)   
        if k <= 2*l:
            summands.append(k)
            return summands
        while k > 0:
            if any(i in optimalSummandsIter(k) for i in summands):
                summands.append(k)
                return summands
            else:
                summands.append(l)
                k -= l
                l += 1

        return summands

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

def optimalSummandsIter(n):
    summands = []
    k = n
    l = 1
    while k > 0:
        if k <= l*2:
            summands.append(k)
            return summands
        summands.append(l)
        k -= l
        l += 1

optimalSummandsIter(8)  --> [1,2,5]
optimalSummandsIter(85) --> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 19]
相关问题