Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

targ

By: a guest on Feb 23rd, 2010  |  syntax: Python  |  size: 0.87 KB  |  views: 122  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. from itertools import count
  2.  
  3.  
  4. mapping = {}
  5. for letters, number in zip("bfpv cgjkqsxz dt l mn r".split(), count(1)):
  6.     mapping.update({letter:number for letter in letters})
  7.  
  8.  
  9. def soundex(word):
  10.     word = word.lower()
  11.     first, rest = word[0], word[1:]
  12.  
  13.     digits = []
  14.     digit = mapping.get(first)
  15.     for letter in rest:
  16.         next_digit = mapping.get(letter)
  17.         if next_digit is not None and next_digit != digit:
  18.             digits.append(next_digit)
  19.             if len(digits) == 3:
  20.                 break
  21.         digit = next_digit
  22.     else:
  23.         digits.extend(0 for x in xrange(3 - len(digits)))
  24.  
  25.     return first + "".join(map(str, digits))
  26.  
  27.  
  28. assert map(soundex, "euler gauss hilbert knuth lloyd lukasiewicz".split()) \
  29.     == map(soundex, "ellery ghosh heilbronn kant ladd lissajous".split()) \
  30.     == "e460 g200 h416 k530 l300 l222".split()