python中最长的偶数序列
使用非库python代码,如何返回最长偶数序列的索引和计数python中最长的偶数序列,python,Python,使用非库python代码,如何返回最长偶数序列的索引和计数 a = [1, 3, 2, 6, 4, 1, 2, 2, 2, 8, 1] 应该返回6和4,6是索引,4是计数。 我试过了,但运气不好 def evenSeq(list): count=0 for i in list: if list[i]%2 and list[i+1]%2==0: count+=1 return count 这不是最漂亮的解决方案,但它可以帮助您了解
a = [1, 3, 2, 6, 4, 1, 2, 2, 2, 8, 1]
应该返回6和4,6是索引,4是计数。
我试过了,但运气不好
def evenSeq(list):
count=0
for i in list:
if list[i]%2 and list[i+1]%2==0:
count+=1
return count
这不是最漂亮的解决方案,但它可以帮助您了解发生了什么以及解决方案的基本逻辑。基本上,它会检查数字是否为偶数,并对存储在temp\u max
中的当前条纹进行计数。检查temp_max
是否是当时已知的最大条纹,并从enumerate更新索引
根据评论编辑:
for count, value in enumerate(a):
这一行基本上遍历了列表,将值放在value
中,将当前索引放在count
中enumerate()
基本上会遍历您传递的内容,并返回从0开始的计数以及项目。例如,见下文
a=[1,3,2,6,4,2,2,2,2,2,1,2,2,2,8,1]
for index, value in enumerate(a):
print('{} index and value is {}'.format(index,value))
打印出:
0 index and value is 1
1 index and value is 3
2 index and value is 2
3 index and value is 6
4 index and value is 4
5 index and value is 2
6 index and value is 2
7 index and value is 2
8 index and value is 2
9 index and value is 2
10 index and value is 1
11 index and value is 2
12 index and value is 2
13 index and value is 2
14 index and value is 8
15 index and value is 1
下面是一个可能的解决方案:
def even_seq(l):
best = (-1, -1)
start_i = 0
count = 0
for i, n in enumerate(l):
if n % 2 == 0:
count += 1
if count > best[1]:
best = (start_i, count)
else:
start_i = i + 1
count = 0
return best
我会这样尝试:
def evenSeq(seq):
i = startindex = maxindex = maxcount = 0
while i < len(seq):
if seq[i]%2==0:
startindex = i
while i < len(seq) and seq[i]%2==0:
i+=1
if maxcount < i - startindex:
maxcount = i - startindex
maxindex = startindex
i+=1
return (maxindex, maxcount)
def evenSeq(seq):
i=startindex=maxindex=maxcount=0
而我
在此处添加一些额外信息。您的代码中当前发生了哪些不符合预期的情况?对于您提供的输入,您当前得到的输出不符合预期?观察:如果遇到奇数,count
会发生什么情况?@PatrickHaugh editedDon您不希望枚举(列表)中的值为i?现在,您正在对列表中的整数进行迭代,并尝试将它们用作索引,这与您想要做的不一样。按你的方式做,你会在数组中跳跃,而不是从头到尾迭代。@moingrawr哈哈,为了对集合的热爱
我杀了itertools
。是的。这不起作用,您是基于值而不是实际索引编制索引。您使用的是列表元素,就好像它们是索引一样。另外,不要隐藏内置的列表的名称
枚举(a)中的count,value的作用是什么?用这个例子试试:evenSeq([4,4,4,1,2,2,2])
,它给出了一个错误的答案answer@FranciscoCouzooops错过了一个等号谢谢你抓住了will update。@Mooningrawr你在哪里错过了“=”?@SanderB抱歉的工作正在调用这里是最后的编辑,如果我仍然错了/有bug抱歉,我会在可以的时候更新。
def evenSeq(seq):
i = startindex = maxindex = maxcount = 0
while i < len(seq):
if seq[i]%2==0:
startindex = i
while i < len(seq) and seq[i]%2==0:
i+=1
if maxcount < i - startindex:
maxcount = i - startindex
maxindex = startindex
i+=1
return (maxindex, maxcount)