Search code examples
pythonpython-3.xlistnumeric

I need help converting mobile numeric sequence into actual sentences


I need to create a working mobile numeric keypad converter in python. For example when I give the input "999 33 7777" it's going to print "yes". And then the "0" input is going to create the " " space output like how the old mobile keypad supposed to work and also the input " " space is going to be ignored like I mention "999 33 7777" will print out "yes" instead of " y e s". But the problem is when I input the space " " between other numbers in order to separating single integer and double/triple integer for example "2", "22", and "222" in the input function it'll print out nothing/blank. Please let me know how can I achieve it with the least or no external modules.

translate = ["a", "b", "c","d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "]
translate_alpha = ['2', '22', '222', '3', '33', '333', '4', '44', '444', '5', '55', '555', '6', '66', '666', '7', '77', '777', '7777', '8', '88', '888', '9', '99', '999', '9999', '0']
def translator(val):
    x=enumerate(translate_alpha)
    output = ""
    for i, j in x:
        if j == val:
            output+=output+translate[i]
    return output

print(translator(input("")))

Solution

  • You can first create a dictionary mapping numbers to letters by zipping the two lists together then using the iterator of tuples constructor:

    translate_dict = dict(zip(translate_alpha, translate))
    

    Then, you can simply split on whitespace, look up items in the dict, then join on the empty string:

    def translator(val):
        return "".join(translate_dict[x] for x in val.split())