编写一个程序,该程序生成100个为0或1的随机整数。然后找到 最长的零游程,连续的最大零数。例如,最长的 [1,0,1,1,0,0,0,0,1,0,0]中的零是4。
所有说明均在代码中
import random
sequence = []
def define_sequence():
for i in range(0,100):
sequence.append(random.randint(0,1))
print(sequence)
return sequence
define_sequence()
def sequence_count():
zero_count = 0 #counts the number of zeros so far
max_zero_count = 0 #counts the maximum number of zeros seen so faz
for i in sequence:
if i == 0: #if i == 0 we increment both zero_count and max_zero_count
zero_count += 1
max_zero_count += 1
else:
zero_count = 0 #if i == 1 we reset the zero_count variable
if i == 0:
zero_count += 1 #if we see again zero we increment the zero_count variable again
if zero_count > max_zero_count:
max_zero_count = zero_count #if the zero_count is more than the previous max_zero_count we assignt to max_zero_count the zero_count value
return max_zero_count
print(sequence_count())
我希望程序在生成的列表中打印最长的零,而不是实际的零。
答案 0 :(得分:4)
正如您所说的,0
或1
只有两个数字,因此我们将使用此功能。它很简单,仅适用于以下数字:
len(max("".join(map(str, a)).split("1")))
示例:
>>> a = [1,0,1,1,0,0,0,0,1,0,0]
>>>
>>> len(max("".join(map(str, a)).split("1")))
4
>>>
说明:
我们正在使用map
将所有整数条目转换为字符串,join
将其转换为字符串,并split
将其置于1
上。 split
使用1
作为分隔符并给出一个列表。之后,我们使用len
计算列表中最长字符串的长度。 max
返回列表中最长的字符串。
答案 1 :(得分:2)
使用itertools.groupby
:
max(len(list(v)) for k, v in groupby(lst) if k == 0)
其中lst
是您的输入列表。
示例:
from itertools import groupby
lst = [1,0,1,1,0,0,0,0,1,0,0]
print(max(len(list(v)) for k, v in groupby(lst) if k == 0))
# 4
答案 2 :(得分:1)
这可以使用您所使用的方法。其他人会给你pythonic的方式:
python manage.py runserver 0.0.0.0:8000
答案 3 :(得分:0)
您可以使用groupby:
from itertools import groupby
a = [1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0]
num = 0
max([len(list(v)) for k, v in groupby(a) if k == num])
4