-3

we have encoded strings that want to decryption it. First, the first letter of the string, then the last letter. Then the rest of the letters are stored in the same way. For example, the string amir is first added to the new letter. Then the last letter is r. This process continues in the same way, ie in the next stage m and in the next stage after the addition. (That is, first the first letter and the last letter, then the second letter and then the last letter of the last letter, and this process continues until the word) In the second step, the whole string is reversed. In the third step, the letter a becomes 4. The letter o is replaced by 0. The letter t becomes 7 and finally the letter i becomes 1.

Note: It is guaranteed that the number of letters is always even and only includes lowercase English letters

example:

input 1mr4
output amir

input w00lrlledh 
output helloworld

I read this but I have no idea of write a program

jasmine
  • 13
  • 1
  • 6

1 Answers1

1

You can use replace to make the character replacements.

For the encoding part: to apply the permutation of the characters, apply the logic with a variable i that you let run from 0 to the half of the string. Take the character at index i and the one that is i positions from the right (i.e. you can use -1-i). Then concatenate those characters. You can reverse the order at the same time.

To do the opposite, replace the opposite characters.

For the permutation, analyse how it works on a piece of paper and you'll find the logic of where to find the characters that need to be placed from left to right.

Here is code:

def encrypt(s):
    for a, b in "a4", "o0", "i1", "t7":
        s = s.replace(a, b)
    return "".join(s[-1-i] + s[i] for i in range(len(s) // 2 - 1, -1, -1))

def decrypt(s):
    for a, b in "a4", "o0", "i1", "t7":
        s = s.replace(b, a)
    return "".join(s[-1-i*2] for i in range(len(s) // 2)) + \
           "".join(s[i*2] for i in range(len(s) // 2))
trincot
  • 317,000
  • 35
  • 244
  • 286