I needed a tree data structure in Python copied it from a website and ran into some really strange issues.
If you create an object with two arguements it works, if you use only one argument it fails at print with
RecursionError: maximum recursion depth exceeded while getting the repr of a list
I understand the error, but it is not clear where and why it happens. The code should also work using the default parameter. I know it is mutable.
class node(object):
def __init__(self, value, children = []):
self.value = value
self.children = children
def __repr__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
def add(self, value):
self.children.append(node(value))
#tree = node([1,4,3], [node([2,5,3])]) <-- works
tree = node([1,4,3]) # <-- fails
tree.add([3,4,3])
tree.add([4,4,3])
print(tree)
You had a mutable object in your default argument
def __init__(self, value, children = []):
This results in a single list instance for children
, so when you constructed the second list your list of children is then added to that default list thus every iteration will traverse inside that list, causing this infinite loop.
You should do something like this
def __init__(self, value, children=None):
self.value = value
if children is None:
children = []
self.children = children
Alternatively you can just
self.children = children or []
Both assigns a new list instance which will remove this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With