I want to generate a list from user entered number using Python
I had tried it but I was unable to find out the proper solution for it.
例如:
如果用户输入2,则列表应为[1,1]
如果用户输入11,则列表应为[1,2,3,4,1]
如果用户输入12,则列表应为[1,2,3,4,2]
如果用户输入16,则列表应为[1,2,3,4,5,1]
如果用户输入24,则列表应为[1,2,3,4,5,6,3]
规则:
答案 0 :(得分:2)
maxNum, current, result = 12, 1, []
while maxNum > current:
result.append(current)
maxNum -= current
current += 1
result.append(maxNum)
print result
<强>输出强>
[1, 2, 3, 4, 2]
修改强>
数学解决方案:
inputNumber = int(raw_input("Please enter the input number: "))
a, b, c = 1, 1, -2 * inputNumber
innerPart = ((b**2) - 4 * a * c)**0.5
N = int(max((-b + innerPart) / (2 * a), (-b - innerPart) / (2 * a)))
result, sumTillN = [i for i in range(1, N + 1)], (N * (N + 1)) // 2
if inputNumber - sumTillN: result.append(inputNumber - sumTillN)
print result
可以使用N(N + 1)/ 2公式计算第一个N-1个元素。我们可以找到N^2+N-2*inputNumber
的正N并填充前N - 1个元素。最后一个元素就是剩余部分。