python 如何打印出最长的一串正面硬币

pqwbnv8z  于 2022-10-30  发布在  Python
关注(0)|答案(3)|浏览(154)

我试图写一个程序,在一个随机的100个硬币投掷中计算最长的连续人头,能够打印出投掷结果,但我不知道如何初始化最长的连续计数,并着手进行,我是新的编程和Python

import random
total_heads = 0
count = 0

while count < 100:

    coin = random.randint(1, 2)
    if coin == 1:
        print("H")
        total_heads += 1
        count += 1``
    elif coin == 2:
        print("T")
bkkx9g8r

bkkx9g8r1#

这样就可以了:

import random
total_heads = 0
count = 0
longest_streak = 0
current_streak = 0

while count < 100:
    coin = random.randint(1, 2)
    if coin == 1:
        print("H")
        total_heads += 1
        current_streak += 1
        if current_streak > longest_streak:
            longest_streak = current_streak
    else:
        print("T")
        current_streak = 0
    count += 1
print(longest_streak)
print(total_heads)
mf98qq94

mf98qq942#

from random import randint as r

heads_streaks = [0]
for i in range(100):
 coin = r(0, 1)
 if not coin:
  print("H")
  heads_streaks[-1] += 1
 else:
  print("T")
  heads_streaks.append(0)
print("longest streak is: {}".format(sorted(heads_streaks, reverse=True)[0]))
fwzugrvs

fwzugrvs3#

冒着太多魔法的风险,这些是我会用的工具:

  • random.choices()可用于一步绘制100个样本
  • itertools.groupby()可用于将这些投掷分组为条纹,即,将随机投掷划分为其中面相同的组
  • 列表解析和生成器使得循环遍历并提取所需信息变得非常容易

把这些放在一起,我得到:

import random
import itertools

# perform 100 coin tosses and print them out

tosses = random.choices('HT', k=100)
print('tosses: ', *tosses)

# turn these into streaks of the same side

streaks = [''.join(streak) for _, streak in itertools.groupby(tosses)]
print('streaks: ', *streaks)

# get the longest streak of heads

lsh = max(len(s) for s in streaks if s[0] == 'H')
print('longest streak of heads: ', lsh)

一次运行,输出:

tosses: H T H T T T H H T T H H H H T H T T T T H T T H H H H H T T H H H H H H T T T T H T H H T H T T H H H H H H H T T T H T H H T T T H H T T H H T H T H H T H H H T T H T T H T H T H H T T T T T T H T H
streaks: H T H TTT HH TT HHHH T H TTTT H TT HHHHH TT HHHHHH TTTT H T HH T H TT HHHHHHH TTT H T HH TTT HH TT HH T H T HH T HHH TT H TT H T H T HH TTTTTT H T H
longest streak of heads: 7

相关问题