Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. import time
  2.  
  3. # store recent function calls into a dictionary
  4. cache_values = {}
  5. def fibonacci(n):
  6. # check if the given number is less than 0
  7. if n < 0:
  8. # output an error message stating that the number given is incorrect
  9. raise ValueError("Has to be a positive integer!")
  10. # check if the value is in our dictionary
  11. if n in cache_values:
  12. # return that value if it is
  13. return cache_values[n]
  14.  
  15. # if that fails you will need to compute the value
  16. if n == 0:
  17. value = 0
  18. # check if the value is equal to 1 or 2
  19. elif n == 1 or n == 2:
  20. # store the value 1 into a variable to later store it in our dictionary
  21. value = 1
  22. # otherwise if the value is greater than 2
  23. elif n > 2:
  24. # get the sum of the previous 2 terms and store it into our value variable
  25. value = (fibonacci(n - 1) + fibonacci(n - 2))
  26.  
  27. # return and store the value into our dictionary above
  28. cache_values[n] = value
  29. return value
  30.  
  31. if __name__ == "__main__":
  32. start = time.time()
  33. print("\nInitializing fibonacci please wait...")
  34. print(fibonacci(100))
  35. load_time = round(time.time() - start, 4)
  36. print("\nThis took: {}.".format(load_time))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement