Perl vs. Python One-Liner

Rating: 3.5
May 20th, 2007

A few years ago a friend of mine asked me the following Perl riddle. Unfortunately, in order to solve it you must know Perl. As I like Python much better, I translated the riddle to Python. Attached are both versions.

I admit the Perl version is a bit more cryptic and if you know both Perl and Python you should try to solve the Perl version (but use Python for everything else in life :-) ).

Oh, and try to solve the riddle without running it (run it only as a last resort).

Perl Logo

perl -wle 'print "True" if (1 x shift) !~ /^1?$|^(11+?)\1+$/' [number]

Python Logo

python -c "import sys, re; print None == re.match('^1?$|^(11+?)\\1+$','1'*int(sys.argv[1]))" [number]

To alleviate all doubt – [number] denotes a numeric command line argument (e.g. 17).

2 Responses to “Perl vs. Python One-Liner”

  1. Nadav Says:

    (Don’t look before you have solved the above riddle)
    What does the next python one-liner function stands for?
    lambda n,l=[]:l.append(lambda k,x:(k==1)*[1]or(k%x==0 and[x]+l[0](k/x,x))or l[0](k,x+1))or l[0](n,2)[:-1]
    Also, try to write a shorter one-liner with the same functionallity

  2. Nadav Says:

    actually, a shorter function would be:
    lambda n,l=[]:l.append(lambda k,x:(k==x)*[x]or(k%x==0 and[x]+l[0](k/x,x))or l[0](k,x+1))or l[0](n,2)

Leave a Reply