My main concern with recursion is the recursion limit in Python, which I think is 1000. Taking this into account, I want to discuss two scenarios:
Scenario 1: Applying recursion for a balanced tree (binary)
For example, to search the maximum value in a tree:
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def max(root):
max_left = max(root.left)
max_right = max(root.right)
if max_left > root.value and max_left > max_right:
return max_left
if max_right > root.value and max_right > max_left:
return max_right
else:
return root.value
Here, the maximum number of calls in the stack at any given time will be the height of the tree, which is log_2(n) where n is the number of elements in the list. Given that the limit in Python is 1000 calls, the tree could store up to 2^1000 (or 2^999) elements without reaching the call limit. For me, that is not a real limitation so I assume we are OK using recursion here.
Scenario 2: Applying recursion for a list
A dummy example would be computing the max of a list, so that we return the max between the head of the list and the result of the same function over the rest of the list:
def max(l):
if len(l) == 1:
return l[0]
max_tail = max(l[1:])
if l[0] > max_tail:
return l[0]
else:
return max_tail
Output:
>>> max(list(range(998)))
997
>>> max(list(range(999)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in max
File "<stdin>", line 4, in max
File "<stdin>", line 4, in max
[Previous line repeated 995 more times]
File "<stdin>", line 2, in max
RecursionError: maximum recursion depth exceeded while calling a Python object
So my understanding is that for lists recursion is not a reasonable option, since it cannot generally process lists larger than 999 (or even less, depending on the stack trace).
Now, my questions:
- Is it reasonable to use recursion to process balanced trees?
- Is it true that for most problems it is just not an option (lists, non-balanced trees, etc)?
- Anything else that I should take into account here? I am just trying to learn more about when recursion is the good option in general when using Python.