Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more succinct / pythonic way to do this? (counting longest seq of heads, tails in coin flips)

Tags:

python

Count the longest sequence of heads and tails in 200 coin flips.
I did this - is there a niftier way to do it in python? (without being too obfuscated)

import random

def toss(n):
    count = [0,0]
    longest = [0,0]
    for i in xrange(n):
        coinface = random.randrange(2)
        count[coinface] += 1
        count[not coinface] = 0

        if count[coinface] > longest[coinface]:
            longest[coinface] = count[coinface]      
        #print coinface, count, longest  

    print "longest sequence heads %d, tails %d" %tuple(longest)

if __name__ == '__main__':
    toss(200)

see this for what prompted my playing

like image 696
Steve D Avatar asked Nov 06 '09 17:11

Steve D


1 Answers

def coins(num):
    lst = [random.randrange(2) for i in range(num)]
    lst = [(i, len(list(j))) for i, j in itertools.groupby(lst)]
    tails = max(j for i, j in lst if i)
    heads = max(j for i, j in lst if not i)
    return {1: tails, 0: heads}
like image 198
SilentGhost Avatar answered Oct 05 '22 10:10

SilentGhost