-1

I want to print the whole list up to the element that is given by function,

such as [1,1,2,3,5,8]

def Fib(a):
    b=[ ]
    if a==0:
        b.append(1)
    elif a==1:
        b.append(1)
    else:
        b.append(Fib(a-1)+Fib(a-2))
    print(b)

Fib(6)

I get the error of "unsupported operand type(s) for +: 'NoneType' and 'NoneType'" Thanks in advance, all the helps are appreciated.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Heyyo
  • 23
  • 1
  • 6
  • 2
    use [return](http://stackoverflow.com/questions/7129285/why-would-you-use-the-return-statement-in-python) – syntonym Feb 23 '16 at 20:19
  • you don't have a return statement for starters. – Jay T. Feb 23 '16 at 20:22
  • 1
    It is worth mentioning that recursive Fibonacci [is not very efficient](http://stackoverflow.com/questions/360748/computational-complexity-of-fibonacci-sequence) – OneCricketeer Feb 23 '16 at 20:23
  • OK, thanks for the comments and advices, I added the return statement, actually changed the line print(b) with return b, and after that I print the function itself outside the function, but right now I have the output as : [[[[[[1, 1], 1], [1, 1]], [[1, 1], 1]], [[[1, 1], 1], [1, 1]]]] – Heyyo Feb 23 '16 at 20:28

3 Answers3

1

Could make a generator

def fibGen(n, a=1, b=1):
    while n > 0:
        yield a
        a, b, n = b, a+b, n-1

Run it

>>> [i for i in fibGen(6)]
[1, 1, 2, 3, 5, 8]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

The function requires a return statement. Furthermore, After each conditional statements, a return statement should be present

If n ==0:
     return 0
Elif n ==1: 
    return 1
Else: 
    return fib(n-1) + fib(n-2)
user229044
  • 232,980
  • 40
  • 330
  • 338
Spyke
  • 114
  • 4
  • 1
    Welcome to Stack Overflow! When answering questions, it is often a good idea to leave a little explanation. You can edit your posts, to make them more informative, if you want. To do so, click the "edit" link below your post. – S.L. Barth is on codidact.com Feb 23 '16 at 20:43
  • 1
    While your answer is "correct", it does not attempt to answer the question. You could explain what needs to be in that return statement to achieve the expected output. I don't think a simple return of the calculated fibonacci value or the `b` list will produce `[1,1,2,3,5,8]` – OneCricketeer Feb 23 '16 at 20:44
0
result = {}
def fibo(n):
    if n ==0 :
        result[n] = 0
        return 0
    elif n == 1:
        result[n] = 1
        return 1
    else:
        val = fibo(n-1) + fibo(n-2)
        result[n] = val
        return (val)

fibo(10)
print(result.values())

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
YBathia
  • 894
  • 1
  • 8
  • 18