Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #87866

Re: fibonacci series what Iam is missing ?

References <CACT3xuVF-MOVQK5wSorRSAfpAQEXvS7QsqarACVZKXsQ0bxzpQ@mail.gmail.com> <CAPTjJmrRv+DQGpzdY5te-vk_u9p5AzWYQ-6B=m1knPoaXpRmRQ@mail.gmail.com> <55105EF4.2070805@davea.name> <meq5i2$53s$1@ger.gmane.org>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2015-03-23 23:20 -0600
Subject Re: fibonacci series what Iam is missing ?
Newsgroups comp.lang.python
Message-ID <mailman.93.1427174452.10327.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Mar 23, 2015 at 4:53 PM, Terry Reedy <tjreedy@udel.edu> wrote:
> Iteration with caching, using a mutable default arg to keep the cache
> private and the function self-contained.  This should be faster.
>
> def fib(n, _cache=[0,1]):
>     '''Return fibonacci(n).
>
>     _cache is initialized with base values and augmented as needed.
>     '''
>     for k in range(len(_cache), n+1):
>         _cache.append(_cache[k-2] + _cache[k-1])
>     return _cache[n]
>
> print(fib(1), fib(3), fib(6), fib(5))
> # 1 2 8 5

Iteration in log space. On my desktop, this calculates fib(1000) in
about 9 us, fib(100000) in about 5 ms, and fib(10000000) in about 7
seconds.

def fib(n):
    assert n >= 0
    if n == 0:
        return 0

    a = b = x = 1
    c = y = 0
    n -= 1

    while True:
        n, r = divmod(n, 2)
        if r == 1:
            x, y = x*a + y*b, x*b + y*c
        if n == 0:
            return x
        b, c = a*b + b*c, b*b + c*c
        a = b + c

>>> list(map(fib, range(15)))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: fibonacci series what Iam is missing ? Ian Kelly <ian.g.kelly@gmail.com> - 2015-03-23 23:20 -0600
  Re: fibonacci series what Iam is missing ? Rustom Mody <rustompmody@gmail.com> - 2015-03-23 23:20 -0700
    Re: fibonacci series what Iam is missing ? Rustom Mody <rustompmody@gmail.com> - 2015-03-23 23:28 -0700
      Unicode magic (was fibonacci series what Iam is missing ?) Rustom Mody <rustompmody@gmail.com> - 2015-03-23 23:33 -0700
    Re: fibonacci series what Iam is missing ? Ian Kelly <ian.g.kelly@gmail.com> - 2015-03-24 08:23 -0600
      Re: fibonacci series what Iam is missing ? CHIN Dihedral <dihedral88888@gmail.com> - 2015-03-24 10:22 -0700

csiph-web