Skip to content

Instantly share code, notes, and snippets.

@Apsu
Created July 7, 2012 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Apsu/3064507 to your computer and use it in GitHub Desktop.
Save Apsu/3064507 to your computer and use it in GitHub Desktop.
One-line Soundex code generator using functional programming and python hackery
from functools import reduce # Needed for Python 3.x
from operator import add
def soundex(letters, duplicates=False, initial=True, size=4,
sounds=[('aeiouyhw', ''), ('bfpv', '1'), ('cgjkqsxz', '2'), ('dt', '3'), ('l', '4'), ('mn', '5'), ('r', '6')]):
return '0'*size if not len(letters) else ((letters[0] if initial else '') +
reduce(lambda stack, next: stack+next if stack[-1:] != next or duplicates else stack,
map(lambda letter: reduce(add, (val for (key,val) in sounds if letter in key), ''), letters[1:]), ''))[:size if size else None].ljust(size, '0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment