Skip to content

Instantly share code, notes, and snippets.

@buunguyen
Created May 5, 2012 04:43
Show Gist options
  • Save buunguyen/2599875 to your computer and use it in GitHub Desktop.
Save buunguyen/2599875 to your computer and use it in GitHub Desktop.
Find words for phone numbers
chars_for = {
'-': ['-'],
'0': ['0'],
'1': ['1'],
'2': ['A', 'B', 'C'],
'3': ['D', 'E', 'F'],
'4': ['G', 'H', 'I'],
'5': ['J', 'K', 'L'],
'6': ['M', 'N', 'O'],
'7': ['P', 'Q', 'R', 'S'],
'8': ['T', 'U', 'V'],
'9': ['W', 'X', 'Y', 'Z'],
}
words = dict.fromkeys(open('/usr/share/dict/words', 'r').read().upper().splitlines())
def rank(phone):
phone = phone.replace('-', ''); length = len(phone)
subs = [phone[start:start+width] for width in range(3, length + 1) for start in range(length - width + 1)]
return sum(map(lambda sub:len(sub)**3, filter(lambda sub:sub in words, subs)))
def phones(str, results, out = '', index = 0):
if len(str) == len(out):
value = rank(out)
if value > 0: results[out] = value
return
chars = chars_for[str[index]]
for c in chars:
out = out + c
phones(str, results, out, index + 1)
out = out[:-1]
def process(str):
results = {}
phones(str, results)
file = open('%s.txt' % str, 'w')
for phone in sorted(results, key=results.get, reverse=True):
file.write('%s: %d\n' % (phone, results[phone]))
file.close()
process('[phone-number-here]')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment