3

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?

1
  • 1
    You're missing return in the first if block. Commented Sep 7, 2013 at 12:32

3 Answers 3

5

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]
Sign up to request clarification or add additional context in comments.

Comments

1

you should return a value when n > 3

Comments

0

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 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.