memo = {}
def f(subproblem):
if subproblem not in memo:
if base_case:
memo[subproblem] = base
else:
memo[subproblem] =recurse_subproblem
return memo[subproblem]
Exemplo de implementação de memoization em Python
Nota: Em geral não implementamos essa operação em Python e utilizamos a função
functools.cache
da biblioteca padrão da linguagem.
def memoization(subproblem):
def inner(*args):
if tuple(args) not in memo:
memo[tuple(args)] = subproblem(*args)
return memo[tuple(args)]
memo = {}
return inner
@memoization
def fibo(n):
if n == 0:
return 0
if n == 1:
return 1
return fibo(n-1) + fibo(n-2)
@memoization
def fat(n):
if n <= 1:
return 1
return n * fat(n-1)
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = dict()
cost_so_far = dict()
came_from[start] = None
cost_so_far[start] = 0
def heuristic(a, b):
"""Manhattan distance on a square grid."""
return abs(a.x - b.x) + abs(a.y - b.y)
while not frontier.empty():
current = frontier.get()
if current == goal:
break
for next in graph.neighbors(current):
new_cost = cost_so_far[current] + graph.cost(current, next)
if next not in cost_so_far or new_cost < cost_so_far[next]:
cost_so_far[next] = new_cost
priority = new_cost + heuristic(goal, next)
frontier.put(next, priority)
came_from[next] = current