beginner code problem

Schüle Daniel uval at rz.uni-karlsruhe.de
Sat Jun 3 01:35:09 CEST 2006


Hello

> Here's the code I wrote:
> 
> import random
> 
> flip = random.randrange(2)
> heads = 0
> tails = 0
> count = 0
> 
> while count < 100:
> 
>     if flip == 0:

flip never changes again
it's not reassigned in the while loop

>         heads += 1
>     
>     else:
>         tails += 1
>     
> 
>     count += 1
>     
>     
> 
> print "The coin landed on heads", heads, 'times ' \
>         "and tails", tails, 'times'
> 


in case you know how many times to iterate
it's better to use for loop (in python and eq C also)

from random import randrange as flip
result = [0,0]
for i in range(100):
	result[flip(2)] += 1

or

from random import randrange as flip
result = {"head":0,
	  "tail":0}
for i in range(100):
	result[["head","tail"]flip(2)] += 1

or

 >>> class Coin:
...     def flip(self):
...             import random
...             return ("head", "tail")[random.randrange(2)]
c = Coin()
result = {"head":0,"tail":0}
for i in range(100):
	result[c.flip()] += 1

or many many more
the important thing is .. to know what is the
most suitable data representation for you

is it throw-away-code or is this going to be read
by other people .. etc

hth, Daniel



More information about the Python-list mailing list