Here's a simple Python function that uses recursion to calculate the nth Fibonacci number:
main.py107 chars6 lines
To use this function, simply call fibonacci(n)
with the number n
representing the index of the desired Fibonacci number. For example, to calculate the 10th Fibonacci number:
main.py27 chars2 lines
Keep in mind that this implementation has exponential time complexity, meaning it's not very efficient for large values of n
. There are more optimized algorithms for calculating Fibonacci numbers, such as using a loop or memoization, but this recursive implementation is the most straightforward to understand.
gistlibby LogSnag