Taskintro
Check whether a string is a palindrome
Also called palindrome, palindrome check, palindrome detection, is palindrome, valid palindrome, reads the same backwards, inexact palindrome, two pointer palindrome.
Check whether a text reads the same backwards as forwards, with case, spaces and punctuation ignored: compare the cleaned text with its reverse, or move two indexes toward the middle.
- Evidence
- Code in 10 languages
Task
A palindrome, in the words of Wikipedia, is a "sequence of symbols that reads the same backwards as forwards"1, such as racecar. For a phrase, "Punctuation, capitalization, and spaces are usually ignored"1, so A man, a plan, a canal: Panama is a palindrome. The Rosetta Code task asks for a function that "checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome"2, and for a second one that "detects inexact palindromes"2, where white space and punctuation do not count and the case does not matter.
The function is_palindrome(text) does the inexact check:
- Keep only the ASCII letters and digits of the text.
- Change
AtoZtoatoz. - Return true if the result is the same as its reverse.
So is_palindrome("No 'x' in Nixon") is true, and is_palindrome("race a car") is false. A text with no letters and no digits gives true, because an empty sequence is the same as its reverse. The contract uses ASCII text. The section Pitfalls shows what changes with other text.
Solutions
There are two methods:
- Compare with the reverse. Build the cleaned text, reverse it, and compare. This is short, and it uses memory for two copies.
- Two indexes. Put one index at the start and one at the end. Move each index past the characters that do not count. Compare the two characters, then move both indexes toward the middle. Stop when the indexes meet. This uses no extra memory, and it stops at the first difference.
| Language | Keep letters and digits | Lower case | Method |
|---|---|---|---|
| Python | c.isascii() and c.isalnum() |
c.lower() |
compare with kept[::-1] |
| JavaScript, TypeScript | replace(/[^a-z0-9]/g, "") |
toLowerCase() |
two indexes |
| Java | a test on the ranges a-z, A-Z, 0-9 |
Character.toLowerCase |
two indexes |
| C# | char.IsAsciiLetterOrDigit |
char.ToLowerInvariant |
two indexes |
| Go | a test on the byte ranges | b | 0x20 on letters |
two indexes |
| Rust | u8::is_ascii_alphanumeric |
to_ascii_lowercase |
iter().eq(iter().rev()) |
| C | isalnum((unsigned char)c) |
tolower |
two indexes |
| C++ | std::isalnum on unsigned char |
std::tolower |
two indexes |
| Bash | ${s//[^a-z0-9]/} |
${1,,} |
two indexes |
- Python.
str.isalnumalone is not enough. It returns true "if all characters in the string are alphanumeric"3, and that includes letters such aséand digits of other scripts. The testc.isascii()keeps the check on the contract.kept[::-1]is the list in reverse order. - JavaScript and TypeScript. The solution changes the text to lower case first, so the regular expression has to remove only the characters outside
a-zand0-9. Then it comparess[i]withs[s.length - 1 - i]for the first half. - Java, C#, C and C++. Each solution moves the two indexes over the original text, so it makes no copy. In C and C++, the argument of
isalnumandtolowermust be a value ofunsigned char, because a negativechargives undefined behavior. In the "C" locale,isalnumis true only for ASCII letters and digits. - Go and Rust. The text is ASCII, so each byte is a character, and the solutions work on bytes.
text[i]in Go andtext.bytes()in Rust give the bytes. - Bash.
${1,,}changes the text to lower case, and${s//[^a-z0-9]/}removes all other characters. The loop compares${s:i:1}with${s:n-1-i:1}. The function printstrueorfalse.
Python, with the method that compares with the reverse:
def is_palindrome(text):
kept = [c.lower() for c in text if c.isascii() and c.isalnum()]
return kept == kept[::-1]
for text in ["racecar", "A man, a plan, a canal: Panama", "race a car", "0P", ""]:
print(repr(text), is_palindrome(text))
print("é".isalnum(), "é".isascii())
'racecar' True
'A man, a plan, a canal: Panama' True
'race a car' False
'0P' False
'' True
True False
Edge cases
- Empty text. It is a palindrome. A program that reads
text[0]before it checks the length fails on it. - No letters and no digits.
?! ...cleans to the empty text, so it is a palindrome too. - One character. Always a palindrome. With two indexes, the loop does not run.
- Case.
Aais a palindrome only after the change to lower case. - Digits. Digits count, so
12321is a palindrome and123is not. - A digit and a letter.
0Pis not a palindrome. A program that compares0(code 48) withp(code 112) is correct. A program that ignores digits, or that removes all characters that are not letters, gives the wrong answer. - Even and odd length.
abbahas no middle character, andabcbahas one. The two index loop stops wheni >= j, so both work.
Pitfalls
- Reversing UTF-16 code units. In JavaScript,
split("")splits a string "by UTF-16 code units. This destroys surrogate pairs"4. An emoji is a pair of code units, so the reverse of the string puts the two halves in the wrong order:
This code runs but gives a wrong answer on purpose.
function isPalindrome(s) {
return s === s.split("").reverse().join("");
}
console.log(isPalindrome("abba"), isPalindrome("a😀a"));
const s = "a😀a";
console.log(s === [...s].reverse().join(""));
true false
true
The spread syntax [...s] uses the string iterator, which "yields the Unicode code points of the string value as individual strings"5, so it keeps each pair together.
- Combining marks. A code point is still not a character on the screen.
écan be one code point, oreand the combining mark U+0301. If the program reverses the code points ofété, each mark moves to the wrong letter. For text that is not ASCII, normalize the text first, for example to NFC, or compare grapheme clusters. - Letters of other scripts.
str.isalnumin Python,Character.isLetterOrDigitin Java andchar.IsLetterOrDigitin C# accept letters and digits of all scripts. That is correct for Unicode text, but it is not the contract of this task. - A sign in C.
isalnum(c)with acharthat has a negative value, such as a byte of UTF-8 text, is undefined behavior. Cast it tounsigned charfirst. - Copying in a loop. A loop that builds the reverse with
reversed = c + reversedcopies the string at each step, so it takes O(n²) time. Use a reverse function of the language, or two indexes.
Related tasks
- Reverse a string: the reverse of a string, and why code points and grapheme clusters give different answers.
- Detect anagrams: another check on the letters of a text.
- String: code units, code points and grapheme clusters.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
def is_palindrome(text: str) -> bool:
"""Return True if the ASCII letters and digits of text, in lower case,
read the same backwards. Other characters do not count."""
kept = [c.lower() for c in text if c.isascii() and c.isalnum()]
return kept == kept[::-1]
if __name__ == "__main__":
print(is_palindrome("A man, a plan, a canal: Panama"))
test_palindrome.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
import pytest
from palindrome import is_palindrome
CASES = [
("racecar", "racecar", True),
("panama", "A man, a plan, a canal: Panama", True),
("hello", "hello", False),
("empty", "", True),
("only-punctuation", "?! ...", True),
("one-letter", "a", True),
("two-letters", "ab", False),
("mixed-case", "Aa", True),
("nixon", "No 'x' in Nixon", True),
("cat-i-saw", "Was it a car or a cat I saw?", True),
("digits", "12321", True),
("digits-not", "123", False),
("zero-p", "0P", False),
("race-a-car", "race a car", False),
("even-near", "abca", False),
]
@pytest.mark.parametrize(("name", "text", "want"), CASES, ids=[c[0] for c in CASES])
def test_is_palindrome(name, text, want):
assert is_palindrome(text) is want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
#ifndef PALINDROME_HPP
#define PALINDROME_HPP
#include <cctype>
#include <cstddef>
#include <string_view>
// Returns true if the ASCII letters and digits of text, in lower case, read
// the same backwards. Two indexes move toward the middle, so the function
// makes no copy of the text.
inline bool is_palindrome(std::string_view text) {
if (text.size() < 2) {
return true;
}
std::size_t i = 0;
std::size_t j = text.size() - 1;
while (i < j) {
const auto a = static_cast<unsigned char>(text[i]);
const auto b = static_cast<unsigned char>(text[j]);
if (std::isalnum(a) == 0) {
++i;
} else if (std::isalnum(b) == 0) {
--j;
} else if (std::tolower(a) != std::tolower(b)) {
return false;
} else {
++i;
--j;
}
}
return true;
}
#endif
test_palindrome.cpp 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
#include <cstdio>
#include "palindrome.hpp"
namespace {
struct test_case {
const char* name;
const char* text;
bool want;
};
const test_case cases[] = {
{"racecar", "racecar", true},
{"panama", "A man, a plan, a canal: Panama", true},
{"hello", "hello", false},
{"empty", "", true},
{"only-punctuation", "?! ...", true},
{"one-letter", "a", true},
{"two-letters", "ab", false},
{"mixed-case", "Aa", true},
{"nixon", "No 'x' in Nixon", true},
{"cat-i-saw", "Was it a car or a cat I saw?", true},
{"digits", "12321", true},
{"digits-not", "123", false},
{"zero-p", "0P", false},
{"race-a-car", "race a car", false},
{"even-near", "abca", false},
};
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
if (is_palindrome(c.text) != c.want) {
std::printf("FAIL %s\n", c.name);
++failures;
}
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
/** Checks whether a text is a palindrome, with case, spaces and punctuation ignored. */
public final class Palindrome {
private Palindrome() {}
private static boolean isAsciiLetterOrDigit(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
/**
* Returns true if the ASCII letters and digits of text, in lower case,
* read the same backwards. Two indexes move toward the middle, so the
* method makes no copy of the text.
*/
public static boolean isPalindrome(String text) {
int i = 0;
int j = text.length() - 1;
while (i < j) {
if (!isAsciiLetterOrDigit(text.charAt(i))) {
i++;
} else if (!isAsciiLetterOrDigit(text.charAt(j))) {
j--;
} else if (Character.toLowerCase(text.charAt(i)) != Character.toLowerCase(text.charAt(j))) {
return false;
} else {
i++;
j--;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("A man, a plan, a canal: Panama"));
}
}
PalindromeTest.java 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class PalindromeTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("racecar", "racecar", true),
Arguments.of("panama", "A man, a plan, a canal: Panama", true),
Arguments.of("hello", "hello", false),
Arguments.of("empty", "", true),
Arguments.of("only-punctuation", "?! ...", true),
Arguments.of("one-letter", "a", true),
Arguments.of("two-letters", "ab", false),
Arguments.of("mixed-case", "Aa", true),
Arguments.of("nixon", "No 'x' in Nixon", true),
Arguments.of("cat-i-saw", "Was it a car or a cat I saw?", true),
Arguments.of("digits", "12321", true),
Arguments.of("digits-not", "123", false),
Arguments.of("zero-p", "0P", false),
Arguments.of("race-a-car", "race a car", false),
Arguments.of("even-near", "abca", false)
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void isPalindrome(String name, String text, boolean want) {
assertEquals(want, Palindrome.isPalindrome(text));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
#include "palindrome.h"
#include <ctype.h>
#include <string.h>
bool is_palindrome(const char *text) {
size_t n = strlen(text);
if (n < 2) {
return true;
}
size_t i = 0;
size_t j = n - 1;
while (i < j) {
unsigned char a = (unsigned char)text[i];
unsigned char b = (unsigned char)text[j];
if (!isalnum(a)) {
i++;
} else if (!isalnum(b)) {
j--;
} else if (tolower(a) != tolower(b)) {
return false;
} else {
i++;
j--;
}
}
return true;
}
palindrome.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
#ifndef PALINDROME_H
#define PALINDROME_H
#include <stdbool.h>
// Returns true if the ASCII letters and digits of text, in lower case, read
// the same backwards. Other characters do not count.
bool is_palindrome(const char *text);
#endif
test_palindrome.c 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
#include "palindrome.h"
#include <stdio.h>
#include <stdlib.h>
struct test_case {
const char *name;
const char *text;
bool want;
};
static const struct test_case cases[] = {
{"racecar", "racecar", true},
{"panama", "A man, a plan, a canal: Panama", true},
{"hello", "hello", false},
{"empty", "", true},
{"only-punctuation", "?! ...", true},
{"one-letter", "a", true},
{"two-letters", "ab", false},
{"mixed-case", "Aa", true},
{"nixon", "No 'x' in Nixon", true},
{"cat-i-saw", "Was it a car or a cat I saw?", true},
{"digits", "12321", true},
{"digits-not", "123", false},
{"zero-p", "0P", false},
{"race-a-car", "race a car", false},
{"even-near", "abca", false},
};
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
if (is_palindrome(cases[i].text) != cases[i].want) {
printf("FAIL %s\n", cases[i].name);
failures++;
}
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
/// <summary>Checks whether a text is a palindrome, with case, spaces and punctuation ignored.</summary>
public static class Palindrome
{
/// <summary>
/// Returns true if the ASCII letters and digits of text, in lower case,
/// read the same backwards. Two indexes move toward the middle, so the
/// method makes no copy of the text.
/// </summary>
public static bool IsPalindrome(string text)
{
var i = 0;
var j = text.Length - 1;
while (i < j)
{
if (!char.IsAsciiLetterOrDigit(text[i]))
{
i++;
}
else if (!char.IsAsciiLetterOrDigit(text[j]))
{
j--;
}
else if (char.ToLowerInvariant(text[i]) != char.ToLowerInvariant(text[j]))
{
return false;
}
else
{
i++;
j--;
}
}
return true;
}
}
PalindromeTests.cs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
using Xunit;
public sealed class PalindromeTests
{
public static TheoryData<string, string, bool> Cases => new()
{
{ "racecar", "racecar", true },
{ "panama", "A man, a plan, a canal: Panama", true },
{ "hello", "hello", false },
{ "empty", "", true },
{ "only-punctuation", "?! ...", true },
{ "one-letter", "a", true },
{ "two-letters", "ab", false },
{ "mixed-case", "Aa", true },
{ "nixon", "No 'x' in Nixon", true },
{ "cat-i-saw", "Was it a car or a cat I saw?", true },
{ "digits", "12321", true },
{ "digits-not", "123", false },
{ "zero-p", "0P", false },
{ "race-a-car", "race a car", false },
{ "even-near", "abca", false },
};
[Theory]
[MemberData(nameof(Cases))]
public void IsPalindrome(string name, string text, bool want)
{
Assert.NotNull(name);
Assert.Equal(want, Palindrome.IsPalindrome(text));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
/**
* Returns true if the ASCII letters and digits of text, in lower case, read
* the same backwards. Other characters do not count.
*/
export function isPalindrome(text) {
const s = text.toLowerCase().replace(/[^a-z0-9]/g, "");
for (let i = 0, j = s.length - 1; i < j; i++, j--) {
if (s[i] !== s[j]) {
return false;
}
}
return true;
}
palindrome.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { isPalindrome } from "./palindrome.js";
const cases = [
["racecar", "racecar", true],
["panama", "A man, a plan, a canal: Panama", true],
["hello", "hello", false],
["empty", "", true],
["only-punctuation", "?! ...", true],
["one-letter", "a", true],
["two-letters", "ab", false],
["mixed-case", "Aa", true],
["nixon", "No 'x' in Nixon", true],
["cat-i-saw", "Was it a car or a cat I saw?", true],
["digits", "12321", true],
["digits-not", "123", false],
["zero-p", "0P", false],
["race-a-car", "race a car", false],
["even-near", "abca", false],
];
for (const [name, text, want] of cases) {
test(name, () => {
assert.equal(isPalindrome(text), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
/**
* Returns true if the ASCII letters and digits of text, in lower case, read
* the same backwards. Other characters do not count.
*/
export function isPalindrome(text: string): boolean {
const s = text.toLowerCase().replace(/[^a-z0-9]/g, "");
for (let i = 0, j = s.length - 1; i < j; i++, j--) {
if (s[i] !== s[j]) {
return false;
}
}
return true;
}
palindrome.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { isPalindrome } from "./palindrome.ts";
const cases: [string, string, boolean][] = [
["racecar", "racecar", true],
["panama", "A man, a plan, a canal: Panama", true],
["hello", "hello", false],
["empty", "", true],
["only-punctuation", "?! ...", true],
["one-letter", "a", true],
["two-letters", "ab", false],
["mixed-case", "Aa", true],
["nixon", "No 'x' in Nixon", true],
["cat-i-saw", "Was it a car or a cat I saw?", true],
["digits", "12321", true],
["digits-not", "123", false],
["zero-p", "0P", false],
["race-a-car", "race a car", false],
["even-near", "abca", false],
];
for (const [name, text, want] of cases) {
test(name, () => {
assert.equal(isPalindrome(text), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
// Package palindrome checks whether a text is a palindrome, with case, spaces
// and punctuation ignored.
package palindrome
// key returns the byte in lower case and true if b is an ASCII letter or
// digit, and false for every other byte.
func key(b byte) (byte, bool) {
switch {
case b >= 'A' && b <= 'Z':
return b | 0x20, true
case b >= 'a' && b <= 'z', b >= '0' && b <= '9':
return b, true
}
return 0, false
}
// IsPalindrome reports whether the ASCII letters and digits of text, in lower
// case, read the same backwards. The text is ASCII, so the function works on
// bytes, with two indexes that move toward the middle.
func IsPalindrome(text string) bool {
i, j := 0, len(text)-1
for i < j {
a, okA := key(text[i])
b, okB := key(text[j])
switch {
case !okA:
i++
case !okB:
j--
case a != b:
return false
default:
i++
j--
}
}
return true
}
palindrome_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
package palindrome
import "testing"
var cases = []struct {
name string
text string
want bool
}{
{"racecar", "racecar", true},
{"panama", "A man, a plan, a canal: Panama", true},
{"hello", "hello", false},
{"empty", "", true},
{"only-punctuation", "?! ...", true},
{"one-letter", "a", true},
{"two-letters", "ab", false},
{"mixed-case", "Aa", true},
{"nixon", "No 'x' in Nixon", true},
{"cat-i-saw", "Was it a car or a cat I saw?", true},
{"digits", "12321", true},
{"digits-not", "123", false},
{"zero-p", "0P", false},
{"race-a-car", "race a car", false},
{"even-near", "abca", false},
}
func TestIsPalindrome(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := IsPalindrome(c.text); got != c.want {
t.Fatalf("IsPalindrome(%q) = %v, want %v", c.text, got, c.want)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
/// Returns true if the ASCII letters and digits of text, in lower case, read
/// the same backwards. The text is ASCII, so the function works on bytes.
pub fn is_palindrome(text: &str) -> bool {
let kept: Vec<u8> = text
.bytes()
.filter(u8::is_ascii_alphanumeric)
.map(|b| b.to_ascii_lowercase())
.collect();
kept.iter().eq(kept.iter().rev())
}
tests/palindrome_test.rs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
use algo_check_whether_a_string_is_a_palindrome::is_palindrome;
const CASES: &[(&str, &str, bool)] = &[
("racecar", "racecar", true),
("panama", "A man, a plan, a canal: Panama", true),
("hello", "hello", false),
("empty", "", true),
("only-punctuation", "?! ...", true),
("one-letter", "a", true),
("two-letters", "ab", false),
("mixed-case", "Aa", true),
("nixon", "No 'x' in Nixon", true),
("cat-i-saw", "Was it a car or a cat I saw?", true),
("digits", "12321", true),
("digits-not", "123", false),
("zero-p", "0P", false),
("race-a-car", "race a car", false),
("even-near", "abca", false),
];
#[test]
fn cases() {
for &(name, text, want) in CASES {
assert_eq!(is_palindrome(text), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
# is_palindrome text: print true if the ASCII letters and digits of text, in
# lower case, read the same backwards, and false if not.
is_palindrome() {
local s=${1,,} i n
s=${s//[^a-z0-9]/}
n=${#s}
for ((i = 0; i < n / 2; i++)); do
if [[ ${s:i:1} != "${s:n-1-i:1}" ]]; then
echo false
return
fi
done
echo true
}
test_palindrome.bats 97 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-string-is-a-palindrome/.
setup() {
source "$BATS_TEST_DIRNAME/palindrome.sh"
}
@test "racecar" {
run is_palindrome 'racecar'
[ "$status" -eq 0 ]
[ "$output" = true ]
}
@test "panama" {
run is_palindrome 'A man, a plan, a canal: Panama'
[ "$status" -eq 0 ]
[ "$output" = true ]
}
@test "hello" {
run is_palindrome 'hello'
[ "$status" -eq 0 ]
[ "$output" = false ]
}
@test "empty" {
run is_palindrome ''
[ "$status" -eq 0 ]
[ "$output" = true ]
}
@test "only-punctuation" {
run is_palindrome '?! ...'
[ "$status" -eq 0 ]
[ "$output" = true ]
}
@test "one-letter" {
run is_palindrome 'a'
[ "$status" -eq 0 ]
[ "$output" = true ]
}
@test "two-letters" {
run is_palindrome 'ab'
[ "$status" -eq 0 ]
[ "$output" = false ]
}
@test "mixed-case" {
run is_palindrome 'Aa'
[ "$status" -eq 0 ]
[ "$output" = true ]
}
@test "nixon" {
run is_palindrome 'No '\''x'\'' in Nixon'
[ "$status" -eq 0 ]
[ "$output" = true ]
}
@test "cat-i-saw" {
run is_palindrome 'Was it a car or a cat I saw?'
[ "$status" -eq 0 ]
[ "$output" = true ]
}
@test "digits" {
run is_palindrome '12321'
[ "$status" -eq 0 ]
[ "$output" = true ]
}
@test "digits-not" {
run is_palindrome '123'
[ "$status" -eq 0 ]
[ "$output" = false ]
}
@test "zero-p" {
run is_palindrome '0P'
[ "$status" -eq 0 ]
[ "$output" = false ]
}
@test "race-a-car" {
run is_palindrome 'race a car'
[ "$status" -eq 0 ]
[ "$output" = false ]
}
@test "even-near" {
run is_palindrome 'abca'
[ "$status" -eq 0 ]
[ "$output" = false ]
}
References
- Palindrome, Wikipedia, Introduction; Words and phrases
- Rosetta Code, Palindrome detection (task text, from acmeism/RosettaCodeData), task text
- Built-in Types, Python documentation, str.isalnum; str.isascii; str.lower
- String.prototype.split(), MDN Web Docs, Description (the warning on the empty separator)
- String.prototype[Symbol.iterator](), MDN Web Docs, Return value; Description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag ES05X5 Edit this page History Report an error Markdown