我尝试编写的应用程序将模拟掷硬币一定次数到最多200次。 它必须记录头部的数量和抛出的尾巴数量,并向用户显示连续抛出的最大头数,连续抛出的最大尾部数量以及除了显示的头部和尾部的百分比
没有负面评论 - 刚开始学习python,我的尝试就在下面!
import random as rn
rolls=int(raw_input("Enter the number of rolls: "))
for rolls in range(rolls):
print rn.choice(['H', 'HH', 'HHH', 'T', 'TT', 'TTT']),
答案 0 :(得分:3)
为每次投掷使用random.choice
生成投掷:
tosses = ''.join(random.choice('HT') for i in range(rolls))
您可以简单地计算结果字符串中H和T的出现次数,分别得到头部和尾部的数量:
heads = tosses.count('H')
tails = tosses.count('T')
最后,您可以通过在其他符号上拆分字符串并找到最大结果子字符串来找到一行中的最大头/尾数:
heads_in_a_row = max(len(s) for s in tosses.split('T'))
tails_in_a_row = max(len(s) for s in tosses.split('H'))
效率不高,但它可能有助于你理解。
答案 1 :(得分:0)
每当你需要找到连续的东西时,最好考虑itertools.groupby
。无论卷数如何,这种方法都需要非常少的额外内存
from itertools import groupby
import random
rolls = int(raw_input("Enter the number of rolls: "))
tosses = (random.choice('HT') for x in range(rolls))
maxes = {'H': 0, 'T': 0}
sums = {'H': 0, 'T': 0}
for g, v in groupby(tosses):
n = sum(1 for x in v)
maxes[g] = max(maxes[g], n)
sums[g] += n
print maxes['H']
print maxes['T']
print sums['H']*100.0/rolls
print sums['T']*100.0/rolls
答案 2 :(得分:0)
令我感到惊讶的是,到目前为止,这两个答案采取了非常繁重的方法,这些方法在很多方面做得非常低效,尤其是内存使用:
此外,从运行时的角度来看,这些解决方案都不是特别优雅,或者善于解释实际上正在进行或需要通过算法完成的过程方面,这是初学者教学的一个重要方面。
以下方法允许您使用任意大的输入(卷数),因为它不需要保留任何副本。因此,它可以很容易地转换为生成器函数或类似的流处理函数。它也更直接,程序更干净。
import random
rolls=int(raw_input("Enter the number of rolls: "))
desc = {0: "H", 1: "T"}
total = [0, 0]
running = [0, 0]
running_max = [0, 0]
last_rolled = None
for roll in xrange(rolls):
# we use 0 for heads and 1 for tails
# this will be the index to the relevant list element for our counters
rolled = random.randint(0,1)
total[rolled] += 1
if last_rolled == rolled:
# we are continuing the run, flipped the same as last time
running[rolled] += 1
else:
# there has been a break in the run
if not last_rolled is None:
# as long as this isnt the first iteration
print running[last_rolled] * desc[last_rolled],
running[last_rolled] = 0
running[rolled] = 1
# update the max count
running_max[rolled] = max(running_max[rolled], running[rolled])
last_rolled = rolled
print running[last_rolled] * desc[last_rolled]
print "total rolls: H=%d, T=%d" % tuple(total)
print "running max: H=%d, T=%d" % tuple(running_max)
示例输出:
Enter the number of rolls: 20
HH TTTT HH TT HHHHHHH T H T
total rolls: H=12, T=8
running max: H=7, T=4