#!/usr/bin/python
#lambdagrams.py -- anagram solver, using map/reduce etc.
# The words to sort, on anagramticallity. Which is a word.
words = ["pans", "pots", "opt", "snap", "stop", "tops"]
# Returns a list with the signature and word
def signWord(word):
signature = sorted(word) # Sort the word
signature = "".join(signature) # Turn it into a string
return signature, word
# Brings words with the same signature together in the list
def squashWords(words):
oldSignature = words[0][0] # First signature = signature of first
squashedWords = [] # The list of lists we plan to return
buffer = [] # What we add a group of words to
for word in words:
# New group of words
if word[0] != oldSignature:
squashedWords.append(buffer) # Append the current group
buffer = [] # Clear
oldSignature = word[0]
buffer.append(word[1])
# Last set aren't added to squashedWords
squashedWords.append(buffer)
return squashedWords
def printSet(words):
for set in squashedWords:
for word in set:
print word,
print # Each set on a new line
signedWords = map(signWord, words) # Calculate signature of words
sortedWords = sorted(signedWords) # Sort words, on signature
squashedWords = squashWords(sortedWords) # Bring like words together
printSet(squashedWords) # Print all words, with one set on a line