Created
January 15, 2014 22:08
-
-
Save zpconn/8445705 to your computer and use it in GitHub Desktop.
A solution to the inverse telephone problem in Python (with no imports). Given a mapping like 1 -> A,B,C
2 -> D,E,F
etc. and a string of integers like "112", determine all possible images of this string under the mapping ("AAD", "AAE", etc.).
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
def product(lists): | |
result = [[]] | |
for l in lists: | |
result = [x + [y] for x in result for y in l] | |
for prod in result: | |
yield prod | |
def inverse_phone(mappings, s): | |
numbers = set([int(n) for n in s]) | |
combinations = product([mappings[n] for n in numbers]) | |
output = [] | |
for combination in combinations: | |
possibility = "" | |
for c in s: | |
possibility += combination[int(c) - 1] | |
output.append(possibility) | |
return output | |
mappings = {1: ['a', 'b', 'c'], 2: ['d', 'e', 'f'], 3: ['g', 'h', 'i', 'j']} | |
print inverse_phone(mappings, "132") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment