Created
January 12, 2013 00:12
-
-
Save typehorror/4515122 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
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 | |
return True | |
# book downloaded from http://www.gutenberg.org/files/2554/2554.txt | |
# 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: | |
words.append(word) | |
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