打印最长连续序列的长度(Python)

时间:2018-08-06 09:17:09

标签: python iteration

这里是Question

enter image description here

  

读取整数,直到输入-1。   打印最长连续数字序列的长度,其中一个数字是前面两个数字的总和。不包括
  序列长度的前两个数字。

1,2,3,4,5,8,13,21,34,55,10,6,7,8,20,25,30,40,-1

1,2,3,4,5,10,15,20,8,13,21,34,55,89,144,-1

5,8,13,21,34,55,89,144,1,2,3,4,5,10,15,20,-1

adi results

这是我失败的尝试:

longest = 0
length = 2
i = int(input())
prev = i
diff = prev - i

while i != -1:
    if i - prev == diff:
        length = length + 1
        prev = i
    else:
        length = 2
        diff = i - prev
        prev = i
    if length > longest:
        longest = length
    i = int(input())
print (longest)

任何帮助解决此问题的人将不胜感激!

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

sequence = []
stop = False
while not stop:
    num = int(input())
    if num == -1:
        stop = True
    else:
        sequence.append(num)

longest = 0
length = 0
for i in range(2, len(sequence)):
    if (sequence[i-2] + sequence[i-1]) == sequence[i]:
        length += 1
    else:
        longest = max(longest, length)
        length = 0

首先,我读取整数序列,直到输入-1。然后,我遍历序列中除前两个之外的所有数字。对于每个数字,我检查它是否为前两个数字的和。如果是这样,我将递增跟踪当前连续序列(length)长度的变量。完成此序列后,我重新计算longest作为其自身和当前子序列的最大值。重复此过程,直到检查完序列中的所有数字为止。