Recursive function going infinite and I can't see why.
Gregory Piñero
gregpinero at gmail.com
Sun Feb 5 00:21:50 EST 2006
Ok, I finally got it working! See below
On 2/4/06, Steven D'Aprano <steve at removethiscyber.com.au> wrote:
> On Sat, 04 Feb 2006 02:18:27 -0500, Gregory Piñero wrote:
> > class Node:
> > def __init__(self):
> > self.arg0=0
> > self.arg1=0
> > self.arg2=0
> > self.arg3=0
>
> You appear to be iterating over these attributes. Hint: as soon as you
> have more than two pieces of data with names like foo0, foo1, foo2...
> you probably want something like this:
>
> def __init__(self):
> self.trees = [0, 0, 0, 0] # they aren't args, they are sub-trees
>
> You are iterating over everything in __dict__ which is probably not what
> you want. Your code has serious side-effects, because you are iterating
> over ALL instance attributes, even the ones which are not nodes.
>
> for varname,value in node.__dict__.items():
> node.__dict__[varname] = value
> # this touches all instance attributes
>
> This is safer:
>
> for index, value in enumerate(node.trees):
> node.trees[index] = value
> # this only touches what you want
Yep, this is what fixed it. Thanks Steve. I turns out that there is
a lot of other stuff in __dict__ that was messing me up and causing
the infinite recursion.
Terry was also kind of right in that I was never hitting my base case,
since I was getting stuck on a var in __dict__ and recursing forever
before I ever got to the base case.
-Greg
More information about the Python-list
mailing list