它讓我感到驚訝,這兩個答案至今採取了非常沉重的做法,效率很低,做了很多的事情,尤其是內存使用明智的:
- 構建和處理字符串
- 存儲輸入
- 創建多個臨時列表和/或字符串計數的目的的冗餘副本。
而且,這些方法都從一個角度運行時特別優雅或擅長解釋什麼是怎麼回事或者需要做算法,這是初學者教學的一個重要方面程序方面。
以下方法允許您使用任意大的輸入(滾動量),因爲它不需要保留任何副本。因此,它可以很容易地轉換爲生成器函數或類似的流處理函數。它也更簡單,程序清潔。
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
有什麼問題嗎? –
這不是隨機的,你可以通過把它們串在一起來偏向連續相同的拋物線。你想要做的是:'tosses = [rn.choice(「HT」)for i in range(rolls)]''。 –
您錯過了「HT」,「TH」,「HTT」,「HTH」,「THT」,「THH」 – inspectorG4dget