Created
May 5, 2012 04:43
-
-
Save buunguyen/2599875 to your computer and use it in GitHub Desktop.
Find words for phone numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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