Ad

The domain of the Fibonacci sequence is the non-negative integers. Test for invalid inputs and for performance.

Code
Diff
  • def fibonacci(n):
        if type(n) is not int or n < 0:
            return None
        def _fibonacci(n, a=0, b=1):
            if not n: return 0
            if n == 1: return b
            else:
                return _fibonacci(n-1, b, a+b)
        return _fibonacci(n)
    • def fibonacci(n, a=0, b=1):
    • if n == 0: return 0
    • if n == 1: return b
    • else:
    • return fibonacci(n-1, b, a+b)
    • def fibonacci(n):
    • if type(n) is not int or n < 0:
    • return None
    • def _fibonacci(n, a=0, b=1):
    • if not n: return 0
    • if n == 1: return b
    • else:
    • return _fibonacci(n-1, b, a+b)
    • return _fibonacci(n)