1
def fibonacci(n): 
    lst = []
    if n == 0:   
        return 0  
    elif n == 1:  
        return 1  
    else :  
        f = fibonacci(n - 1) + fibonacci(n - 2)
        return f

h = fibonacci(4)

but I wnat to get a list like this : [0, 1, 1, 2, 3, ......] how to get it?

jpp
  • 147,904
  • 31
  • 244
  • 302
Eric
  • 143
  • 1
  • 6
  • @Kasramvd, I get why this is marked as a duplicate. But, equally, it's not obvious whether OP wants the best solution, or wants to learn how to return the results of a function applied to a range. In the latter case, `map` is the solution. Still maybe a dup, but a different one. – jpp May 08 '18 at 12:05
  • 1
    @jpp I think you can find answer of all those questions in mentioned dups but if the question is about *returning the results of a function applied to a range*, OP should have mentioned that in title or question body. Although, I added three duplicates that shows how much this question's been asked before. – Mazdak May 08 '18 at 12:09
  • @Kasramvd, OP may not know about `map` or `range`, so probably doesn't have the necessary vocabulary. But I do like the dup targets, they should remain :). – jpp May 08 '18 at 12:12

3 Answers3

1

This is an extremely inefficient solution, but with your current logic you can simply use map with list:

h = list(map(fibonacci, range(10)))

print(h)

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
jpp
  • 147,904
  • 31
  • 244
  • 302
0
def fibonacci(n):
    lst = [0, 1]
    if n == 0:
        return [0]
    for i in range(2, n+1):
        lst.append(lst[i - 1] + lst[i - 2])
    return lst

print(fibonacci(0))  # ->[0]
print(fibonacci(1))  # ->[0,1]
print(fibonacci(2))  # ->[0,1,1]
print(fibonacci(3))  # ->[0,1,1,2]
print(fibonacci(4))  # ->[0,1,1,2,3]
print(fibonacci(10)) # ->[0,1,1,2,3,5,8,13,21,34,55]

OR

if you want the fibonacci(0) to return []

def fibonacci(n):
    lst = [0, 1]
    if n == 0:
        return []
    if n == 1:
        return [0]
    for i in range(2, n):
        lst.append(lst[i - 1] + lst[i - 2])
    return lst


print(fibonacci(0))  # ->[]
print(fibonacci(1))  # ->[0]
print(fibonacci(2))  # ->[0,1]
print(fibonacci(3))  # ->[0,1,1]
print(fibonacci(4))  # ->[0,1,1,2]
print(fibonacci(10)) # ->[0,1,1,2,3,5,8,13,21,34]
ktzr
  • 1,577
  • 1
  • 10
  • 25
0

also a possibility (will not work for n<2 but that is an easy fix...):

def fib(n, lst=None):
    if lst is None:
        lst = [0, 1]
    while len(lst) < n:
        lst.append(lst[-2] + lst[-1])
    return lst
hiro protagonist
  • 40,708
  • 13
  • 78
  • 98