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