令我惊讶的是,到目前为止,这两个答案都采取了一种非常繁重的方法,这种方法非常低效地做很多事情,尤其是在内存使用方面:
- 构造和处理字符串
- 存储输入的冗余副本
- 为计数目的创建多个临时列表和/或字符串。
此外,从运行时的角度来看,这些解决方案都不是特别优雅,也不能很好地解释真正发生或需要通过算法完成的程序方面,这是初学者教学的一个重要方面。
以下方法允许您使用任意大的输入(卷数),因为它不需要保留任何副本。因此,它可以很容易地转换为生成器函数或类似的流处理函数。它也更直接,程序更干净。
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