Problem
The code is to decode the word in such a way that For every letter x, if it is the ith letter of
the alphabet starting from the left, replace it with the ith letter starting from the right.
. For example, the string 'abcd' would be encoded to 'zyxw'.
Note: all the letters of the word are lower case alphabets
Editorial:
"abcdefghijklmnopqrstuvwxyz" is the sequence.
⚫ Here a is the fist alphabet appear in the sequence, so it will be replaced with the last
alphabet in the sequence i.e. z. ⚫b is the second alphabet from the begining in the sequence, so it will be replaced by the second last alphabet from the end i.e. y, and so on.
⚫ Here a is the fist alphabet appear in the sequence, so it will be replaced with the last
alphabet in the sequence i.e. z. ⚫b is the second alphabet from the begining in the sequence, so it will be replaced by the second last alphabet from the end i.e. y, and so on.
CodePudding user response:
If you have a list of the alphabet you find the index of that letter and then word backwords with the letter index it works, you can also modify the code to get a different encoding.
def translate_words(stringw):
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q","r", "s", "t", "u", "v", "w", "x", "y", "z"]
newstring=""
stringw = stringw.lower()
for count, letter in enumerate(stringw):
if letter in alphabet:
letternum = alphabet.index(letter)
newstring = alphabet[25-letternum]
return newstring
print(translate_words("abcd"))
CodePudding user response:
At the risk of doing your homework for you...
def codeword(word: str) -> str:
ABC = 'abcdefghijklmnopqrstuvwxyz'
encoded_chars = [ABC[-ABC.index(char) - 1] for char in word.lower()]
return ''.join(encoded_chars)
print(codeword('aaa'))
# => 'zzz'
print(codeword('abc'))
# => 'zyx'
print(codeword('stackoverflow')
# => 'hgzxpleviuold'