Python 模拟 随机100个...

数学
Python 模拟 随机100个数 50%概率0或者1. 来看看有几个连续的0

用户头像
物理竞赛鹏鹏鹏 更新于2023-10-25 10:59:32

代码

import random

# 用于存储生成的数的列表
numbers = []

# 生成100个数
for _ in range(100):
    # 以50%的概率生成0或1
    number = random.choice([0, 1])
    numbers.append(number)

# 打印生成的数
print("生成的数:", numbers)

# 查找最长连续0序列及其长度
max_sequence = 0
current_sequence = 0

for num in numbers:
    if num == 0:
        current_sequence += 1
        max_sequence = max(max_sequence, current_sequence)
    else:
        current_sequence = 0

print("最长连续0序列的长度:", max_sequence)

运行的结果(每次会不一样,因为是随机数)

生成的数: [0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1,
 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1,
 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1,
 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 
1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 
1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 
0, 1, 1, 0, 0, 1, 0]
最长连续0序列的长度: 7
收起
8
2
共2条回复
时间正序
用户头像
好好学习,天天向上!
2年前
月月鸟终于想起论坛密码了(doge)
用户头像
芝士雪豹
2年前
一眼Python