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


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

最佳答案

这可以使用您所使用的方法。其他人会给你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())

关于python - 计算给定数字的最大行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57710721/

10-12 07:37