Palindromic palindrome checker

37

3

Write a program to test if a string is palindromic, with the added condition that the program be palindromic itself.

marcog

Posted 2011-03-26T12:44:21.377

Reputation: 10 244

Question was closed 2016-03-28T17:50:26.373

4I know this is an old question, but I think it needs an arbitrary winning criterion, such as popularity contest or code-golf. The question specifies none. – mbomb007 – 2015-09-13T21:41:24.383

1If the language has till-the-end-of-the-line comments this is trivial so I guess those should be disallowed. – Joey – 2011-03-26T14:05:22.430

1@Joey I'd happily discourage use of such comments, but disallowing them after posing the question is harsh on those who have already answered. @Ventero's answer (the only one not using them) is way ahead on vote count, so everyone seems to agree. – marcog – 2011-03-26T14:07:03.333

1Well, to weed out such problems earlier (this also occurred in a similar task on SO) you could use the sandbox or the Puzzle lab ;-) – Joey – 2011-03-26T14:13:46.560

1How about imposing that the program should be a palindromic quine itself evil grin ;-) – Quixotic – 2011-03-26T14:43:04.050

1If someone find a way, he instantly wins because of the characters saved. – Ming-Tang – 2011-06-23T20:18:31.947

Answers

34

Ruby

z=gets;puts *z.reverse==z&&1||0||1&&z==esrever.z* stup;steg=z

Prints 1 if the input is a palindrome, 0 if it isn't. Input without linebreak.

Doesn't use any comments, instead it uses 2 tricks:

  • Short-circuiting: 0 is true-ish in Ruby (only nil and false evaluate to false), so 1&&z==esrever.z* stup isn't evaluated and thus can't raise a runtime exception
  • The splat/multiplication operator (*): To avoid a syntax error in z=esrever.z stup, we force the parser to parse this as z=esrever.z()*stup by adding a *. On the other side, the * is parsed as a splat operator, which in a function call splits an array in a series of parameters. If there's only one element instead of an array, it basically does nothing, so puts *foo is equivalent to puts foo.

Obvious solution using comments (prints true/false):

puts gets.reverse==$_#_$==esrever.steg stup

Ventero

Posted 2011-03-26T12:44:21.377

Reputation: 9 842

Can you explain how this works. I don't know ruby. – mellamokb – 2011-03-28T20:52:41.440

@mellamokb: I added a short explanation. Let me know if it's still not clear. – Ventero – 2011-03-30T12:23:26.847

26

Python without comment

"a\";w=]1-::[w trinp;)(tupni_war=w;";w=raw_input();print w[::-1]==w;"\a"

I'm surprised that no one found that trick yet, it should work in most languages!

Jules Olléon

Posted 2011-03-26T12:44:21.377

Reputation: 731

Nice solution, you could even drop the print statement and if you allow the input to specified enclosed in quotes raw_input() can be shortened to input(). Missing an extra '=' at the start. – Willem – 2014-05-10T07:06:15.697

removed trailing output after True or False: "a\"#;w==]1-::[w;)(tupni_war=w;";w=raw_input();w[::-1]==w;#"\a" – Willem – 2014-05-10T07:13:43.060

2Very Clever, I like the escaping quote. – Wayne Werner – 2011-08-12T15:24:21.570

13

Perl

perl -nle "$s=$_ eq+reverse;print$s;s$tnirp;esrever+qe _$=s$"

no comment tricks, just cleverly abusing the substitution operator (hey, perl variables start with a $ too, so what?)

Anonymous

Posted 2011-03-26T12:44:21.377

Reputation: 131

7

Python 2.7

s=raw_input();print'YNEOS'[s!=s[::-1]::2]#]2::]1-::[s=!s['SOENY'tnirp;)(tupni_war=s

fR0DDY

Posted 2011-03-26T12:44:21.377

Reputation: 4 337

6

C

#include <stdio.h>                   //
#include <string.h>                  //
int main() {                         //
  char str[1024];                    //
  fgets(str, sizeof(str), stdin);    //
  int i = 0, j = strlen(str) - 2;    //
  for (; i < j; i++, j--)            //
    if (str[i] != str[j]) {          //
      printf("no\n");                //
      return 0;                      //
    }                                //
  printf("yes\n");                   //
}                                    //
//                                    }
//                   ;)"n\sey"(ftnirp  
//                                }    
//                      ;0 nruter      
//                ;)"n\on"(ftnirp      
//          { )]j[rts =! ]i[rts( fi    
//            )--j ,++i ;j < i ;( rof  
//    ;2 - )rts(nelrts = j ,0 = i tni  
//    ;)nidts ,)rts(foezis ,rts(stegf  
//                    ;]4201[rts rahc  
//                         { )(niam tni
//                  >h.gnirts< edulcni#
//                   >h.oidts< edulcni#

Running example:

$ gcc -std=c99 c.c && ./a.out 
blahalb
yes

Alexandru

Posted 2011-03-26T12:44:21.377

Reputation: 5 485

lol, clever-lvl 11/10. – nymo – 2015-10-12T04:16:17.153

won't win for brevity, but I'm impressed – Wayne Werner – 2011-08-12T15:25:22.050

5

Golfscript

.-1%=#=%1-.
  • just with comment trick
  • input without \n at the end
  • perform matching char by char (even for punctuation)
  • returns 1 for success, 0 for failure

YOU

Posted 2011-03-26T12:44:21.377

Reputation: 4 321

4

PHP

echo strrev($z)==$z;#;z$==)z$(verrts ohce

Facts:

  • $z string, the input string to check
  • $t boolean, TRUE if the input string $z is palindrome, FALSE otherwise
  • Using comments to help me make the code palindrome.
  • Outputs $t
  • Source itself is a palindrome

The reason why it will not be possible to implement palindromic palindrome checker in PHP it's because PHP variables are named starting with a $. You cannot end an identifier name with $ in PHP.

mauris

Posted 2011-03-26T12:44:21.377

Reputation: 636

2

PHP

<?php eval/*/*/(';{$i=fgets(STDIN,2e9);};{$a="strrev";}{var_dump("{$i}"=="{$a($i)}");}/*}{*\{;("{(tupni$)a$}"=="{putni$}")ohce}{;"verrts"==a$};{;(9e2,NIDTS)stegf=i$);');/*\*\eval php?>

Uses some odd tricks to avoid the $ issue, technically isnt a palindrome as I had to sneak a ; in at the end.

 <?php $i = fgets(STDIN,2e9); echo $i == strrev($i);/*\;(i$)verrts == i$ ohce ;(9e2, NIDTS)stegf = $i php?>

This is a working one that uses PHP's /* */ comments and the fact that you don't need the end for them.

Kevin Brown

Posted 2011-03-26T12:44:21.377

Reputation: 5 756

2In the end first code, eval should be lave. – Aycan Yaşıt – 2014-01-29T18:48:44.260

1

CoffeeScript

I actually struggled with the reverse spellings of 'split', 'reverse' and 'join' :\

p=(s)->s.split('').reverse().join('')==s#s==)''(nioj.)(esrever.)''(tilps.s>-)s(=p

Cain

Posted 2011-03-26T12:44:21.377

Reputation: 111

1

Groovy

print args[0]==args[0].reverse()?1:0//0:1?)(esrever.]0[sgra==]0[sgra tnirp

Salesman

Posted 2011-03-26T12:44:21.377

Reputation: 121

You have used comments over here! – Ant's – 2011-06-20T05:31:43.170

1

Python 3, 55 bytes

Uses a comment, but is shorter than the other Python one that uses comments.

s=input();print(s==s[::-1])#)]1-::[s==s(tnirp;)(tupni=s

mbomb007

Posted 2011-03-26T12:44:21.377

Reputation: 21 944

1

Fuzzy Octo Guacamole, 17 bytes

^Cz.=i_;@;_i=.zC^

Not exactly sure how the win is defined, but I put the byte count up top.

^ gets the input and pushes it to the first stack.

C copies the first stack to the second.

z reverse the top of the stack, so "as" becomes "sa".

. shifts the active stack, so the active stack has the input, and the inactive one has the reversed input.

= checks for equality, returning 0 for equality.

i inverts the ToS, so 0 becomes 1, and anything else pretty much becomes False.

_ pops and sets the temp variable which the ; then prints.

@ ends the program manually, so it doesn't hit the reversed part. This makes the palindrome.

Rɪᴋᴇʀ

Posted 2011-03-26T12:44:21.377

Reputation: 7 410

0

Javascript

function a(b){return b==b.split('').reverse().join('')}//})''(nioj.)(esrever.)''(tilps.b==b nruter{)b(a noitcnuf

Hard to do it without comments...

Spedwards

Posted 2011-03-26T12:44:21.377

Reputation: 159