This is the popular correspondence table:
d = { '2': "ABC",
'3': "DEF",
'4': "GHI",
'5': "JKL",
'6': "MNO",
'7': "PQRS",
'8': "TUV",
'9': "WXYZ",
}
Given this, or any other d
, (executable) pseudocode to transform a string of digits into all possible strings of letters:
def digstolets(digs):
if len(digs) == 0:
yield ''
return
first, rest = digs[0], digs[1:]
if first not in d:
for x in digstolets(rest): yield first + x
return
else:
for x in d[first]:
for y in digstolets(rest): yield x + y
tweakable depending on what you want to do for characters in the input string that aren't between 2
and 9
included (this version just echoes them out!-).
For example,
print list(digstolets('1234'))
in this version emits
['1ADG', '1ADH', '1ADI', '1AEG', '1AEH', '1AEI', '1AFG', '1AFH', '1AFI',
'1BDG', '1BDH', '1BDI', '1BEG', '1BEH', '1BEI', '1BFG', '1BFH', '1BFI',
'1CDG', '1CDH', '1CDI', '1CEG', '1CEH', '1CEI', '1CFG', '1CFH', '1CFI']
Edit: the OP asks for more explanation, here's an attempt. Function digstolets
(digits to letters) takes a string of digits digs
and yields a sequence of strings of characters which can be letters or "non-digits". 0
and 1
count as non-digits here because they don't expand into letters, just like spaces and punctuations don't -- only digits 2
to 9
included expand to letters (three possibilities each in most cases, four in two cases, since 7
can expand to any of PQRS
and 9
can expand to any of WXYZ
).
First, the base case: if nothing is left (string digs
is empty), the only possible result is the empty string, and that's all, this recursive call is done, finished, kaput.
If digs
is non-empty it can be split into a "head", the first character, and a "tail", all the rest (0 or more characters after the first one).
The "head" either stays as it is in the output, if a non-digit; or expands to any of three or four possibilities, if a digit. In either case, the one, three, or four possible expansions of the head must be concatenated with every possible expansion of the tail -- whence, the recursive call, to get all possible expansions of the tail (so we loop over all said possible expansion of the tail, and yield each of the one, three, or four possible expansions of the head concatenated with each possible expansion of the tail). And then, once again, th-th-that's all, folks.
I don't know how to put this in terms that are any more elementary -- if the OP is still lost after THIS, I can only recommend a serious, total review of everything concerning recursion. Removing the recursion in favor of an explicitly maintained stack cannot simplify this conceptual exposition -- depending on the language involved (it would be nice to hear about what languages the OP is totally comfortable with!), recursion elimination can be an important optimization, but it's never a conceptual simplification...!-)