LambdaGrams.py

Python

Public Domain

Takes a set of words, returns grouped by anagrams

Download (right click, save as, rename as appropriate)

Embed

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/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