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
# 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