Home > Net >  Why does using `any` here cause this program to exceed recursion depth, but using a `for` loop doesn
Why does using `any` here cause this program to exceed recursion depth, but using a `for` loop doesn

Time:11-08

Input

sum_possible(2017, [4, 2, 10]) # -> False

Usage of any which causes RecursionError: maximum recursion depth exceeded

def sum_possible(amount, numbers, cache = None):
  if cache is None:
    cache = {}
  if amount in cache:
    return cache[amount]
  if amount == 0:
    return True
  if amount < 0:
    return False
  cache[amount] = any(sum_possible(amount - number, numbers, cache) for number in numbers)
  return cache[amount]

Usage of a for loop which solves the solution

def sum_possible(amount, numbers, cache = None):
  if cache is None:
    cache = {}
  if amount in cache:
    return cache[amount]
  if amount == 0:
    return True
  if amount < 0:
    return False
  
  for number in numbers:
    if sum_possible(amount - number, numbers, cache):
      cache[amount] = True
      return True
  
  cache[amount] = False
  return False

CodePudding user response:

The default recursion limit is 1000 calls. Although it's called a "recursion limit", it's actually the maximum depth of all nested function calls -- we just describe it in terms of recursion because it's hard to reach the limit without recursion -- you would need hundreds of different functions calling each other. The most common reason for exceeding the recursion limit is "infinite" recursion (e.g. failing to detect the base case properly).

In the version with a for loop, that allows 1000 recursive levels. Along with the cache, this is enough for your test case.

In the version that uses any(), the effective recursion limit is cut in half, because each recursive call is inside a call to any(). And this isn't enough.

  • Related