Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Iterative and Recursive Fibonacci

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Iterative and Recursive Fibonacci. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

IDT services may use sequence calculations in scheduling and validation logic. Implement a function that computes the nth Fibonacci number using either an iterative or a recursive strategy.

Define the sequence as F(0) = 0, F(1) = 1, and F(n) = F(n - 1) + F(n - 2) for n > 1.

Your function must accept a non-negative integer n and a method string. If method is "iterative", compute the result with a loop. If method is "recursive", compute it with direct recursion. Return the Fibonacci value as an integer.

Formal Specification

  • Input: n, an integer from 0 through 30, and method, either "iterative" or "recursive".
  • Output: The integer value of F(n).
  • Do not use a library Fibonacci implementation.

Constraints

  • 0 <= n <= 30
  • method is either "iterative" or "recursive"
  • F(0) = 0 and F(1) = 1

Function Signature

def fibonacci(n, method):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output