Can python find fibonacci series in a single line of code?

Mel Wilson mwilson at the-wire.com
Mon Nov 11 11:17:03 EST 2002


In article <fa61a3d8.0211110720.16a645f8 at posting.google.com>,
a_human_work at hotmail.com (Pittaya) wrote:
>My Perl-addicted friend shows me that he can find fibanicci series in
>a single line of code.
>
>perl -le '$b=1; print $a+=$b while print $b+=$a'
>
>can python do something like this?

   One-liner contests are noxious, but what the heck; the
first 10, governed by the xrange ..


print reduce (lambda x,y: (x[1],x[0]+x[1], x[2]+[x[1]]), xrange(10), (0,1,[]))[2]


   While this may look a tad obscure, note that it needn't
just print the series, it makes the members available in a
list for other processing.  And there's an easy way to
generate only as much of the series as you might want.


   The obvious attempt,

a,b=0,1; while 1: print b; a,b = b, a+b

gets into trouble at `while`.  Since whitespace is
significant in Python programs, there are limits to the kind
of vaguely-related stuff you can mash onto one line.

        Regards.        Mel.



More information about the Python-list mailing list