How do you write code to implement a recursive fibonacci algorithm?

def recursiveFib(x):  x = int(x)  if x == 0:    return (0)  elif x == 1 or x == 2:    return (1)  elif x > 2:    return (recursiveFib(x-2)+recursiveFib(x-1))     print ("Please enter a number of fibonacci numbers required... (recursion)")max = int(input())print (recursiveFib(max))def iterativeFib(x):  x = int(x)  if x <= 1:    return (x)  else:    previous = 0    current = 1    i = 2    while i <= x:      print (current)      nextOne = current + previous      previous = current      current = nextOne      i = i + 1    return (current)   print ("Please enter a number of fibonacci numbers required... (iterative)")max = int(input())print (iterativeFib(max))         Here is an example of how to implement a recursive algorithm. We have two functions (one recursive and one that isn't). The second algorithm can be used to verify that the first algorithm has worked. Recursion is a function that calls itself. The purpose of recursion is to write algorithms using less code. Recursion can be thought of as an onion, it has many layers and it isn't until you peel off all the layers you get the answer.

Answered by Jazir L. Python tutor

1204 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

h


What are recursive functions and when should they be used?


How do I check if a number is prime using a python program?


Whats is the difference between a function and a procedure?


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo
Cookie Preferences