Skip to content

Instantly share code, notes, and snippets.

Created January 3, 2013 18:40
What would you like to do?
# Ask user for text file to inspect
filename = raw_input('Enter name of text file to inspect: ')
# If the file is legit
# Grab file
f = open(filename)
# Read file, make all lowercase
file_string =
# Remove all non word characters
import re
string = re.sub(r'\W+', '', file_string)
# Record list of longest palendromes
pal_list = []
# Length of longest palendrome
pal_len = 0
# For each character in string, search substrings of length MAX_LENGTH and check if palendromic
for m, l in enumerate(string):
for n in range(m+2, m+MAX_LENGTH):
substr = string[m:n+1]
if len(substr) > 1:
substr_rev = substr[::-1]
if substr == substr_rev:
print "Found \"%s\" beginning at character %s" % (substr, str(m))
if len(substr) == pal_len:
pal_list.append((m, substr))
elif len(substr) > pal_len:
pal_len = len(substr)
pal_list = [(m, substr)]
# List longest palindromes
print "\n---\nLongest palendromes found:"
for tup in pal_list:
print "Found \"%s\" beginning at character %s" % (tup[1], str(tup[0]))
except IOError as e:
print "Couldn't open file: %s" % e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment