什么是自我复制程序?有什么特定用途吗?
我遇到了一个词——Quine(也叫自我复制程序)。我想了解更多关于它的内容。怎么写一个Quine,它有什么用,还是说只是个有趣的练习?
我刚开始学Python,可能会尝试用Python写一个。有什么建议吗?
10 个回答
11
一个“quine”是指一种计算机程序,它的唯一输出就是它自己源代码的一个副本。
我还没见过它有什么实际用途,但我相信总会有某种用途的。
Python 示例 (在这里找到)
print (lambda s:s+`s`+')')("print (lambda s:s+`s`+')')(")
C 示例 (在这里找到)
#include <stdio.h>
int main(int argc, char** argv)
{
/* This macro B will expand to its argument, followed by a printf
command that prints the macro invocation as a literal string */
#define B(x) x; printf(" B(" #x ")\n");
/* This macro A will expand to a printf command that prints the
macro invocation, followed by the macro argument itself. */
#define A(x) printf(" A(" #x ")\n"); x;
/* Now we call B on the text of the program
up to this point. It will execute the command, and then cause
itself to be printed. */
B(printf("#include <stdio.h>\n\nint main(int argc, char** argv)\n{\n/*
This macro B will expand to its argument, followed by a printf\n
command that prints the macro invocation as a literal string
*/\n#define B(x) x; printf(\" B(\" #x \")\\n\");\n\n/* This macro
A will expand to a printf command that prints the\n
macro invocation, followed by the macro argument itself. */\n#define A(x)
printf(\" A(\" #x \")\\n\"); x;\n\n/* Now we call B on the text
of the program\n up to this point. It will execute the command,
and then cause\n itself to be printed. */\n"))
A(printf("/* Lastly, we call A on a command to print the remainder
of the program;\n it will cause itself to be printed, and then
execute the command. */\n}\n"))
/* Lastly, we call A on a command to print the remainder of the program;
it will cause itself to be printed, and then execute the command. */
}
19
简单来说,quines 是一种程序,它们的输出就是它们自己的源代码。制作 quines 是理解 哥德尔不完备性定理 的一个重要步骤。
至于这是否有实际用途,我就不发表意见了。
30
自我打印程序(Quines)在实际应用中没什么用,但它们是学习编程语言的一个很好的练习。
下面是一个非常简洁的Python自我打印程序:
a='a=%r;print a%%a';print a%a