首页 > 解决方案 > 计算给定数字的最大行数

问题描述

编写一个程序,生成 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())

我希望程序打印最长的零,而不是生成列表中的实际零数

标签: pythoncounter

解决方案


正如您所说,只有两个数字,01,所以我们将使用此功能。它很简单,仅适用于这些数字:

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其设置为1split用作1分隔符并给出一个列表。之后,我们使用 计算列表中最长字符串的长度lenmax返回列表中最长的字符串。


推荐阅读