Reputation: 55
I made a simple coin flipper program that, as named flips a coin and prints out the value.
My goal is to print lots of coin flips and record how many times it lands on heads and how many times it lands on tails. But obviously I can't because I don't know how to count how many times it lands on a specific value.
import random
heads_or_tail = ['heads', 'tail']
def flip_coin():
flip_coin = random.choice(heads_or_tail)
print(flip_coin)
for x in range(100):
flip_coin()
Upvotes: 1
Views: 105
Reputation: 449
If there is no reason why you are forget about the result of each individual Tour i would recommend the other way around. Reasons could be limited memory but i wouldn't expect that;) Within the package numpy, you also have the function choice.
At the end you can Count with a boolean expression.
Result = numpy.random.choice(["head", "tail"], 100)
print(Result)
Numbe_of_head = (Result == "head").sum()
print(Number_of_head)
Fürther this solution uses numpy with its iterations.
Upvotes: 0
Reputation: 1355
The collections
module has a great feature for this called Counter
:
import collections
import random
heads_or_tail = ['heads', 'tail']
def flip_coin():
flip_coin = random.choice(heads_or_tail)
return flip_coin
cnt = collections.Counter()
for x in range(100):
cnt[flip_coin()] += 1
Output:
>>> cnt
Counter({'tail': 50, 'heads': 50})
Alternatively, you could just use a normal dict
but that requires a bit more boiler-plate code:
# Alternatively, you could just use a `dict`
dict_cnt = {}
for x in range(100):
fc = flip_coin()
if fc in dict_cnt:
dict_cnt[fc] += 1
else:
dict_cnt[fc] = 1
Remember, the most pythonic thing to do is to use libraries that others have perfected - especially from the Python standard library. So, when counting, I would recommend you use collections.Counter
.
Also, Counter
has many more cool features you can check out in the docs.
As others have mentioned, you could use a generator passed into the Counter
constructor, since it is an iterable - this would shorten your code significantly:
import collections
import random
flip_gen = (random.choice(['heads', 'tails']) for _ in range(100))
cnt = collections.Counter(flip_gen)
>>> cnt
Counter({'heads': 51, 'tail': 49})
Upvotes: 1
Reputation: 336
I like the solution from @Samwise, in case the number of iterations is really high though, I would use generators (range is being evaluated lazily).
import random
from collections import defaultdict
heads_or_tail = ['heads', 'tail']
d = defaultdict(int)
def flip_coin(iterations):
for i in range(iterations):
result_iteration = random.choice(heads_or_tail)
d[result_iteration] += 1
yield result_iteration
You can then get the values on demand basis calling next() method as here:
a = flip_coin(100)
next(a)
next(a)
next(a)
next(a)
output :
defaultdict(int, {'heads': 1, 'tail': 3})
Upvotes: 0
Reputation: 62
Try this, It's the beginner friendly solution so far:
import random
head = []
tail = []
def flip_coin():
for _ in range(100):
flip_coin = random.choice(['heads', 'tail'])
if flip_coin == 'heads':
head.append(flip_coin)
else:
tail.append(flip_coin)
return f'heads: {len(head)}, tails: {len(tail)}'
print(flip_coin())
Upvotes: 0
Reputation: 71454
A simple way to keep track of the counts of each result is to put them in a dict where each entry corresponds to a particular result. collections.defaultdict
is nice for this because it takes care of initializing default values for you:
from collections import defaultdict
import random
results = defaultdict(int)
for _ in range(100):
results[random.choice(['heads', 'tails'])] += 1
for result, count in results.items():
print(f"{result}: {count}")
prints something like:
heads: 58
tails: 42
Upvotes: 0