[Tutor] Help with objects

Vincent Wan wan at walrus.us
Tue Nov 22 06:04:41 CET 2005


Thank you bob. I fixed the errors where I tried to index a dictionary  
with name()
so so that they say name[]

>> Beyond the error I'm still not sure I understand how to make and
>> use a tree data structure using objects.

There is a new error as well

Traceback (most recent call last):
   File "/Users/Wally/obj_tree1.py", line 28, in -toplevel-
     currentTree = Tree()
   File "/Users/Wally/obj_tree1.py", line 21, in __init__
     nodeList[0] = Tree.Node(0)    # adds a root node 0 to the tree
NameError: global name 'nodeList' is not defined

Code with error bob fixed fixed throughout

# obj_tree1.py

import random

# constants that control the simulation
NUMBER_REPS = 10        # run's the simulation
MAX_LINAGES = 10        # number of species in each run
BRANCHING_PROBABILITY = 0.5

class Tree(object):
     numLinages = 0    # keeps track of how many nodes there are
     nodeList = {}    # keeps track of the nodes
     class Node(object):
         def __init__(self, name):
             self.name = name    # an integer
             self.alive = True
             self.descendents = {}    # nodes descending from self
             Tree.numLinages += 1    # records node creation
             Tree.nodeList[self.name] = self    # makes node  
accesable from tree
     def __init__(self):
         nodeList[0] = Tree.Node(0)    # adds a root node 0 to the tree
     def AddBranch(self, offspring):
         self.descendents[offspring] = Tree.Node(offspring)    # adds  
a descendent node
     def NumLinages( ):
         return Tree.numLinages
     NumLinages = staticmethod(NumLinages)

currentTree = Tree()

for i in range(NUMBER_REPS):
     j = 0
     while j <= currentTree.NumLinages():   # checks all node because  
their names are sequential integers
         if j.alive:
             if random.random() >= BRANCHING_PROBABILITY:
                 currentTree.AddBranch(j, (currentTree.NumLinages() +  
1)) # creates a new node
         j += 1

Thank you for the help


Vincent Wan

------------------------------------------------------------------------ 
--------------
PhD Candidate
Committee on the Conceptual and Historical Studies of Science
University of Chicago

PO Box 73727
Fairbanks, AK 99707

wan AT walrus DOT us (change CAPS to @ and . )



More information about the Tutor mailing list