1

I'm new to python and I'm trying to create a coinflip loop which will keep flipping and counting the number of flips until the number of heads = the number of tails, where it will stop and print the total number of flips it took to reach that. I'm trying to get the results in order to work on my maths coursework, but I cannot seem to figure out how to get it to stop or print the results, and when I do it prints 0. Here is the code I have so far:

import random heads = 1 tails = sum(random.choice(['head', 'tail']) == 'tail' count = 0 while True: coinresult = random.randint(1, 2) if heads == tails: break print("The number of flips was {count}".format(count = heads + tails)) 
2
  • You are essentially doing a random walk. It can take a long time for it to terminate. I ran James Kent's algorithm 20 time and had two walks in the thousands. Commented Oct 3, 2014 at 8:53
  • i ran the walk recursively 100 times, the average run was 360ish, as you say the highest was in the thousands Commented Oct 3, 2014 at 9:31

3 Answers 3

1

not sure what is going on with your indentation but try this:

import random heads = 0 #initialize the count variables tails = 0 while True: coinresult = random.randint(1, 2) #flip coin if coinresult == 1: #if result = 1 then increment heads counter heads += 1 elif coinresult == 2: #if result = 2 then increment tails counter tails += 1 if heads == tails: #check if counts are equal and break loop if they are break print("The number of flips was {count}".format(count = heads + tails)) 
Sign up to request clarification or add additional context in comments.

Comments

0
import itertools as it import random def flips(): while True: yield (random.getrandbits(1)<<1) - 1 def cumsum(seq): s = 0 for i in seq: s += i yield s def length(seq): n = 0 for _ in seq: n += 1 return n print("The number of flips was {}".format(length(it.takewhile((0L).__cmp__, cumsum(flips()))))) 

Comments

0

I think this will be a nice implementation

import random s = 0 iteration = 0 while True: coin = random.sample([-1,1], 1)[0] s = s + coin iteration = iteration + 1 if s == 0: break print(iteration) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.