1

Given a number, translate it to all possible combinations of corresponding letters. For example, if given the number 1234, it should spit out abcd, lcd, and awd because the combinations of numbers corresponding to letters could be 1 2 3 4, 12 3 4, or 1 23 4.

I was thinking of ways to do this in Python and I was honestly stumped. Any hints?

I basically only setup a simple system to convert single digit to letters so far.

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236

2 Answers2

1

Make str.

Implement partition as in here.

Filter lists with a number over 26.

Write function that returns letters.

def alphabet(n):
    # return " abcde..."[n]
    return chr(n + 96)


def partition(lst):
    for i in range(1, len(lst)):
        for r in partition(lst[i:]):
            yield [lst[:i]] + r
    yield [lst]


def int2words(x):
    for lst in partition(str(x)):
        ints = [int(i) for i in lst]
        if all(i <= 26 for i in ints):
            yield "".join(alphabet(i) for i in ints)


x = 12121
print(list(int2words(x)))
# ['ababa', 'abau', 'abla', 'auba', 'auu', 'laba', 'lau', 'lla']
Community
  • 1
  • 1
pacholik
  • 8,607
  • 9
  • 43
  • 55
0

I'm not gonna give you a complete solution but an idea where to start:

I would transform the number to a string and iterate over the string, as the alphabet has 26 characters you would only have to check one- and two-digit numbers.

As in a comment above a recursive approach will do the trick, e.g.:

Number is 1234

*) Take first character -> number is 1

*) From there combine it with all remaining 1-digit numbers -->

      1 2 3 4

*) Then combine it with the next 2 digit number (if <= 26) and the remaining 1 digit numbers -->

      1 23 4

*) ...and so on

As i said, it's just an idea where to start, but basically its a recursive approach using combinatorics including checks if two digit numbers aren't greater then 26 and thus beyond the alphabet.

p9teufel
  • 99
  • 1
  • 5