Recursion bug...

Devan L devlai at gmail.com
Wed Nov 30 22:10:38 EST 2005


ex_ottoyuhr wrote:
> 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:
>
> [ex_ottoyuhr's code]
>
> 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?

Well, for one, in your __init__ method, you never do anything with
anOpcode. You simply assign the name 'opcode' to anOpcode. The reason
why everything is the same is that you're accessing
TreeCommand.children or Treecommand.opcode, which is shared by all
instances unless you assign to it. And you never increment generated,
so I don't see why the while loop would ever end, unless you
intentionally wanted that. Try this code instead:

max_opcode = 20
max_with_args = 15

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

def MakeTreeCommand(depth, maxdepth) :
    if depth == 0:
        command = TreeCommand(random.randint(0, max_with_args)
    elif depth == maxdepth:
        command = TreeCommand(random.randint(max_with_args+1,
max_opcode))
    else:
        command = TreeCommand(random.randint(0, max_opcode))

    if command.opcode <= max_with_args:
        children_required = something_greater_than_0
    else:
        children_required = 0

    generated = 0

    for i in range(children_required):
        command.children.append(MakeTreeCommand(depth+1, maxdepth))

    return command




More information about the Python-list mailing list