Last active
December 15, 2015 02:49
-
-
Save dirn/5190272 to your computer and use it in GitHub Desktop.
PyCon Anagrams
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/env python | |
"""Checks for anagrams in stdin. | |
Example: $ curl -sL http://thumb.tk/8Qdr | python anagrams.py | |
""" | |
import itertools | |
import sys | |
def flatten(words): | |
"""Flattens, lowers, and sorts characters in an iterable.""" | |
return ''.join(sorted(itertools.chain(*map(lambda x: x.lower(), words)))) | |
def strip(characters): | |
("Strips invalid characters from an iterable, leaving only alpha " | |
"and whitespace.") | |
def valid(s): | |
return s.isalpha() or s.isspace() | |
return ''.join(filter(valid, characters)) | |
results = [] | |
sentence = sys.stdin.readline() | |
words = strip(sentence).split() | |
pairs = itertools.combinations(words, 2) | |
inner, outer = itertools.tee(pairs) | |
# Without coverting outer to a list, it would be empty after the first | |
# iteration. | |
outer = list(outer) | |
for x in inner: | |
x_original = x | |
x = flatten(x) | |
for y in outer: | |
y_original = y | |
if sorted(x_original) == sorted(y_original): | |
continue | |
y = flatten(y) | |
if x != y: | |
continue | |
if (x_original, y_original) in results: | |
continue | |
if (y_original, x_original) in results: | |
continue | |
results.append((x_original, y_original)) | |
for match in results: | |
output = (x for t in match for x in t) | |
print '"{}, {}" is an anagram for "{}, {}"'.format(*output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment