计算给定数字的最大行

Counting the maximum row of a given number

编写一个程序,生成 100 个 0 或 1 的随机整数。然后找到 longest 运行 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())

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

正如您所说,只有两个数字,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, joining it to get a string, & splitting it on 1. split uses 1 as delimiter and gives a list. After that, we are counting the length of the longest string in the list using len. max returns 列表中最长的字符串将所有整数条目转换为字符串。

使用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

您可以使用 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

这有效,与您使用的方法一致。其他人会给你 pythonic 方式:

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
            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
        else:
            zero_count = 0 #if i == 1 we reset the zero_count variable
    return max_zero_count
print(sequence_count())