fortin icon

Fibonacci generator (recursive)

fortin | PRO | 11/26/20 10:13:56 AM UTC (Edited) | 0 ⭐ | 532 👁️ | Never ⏰ | []
Python |

1.81 KB

|

None

|

0 👍

/

0 👎

from functools import lru_cache
 
@lru_cache(maxsize=1000)
 
def fibonacci(n):
    if n == 1 or n == 0:
        return 1
    if n == 2:
        return 2
    if n > 2:
        return (fibonacci(n-1) + fibonacci(n-2))
 
 
def ordinal(n):
    return "%d%s" % (
        n,
        "tsnrhtdd"[(n / 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4],
    )
 
 
while True:
    try:
        while True:
            try:
                n = int(input("Pick your Fibonacci number: "))    
                if type(n) == int:
                    break
            except Exception:
                print("It must be a positive integer")
 
        if n < 1:
            raise ValueError("It must be a positive integer")
        else:
            while True:
                try:
                    q = input("Series? [y/n] ")
                    if q == "y" or q == "n":
                        break
                    print("Your answer must be 'y' or 'n'")
                except:
                    raise TypeError("Your answer must be 'y' or 'n'")
 
            if q == "y":
                try:
                    for n in range(1,n+1):
                        print(n, ":", fibonacci(n-1))
                except RecursionError:
                    print("Your computer doesn't have the capacity for such calculations!")
            elif q == "n":
                print(f"The {ordinal(n)} Fibonacci number is {fibonacci(n-1)}.")
            else:
                raise ValueError("answer must be y or n")
    except RecursionError:
        print("Your computer doesn't have the capacity for such calculations!")
    quit = input("Another one? [y/n] ")
    if quit != "y" and q != "n":
        print("Your answer must be 'y' or 'n'")
    elif quit == "y":
        continue
    else:
        break
 

Comments