Skip to content

Instantly share code, notes, and snippets.

@robert-king
Last active October 1, 2018 02:36
Show Gist options
  • Save robert-king/4882bc8768df90c874ae5650a8c8b9cd to your computer and use it in GitHub Desktop.
Save robert-king/4882bc8768df90c874ae5650a8c8b9cd to your computer and use it in GitHub Desktop.
// in this example we don't need Math.floor, we just check i < j
function isPalindrome(phrase){
alpha = [];
for (var char of phrase.toLowerCase()) {
if ('a' <= char && 'z' >= char) {
alpha.push(char);
}
}
phrase = alpha.join('');
var j = phrase.length - 1;
for (var i = 0; i < j; i++, j--) {
if (phrase[i] !== phrase[j]) {
return false
}
}
return true;
}
# in this verison, we create an unsafe palindrome checker which remarkably,
# works on every word in the english language I could find
def palindrome(s):
return s == s[::-1]
def unsafe(s):
if s[0] != s[-1]:
return False
n = len(s)
return n <= 3 or s[1] == s[-2] and (n <= 5 or n <= 7 and s[2] == s[-3])
words = open('dict.txt').read().splitlines()
assert(map(unsafe, words) == map(palindrome, words))
from timeit import timeit
print(timeit("list(map(palindrome,words))",setup="from __main__ import words, palindrome", number=100))
print(timeit("list(map(unsafe,words))",setup="from __main__ import words, unsafe", number=100))
print(timeit("list(map(bool,words))",setup="from __main__ import words, unsafe", number=100))
# palindrome 6.2 seconds
# unsafe 4.2 seconds
# bool 1.8 seconds (theoretic optimum?)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment