打印奇偶数交替的最长连续序列的长度
Posted
技术标签:
【中文标题】打印奇偶数交替的最长连续序列的长度【英文标题】:Print the length of the longest continuous sequence of alternating odd and even numbers 【发布时间】:2019-01-15 04:38:52 【问题描述】:在输入 -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)
【问题讨论】:
【参考方案1】:我就是这样做的。我认为这可能比上面的例子更简单。
def 交替(lst):
longSeries = []
currentSeries=[]
for i in range (len(lst)-1):
if i == 0:
currentSeries = [lst[0]]
if(abs(lst[i] - lst[i+1]) % 2 == 1):
currentSeries.append(lst[i+1])
else:
currentSeries = [lst[i+1]]
if(len(currentSeries) > len(longSeries)):
longSeries = currentSeries
print ("The longest series is: " +str(longSeries))
print(len(longSeries))
【讨论】:
【参考方案2】:您可以使用 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
)
【讨论】:
【参考方案3】:一种选择是随时跟踪最长的序列:
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
时无需进行任何后处理,结果已准备就绪。
【讨论】:
【参考方案4】:您可以申请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]
【讨论】:
以上是关于打印奇偶数交替的最长连续序列的长度的主要内容,如果未能解决你的问题,请参考以下文章