Created
January 11, 2014 19:00
-
-
Save xsleonard/8375230 to your computer and use it in GitHub Desktop.
Phone number -> letter permutations
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
from sys import argv | |
from string import ascii_uppercase | |
def map_number(number): | |
""" Maps a number's digits to its possible phone letters """ | |
sets = [] | |
for n in str(number): | |
assert n != '0' | |
pos = (int(n) - 1) * 3 | |
s = ascii_uppercase[pos:pos + 3] | |
sets.append(list(s)) | |
return sets | |
def update_indices(indices, lens, index=-1): | |
if abs(index) > len(indices): | |
return | |
indices[index] = (indices[index] + 1) % lens[index] | |
if indices[index] == 0: | |
update_indices(indices, lens, index=index - 1) | |
def compute_perms(number): | |
sets = map_number(number) | |
lens = [len(s) for s in sets] | |
permcount = reduce(lambda x, y: x * y, lens) | |
indices = [0] * len(sets) | |
perms = [] | |
for i in xrange(permcount): | |
perm = ''.join([sets[n][i] for n, i in enumerate(indices)]) | |
perms.append(perm) | |
update_indices(indices, lens) | |
return perms | |
if __name__ == '__main__': | |
perms = compute_perms(argv[1]) | |
print '\n'.join(perms) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment