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?

4

3 回答 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]
于 2013-09-07T12:32:46.390 回答
1

当 n > 3 时你应该返回一个值

于 2013-09-07T12:47:41.147 回答
0

这是完整的更正代码:

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 
于 2013-09-07T17:53:57.553 回答