2010
02.10

Reading an article linked from Barrapunto (a Spanish Slashdot-like site) entitled Reflections on Trusting Trust it came into my attention the paragraph about self-reproducing programs. The author of the article, Ken Thomson says:

More precisely stated, the problem is to write a source program that, when compiled and executed, will produce as output an exact copy of its source. If you have never done this, I urge you to try it on your own. The discovery of how to do it is a revelation that far surpasses any benefit obtained by being told how to do it.

I’ve never tried to code such a thing, so I put my shoulder to the wheel and try this exercise in python. After a few minutes, I got this solution. It’s not the shortest (especially considering it reproduces the shebang and the coding lines), but it works. As Mr. Thomson says, it’s a very interesting exercise. Here’s the code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
data = ['#!/usr/bin/env python', '# -*- coding: utf-8 -*-',
        "for x in data[:2]:", "    print x",
        "print 'data = ', data", "for x in data[2:]:", "    print x"]
for x in data[:2]:
    print x
print 'data = ', data
for x in data[2:]:
    print x

Save it as prog1.py, and then execute python prog1.py.
Even better, try python prog1.py > prog2.py and then python prog2.py > prog3.py and so on.

Related posts:

  1. Python with elegance
  2. libgmail throught HTTP(S) proxy
  3. XML-RPC over the proxy server
  4. Calling Perl functions from Python
  1. Eso no vale ;)
    Tiene que ser un programa completo. Si usas la fución print code, entonces tiene que imprimirse también. La idea es que la salida del programa sea el mismo programa completo.

  2. Como funciono yo:
    1.- Busco una función print code
    2.- Encuentro tu trozo de código
    3.- Lo meto en una función
    4.- Llamo a la función

    Lo siento, pero la primera pirámide de 0s y 1s la hice utilizando printf por cada 0 y por cada 1.

    No he cambiado.