Python使用while循环读取前面的数字

2024-09-29 06:22:52 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个问题,在输入-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个数字并读取下一个数字。但我不明白的是如何读取前面的数字,并计算出它是否是和,或如何计算出最长的数字序列。你知道吗


Tags: theto答案gtinput序列数字整数
3条回答

试试这个:-

cnt=0
sm=0
res=0
len_of_seq=0

while True:
   n=input()

   if cnt<2:
       sm+=n
       cnt+=1

   elif cnt==2:
       if sm==n:
           if len_of_seq<=2: #not increase value of count for  first two number
               res+=1
           else:
               res+=cnt+1
       sm=0
       cnt=0

   len_of_seq+=1
   if n==-1:
       break

  print(res)

有多种方法可以解决这个问题。您可以在读取时处理输入,但将输入读入列表,然后处理列表会使事情变得更简单。你知道吗

您可以这样读取输入:

a = []
while True:
    n = int(input())
    if n == -1:
        break
    a.append(n)

请注意,如果读取非整数,则会引发ValueError。你知道吗

既然我们已经把数字列在了一个列表中,我们就可以按照罗里·道尔顿的建议来处理它们了。你知道吗

a = [1, 2, 3, 4, 5, 8, 13, 21, 34, 55, 10, 6, 7, 8, 20, 25, 30, 40]

prev2, prev1, *a = a
maxlen = seqlen = 0
for n in a:
    seqlen = seqlen + 1 if n == prev1 + prev2 else 0
    maxlen = max(maxlen, seqlen)
    prev2, prev1 = prev1, n

print(maxlen)

输出

4

只是为了好玩,这里有一个“一行”。你知道吗

from itertools import groupby

maxlen = max((len(list(g)) for k, g in groupby(u + v == w 
    for u,v,w in zip(a, a[1:], a[2:])) if k), default=0)

这两种解决方案都适用于len(a) <= 2。你知道吗

最后一个有点晦涩难懂。下面是一个细分:

from itertools import groupby

a = [1, 2, 3, 4, 5, 8, 13, 21, 34, 55, 10, 6, 7, 8, 20, 25, 30, 40]

print('tuples')
b = list(zip(a, a[1:], a[2:]))
print(b)

print('tests')
b = [u + v == w for u,v,w in b]
print(b)

print('group lengths')
b = [(k, len(list(g))) for k, g in groupby(b)]
print(b)

maxlen = max((l for k, l in b if k), default=0)
print(maxlen)

输出

tuples
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 8), (5, 8, 13), (8, 13, 21), (13, 21, 34), (21, 34, 55), (34, 55, 10), (55, 10, 6), (10, 6, 7), (6, 7, 8), (7, 8, 20), (8, 20, 25), (20, 25, 30), (25, 30, 40)]
tests
[True, False, False, False, True, True, True, True, False, False, False, False, False, False, False, False]
group lengths
[(True, 1), (False, 3), (True, 4), (False, 8)]
4

除了n,当前数字还有两个变量:

  • previous1n的前一个值
  • previous2previous1之前的值。你知道吗

很明显,您是如何将当前值与前两个值之和进行比较的。当您需要输入一个新号码时,请执行以下操作:

previous2, previous1 = previous1, n

然后输入一个新值n。你知道吗

相关问题 更多 >