Fibonacci: returning a selection of the series

News123 news1234 at free.fr
Sun Aug 29 20:47:57 CEST 2010


On 08/29/2010 07:36 PM, Baba wrote:
> level: beginner
> 
> i would like to return a selection of the Fibonacci series.
> example:
> 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 (http://groups.google.ie/group/
> comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/
> 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?
Of course, This is probably the whole point of this exercise.

Just because something can be defined recursively doesn't mean, that it
should be
calculated recursively

> - 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

lateron you should probably use a generator function for i_fib(n)
Then you will only calculate what is needed.

minor suggestion for above code.
Instead of:
list = list + [b,]
it is common practice to write
list.append(b)

> 
> 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'
> 
> fib_range(5,55)


you know, that the list returned by i_fib() is sorted.
Knowing this you can look at the python module bisect.
It allows you to identify the index of the closest entry in a list.

Just read it up in the net:
http://docs.python.org/library/bisect.html



You could do this of course also do manually
(perhaps better for learning python than just using exsitng funtions)

Search for the first Fibonacci number which is bigger than your start number
Then search for the first Fibonacci number, which is bigger than your
end number

Display all numbers between these two indices




More information about the Python-list mailing list