Hello,

I am trying to write a program that flips a coin until it gets the sequence "heads tails heads" and then stops and says how many flips it took to get that sequence. This is what I have so far:

import random
import time
import string

def coinflip():	
	
	heads = 0
	tails = 0
	flips = 0
	hth = "HTH"

	rec = open('cointoss.txt', 'w')

	N = int(raw_input('Welcome to the Coin Toss!  How many times do you want to flip the coin?: '))

	while (flips < N):
		flip = random.randint(1,2)
		if flip == 1:
			heads += 1
			if heads > 0:
				rec.write('H')
				time.sleep(.1)
				file = open('cointoss.txt', 'r')
				text = file.read()
				file.close()
				search = text.find(hth)

				if search == -1:
					flips += 1
				else:
					flips += 1
					print "needed", flips ," flips to get hth."
					flips = N

			
		else:
			tails += 1
			if tails > 0:
				rec.write('T')
				time.sleep(.1)
				file = open('cointoss.txt', 'r')
				text = file.read()
				file.close()
				search = text.find(hth)
				
				if search == -1:
					flips += 1

				else:
					flips += 1
					print "needed", flips ," flips to get hth."
					flips = N


	print "you got", heads ," heads and", tails ," tails."

The way the code is, it runs to for the full N every time regardless of whether the sequence appears before it runs the full number of times. Why doesn't it stop when the HTH sequence appears? Any help is greatly appreciated.

For heaven sake do us a favor and don't use tabs for your Python indentations. It makes code look ungainly! Use the standard 4 spaces as recommended in the Python style guide. I would love to highlight and copy your code to paste it into my editor for a quick test, but it gets all screwed up in the process!

The Python style guide by GVR ('Mr. Python') himself:
http://www.python.org/peps/pep-0008.html

Note: The story has it that GVR regretted to even mention tabs!

Here:

import random
import time
import string

def coinflip():	
	
    heads = 0
    tails = 0
    flips = 0
    hth = "HTH"

    rec = open('cointoss.txt', 'w')

    N = int(raw_input('Welcome to the Coin Toss!  How many times do you want to flip the coin?: '))

    while (flips < N):
        flip = random.randint(1,2)
        if flip == 1:
            heads += 1
            if heads > 0:
            rec.write('H')
            time.sleep(.1)
            file = open('cointoss.txt', 'r')
            text = file.read()
            file.close()
            search = text.find(hth)

            if search == -1:
                flips += 1
            else:
                flips += 1
                print "needed", flips ," flips to get hth."
                flips = N

			
        else:
            tails += 1
            if tails > 0:
                rec.write('T')
                time.sleep(.1)
                file = open('cointoss.txt', 'r')
                text = file.read()
                file.close()
                search = text.find(hth)
				
                if search == -1:
                    flips += 1

                else:
                    flips += 1
                    print "needed", flips ," flips to get hth."
                    flips = N


    print "you got", heads ," heads and", tails ," tails."

Your program does not work since you are trying to write to and read from the file at the same time. Store your temporary results in a string and then write to the file at the end ...

import random
import time

def coinflip():
    """flip the coin until you get an HTH pattern"""
    heads = 0
    tails = 0
    flips = 0
    hth = "HTH"

    # might be easier to set N to something like 50
    N = int(raw_input('Welcome to the Coin Toss!  '\
        'How many times do you want to flip the coin?: '))
    # optional, make sure N is large enough
    if N < 20:
        N = 20

    # create an empty string
    text = ""
    while (flips < N):
        flip = random.randint(1, 2)
        if flip == 1:
            heads += 1
            if heads > 0:
                text += 'H'
                time.sleep(.1)
                search = text.find(hth)
                #print flip, text, search  # testing
        else:
            tails += 1
            if tails > 0:
                text += 'T'
                time.sleep(.1)
                search = text.find(hth)
                #print flip, text, search  # testing
                
        print flip, text, search  # for testing only
        flips += 1
        if search != -1:
            print "needed", flips ," flips to get hth."
            flips = N

    print "you got", heads ," heads and", tails ," tails."
    rec = open('cointoss.txt', 'w')
    rec.write(text)
    rec.close()


# used to test module coinflip as a standalone program
# you can leave these lines in the module
if __name__ == '__main__':
    coinflip()

Your program does not work since you are trying to write to and read from the file at the same time. Store your temporary results in a string and then write to the file at the end ...

import random
import time

def coinflip():
    """flip the coin until you get an HTH pattern"""
    heads = 0
    tails = 0
    flips = 0
    hth = "HTH"

    # might be easier to set N to something like 50
    N = int(raw_input('Welcome to the Coin Toss!  '\
        'How many times do you want to flip the coin?: '))
    # optional, make sure N is large enough
    if N < 20:
        N = 20

    # create an empty string
    text = ""
    while (flips < N):
        flip = random.randint(1, 2)
        if flip == 1:
            heads += 1
            if heads > 0:
                text += 'H'
                time.sleep(.1)
                search = text.find(hth)
                #print flip, text, search  # testing
        else:
            tails += 1
            if tails > 0:
                text += 'T'
                time.sleep(.1)
                search = text.find(hth)
                #print flip, text, search  # testing
                
        print flip, text, search  # for testing only
        flips += 1
        if search != -1:
            print "needed", flips ," flips to get hth."
            flips = N

    print "you got", heads ," heads and", tails ," tails."
    rec = open('cointoss.txt', 'w')
    rec.write(text)
    rec.close()


# used to test module coinflip as a standalone program
# you can leave these lines in the module
if __name__ == '__main__':
    coinflip()

Cool, I'll try that! I thought that would pose a problem somewhere. Thanks!

This question has already been answered. Start a new discussion instead.