2

创建了一个程序,可以抛硬币 100 次,每次都给出随机结果。只是想知道是否可以计算每个结果出现的次数。不知道从哪里开始。我到目前为止所拥有的......

# A program which flips a coin 100 times and tells you the outcome each time

import random

counter = 0
flip = ["true", "false"]

while counter <= 99:
    counter = counter+1
    print (counter)
    print (random.choice(flip))
4

6 回答 6

7

如果 1 代表正面,那么正面的数量:

import random
print sum(random.choice([0,1]) for x in range(100))
# or more verbose:
print sum('heads' == random.choice(['heads','tails']) for x in range(100))
于 2013-05-28T12:58:10.287 回答
2

您可能还想看看collections.Counter

Docstring:
Dict subclass for counting hashable items.  Sometimes called a bag
or multiset.  Elements are stored as dictionary keys and their counts
are stored as dictionary values.

In [1]: import random

In [2]: from collections import Counter

In [3]: Counter(random.choice(('heads','tails')) for _ in range(100))
Out[3]: Counter({'heads': 51, 'tails': 49})
于 2013-05-28T13:10:01.520 回答
2

这是我的看法

heads=0
tails=0
for i in range(100):
  if random.randrange(2) == 0:
      heads+=1
  else:
      tails+=1

这不像理解那么清晰,但即使你来自另一种语言,也很容易理解这里发生了什么。

于 2013-05-28T12:58:15.997 回答
2

sum(random.choice((1, 0)) for x in range(100))

于 2013-05-28T13:00:29.800 回答
1
>>> import random
>>> sides = ['heads', 'tails']
>>> headsc = tailsc = 0
>>> for _ in xrange(100):
...     if random.choice(sides) == 'heads':
...         headsc += 1
...     else:
...         tailsc += 1
于 2013-05-28T13:00:40.147 回答
0

像这样:

heads = 0
counter = 0
flip = ["true", "false"]

while counter <= 99:
    counter = counter+1
    print (counter)
    result = random.choice(flip))
    if result == "true":
        heads = heads+1
    print (result)
print ("heads: " + heads)
print ("tails: " + (99 - heads))

实际上我的 Python 已经生锈了,所以我不知道我的语法是否正确,但应该差不多。

于 2013-05-28T12:55:38.013 回答