Hi, I am pretty new to coding in general and have been following lots of tutorials to try and learn python. I am attempting a question from one of the tutorials, translating digits to letters.
def keypad_string(keys):
'''
Given a string consisting of 0-9,
find the string that is created using
a standard phone keypad
| 1 | 2 (abc)| 3 (def) |
| 4 (ghi) | 5 (jkl) | 6 (mno)|
| 7 (pqrs)| 8 (tuv) | 9 (wxyz)|
| * | 0 () | # |
You can ignore 1, and 0 corresponds to space
>>> keypad_string('12345')
'adgj'
>>> keypad_string('4433555555666')
'hello'
>>> keypad_string('2022')
'a b'
>>> keypad_string('')
''
>>> keypad_string('111')
''
The way I thought of initially was to split all the letters into their corresponding groups before translating them. So a string ‘1223333’ would end up being ‘1’, ‘22’, ‘333’, ‘3’. I am aiming to check the digit in the string, see if it is the same as the previous digit, if not move the digit into the final string, and add the new digit into the buffer to correctly split the numbers into their groups.
Here is what I have so far, but I can’t seem to get the True/ False variables to change, so everything ends up in the buffer + final string!
keys = '1223333'
keylist = list(keys)
global sameletter
sameletter = True
def splitter(keylist):
split_letters = []
buffer = []
previousdigit = ''
for digit in keylist:
check_previous(digit, previousdigit)
check_buffer_len(buffer, previousdigit)
if sameletter == True:
buffer.append(digit)
previousdigit = digit
else:
split_letters.append(buffer)
buffer.clear
buffer.append(digit)
previousdigit = digit
print(split_letters)
def check_previous(digit, previousdigit):
if digit != previousdigit:
sameletter = False
def check_buffer_len(buffer, previousdigit):
if len(buffer) == 3:
if previousdigit in {'7','9'}:
sameletter = True
else:
sameletter = False
splitter(keys)
I think the problem, looking through it with the debugger, is that the sameletter variable never actually changes to false? Would anybody be able to help
Thanks!