gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:30:50 25 4
gpt4 key购买 nike

这个作业的目的是找到最大数量的数字,总和为数字 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

最佳答案

这应该可以解决问题:

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]

关于python - 不同的成对加法迭代失败 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37222488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com