[Tutor] loops
Lie Ryan
lie.1296 at gmail.com
Wed Dec 9 01:02:08 CET 2009
On 12/9/2009 3:18 AM, Rich Lovely wrote:
> 2009/12/8 spir<denis.spir at free.fr>:
>
> This, of course is a rather dirty, implementation (and probably
> version) specific hack, but I can /calculate/ the sequence, using just
> one line:
>
>>>> print " ".join(str(i) for i in [x if x<2 else (locals()['_[1]'][-1]+locals()['_[1]'][-2]) for x in xrange(20)])
> 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
>
> (CPython 2.6, on osx10.6)
the best one-liner golf score for now (83 chars, requires python3),
quite obfuscated:
(lambda*n:n[0](*n))(lambda f,n,a=0,b=1:n<0 or print(a,end=' ')or
f(f,n-1,b,a+b),19)
and though not a pure one-liner, the most "straightforward" method is
just a char away (84 chars, python2):
a=[0,1];[a.append(sum(a[-2:]))for x in range(3)][0];print'
'.join(str(x)for x in a)
if you don't require one-liner you can make it even shorter (81 chars,
'\n'==1char, requires python2)
a=[0,1]
for x in range(18):a.append(sum(a[-2:]))
print' '.join(str(x) for x in a)
All codes tested on command-line with -c argument (i.e. the shell's
default repr()-ing of expressions is ignored), result must be printed to
screen as numbers separated by space (printing with list repr, e.g. [0,
1, ...] is not acceptable). Trailing space is ignored.
> It's slightly more typing than the plain string, but extend it to
> about 30 entries, and I think I win?
Think again...
> Note to OP: don't _ever_ do it this way in a serious project.
OP: In a real project, readability counts. Inglfng,spcecnts.
PS: Perl fans might complain that their favorite pastime is stolen
More information about the Tutor
mailing list