[Tutor] Finding the "streaks" in heads/tails list

Kent Johnson kent37 at tds.net
Wed Oct 1 23:27:07 CEST 2008


On Wed, Oct 1, 2008 at 4:56 PM, Alec Henriksen <alecwh at gmail.com> wrote:
> Hello,
>
> I thought it'd be cool to write a program for my logic/critical thinking
> class, and right now we're evaluating randomness - and the deception of
> it. A previous post inspired it - coin flipping.
>
> So, I've written a program that flips a coin 1000 times and records it
> all in a dictionary, like this:
>
> # 0 = heads, 1 = tails
> flips = [0,0,0,1,0,1,0,0,1,1,1,1,1,0,0,1,0,1,0,1,0,1]
>
> What I want to do, is find out the largest "streak" of digits. In the
> above example, the streak would be 5, because there are 5 tails flips in
> a row.
>
> I've thought about this, and it seems like regular expressions would be
> needed.

Regular expressions are for processing strings, not loops.

I would loop through the list with a for loop, keeping track of the
last value seen and the current count. If the current value is the
same as the last, increment the count; if it is different, reset the
count.

You don't actually have to put the flips into a list, you could count
the runs directly as you make the flips.

Kent


More information about the Tutor mailing list