python - 计算给定数字的最大行数
问题描述
编写一个程序,生成 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())
我希望程序打印最长的零,而不是生成列表中的实际零数
解决方案
推荐阅读
- maven - 在 Jenkins 构建期间在 Maven 中添加第三方依赖项的问题 - ODM
- msbuild - Azure DevOps 将 sqlproj 构建到 $(Build.ArtifactStagingDirectory)
- javascript - 如何使用变量进行推送?
- javascript - 如何在 HTML5 中播放多个音轨视频
- jenkins-pipeline - Jenkins管道阶段基于if条件在另一个阶段内
- c# - 如何获取表中分配的值
- javascript - 如何在地图中使用 react useRef 定位 DOM
- java - Weblogic 10.3.6:从 web.xml 激活 Spring Boot 配置文件
- html - 缩放元素时,部分边框在 Firefox 上不可见
- java - 如何避免由于代码重复而导致的重载?