# 题目
'''
Description:
You are given a secret message you need to decipher. Here are the things you need to know to decipher it:
For each word:
the second and the last letter is switched (e.g. Hello becomes Holle)
the first letter is replaced by its character code (e.g. H becomes 72)
Note: there are no special characters used, only letters and spaces
Examples
decipherThis('72olle 103doo 100ya') // 'Hello good day'
decipherThis('82yade 115te 103o') // 'Ready set go'
'''
'''
Description:
You are given a secret message you need to decipher. Here are the things you need to know to decipher it:
For each word:
the second and the last letter is switched (e.g. Hello becomes Holle)
the first letter is replaced by its character code (e.g. H becomes 72)
Note: there are no special characters used, only letters and spaces
Examples
decipherThis('72olle 103doo 100ya') // 'Hello good day'
decipherThis('82yade 115te 103o') // 'Ready set go'
'''
自己
'''
解题思路:
1、依次读取字符串的每个字符,检测是否为数字,如果不是的话就记录当前位置,并且把第一个密文解密出来。
2、记录当前最后的字符和数字后的第一个字符,分别记为second_char和end_char。然后将1.2.3字符拼接起来,返回拼接后的值
3、如果在第一步检测时一直没有检测到非数字的字符,则直接返回该数字的字符
'''
# 交作业
def decipher_this_test(string):
length = len(string)
for i in range(len(string)):
if not string[i].isdigit():
first_char = chr(int(string[:i]))
end_char = string[i:i+1]
second_char = string[length - 1:]
if len((string[i::])) == 1:
return first_char + second_char
data = first_char + second_char + string[i+1:length-1] + end_char
return data
return chr(int(string))
def decipher_this(string):
string_list = string.split(' ')
data = []
for i in string_list:
data.append(decipher_this_test(i))
return ' '.join(data)
他人
'''
值得学习的地方:
1、使用了map函数,并且利用string.split()函数的特性将题目中的入参很好的划分成需要执行的列表
2、熟练使用sum()、map()、还有str.isdigit()函数,简洁的计算出数字结尾的位置
3、使用+=,拼接字符串
'''
def decipher_word(word):
i = sum(map(str.isdigit, word))
decoded = chr(int(word[:i]))
if len(word) > i + 1:
decoded += word[-1]
if len(word) > i:
decoded += word[i + 1:-1] + word[i:i + 1]
return decoded
def decipher_this(string):
return ' '.join(map(decipher_word, string.split()))