编写一个程序,生成 100 个 0 或 1 的随机整数。然后找到 longest run of zeros,一行中最大数量的零。例如,最长的运行 [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 或 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返回列表中最长的字符串。
