memoisation.py

Created by schraf

Created on October 13, 2020

475 Bytes

Exemple tiré de Wikipédia


from time import monotonic

# Nieme nombre de Fibonacci
N = 30

# version classique

def fib(n):
   if n == 1 or n == 2: return 1
   return fib(n-1) + fib(n-2)

t = monotonic()
fib(N)
print(monotonic() - t)

# version memoisation

table = {}

def memofib(n):
  global table
  if n not in table:
      if n == 1 or n == 2: table[n] = 1
      else: table[n] = memofib(n-1) + memofib(n-2)
  return table[n]

t = monotonic()
memofib(N)
print(monotonic() - t)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.