I'm a palindrome. Are you?


  • There have been a couple of previous attempts to ask this question, but neither conforms to modern standards on this site. Per discussion on Meta, I'm reposting it in a way that allows for fair competition under our modern rulesets.




    Background



    A is a string that "reads the same forwards and backwards", i.e. the reverse of the string is the same as the string itself. We're not talking about "convenient palindromes" here, but a strict character-by-character reversal; for example, ()() is not a palindrome, but ())( is.



    The task



    Write a program or function that takes a string S (or the appropriate equivalent in your language) as input, and has one output Q (of a type of your choice). You can use any reasonable means to take the input and provide the output.




    • When the input S is a palindrome, the output Q should have a value A (that is the same for any palindromic S).

    • When the input S is not a palindrome, the output Q should have a value B (that is the same for any non-palindromic S).

    • A and B must be distinct from each other.



    Or in other words: map all palindromes to one value, and all non-palindromes to another.



    Additionally, the program or function you write must be a palindrome itself (i.e. its source code must be palindromic), making this a challenge.



    Clarifications




    • Although true and false are obvious choices for A and B, you can use any two distinct values for your "is a palindrome" and "isn't a palindrome" outputs, which need not be booleans.

    • We're defining string reversal at the character level here; éé is palindromic regardless of whether the program is encoded in UTF-8 or Latin-1, even though it's not a palindromic sequence of octets after UTF-8 encoding.

    • However, even if your program contains non-ASCII characters, it only needs to work for ASCII input. Specifically, the input S will only contain printable ASCII characters (including space, but not including newline). Among other things, this means that if you treat the input as a sequence of bytes rather than a sequence of characters, your program will still likely comply with the specification (unless your language's I/O encoding is very weird). As such, the definition of a palindrome in the previous bullet only really matters when checking that the program has a correct form.

    • Hiding half the program in a comment or string literal, while being uncreative, is legal; you're being scored on length, not creativity, so feel free to use "boring" methods to ensure your program is a palindrome. Of course, because you're being scored on length, parts of your program that don't do anything are going to worsen your score, so being able to use both halves of your program is likely going to be helpful if you can manage it.

    • Because the victory criterion is measured in bytes, you'll need to specify the encoding in which your program is written to be able to score it (although in many cases it will be obvious which encoding you're using).



    Victory criterion



    Even though the program needs to be a palindrome at the character level, we're using bytes to see who wins. Specifically, the shorter your program is, measured in bytes, the better; this is a challenge. In order to allow submissions (especially submissions in the same language) to be compared, place a byte count for your program in the header of your submission (plus a character count, if it differs from the number of bytes).


    Would someone please explain why would ()() not be a palindrome??

    @EmilioMBumachar Try replacing `(` with `a` and `)` with `b`. Is `abab` a palindrome? No, it would have to be `abba`. Then `()()` isn't a palindrome either; it would have to be `())(`.

    Those solutions entirely using comments to make the program palindromic looks like a loophole to me :(

    @kennytm The OP himself allows it.

    Can I give no output if S is not a palindrome and print 1 if it is?

    @kennytm Disallowing them would be worse, because there's no satisfactory way to do that objectively in a language-agnostic way. (What's a comment? What about putting the unused half in a string literal that is discarded? What about 2D languages where you can have perfectly executable code that is simply never reached?)

    I think another interesting result of this could be the longest program in which every bit of code is executed. I.E., there are no comments or sections of code that are never reached just to make it a palindrome.

    @EngineerToast: We've had a few challenges along those lines. The solution nearly always ends up to be putting most of the program in a string literal, and then using some sort of checksum to ensure that it actually has an effect on the program, which probably isn't what you were expecting.

    I had to join this stack just to leave a comment and up-vote here. It boggles the mind how you guys come up with these challenges that look complex yet get solved in 3 bytes in a bunch languages, even regular ones.

    `()() is not a palindrome, but ())( is.` Congratulations, you made it onto reddit!

    This one popped back up to the top of the stack and I have to ask, is `éé` a palindrome? (Fair warning, it is not strictly equal to `éé`). Reversed by unicode character endpoints, it would be `́ée`.

  • Brachylog (2), 3 bytes in Brachylog's codepage



    I↔I


    Try it online!



    This is a full program that takes input via standard input (using Brachylog's syntax for constants, i.e. strings are enclosed in double quotes), and outputs via standard output. The outputs are true. for a palindromic input, and false. for a non-palindromic input.



    Not only is this program palindromic, it also has left/right (and probably in some fonts up/down) mirror symmetry.



    Explanation



    In Brachylog, capital letters mark points in the program which have identical values; this is used almost like an electrical circuit to carry information from one part of the program to another. One consequence of this is that if you enclose a command between an identical pair of capital letters, you're effectively asserting that the command's input and output are the same. Brachylog implicitly takes input, so in this case we're also asserting that the input to the command is the same as the input to the program. In this program, we're using the command , which reverses things (in this case, strings); so the program effectively asserts that the input is the same forwards and backwards.



    A full program (as opposed to a function) in Brachylog returns a boolean, false. if there's no way to make all the assertions in the program correct at once, or true. if the assertions in the program are all compatible with each other. We only have one assertion here – that reversing the input does not change it – so the program acts as a palindrome checker.


    And 180 degree rotational symmetry, It's beautiful.

    ... and symmetry along vertical and horizontal axes :-)

    More like 5 bytes in UTF-8, isn't it?

    @SteakOverflow Brachylog uses a custom code-page, so those characters are not encoded in UTF-8

    I joined this community just to up vote this program. Wow.

    @ATaco The combination of left/right and up/down symmetries imply 180 degree rotational symmetry. ;)

  • Pyth, 3 bytes



    _I_


    Returns True or False.



    Try it online!



    How it works



      _  Reverse the input.
    _I Invariant-reverse; test if the reversed input is equal to its reverse.

    Why do you need the final `_`?

    @busukxuan From the question, "Additionally, the program or function you write must be a palindrome itself"

    Why so many upvotes...This answer doesn't seem that hard to come up with...?

    @ghosts_in_the_code The vast majority of answers to this challenge weren't difficult to come up with...

    I guess so. Still it seems kind of unfair. On some questions, one must put a lot of hard work to answer, and others are much easier. Still the payout is the same. Btw I've also upvoted :P

    @ghosts_in_the_code Only one of my answers with 100+ was actually challenging to write, yet there are answers I spent days on that only got a handful of upvotes. In the end, it all evens out...

  • Python, 39 bytes





    lambda s:s[::-1]==s#s==]1-::[s:s adbmal


    Try it online!



    Boring, but if there is shorter in Python it will be impressive.


    Wow, thos `(`, `)` were some good (and confusing) inputs :)

  • Jelly, 5 bytes



    ḂŒ
    ŒḂ


    Returns 1 or 0. The first line is an unexecuted helper link, the second line calls the palindrome test.



    Try it online!


    wow, recent addition.

    Yep, only 18 hours old.

    you didn't specify the encoding. I'm guessing UTF-8?

    @BrianMinton No, this would be 11 bytes in UTF-8. Jelly uses this code page.

    @Dennis, thanks for the info.

  • Jelly, 5 bytes



    ⁼ṚaṚ⁼


    Try it online!



    Equals reverse and reverse equals.



    Or the more efficient yet less aesthetically pleasing:



    ⁼Ṛ
    Ṛ⁼


    or



    Ṛ⁼
    ⁼Ṛ

  • Haskell, 87 85 44 34 bytes



    p=(==)<*>reverse--esrever>*<)==(=p


    Explanation: ((->) a) is an instance of Applicative (thanks @faubiguy), with <*> defined as



    (<*>) f g x = f x (g x)


    So by substituting in the arguments one can see why this works.


    Can you explain the code?

    @bli everything after the `--` is a comment.

    @theonlygusti Haskell is sufficiently alien that that only half helps.

    @Yakk It's some sort of combination of the `(==)`, `reverse`, and `id` functions (`id` is the identity function).

    You can save 10 bytes by using `<*>` instead of `<$>` and removing the `<*>id`

    Nice thinking! Applicative is still weird to me...

  • Mathematica, 23 bytes



    QemordnilaP;PalindromeQ


    Not very interesting, but for the sake of completeness...



    The above is a CompoundExpression which evaluates to PalindromeQ, a built-in that solves the challenge. QemordnilaP is simply an undefined identifier, which is ignored because of the ;.


  • 05AB1E, 3 bytes



    Code:



    ÂQÂ


    Explanation:



    Â     # Bifurcate (duplicate and reverse the duplicate) implicit input
    Q # Check if equal
    Â # Bifurcate the result


    Uses the CP-1252 encoding. Try it online!


    Why not just `ÂQ`

    @NeilA. The code itself needs to be a palindrome as well.

  • PHP, 55 bytes



    <?=strrev($s=$argv[1])==$s;#;s$==)]s[TEG_$=s$(verrts=?<

    Try it online!


    Sneaky solution.

  • MATL, 7 bytes



    tPX=XPt


    Try it online!



    Returns [1; 1] for palindromic input and [0; 0] otherwise.



    t       % duplicate the input
    P % reverse the second string
    X= % check the two strings are exactly equal (returns 0 or 1)
    XP % flip array (does nothing)
    t % duplicate the answer, giving either [1;1] or [0;0]
    % (implicit) convert to string and display

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM