I have a segment tree which holds data for a range of numbers (data structure chosen here). Here’s the code:
class SegmentTree:
def __init__(self, N):
def _init(b, e):
if b is e:
data = foo() # No dependency
return Node(b, e, data, None, None)
else:
mid = (b + e ) / 2
L = _init(b, mid)
R = _init(mid + 1, e)
data = foo() #Data depends on L and R
return Node(b, e, data, L, R)
self.root = _init(1, N)
This fails for N around 300 with a max recursion depth exceeded error. Is there a way to create the tree iteratively instead of recursively?
The real problem is not the recursion depth of your algorithm, which should be about 10 for a value like 300, but that you are comparing numbers with
is. Theiskeyword checks for object identity, while==checks for equality:Because of that your
ifcondition that should terminate the recursion will never be true and the function will keep recursing, even ifbandeare equal.If you change the
ifthis problem should go away:For small numbers the problem might not occur because Python “caches” and reuses the objects for ints up to a certain size.