Question

Using python 2.7.

(edit at the top in case you miss something at the bottom: I have been executing the code with exec(), which makes it part of the source. More info about my usage of this is in the bottom of this post)

Recently, I have taken an interest in quines. So far, my attempt that is the closest to a quine is:

_="print '_={0}'.format(_)"

Unfortunately, that prints this

_=print '_={0}'.format(_)

instead of this

_="print '_={0}'.format(_)"

which is a major problem because executing

_=print '_={0}'.format(_)

will result in an error, and is not the same as the original source code.

I have been struggling to get those quotation marks in there. One way I tried is using escapes to do this:

_="print '_=\"{0}\"'.format(_)"

and that prints this:

_="print '_="{0}"'.format(_)"

and that code will once again print

_=print '_={0}'.format(_)

and that is not the same and errors. Does anyone have any idea for a modification I could make?

And, as I write this, I have realized something else. I have been executing the code this whole time with exec(), and this quine can only be run with exec(), which makes exec() part of the code, so that needs to be added too. So, now another attempt with exec() added:

_=print '_={0}'.format(_); exec(_)

but that creates a horrible loop and still lacks quotation marks

>>>> _="print '_={0}'.format(_); exec(_)"; exec(_)
_=print '_={0}'.format(_); exec(_)
_=print '_={0}'.format(_); exec(_)
_=print '_={0}'.format(_); exec(_)
_=print '_={0}'.format(_); exec(_)
_=print '_={0}'.format(_); exec(_)
_=print '_={0}'.format(_); exec(_)
[etc]

So, now I need to get exec() in there without an ugly loop and get the quotation marks in the right spots.

So now, this leads me to repeat myself again: Does anyone have any idea for a modification I could make?

Was it helpful?

Solution

A quine just needs to output it's own source code without receiving any input. It's not a requirement that it must also include the code necessary to execute itself.

In python, you can test a quine by simply entering it in an interactive session and checking that the output lines exactly match the input lines:

>>> _ = '_ = {!r}; print(_.format(_))'; print(_.format(_))
_ = '_ = {!r}; print(_.format(_))'; print(_.format(_))

This example solves your quoting problem by using a repr of the argument to format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top