Arjun Verma
Arjun Verma

Reputation: 53

Recursion not working in python

I am trying to print a series in python which actually like Fibonacci but instead of adding you have to multiply.

My code is :

def robLan(n):
    if n > 3:
        robLan(n -1) * robLan(n - 2)

    elif n == 1:
        return 1

    elif n == 2:
        return 2

    elif n == 3:
        return 2

list = []
for i in range(1,10):
    z =  robLan(i)
    list.append(z)
print list  

These are the error I get:

File "C:\Users\Arjun's\Documents\Aptana Studio 3 Workspace\List\com\__init__.py", line 16, in <module>
    z =  robLan(i)
  File "C:\Users\Arjun's\Documents\Aptana Studio 3 Workspace\List\com\__init__.py", line 3, in robLan
    robLan(n -1) * robLan(n - 2)
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

What is wrong here?

Upvotes: 3

Views: 169

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121494

Your function doesn't return the recursive call:

if n > 3:
    robLan(n -1) * robLan(n - 2)

Without a return statement here, your function ends without an explicit return and None is returned instead:

>>> robLan(4) is None
True

The above should have returned 4 (roblan(3) * roblan(2) gives 2 * 2 is 4). For any starting value of 5 or over the function uses more than one level of recursion and a None return value ends up being used for multiplication.

Add return:

if n > 3:
    return robLan(n - 1) * robLan(n - 2)

Your statements can be simplified:

def robLan(n):
    if n > 2:
        return robLan(n - 1) * robLan(n - 2)
    return n

Your sample loop then generates:

[1, 2, 2, 4, 8, 32, 256, 8192, 2097152]

Upvotes: 5

Serjik
Serjik

Reputation: 10931

This is complete corrected code:

def robLan(n):
    if n > 3:
        return robLan(n -1) * robLan(n - 2)

    elif n == 1:
        return 1

    elif n == 2:
        return 2

    elif n == 3:
        return 2

list = []
for i in range(1,10):
    z =  robLan(i)
    list.append(z)
print list 

Upvotes: 0

JeremyWang
JeremyWang

Reputation: 31

you should return a value when n > 3

Upvotes: 1

Related Questions