所以我有一个问题,在输入-1之前,我在哪里读取一组整数。我需要打印最长的连续数列的长度,其中一个数是前两个数的和。这不包括序列长度中的前2个数字。你知道吗
例如,输入什么数字,答案是: 1,2,3,4,5,8,13,21,34,55,10,6,7,8,20,25,30,40,-1=>;4
到目前为止我所拥有的:
n = int(input()) #reads the initial input
numberSkip = 0 #numberSkip allows me to skip the first 2 numbers
while n != -1:
if numberSkip < 2:
numberSkip += 1
elif numberSkip >= 2:
print (n) #this is where the rest of the code would go I'm assuming
n = int(input())
因此,我已经研究了如何在循环达到-1时结束循环,如何跳过前2个数字并读取下一个数字。但我不明白的是如何读取前面的数字,并计算出它是否是和,或如何计算出最长的数字序列。你知道吗
试试这个:-
有多种方法可以解决这个问题。您可以在读取时处理输入,但将输入读入列表,然后处理列表会使事情变得更简单。你知道吗
您可以这样读取输入:
请注意,如果读取非整数,则会引发
ValueError
。你知道吗既然我们已经把数字列在了一个列表中,我们就可以按照罗里·道尔顿的建议来处理它们了。你知道吗
输出
只是为了好玩,这里有一个“一行”。你知道吗
这两种解决方案都适用于
len(a) <= 2
。你知道吗最后一个有点晦涩难懂。下面是一个细分:
输出
除了
n
,当前数字还有两个变量:previous1
,n
的前一个值previous2
,previous1
之前的值。你知道吗很明显,您是如何将当前值与前两个值之和进行比较的。当您需要输入一个新号码时,请执行以下操作:
然后输入一个新值
n
。你知道吗相关问题 更多 >
编程相关推荐