Irhad Fejzic - 6 months ago 45

Python Question

I can easily find the number of heads out of 100 and the chances of coin flipping heads out of 100 flips. That code is below. However, I can't figure out how to easily get the odds of coin flipping heads 10 times *in a row*.

`import random`

n = int(input("Enter the number of flips: "))

sum = 0

heads = 0

tails = 0

for n in range(1, n + 1):

number = random.randrange(0,2)

if number == 0:

heads += 1

else:

tails += 1

sum += number

odds = sum / n

print("No. of heads: ", heads)

print("No. of tails: ", tails)

print("Odds: ", odds)

Answer

You need to flip the coin 10 times, but only report success if they *all* come up heads. Do this with reverse logic: if any one comes up tails, set your flag to False.

```
all_heads = True
for i in range(10):
number = random.randrange(0,2)
if number != 0:
all_heads = False
```

Or, more succinctly

```
all_heads = True
for i in range(10):
all_heads &= random.randrange(0,2) == 0
```

... and even more pythonic

```
all_heads = all(random.randrange(0,2) == 0 for i in range(10))
```

Whichever you choose, you'll need to do it enough times to approximate a statistical universe. Since you expect only one success in 1024 trials, you'll want on the order of 10,000 - 100,000 trials. Count the number of successes, divide by the number of trials. You already know how to do that part.

**SPOILER:**

Given the length of the run of heads, **n**, and the number of trials, this reduces to

```
print (sum(all(random.randrange(0,2) for _ in range(n)) \
for _ in range(trials)) \
/ float(trials) )
```

Welcome to Python. :-)