Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
from __future__ import with_statement
# To run:
# python -m timeit -n5 -s 'from palindrome import run, get_words, palindrome_X; words = get_words()' 'run(words, palindrome_X)'
def palindrome_1(x):
# 998ms / loop (Best of 3)
return x == ''.join(reversed(x))
def palindrome_2(x):
# 1.01s / loop (Best of 3)
middle = len(x) / 2
return x[:middle] == ''.join(reversed(x[-middle:]))
def palindrome_3(x):
# 555ms / loop (Best of 3)
middle = len(x) / 2
for i, letter in enumerate(x[:middle]):
if letter != x[-i-1]:
return True
# book downloaded from
# CRIME AND PUNISHMENT By Fyodor Dostoevsky
def get_words():
words = []
with open('2554.txt', 'r') as f:
for line in f.readlines():
for word in line.split():
if len(word) > 1:
return words
def run(words, method):
total = 0
for word in words:
if len(word) > 1 and method(word):
total += 1
print total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment