Shortest Python Quine?
by Sean B. Palmer
This morning I scribbled down, pen on paper, a Python
Quine
. I hadn't actively looked into Quine techniques before; it was nice to start from scratch. Here's what I got, with a little reduction when I typed it up (my scribbled version had used a function instead of lambda):-
print (lambda s:s+`s`+')')("print (lambda s:s+`s`+')')(")
At this point, I went searching for the shortest Python Quine that anyone had come up with. I found
Seth Schoen's challenge
again, though it doesn't actually contain the code for the Quine that he came up with. Searching elsewhere, I found a couple of sites (
The Quines List
,
The Quine Page
) that had basically the same Quine (one credited to Manus Hand, the other to Frank Stajano):-
_='_=%s;print _%%`_`';print _%`_`
It was shorter than mine (since it assigns first and then prints), but I noticed that it could easily be made shorter still. So here I present what might just be the shortest possible non-empty Python Quine, at thirty characters:-
_='_=%r;print _%%_';print _%_
It seems odd that the original authors didn't use %r in the first place (perhaps they were going by a version of Python that didn't have %r; when was it added?). For total authenticity, you should include a line break after it. Putting a comma after each %_ would stop the line break, but make it two characters longer, and therefore longer overall by one character.
As for my print-first approach, I managed to shorten it to the following:-
print (lambda s='print (lambda s=%r:s%%s)()':s%s)()
Which is fairly respectible, at fifty-two characters.
I wonder what the shortest possible multi-quine is? (Check out David Madore's
investigation into Quines
for a definition.) Also, I wonder if it's possible to prove that a Quine in a given langauge is the shortest possible for that language, other than by using the evidence that no-one has come up with a shorter one yet? Feedback most welcome.