给一个字典,其中1:a,2:b ... 26:z。我需要找到可以由三个数字组成的所有可能的字母组合。
所有数字都应在末尾用完。每个数字应该单独翻译为一个字母,或者我可以组合相邻的数字来检查一个字母。例如-
121转换为aba,au,la;
151转换为ea,oa;
101转换为ja;
我能够使它工作,但是我觉得我的代码不是很“ pythonic”。我正在尝试找出一个更有效和类似Python的解决方案。
# 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]