[Tutor] Random Variable at root

Eric Walstad eric at ericwalstad.com
Wed Oct 4 03:42:03 CEST 2006

Hi Hugo,

halamillo wrote:
> I;m starting this
> code so I can assign either a 0 or a 1 at a root node that I will later 
> evolve throughout a tree, but for some reason it is not printing the 
> rootState value.

It's not clear to me which variable you are trying to assign a zero or 
one.  Here's my guess at how you are wanting to use your class:

 >>> import random
 >>> from random import random as rnd
 >>> class Root:
...     """Single Node in a Tree"""
...     def __init__(self, rootState):
...         self._rootState = rootState
...         # random choice for root state from a list
...         self._rootState = random.choice([0, 1])
...     def __str__(self):
...         return str( self._rootState )
 >>> rs = 99
 >>> r = Root(rootState=rs)
 >>> print rs
 >>> print r
 >>> print "The character state at the root is %0.f" % float(r._rootState)
The character state at the root is 0

   1. I removed the loop in your __init__method because it was simply 
making two random choices when one should do.
   2. I assigned the random choice to the class' _rootState attribute, 
not the rootState argument to the __init__ method.  You can also make a 
"rootState" property of the class so that the last line, above, would 
look like:
 >>> print "The character state at the root is %0.f" % float(r.rootState)

I hope that helps.


More information about the Tutor mailing list