shortest python quine?

后端 未结 10 1752
天涯浪人
天涯浪人 2020-12-23 19:55
_=\'_=%r;print _%%_\';print _%_

Is this the shortest possible python quine, or can it be done better? This one seems to improve on all the entrie

相关标签:
10条回答
  • 2020-12-23 20:24

    Here is another similar to postylem's answer.

    Python 3.6:

    print((lambda s:s%s)('print((lambda s:s%%s)(%r))'))
    

    Python 2.7:

    print(lambda s:s%s)('print(lambda s:s%%s)(%r)')
    
    0 讨论(0)
  • 2020-12-23 20:26

    In a slightly non-literal approach, taking 'shortest' to mean short in terms of the number of statements as well as just the character count, I have one here that doesn't include any semicolons.

    print(lambda x:x+str((x,)))('print(lambda x:x+str((x,)))',)
    

    In my mind this contends, because it's all one function, whereas others are multiple. Does anyone have a shorter one like this?

    Edit: User flornquake made the following improvement (backticks for repr() to replace str() and shave off 6 characters):

    print(lambda x:x+`(x,)`)('print(lambda x:x+`(x,)`)',)
    
    0 讨论(0)
  • 2020-12-23 20:26

    As of Python 3.8 I have a new quine! I'm quite proud of it because until now I have never created my own. I drew inspiration from _='_=%r;print(_%%_)';print(_%_), but made it into a single function (with only 2 more characters). It uses the new walrus operator.

    print((_:='print((_:=%r)%%_)')%_)

    0 讨论(0)
  • 2020-12-23 20:30

    Technically, the shortest Python quine is the empty file. Apart from this trivial case:

    Since Python's print automatically appends a newline, the quine is actually _='_=%r;print _%%_';print _%_\n (where \n represents a single newline character in the file).

    0 讨论(0)
  • 2020-12-23 20:32

    Python 3.8

    exec(s:='print("exec(s:=%r)"%s)')
    
    0 讨论(0)
  • 2020-12-23 20:37

    I am strictly against your solution.

    The formatting prarameter % is definitively a too advanced high level language function. If such constructs are allowed, I would say, that import must be allowed as well. Then I can construct a shorter Quine by introducing some other high level language construct (which, BTW is much less powerful than the % function, so it is less advanced):

    Here is a Unix shell script creating such a quine.py file and checking it really works:

    echo 'import x' > quine.py
    echo "print 'import x'" > x.py
    python quine.py | cmp - quine.py; echo $?
    

    outputs 0

    Yes, that's cheating, like using %. Sorry.

    0 讨论(0)
提交回复
热议问题