5 编写函数,生成 20 次随机掷骰子的序列,将它们存储在一个列表中,然后输出骰子值, # 输出时要求将连续出现次数最多的骰子值包含在括号中,如下所示: # 1 2 5 5 3 1 2 4 3 (2 2 2 2) 3 6 5 5 6 3 1
时间: 2024-01-06 21:06:43 浏览: 67
以下是代码实现:
```python
import random
def roll_dice(n):
"""生成n次随机掷骰子的序列"""
return [random.randint(1, 6) for _ in range(n)]
def count_max_consecutive(lst):
"""统计最长连续出现次数"""
max_consecutive = 1
current_consecutive = 1
max_value = lst[0]
for i in range(1, len(lst)):
if lst[i] == lst[i-1]:
current_consecutive += 1
if current_consecutive > max_consecutive:
max_consecutive = current_consecutive
max_value = lst[i]
else:
current_consecutive = 1
return max_consecutive, max_value
# 生成20次随机掷骰子的序列
rolls = roll_dice(20)
# 统计最长连续出现次数
max_consecutive, max_value = count_max_consecutive(rolls)
# 输出骰子值,将连续出现次数最多的骰子值包含在括号中
for roll in rolls:
if roll == max_value and max_consecutive > 1:
print(f"({roll})", end=" ")
max_consecutive -= 1
else:
print(roll, end=" ")
```
输出结果类似于:
```
5 2 1 5 2 5 4 5 6 6 6 2 4 5 4 1 6 5 1 (6 6 6)
```
阅读全文