0

Given a dictionary where 1:a , 2:b ... 26:z. I need to find all the possible letter combinations that can be formed from the three digits.

All digits should be used up at the end. Either each digit should translate to a letter individually or I can combine adjacent digits to check for a letter. For example -

121 translates to aba, au, la;

151 translates to aea, oa;

101 translates to ja;

I was able to get this working but I feel my code is not very "pythonic". I am trying to figure out a more efficient & python-like solution for this problem.


# creating the dict that has keys as digits and values as letters
root_dict = {}
for num in range(0,26):
    root_dict[str(num+1)] = string.ascii_lowercase[num]

# asking user for a three digit number
sequence_to_convert = raw_input('Enter three digit number \n')

# storing all possible permutations from the three digit number
first_permutation = sequence_to_convert[0]
second_permutation = sequence_to_convert[1]
third_permutation = sequence_to_convert[2]
fourth_permutation = sequence_to_convert[0]+sequence_to_convert[1]
fifth_permutation = sequence_to_convert[1]+sequence_to_convert[2]

# checking if the permutations exist in the dict, if so print corresponding letters
if first_permutation in root_dict and second_permutation in root_dict and third_permutation in root_dict:
    print root_dict[first_permutation]+root_dict[second_permutation]+root_dict[third_permutation]
if first_permutation in root_dict and fifth_permutation in root_dict:
    print root_dict[first_permutation]+root_dict[fifth_permutation]
if fourth_permutation in root_dict and third_permutation in root_dict:
    print root_dict[fourth_permutation]+root_dict[third_permutation]
6
  • 1
    This question is more appropriate for codereview.stackexchange.com than here :)
    – arshovon
    Commented Apr 1, 2019 at 6:21
  • Just a quick question though : for 121, 'a' and 'b' also should in the resultset as 1 and 2 are among possible combinations or am i reading your problem statement wrong? Commented Apr 1, 2019 at 6:39
  • 'All digits should be used up at the end.' So, for input as 123, the solution will be 'abc' only? Commented Apr 1, 2019 at 6:40
  • @SatishGarg - No 123 becomes abc, aw and lc
    – user168115
    Commented Apr 2, 2019 at 4:24
  • thanks @arsho , let me try codereview too.. :)
    – user168115
    Commented Apr 2, 2019 at 4:24

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.