I'm trying to write a coin-flipping program.

I can get the program to produce a random coin flip result (represented as either "h" or "t") but I want to add the individual result to an ever expanding string.

For example, the first result would be "h"
and the big string would be : h
The second flip would be "t"
and the big string would CHANGE to: ht

But, I can figure out how to add the strings together.

here's my code:

import random
numflips = 1
def flip():
	cheads, ctails, = 0,0
	cflips = random.randrange(2)
	if cflips == 0:
		cheads += 1
		return 'h'
		ctails += 1
		return 't'
numflips +=1	
while flip() == 't' or 'h':

when the sequence "hth" appears, I want the program to stop and tell me how many flips it took to get there. With this, I am totally lost. Does Python have a "find" command :-P?

Thanks for any help.

9 Years
Discussion Span
Last Post by scru

you can do something like:

big_string = ""
while not big_string.endswith("hth"):
    big_string += flip()
flips = len(big_string)

By find command I assume you mean find an occurence of a substring withing a string? Yes, just do s.find(sub, start, end) where s is the string, and sub is the substring that you want to find. The start and end indexes are both optional and can be omitted

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.