Reputation:
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
Upvotes: 0
Views: 3833
Reputation: 236150
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".
Upvotes: 1
Reputation: 388403
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
Upvotes: 5