loading...

Discussion on: Daily Challenge #217 - SMS w/ an Old Phone

Collapse
vidit1999 profile image
Vidit Sarkar

Here is Python solution based on my C++ solution

# returns key bindings for characters as a dictionary
# Example :
# = ----> ****
# l ----> 555
# - ----> **
# # ----> #-
# . ----> 1
# c ----> 222
# 4 ----> 4-
# etc.
def keyBindings() -> dict:
    # all options are in this list
    # last empty string is for '#'
    allOptions = ['.,?!','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz',"'-+=",' ','']

    # key bindings for different keys
    # like for '1' -> ['.', ',', '?', '!']
    # for '2' -> ['a', 'b', 'c'] etc.
    keyOptions = {}
    for i in range(9):
        keyOptions[str(i+1)] = list(allOptions[i])
    keyOptions['*'] = list(allOptions[9])
    keyOptions['0'] = list(allOptions[10])
    keyOptions['#'] = list(allOptions[11])

    # maps a character to its key-typing
    # like 'a' -> "2", 'b' -> "22" etc.
    keyTypings = {}
    for key, value in keyOptions.items():
        for i in range(len(value)):
            keyTypings[value[i]] = key*(i+1)
        # add options for numbers like '2' -> "2-", '4' -> "4-"
        keyTypings[key] = key+'-'

    return keyTypings

def sendMessage(message: str) -> str:
    kb = keyBindings() # get the key bindings for characters
    capital = False # whether the word is upper case or not, true for upper case
    res = "" # answer string

    for i in range(len(message)):
        # if the letter is lower case and capital is true
        # or letter is upper case and capital is false
        # then add a "#" and inverse the capital, true to false or false to true
        if((message[i].islower() and capital) or (message[i].isupper() and not capital)):
            res += '#'
            capital = not capital

        # if same character is repeating then add a space
        # like for the case "hi" -> "44 444"
        if(res != '' and (res[-1] == kb[message[i].lower()][0])):
            res += ' '

        # add the keybinging for the character's lower case
        res += kb[message[i].lower()]
    return res


print(sendMessage("Def Con 1!")) # output -> 3#33 3330#222#666 6601-1111
print(sendMessage("hey")) # output -> 4433999
print(sendMessage("one two three")) # output -> 666 6633089666084477733 33
print(sendMessage("Hello World!")) # output -> 44#33555 5556660#9#66677755531111