Recursion bug...

ex_ottoyuhr ex_ottoyuhr at hotmail.com
Wed Nov 30 21:45:55 EST 2005


To start with, I'm new at Python, so if this is something relatively
ordinary or a symptom of thinking in C++, I apologize...

Anyhow, I'm currently trying to write a means of generating
genetic-programming functions in Python; the details would be a little
much for a Usenet post, but suffice it to say that it would involve
trees of objects with an opcode and a variable number, between in this
case 0 and 3, of 'arguments' -- also objects of the same sort. As a
function to implement them, I'm doing something to the effect of this:

max_opcode = ( 20, )
max_with_arguments = ( 15, )

class TreeCommand:
    opcode = 0
    children = []
    def __init__(self, anOpcode) :
        opcode = anOpcode

def MakeTreeCommand( maxdepth, currdepth ) :
    if ( currdepth == 0 ) :
        toRet = TreeCommand(random.randint(0, max_with_arguments[0])
    elif ( maxdepth == currdepth ) :
        toRet = TreeCommand(random.randint(max_with_arguments[0]+1,
max_opcode[0]))
    else :
        toRet = TreeCommand(random.randint(0, max_opcode[0]))

    if ( toRet.opcode <= max_with_arguments[0] ) :
        childrenRequired = something_greater_than_0
    else :
        childrenRequired = 0

    generated = 0

    while ( generated < childrenRequired ) :
        toRet.children.append(MakeTreeCommand(maxdepth, currdepth + 1))

    return toRet

Sorry to have given such a long example... But anyways, the problem is
that, while I think this should generate a number of children for each
toRet equivalent to the required number of children, it's actually
appending all children generated in the function to the 'root' toRet
rather than to child functions -- so that if I ask for a tree with
depth 2, and the root would have 2 arguments, the first child would
have 1, and the second child would have 2, the result is a root with a
5-argument-long children and two child functions with 0-argument ones.
There's some other strange stuff going on here, too; in particular,
with one particular opcode, toRet is assigned a member 'value' which is
randomly generated between 0 and 10,000. All toRets assigned value seem
to be ending up with the same result...

Could anyone explain what I'm doing wrong? I'm beginning to suspect
that Python scope rules must not work like my native C++; have I made a
common mistake?




More information about the Python-list mailing list