4 ms·
A slightly more general formula works in any language that can manipulate strings, without leveraging the built-in escaping mechanism. Basically, create a progr
by CGamesPlay 4y ago
A slightly more general formula works in any language that can manipulate strings, without leveraging the built-in escaping mechanism. Basically, create a program that prints a variable, but replaces a token in the variable with the contents of another variable, properly escaped for the target language. Finally, replace the content of the variable with the entire source code of the program. Naively applying this formula to Python gives you this: step 1:
CODE = 'XXX'
print(CODE.replace('"XXX"', repr(CODE), 1))
Step 2:
CODE = 'CODE = "XXX"\nprint(CODE.replace(\'"XXX"\', repr(CODE), 1))'
print(CODE.replace('"XXX"', repr(CODE), 1))
The beauty of this approach is that you could include the definition of the repr function in the code, so it works in any language that can manipulate strings. Another generally-applicable approach is to use eval: write a program that prints a variable assignment and an eval of that variable, then wrap that program in a variable and eval it:
code = 'print("code = {!r}\\neval(code)".format(code))'
eval(code)
Again this uses "!r" for brevity but it could easily include the function responsible for doing the escaping. Requires eval, so not as universally applicable as the previous method (but produces shorter quines).
Anyone aware of other generally-applicable techniques for producing quines?