数学 Python 模拟 随机100个数 50%概率0或者1. 来看看有几个连续的0
代码
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
共2条回复
时间正序