Darshan

Darshan

14-09-2022

15:49

A Quine is a self replicating computer program, a digital DNA if you will. It takes no input and produces a copy of its own source code. A Quine can be written in any Turing-complete programming language. Below is a step by step guide to write your first Quine in Python:

Let's start with 2 pieces in our code. - A variable to hold the string representation of the source code. - A print statement to output the variable.

Let's call the variable "s". And since we don't know the final source code yet, let's use "???" as a placeholder. Print statement can leverage f-strings to output the variable. The output is close to line 1. Great start! How do we output line 2?

Let's try appending line 2 to itself, as a snippet in the f-string. We'll ignore quotes for now. The output is starting to look like the source from the previous step! But in doing so, we altered line 2 of the source. How do we reflect that in the output?

The f-string in line 2 is evaluating the variable "s". But "s" doesn't contain the updated source anymore. Let's append the same snippet to the variable "s" in line 1. Sweet. Looks close. But we still have the "???" lying around.

Notice the position of "???" in line 2 of output matches to the position of "{s}" in line 2 of source. Let's replace "???" with "{s}". Almost there! Time to fix the missing quotes now. But how?

In Python - f'{s}' calls str(s) - str('hi') outputs hi - repr('hi') outputs 'hi', with quotes That's exactly what we need! Let's replace every "{s}" with "{repr(s)}" in line 2. Yay! Line 1 in source and output are an exact match. But we altered the line 2 of the source, again!

We can fix this by wrapping every "{s}" with repr on line 1 as well. And while we are at it. Let's add the missing "\n" in the same line. Viola! There you have it. A valid Quine!

By renaming the variable to underscore, substituting repr with "%r", and getting rid of newline we can shorten the Quine considerably. For example, here's the shortest Quine yet in Python.

Here's an interesting one. It's an Error-Quine in python. The source code is an error like text which throws the exact error when executed. The only difference being the output now goes to stderr instead of stdout.

Quines are an interesting topic and an art in their own right. We'll go more in depth and explore topics like "Quine Relays", "Multi Quine", and "Radiation-hardened Quine" in the upcoming threads. Stay tuned!



Follow us on Twitter

to be informed of the latest developments and updates!


You can easily use to @tivitikothread bot for create more readable thread!
Donate 💲

You can keep this app free of charge by supporting 😊

for server charges...