打印交替的奇数和偶数的最长连续序列的长度

时间:2018-08-08 02:26:32

标签: python list list-manipulation

在输入-1之前,我将如何读取整数,然后在有数字的地方打印最长连续数字序列的长度 交替的奇数然后是偶数?

我已经完成了第一部分,但是从那开始走下坡路。

一些测试列表:

[1,2,3,4,5,10,6,7,8,20,25,30,40,-1]              
[6,7,8,20,25,30,40,1,2,3,4,5,10,15,20,-1]  

这是我的代码:

evenOdd=[]

while True:
    try:
        n=int(input())
        if n != -1:
            evenOdd.append(n)
    except:
            break
evenOdd=[]
longest = 0
length = 0
for i in range(len(evenOdd)):
    if ((evenOdd[i-2]% 2 == 0) and (evenOdd[i-1]% 2 == 1) and (evenOdd[i]% 2 == 0):
        length += 1
    else:
        longest = max(longest, length)
        length = 0

print(longest)

4 个答案:

答案 0 :(得分:0)

一种选择是跟踪最长的序列:

]\n[C\1

这里的好处是,当输入longest = [] current = [] while True: n = int(input("Enter value: ")) if n == -1: break if current and current[-1] % 2 != n % 2: current.append(n) else: current = [n] if len(current) > len(longest): longest = current 时,不需要进行任何后处理。

答案 1 :(得分:0)

您可以使用itertools.cycle在0和1的余数之间交替,并使用itertools.groupby对奇偶序列进行分组:

from itertools import groupby, cycle
l = [1,2,3,4,5,10,6,7,8,20,25,30,40]
r = cycle((0, 1))
print(max(sum(1 for i in g) for _, g in groupby(l, key=lambda n: n % 2 == next(r))))

这将输出:6(由于最长的奇偶序列是1,2,3,4,5,10

答案 2 :(得分:0)

这就是我的做法。我认为这可能比上面的示例更简单。

def交替(lst):

setSquareColor(...)

答案 3 :(得分:-1)

您可以两次申请itertools.groupby

import itertools
d = [[1,2,3,4,5,10,6,7,8,20,25,30,40,-1], [6,7,8,20,25,30,40,1,2,3,4,5,10,15,20,-1]]
def key_func(d):
  start= not d[0]%2
  for i in d[1:]:
    if i%2 == start:
      start = (not i%2)
    else:
      return False
  return True

for l in d:
  new_l = [list(b) for _, b in itertools.groupby(l, key=lambda x:x%2)]
  second_l = [[i for [i] in b] for a, b in itertools.groupby(new_l, key=lambda x:len(x) ==1) if a]
  print(max(second_l, key=lambda x:[key_func(x), len(x)]))

输出:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 10, 15, 20, -1]