Newbie: Help Figger Out My Problem

qwweeeit at yahoo.it qwweeeit at yahoo.it
Tue Jun 28 06:42:44 EDT 2005


Hi,
About the error, you already got the answer from the "experts".
Beeing almost a newbie, I tried instead an elaboration of your example,
using lists.
Furthermore I timed the two methods and to my surprise the "list
method" takes longer:

# Head_Tail.py
import random, time
nStart= time.time()

# --------------------------------------
# profiling: 15.3 seconds
heads = 0
tails = 0
flips = 0
while flips < 999999:
    coin = random.randrange(0, 2)
    if coin == 0:
        heads = heads + 1
    else:
        tails = tails + 1
    flips = flips + 1
print  "heads",heads
print  "tails",tails
print  "flips",flips
nSecondsTM=time.time()-nStart
print "seconds taken by the traditional method",nSecondsTM
#---------------------------------------

# profiling: 16.8 seconds
nFlips=0
lFlip=[]        # list initialization
while nFlips < 999999:
        lFlip.append(random.randrange(0, 2)) # filling the list
        nFlips += 1

print  "heads",lFlip.count(0)
print  "tails",lFlip.count(1)
print  "flips",nFlips
print "seconds taken by the list method",time.time()-nStart-nSecondsTM
# --------------------------------------

Perhaps there are other more clever approaches...
Bye.




More information about the Python-list mailing list