Fibonacci: returning a selection of the series

Baba raoulbia at
Sun Aug 29 19:36:45 CEST 2010

level: beginner

i would like to return a selection of the Fibonacci series.
start = 5 ; end  = 55
the function should then return [5, 8, 13, 21, 34, 55]

it seems that this is best resolved using an iterative approach to
generate the series. In another post (
d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach
which seems best to compute the nth number but it seems to me that the
recursive code is not suited for generating the actual list.

my questios:
- would you agree that recursive is not ideal for generating a list?
(in this particular case and in general)
- can my code below be optimised?
- how to deal with 'start' and 'end' values that are not in the list
e.g. 4,76 ?

def i_fib(n):
    a = 0
    b = 1
    list = []
    counter = 0
    while counter < n:
        a, b = b, a+b
        counter += 1
        list = list + [b,]
    return list

def fib_range(start,end):
    list = i_fib(12)
    if start in list and end in list:
        start = list.index(start)
        end = list.index(end)
        print list[start:end+1]
    else: print 'not in list'



More information about the Python-list mailing list