| Bytes | Lang | Time | Link |
|---|---|---|---|
| 073 | Swift | 230710T080615Z | macOSist |
| 067 | Python | 250426T003504Z | a random |
| 018 | K ngn/k | 230709T194750Z | coltim |
| 004 | Thunno 2 | 230709T185156Z | The Thon |
| 063 | Julia 1.0 | 230119T170543Z | Ashlin H |
| 026 | Perl | 130408T223050Z | mob |
| 042 | Zsh | 230119T042845Z | roblogic |
| nan | 230119T020954Z | user1165 | |
| 079 | Python 2.7.6 | 170331T180527Z | salRoid |
| 010 | Jelly | 160815T043527Z | X88B88 |
| 031 | Retina | 170729T212005Z | ovs |
| 006 | Vyxal | 210714T223012Z | Undersla |
| 008 | Japt v2.0a0 | 210713T154143Z | Shaggy |
| 118 | C gcc | 210713T140514Z | a stone |
| 004 | 05AB1E | 160813T143702Z | Adnan |
| 019 | QuadS | 171025T163242Z | Adá |
| 065 | Common Lisp | 170729T195334Z | Renzo |
| 018 | Dyalog APL | 170729T204408Z | James He |
| 065 | APL | 161103T021637Z | Adalynn |
| 084 | REXX | 170405T105435Z | idrougge |
| 199 | C | 170405T075715Z | user5898 |
| 837 | AHK | 170405T035402Z | Engineer |
| 118 | Racket | 170404T140506Z | rnso |
| 063 | PHP | 170331T192730Z | Titus |
| 104 | C++14 | 161123T171541Z | Karl Nap |
| 074 | C++ | 161114T213959Z | Alecto |
| 132 | Racket | 160815T074724Z | Winny |
| 190 | PowerShell | 160811T164127Z | Bevo |
| 024 | Pylongolf2 | 160331T144738Z | user4701 |
| 053 | Mathematica | 130408T203201Z | DavidC |
| 060 | PHP | 131127T122701Z | Carlos G |
| 045 | Windows PowerShell | 131126T183957Z | goric |
| 081 | C++ | 130628T131141Z | Adrian M |
| 048 | Ruby | 130625T003517Z | Doorknob |
| 051 | Python 3 | 130623T145947Z | AMK |
| nan | Smalltalk | 130413T121001Z | aka.nice |
| 043 | Haskell | 130410T094604Z | Jon Purd |
| 048 | Haskell | 130412T075114Z | SlimJim |
| nan | JAVA or the most verbose language ever | 130408T232241Z | jsedano |
| 059 | Python 3/2 | 130409T050234Z | Amith KK |
| nan | GolfScript | 130408T205231Z | John Dvo |
| nan | 130409T060026Z | Bakuriu | |
| 046 | Bash | 130409T101943Z | manatwor |
| 038 | k | 130408T193146Z | skeevey |
| 038 | Ruby | 130409T074919Z | manatwor |
| nan | 130408T202015Z | Cristian | |
| 066 | R | 130409T113821Z | plannapu |
| 064 | Python 2 64 Charecters | 130409T045059Z | abhiram |
| 140 | JavaScript Code ONLY | 130409T065515Z | Praveen |
| 025 | K | 130408T223825Z | tmartin |
| 030 | J | 130408T232241Z | Gareth |
| 056 | Lua | 130408T193324Z | mniip |
| 053 | Javascript | 130408T193206Z | John Dvo |
Swift, 82 77 75 73 bytes
{{[]+$0==$0.reversed()}(($0+"").lowercased().replacing(/[\W_]/,with:""))}
Python, 67 bytes
probably a bad solution
def f(x):y=''.join(filter(str.isalpha,x.lower()));return y==y[::-1]
K (ngn/k), 18 bytes
#|:\(2!"0:a{"')__:
Uses @scrawl's suggestion here to return 1 for palindromes and 2 for non-palindromes. If 1 and 0 are required, the solution can be adjusted by prefixing 1=.
_:lowercase the (implicit) input(...)_filter out values where the code in(...)returns a non-0 value2!"0:a{"'do a bins lookup, then mod the result by two; returns0if the input is within"a"-"z"or"0"-"9"and1otherwise
|:\set up a converge-scan, reversing the input until the original input is returned. on palindromes, returns a one-item list; on non-palindromes, a two-item list#take the count of the result from above. As noted, if a strict1and0output are required for palindrome/non-palindrome, prefix1=for two bytes
Thunno 2, 4 bytes
LỊḲ⁼
Explanation
LỊḲ⁼ # Implicit input
L # Convert to lowercase
Ị # Only keep alphabetic characters
Ḳ # Duplicate and reverse
⁼ # Are they equal?
# Implicit output
Julia 1.0, 63 bytes
~s=((x=filter(in(['0':'9';'A':'Z']),uppercase(s)))==reverse(x))
Since punctuation is filtered out, "5,000 0.005" is considered a palindrome.
Perl, 26 char
s/_|\W//g;uc eq reverse uc
Evaluates to 1 when $_ is a palindrome, "" (one of Perl's false values) when it is not.
Sample usage:
sub palin {
s/_|\W//g;uc eq reverse uc
}
while (<DATA>) {
chomp;
print "$_ => ",palin()?"yes":"no","\n";
}
__DATA__
Eva, can I stab bats in a cave?
A man, a plan, a canal. Panama!
Madam, I'm Adam Carolla.
757
Boeing 757
A man, a plan, a big shovel, a canal. Panama!
A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal >> __Panama__
output:
Eva, can I stab bats in a cave? => yes
A man, a plan, a canal. Panama! => yes
Madam, I'm Adam Carolla. => no
757 => yes
Boeing 757 => no
A man, a plan, a big shovel, a canal. Panama! => no
A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal >> __Panama__ => yes
Zsh, 42 bytes
s=${(L)1//[^A-Za-z0-9]}
<<<${s/`rev<<<$s`}
Truthy (palindrome) is empty string, falsy otherwise. TIO link includes a test harness that outputs T or F.
n=>n.split('').reverse().join('')==n;
Python 2.7.6, 79 bytes
"Sorry I don't get what characters to count so I wrote the whole program"
import re
n=raw_input()
n=re.sub("[^a-z]+","",n.lower())
print n==n[::-1]
This will print True if input string is palindrome else False.
Code_link: http://ideone.com/b4NzLD
Vyxal, 6 bytes
kr↔⇩Ḃ= #
kr # push the upper and lowercase alphabet
↔⇩ # remove all chars in input that are not in that, and lowercase
Ḃ # push a and a.reverse()
= # equal?
Japt v2.0a0, 8 bytes
k\W v
¶Ô
k\W v\n¶Ô :Implicit input of string U
k :Remove
\W : RegEx /[^a-z0-9/gi
v :Lowercase
\n :Reassign to U
¶ :Is equal to
Ô :Reverse
C (gcc), 118 bytes
p(s,n)char*s,*n;{char*r=s+strlen(s)-1;for(*n=1;*s;s++)if(isalnum(*s)){for(;!isalnum(*r);r--);*n*=(*s|32)==(*r--|32);}}
Used like: p(string, &result);; outputs by modifying result.
05AB1E, 4 bytes
álÂQ
Explanation:
á # Only keep the alphabetic characters.
l # Lowercase the characters.
 # Bifurcate, which duplicates the letters and reverses the duplicate.
Q # Check if they are equal.
Uses the CP-1252 encoding. Try it online!.
QuadS, 19 bytes
Equivalent to James Heslip's solution.
⍵≡⌽⍵
\w
\u&
Is…
⍵≡⌽⍵ the text identical to its reverse
\w after finding all word characters
\u& and uppercasing them
?
Common Lisp, 72 65 bytes
(let((y(remove-if-not'alphanumericp(read))))(equalp(reverse y)y))
-7 bytes thanks to @ceilingcat !
Dyalog APL (18 characters)
{⍵≡⌽⍵}'\w'⎕S'\u0'⊢
Search for alphanumeric characters in the right argument, and return any found upper-cased (this avoids any need for punctuation, whitespace and casing). Then just check what's returned to see if it matches the reverse.
Example
{⍵≡⌽⍵}'\w'⎕S'\u0'⊢'Eva, can I stab bats in a cave?'
1
APL, 78 65 Bytes
l←⎕D,⎕UCS v+32⊣c←⎕D,⎕UCS v←64+⍳26⋄(⌽≡⊢)∊{⍵/⍨⍵∊l}¨{⍵∊c:l[c⍳⍵]⋄⍵}¨⎕
I'm going to assume that the Original Poster meant limit the INPUT string to the Ascii character set.
REXX, 84 bytes
arg n
n=space(translate(n,,translate(n,,xrange(a,z)xrange(0,9))),0)
say n=reverse(n)
arg n
reads argument into variable n, converting it to upper-case.
xrange(a,z)xrange(0,9) concatenates the two ranges A—Z and 0—9.
translate takes a string to process, an output translation table and an input translation table, and optionally a padding character to replace those characters not found in the output table with. Hence
translate(n,,xrange(a,z)xrange(0,9)) maps the string n with an input table consisting only of alphanumerical characters and an empty output table, resulting in a string consisting only of punctuation, spaces and other non-alphanumericals (since they were not in either table). The filtered-out characters are rendered as spaces.
translate(n,,translate(n,,xrange(a,z)xrange(0,9))) uses the above non-alphanumerics string as an input table and an empty output table, applying it to n, resulting in a string consisting only of alphanumericals, since they were not in the input or output tables. The non-alphanumerics are rendered as spaces.
space() takes a string and a number, spacing out the words with the supplied amount of spaces between. In this case, the supplied number is 0, hence all spaces are removed.
By this point, n has been reduced to consisting only of alphanumeric characters without any spaces.
say n=reverse(n) prints out whether n is identical to its reversed version.
C, 199 bytes
#define R return
#define C unsigned char
#define F for
s(C*a){C*b;if(a&&*a)F(b=a+strlen(a)-1;;++a,--b){F(;a<b&&!isalnum(*a);)++a;F(;a<b&&!isalnum(*b);)--b;if(a>=b)R 1;if((*a|32)-(*b|32))R 0;}R 1;}
//ungolf
v(C*a)
{ C*b;
if(a&&*a)
F(b=a+strlen(a)-1;;++a,--b)
{F(;a<b&&!isalnum(*a);)++a;
F(;a<b&&!isalnum(*b);)--b;
if(a>=b) R 1;
if((*a|32)-(*b|32))R 0;
}
R 1;
}
#define P printf
main()
{C*b="Eva, can I stab bats in a cave?";
P("%s %d\n", b, s(b));
R 0;
}
//results
//Eva, can I stab bats in a cave? 1
AHK, 83 bytes (L7 loser)
StringUpper,s,1
s:=RegExReplace(s,"[\W_]")
Loop,Parse,s
t:=A_LoopField t
Send % s=t
Outputs 1 for palindromes and 0 for not.
Racket 118 bytes
(let((l(filter(λ(x)(or(char-alphabetic? x)(char-numeric? x)))(string->list(string-upcase s)))))(equal? l(reverse l)))
Ungolfed:
(define (palindrome? s)
(let((l(filter(λ(x)(or(char-alphabetic? x)
(char-numeric? x)))
(string->list (string-upcase s)))))
(equal? l(reverse l))))
Testing:
(palindrome? "abc dcB;_A")
(palindrome? "abc;@#$zdc b a")
(palindrome? "1%^&234 56")
(palindrome? "1a234 * ^ && 565432A1")
Output:
#t
#f
#f
#t
PHP, 26 84 80 78 62 63 bytes
<?=strrev($s=strtolower(preg_replace("#\W#","",$argv[1])))==$s;
takes input from first command line argument; prints 1 for truthy, empty string for falsy.
I18n is a littly expansive, as there is no multibyte alternative for strrev (110 bytes; run with -r):
preg_match_all("#.#us",$s=strtolower(preg_replace("#\W#u","",$argv[1])),$m);echo$s==join(array_reverse($m[0]);
utf8_strrev blatantly stolen from the PHP manual. You might also want to take a look at this blog post.
C++14, 104 bytes
Actually overlooked the requirement to ignore case and whitespace, so here is:
auto f=
[](auto s,int&n){
auto r=s.rbegin();n=1;for(auto c:s){if(isalnum(c)){while(!isalnum(*r))r++;if((c|32)!=(*(r++)|32))n=0;}}
}
;
strict solution, 72 68 bytes
-4 bytes for returning by parameter.
As unnamed lambda, assuming input s is of type std::string and returning the result by a parameter:
[](auto s,int&n){auto r=s.rbegin();n=1;for(auto c:s)if(c!=*r++)n=0;}
Ungolfed & usage:
#include <iostream>
#include <string>
auto f=
[](auto s, int& n){
auto r=s.rbegin();
n=1;
for(auto c:s)
if(c!=*r++)
n=0;
}
;
int main(){
int n;
#define p(s) f(std::string(s),n); std::cout << n << std::endl
p("Hello");
p("ABCCBA");
p("ABCBA");
}
C++, 74 bytes
This code is actually really elegant, and easy to understand (when formatted correctly). I don't believe it's possible to get any shorter in C++, and it doesn't use any standard library functions.
p(auto c){auto e=c;while(*e)++e;--e;while(*e==*c&e>c)--e,++c;return e<=c;}
Example usage:
p("Hello"); //Outputs 0
p(""); //Outputs 1
p("a"); //Outputs 1
p("HellolleH"); //Outputs 1
Nicely formatted version:
p(auto c)
{
auto e=c;
while(*e) ++e;
--e;
while(*e==*c & e>c)--e,++c;
return e<=c;
}
Racket, 132 bytes
Pretty embarrassing, but maybe somebody can see a way of making this shorter!
((λ(l[n(floor(/(length l)2))])(equal?(take l n)(take(reverse l)n)))(string->list(regexp-replace*"[^0-9a-z]"(string-downcase s)"")))
Code listing with test module
#lang racket
(define/contract (palindrome? s)
(string? . -> . boolean?)
((λ(l[n(floor(/(length l)2))])(equal?(take l n)(take(reverse l)n)))(string->list(regexp-replace*"[^0-9a-z]"(string-downcase s)""))))
(module+ test
(require rackunit)
(define tests
'(("Eva, can I stab bats in a cave?" . #t)
("A man, a plan, a canal. Panama!" . #t)
("Madam, I'm Adam Corolla." . #f)
("757" . #t)
("Boeing 757" . #f)
("A man, a plan, a big shovel, a canal. Panama!" . #f)
("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal >> __Panama__" . #t)))
(for ([t tests])
(check-equal? (palindrome? (car t)) (cdr t) (~a t))))
PowerShell, 194 190 bytes
A recursive implementation to show how an unnamed PowerShell scriptblock can call itself.
$P={param([string]$s)$s=($s-replace'[^a-z]').tolower();if(!$s){return $true};if($s.length-lt4){return $s[0]-eq$s[-1]};$s[0]-eq$s[-1]-and(&$MyInvocation.MyCommand.ScriptBlock $s.trim($s[0]))}
ungolfed:
$P={
param([string]$s)
$s=($s-replace'[^a-z]').tolower();
if(!$s){return $true};
if($s.length-lt4){return $s[0]-eq$s[-1]};
$s[0]-eq$s[-1]-and(&$MyInvocation.MyCommand.ScriptBlock $s.trim($s[0]))
}
tests:
&$P "Eva, can I stab bats in a cave?"
&$P "Eva, can I stab cats in a cave?"
&$P "A man, a plan, a canal. Panama!"
&$P "A man, a plan, a big shovel, a canal. Panama!"
&$P "Madam, I'm Adam."
&$P "Madam, I'm Adam Corolla."
&$P "757"
&$P "Boeing 757"
Pylongolf2, 24 bytes
c╨2"[^a-zA-Z]"-_╨1=~
c takes the input, ╨2 to convert to lower case.
I then push a regex onto the stack and use - to remove all non-alphabetical characters in the input.
_ duplicates the input.
╨1 reverses it and = then compares them.
~ prints the stack in the end which prints either true or false.
Mathematica 54 53
One byte saved thanks to CatsAreFluffy:
PalindromeQ@StringCases[ToUpperCase@#,WordCharacter]&
For those with version 10.2 or earlier:
#==Reverse@#&@StringCases[ToUpperCase@#,WordCharacter]&
Example
PalindromeQ@StringCases[ToUpperCase@#, WordCharacter]&["Eva,can I stab bats in a cave?"]
True
PHP 60 characters.
First try on codegolf.
//thank you manatwork
echo($x=preg_replace('/\W/','',strtolower($c)))==strrev($x);
Example:
$c='Eva, can I stab bats in a cave?';
echo($x=preg_replace('/\W/','',strtolower($c)))==strrev($x);
//prints 1
Windows PowerShell, 56 47 45 chars
Updated (see comments), and can remove the brackets around the regex:
($s=$s-replace'\W')-eq(-join$s[$s.length..0])
Original (56)
$s=$s-replace'[^\w]','';$s-eq($s[-1..-$s.length]-join'')
Original Un-golfed:
$s = "Eva, can I stab bats in a cave?"
$s = $s -replace '[^\w]', ''
$rev = $s[-1..-$s.length] -join ''
$s -eq $rev
C++, 107 (miscounted), 100 (miscounted), 81
string s;for(int c:t)if(isalnum(c))s+=c|32;return s==string(s.rbegin(),s.rend());
- Exploits ASCII bit patterns.
- Relies on an evil
using namespace std;. - Uses bitwise AND and OR instead of the logical operators.
Uses
intbecause it's shorter thancharorauto.#include <string> using namespace std; bool IsPalindrome(const string & t) { string s;for(int c:t)if(isalnum(c))s+=c|32;return s==string(s.rbegin(),s.rend()); } #include <cassert> int main() { assert(!IsPalindrome("gorilla")); // simple failure assert( IsPalindrome("racecar")); // simple success assert( IsPalindrome("Hannah")); // case blind assert(!IsPalindrome("1999")); // digit failure assert( IsPalindrome("2002")); // digit success // Ignore spacing, punctuation, and case: assert( IsPalindrome(" \t09AZ/:@[`{za90")); // boundaries assert( IsPalindrome("A man, a plan, a canal: Panama.")); assert( IsPalindrome("Eva, can I stab bats in a cave?")); assert( IsPalindrome("")); // empty string return 0; }
Ruby, 48
p((g=gets.upcase.gsub /[^A-Z\d]/,'')==g.reverse)
Quite simple, and hastily made so not golfed too much. I shall golf it more later.
Python 3 (51 char)
and may be Python 2
based on abhiram solution (with more agressive golfing)
from re import findall
def palindrome(i):
i=findall('[a-z\d]',i.lower())
return i==i[::-1]
print(palindrome(input('Phrase: ')))
may be shortened to 46 chars, using RE '\w'
and variant with extremely shortened function body (27 chars)
import re
l=str.lower
f=re.compile('[a-z\d]').findall
def palindrome(i):i=f(l(i));return i==i[::-1]
print(palindrome(input('Phrase: ')))
Smalltalk, Squeak/Pharo flavour
116 chars using traditional formatting with tabs
You add two methods to String:
selffles
^self = self reverse
isPalindrome
^(self asUppercase asDecomposedUnicode select: #isAlphaNumeric) selffles
We could of course eliminate some spaces, or use shorter method names, but let's not betray the spirit of Smalltalk.
More over, this will handle French palindromes, like in http://fr.wikipedia.org/wiki/Liste_de_palindromes_fran%C3%A7ais, not many answers in this page can.
['Léon a trop par rapport à Noël' isPalindrome] assert.
Haskell, 43
Using the standard libraries Control.Monad, Control.Monad.Instances, and Data.Char:
ap(==)reverse.map toLower.filter isAlphaNum
Haskell 48
(\x->x==reverse x).map toLower.filter isAlphaNum
used like this:
(\x->x==reverse x).map toLower.filter isAlphaNum$"Eva, can I stab bats in a cave?"
JAVA (or the most verbose language ever), 102 96 95 char
s=s.replaceAll("\\W|_","");return s.equalsIgnoreCase(new StringBuffer(s).reverse().toString());
Usage (with ungolfed code):
static boolean q(String s) {
s=s.replaceAll("\\W|_","");
return s.equalsIgnoreCase(new StringBuffer(s).reverse().toString());
}
public static void main(String[] args) {
System.out.println(q("'A man, a plan, a canal - Panama!'"));
}
Shortened with the help of the commenter below
Python 3/2 59 chars:
def pld(i):
p=[c for c in i.lower() if c.isalnum()]
return(p == p[::-1])
GolfScript, 36 34 31 30 characters
{0"0:A[a{"@{>^}+/},{32|}%.-1%=
Similar algorithm to my previous (Javascript) solution.
0"0:A[a{"@{>^}+/ -- Optimised by Peter Taylor and Howard. My version was "/9@Z"{1$<},,2%\;. Howard donated function concatenation and Peter Taylor donated XOR for modulo-2. It's basically a generic method of comparing if the value is in a sequence of ranges.
{.96>32*-}% (11 characters) is not really an improvement over Javascript's .toUpperCase() (14 characters), especially since it mangles some weird punctuation that follows z in the ASCII table (which doesn't matter here).
as Peter Taylor's suggested, however, if we filter out alphanumerics first, we can convert to lowercase and digits just by setting one bit in each character: {32|}
.-1%= does all the palindromic heavy lifting. One part I'm not really fond of is how long it took me to find out how to reverse an array. I should have read the docs. The other two characters perform stack management and comparison.
Further, if I can assume that none of the following control characters are present: (Data link escape, device control 1-4, negative acknowledge, synchronous idle, end of transmission block, cancel, end of medium) (we all agree these are all pretty obscure) or if I can treat them as uppercase versions of the digits 0-9, we can save another two characters:
GolfScript, 28 characters
{32|}%{0"0:a{"@{>^}+/},.-1%=
Python 2: 49 (without counting the method signature)
def f(s):
s=filter(str.isalnum,s.upper())
return s==s[::-1]
A complete program, with input and output can be writte in 74 characters.
import sys
s=filter(str.isalnum,sys.stdin.read().upper())
print s==s[::-1]
Example usage:
$echo 'Eva,can I stab bats in a cave?' | python palindrome.py
True
$ cat huge_palindrome.txt | python palindrome.py
True
$echo 'Able was I ere i SaW elBa' | python palindrome.py
True
(huge_palindrome.txt contains this 17,826 word palindrome)
This solution can be adapted to python 3 adding some characters:
Python 3: 55
def f(s):
s=list(filter(str.isalnum,s.upper()))
return s==s[::-1]
Bash: 52 48 46 characters
s=${1,,};s=${s//[^a-z0-9]};[ $s = `rev<<<$s` ]
This takes the sting to check as first parameter and sets the exit code to 0 for palindrome and 1 for not.
Sample run:
bash-4.2$ p() { s=${1,,};s=${s//[^a-z0-9]};[ $s = `rev<<<$s` ]; }
bash-4.2$ p 'Eva, can I stab bats in a cave?'; echo $?
0
bash-4.2$ p 'A man, a plan, a canal. Panama!'; echo $?
0
bash-4.2$ p "Madam, I'm Adam Corolla."; echo $?
1
bash-4.2$ p '757'; echo $?
0
bash-4.2$ p 'Boeing 757'; echo $?
1
bash-4.2$ p 'A man, a plan, a shovel, a canal. Panama!'; echo $?
1
bash-4.2$ p 'A_man,_a_plan, a_caremer, a canal:_Panama!'; echo $?
0
k (50 48 45 38 chars)
Suppresses all errors, returning a default of 0b (false).
{X~|X@:&(X:_:x)in 10h$(48+!10),97+!26}
Example:
k){X~|X@:&(X:_:x)in 10h$(48+!10),97+!26} "Eva, can I stab bats in a cave?"
1b
edit: shaved three more character by avoiding intermediate variable. H/T, CS. -7: No need to suppress errors.
Ruby: 43 38 characters
s=s.upcase.tr'^A-Z0-9','';s==s.reverse
Sample run:
irb(main):001:0> p=->s{s=s.upcase.tr'^A-Z0-9','';s==s.reverse}
=> #<Proc:0x854592c@(irb):1 (lambda)>
irb(main):002:0> p['Eva, can I stab bats in a cave?']
=> true
irb(main):003:0> p['A man, a plan, a canal. Panama!']
=> true
irb(main):004:0> p["Madam, I'm Adam Corolla."]
=> false
irb(main):005:0> p['757']
=> true
irb(main):006:0> p['Boeing 757']
=> false
irb(main):007:0> p['A man, a plan, a shovel, a canal. Panama!']
=> false
irb(main):009:0> p['A_man,_a_plan, a_caremer, a canal:_Panama!']
=> true
C# 82 only :)
var x=s.ToLower().Where(char.IsLetterOrDigit);return x.SequenceEqual(x.Reverse());
Couldn't resist the temptation of writing a boilerplate-free program in my favorite language.
A test is available here: http://ideone.com/8bwz7z
R: 66
w=grep("[a-z0-9]",strsplit(tolower(s),"")[[1]],v=T);all(w==rev(w))
Usage:
f=function(s){w=grep("[a-z0-9]",strsplit(tolower(s),"")[[1]],v=T);all(w==rev(w))}
f("Eva, can I stab bats in a cave?")
[1] TRUE
Python 2 64 Charecters:
i =''.join(re.findall('[a-z0-9]+',i.lower()))
return i==i[::-1]
JavaScript Code :: ONLY 140 characters Palindrome
function palindrome()
{
var user=prompt("Enter the characters to check the palindrome");
var split=user.split('').reverse().join(''); // ONLY this line counts
if(user == split)
{
alert("The given word is a Palindrome");
} else
{
alert("The given word is not a Palindrome");
}
}
palindrome();
K, 25
{x~|x:_x@&x in,/.Q`a`A`n}
.
k){x~|x:_x@&x in,/.Q`a`A`n}"Eva, can I stab bats in a cave?"
1b
J, 30 characters
*/(=|.)tolower(#~'[^_\W]'rxE])
Usage:
*/(=|.)tolower(#~'[^_\W]'rxE])'A man, a plan, a canal - Panama!'
1
*/(=|.)tolower(#~'[^_\W]'rxE])'Doc, note: I dissent. A fast never prevents a fatness. I diet on cod'
1
Lua, 56
a=io.read"*l":lower():gsub("%W","")print(a:reverse()==a)
Javascript, 53 characters:
(x=x.toLowerCase().match(/[a-z\d]/g))+""==x.reverse()
is a javascript expression that evaluates to true if x is a palindrome, to false if it isn't. It assumes x is a string. If that's not guaranteed, prepend x+="",
Here's a breadcrumb: Due to how reverse() works,
(x=x.toLowerCase().match(/[a-z\d]/g))==""+x.reverse()
fails. However,
""+(x=x.toLowerCase().match(/[a-z\d]/g))==x.reverse()
is perfectly fine.