Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@StevenClontz
Created January 3, 2013 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StevenClontz/4445807 to your computer and use it in GitHub Desktop.
Save StevenClontz/4445807 to your computer and use it in GitHub Desktop.
# Ask user for text file to inspect
filename = raw_input('Enter name of text file to inspect: ')
# If the file is legit
try:
# Grab file
f = open(filename)
# Read file, make all lowercase
file_string = f.read().lower()
# 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
MAX_LENGTH = 50
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