Secret Message
Note: This page contains a small but interesting piece of Python code which I call snippets. You can find more such codes on my Python snippets page.
Contents
Problem ¶
You are trying to send a secret message, and you've decided to encode it by replacing every letter in your message with its corresponding letter in a backwards version of the alphabet. What do your messages look like?
Task:
Create a program that replaces each letter in a message with its corresponding letter in a backwards version of the English alphabet.
Input Format:
A string of your message in its normal form.
Output Format:
A string of your message once you have encoded it (all lower case).
Sample Input:
Hello World
Sample Output:
svool dliow
Solution ¶
Here is my solution to the above problem. Remember that there could be more than one way to solve a problem. If you have a more efficient or concise solution, please leave a comment.
import string
az=string.ascii_lowercase
print("".join([az[-az.index(x)-1] if x in az else x for x in input().lower()]))
Explanation ¶
My approach (or the algorithm)¶
- Convert the input to lowercase.
- Create a list of lowercase letters from a to z.
- Find the position of each letter of the input string in the alphabet list.
- Find a corresponding letter in the alphabet list with the same position from the end of the list.
- Replace each letter from input string with the corresponding letter found in the alphabet llst.
The code¶
-
input().lower()
converts input to lowercase. -
if x in az
we will make changes only if the letter is an alphabet and not a number or a special character. -
az.index(x)
gives the position of the input letter in the alphabet list. -
-az.index(x)-1
gives the position of the letter in the alphabet list from the end. -
[az[-az.index(x)-1] if x in az else x for x in input().lower()]
replace all letters using list comprehension. -
"".join()
join into a string.
The problem question is picked from SoloLearn. Here is my SoloLearn code and my SoloLearn profile page.
Last updated 2021-01-09 18:18:58.213994 IST
Comments