0

I couldn't decide if the following function is iterative or recursive,

I think it's recursive because it repeats itself, but since it has a while loop I have doubts,

def function(n):
    while((n!=1) and (n!=0)):
        return function(n-1) + function(n-2)
    return n
2
  • It's recursive, because function calls itself. That's the definition of recursion. Also see my comment. Commented Oct 28, 2012 at 1:41
  • The question does not make sense, first because "iterative" and "recursive" are not mutually exclusive, and second because there is no good reason to write a while loop that simply contains an unconditional return. Commented Dec 11, 2022 at 16:03

2 Answers 2

5

It’s recursive as it calls itself. Recursivity (is that a word) does not mean that there are no “standard” iterations allowed.

And btw. in your case, there are no further iterations. The while loop is essenially identical to a simple if statement, as you immediately return in the first loop. So you could write it like this:

def function(n):
    if (n != 1) and (n != 0):
        return function(n - 1) + function(n - 2)
    return n
Sign up to request clarification or add additional context in comments.

Comments

1

A function can have a loop and be recursive. A function is called recursive if it calls itself, but be aware that a function doesn't necessarily need to call itself to be considered recursive, take a look at this example:

def even(n):
    return True if n == 0 else odd(n - 1)

def odd(n):
    return False if n == 0 else even(n - 1)

even(10)
> True
odd(10)
> False

The above functions are "mutually recursive".

1 Comment

Well, you would still say that they call themselves—indirectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.