Advertisement
fortin

Fibonacci generator (recursive)

Mar 10th, 2020 (edited)
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. from functools import lru_cache
  2.  
  3. @lru_cache(maxsize=1000)
  4.  
  5. def fibonacci(n):
  6.     if n == 1 or n == 0:
  7.         return 1
  8.     if n == 2:
  9.         return 2
  10.     if n > 2:
  11.         return (fibonacci(n-1) + fibonacci(n-2))
  12.  
  13.  
  14. def ordinal(n):
  15.     return "%d%s" % (
  16.         n,
  17.         "tsnrhtdd"[(n / 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4],
  18.     )
  19.  
  20.  
  21. while True:
  22.     try:
  23.         while True:
  24.             try:
  25.                 n = int(input("Pick your Fibonacci number: "))    
  26.                 if type(n) == int:
  27.                     break
  28.             except Exception:
  29.                 print("It must be a positive integer")
  30.  
  31.         if n < 1:
  32.             raise ValueError("It must be a positive integer")
  33.         else:
  34.             while True:
  35.                 try:
  36.                     q = input("Series? [y/n] ")
  37.                     if q == "y" or q == "n":
  38.                         break
  39.                     print("Your answer must be 'y' or 'n'")
  40.                 except:
  41.                     raise TypeError("Your answer must be 'y' or 'n'")
  42.  
  43.             if q == "y":
  44.                 try:
  45.                     for n in range(1,n+1):
  46.                         print(n, ":", fibonacci(n-1))
  47.                 except RecursionError:
  48.                     print("Your computer doesn't have the capacity for such calculations!")
  49.             elif q == "n":
  50.                 print(f"The {ordinal(n)} Fibonacci number is {fibonacci(n-1)}.")
  51.             else:
  52.                 raise ValueError("answer must be y or n")
  53.     except RecursionError:
  54.         print("Your computer doesn't have the capacity for such calculations!")
  55.     quit = input("Another one? [y/n] ")
  56.     if quit != "y" and q != "n":
  57.         print("Your answer must be 'y' or 'n'")
  58.     elif quit == "y":
  59.         continue
  60.     else:
  61.         break
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement