Skip to content

Instantly share code, notes, and snippets.

@yourcelf
Created June 20, 2013 01:12
Show Gist options
  • Save yourcelf/5819531 to your computer and use it in GitHub Desktop.
Save yourcelf/5819531 to your computer and use it in GitHub Desktop.
find_palindromes.py
# Find unintentional palindromes in a text file.
import re
import argparse
from collections import defaultdict
parser = argparse.ArgumentParser(description="Find unintentional palindromes in a text file.")
parser.add_argument("filename", help="The name of the file to look in.")
parser.add_argument("--min", help="Minimum length", default=4)
parser.add_argument("--max", help="Maximum length", default=500)
def scan_file(args):
with open(args.filename) as fh:
content = fh.read()
cleaned = re.sub('[^a-z]', '', content.lower())
dromes = defaultdict(list)
for length in range(args.min, args.max):
for i in range(0, len(cleaned) - length):
test = cleaned[i:i + length]
if test == test[::-1]:
dromes[length].append(test)
if len(dromes[length]) > 0:
print length, dromes[length]
if __name__ == "__main__":
args = parser.parse_args()
print args
scan_file(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment