0, 1, 1, 2, 3, 5, 8, 13, 21, …
fibonacci(0)
is defined to be 0
fibonacci(1)
is defined to be 1
fibonacci(n) = fibonacci(n – 1) + fibonacci(n – 2)
fibonacci(0)
is 0, andfibonacci(1)
is 1.fibonacci
¶fibonacci
is not a recursive callfibonacci
’s block are recursive fibonacci(0)
is 0
and fibonacci(1)
is 1
def fibonacci(n):
if n in (0, 1): # base cases
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
fibonacci
¶for n in range(41):
print(f'Fibonacci({n}) = {fibonacci(n)}')
fibonacci
¶fibonacci
results in two more recursive callsfibonacci(20)
requires 21,891 calls fibonacci(30)
requires 2,692,537 calls!fibonacci(31)
requires 4,356,617 callsfibonacci(32)
requires 7,049,155 calls!©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.