simple substitution cipher implementation using Python

substitution cipher implementation using Python

substitution cipher implementation using Python – You want to develop a secret communication method with your friend. One day, you read a book about a simple substitution cipher and you want to implement it by using Python.

The logic of substitution cipher implementation using Python is easy. Your friend and you came up with the following naive substitution algorithm.


That is, you swap characters “a” with “c”, “d” with “q”, “i” with “m”, and “t” with “y”. Other characters leave unchanged.

Based on your algorithm, a plaintext “raymond” will be encrypted as “rctionq”.

Implement the encryption algorithm and named your function as encrpt. Take one argument as the input and one argument contains the key pairs. You only require to handle lowercase character.

A two-dimension array is used to represent the key-value pairs.

keys = [["a", "c"], ["c", "a"], ["d", "q"], ["i", "m"], ["m", "i"], ["q", "d"], ["t", "y"], ["y", "t"]]

You can access the first key pair by keys[0]In [ ]:

keys = [["a", "c"], ["c", "a"], ["d", "q"], ["i", "m"], ["m", "i"], ["q", "d"], ["t", "y"], ["y", "t"]]


Out[ ]:

['a', 'c']

The first key can be obtained by keys[0][0]In [ ]:


Out[ ]:


The first value of key “a” can be obtained by keys[0][1]In [ ]:


Out[ ]:


The last pair of key can be obtained by the following example code:In [ ]:

last = len(keys)   # last = 8
print(keys[(last-1)])     # the first index is 0, the last index is 7. and this will give you a list of ["y", "t"]

# assign the last keypair to a variable named temp
temp = keys[(last-1)]
print(temp)     # it will give you the same ouput as above

print(temp[0])  # "y"
print(temp[1])  # "t"
['y', 't']
['y', 't']

You can test your function by checking the following input-output pairs.
Input: “raymond”
Ouput: “rctionq”

Input: “peter is a good guy”
Output: “peyer ms c gooq gut”

if you really can’t use a flexible way to implement the code, you can forget about the keys variable and use if-else statements to complete itIn [11]:

# implementation

keys = [["a", "c"], ["c", "a"], ["d", "q"], ["i", "m"], ["m", "i"], ["q", "d"], ["t", "y"], ["y", "t"]]

input = "raymond"

def encrypt(input, keys):
    output = ""

    # Write your code below:
    for c in input:
        for k in keys:
            if c == k[0]:
                c = k[1]
        output += c
    return output

In [12]:

# Test your function
encrypt("raymond", keys)



If you have another efficient method, please share the comment section.

If you have also used python or any other language to do your work. Share it in the comments section to help others

keep visiting : shaadcoding


One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *