B
B
barswert2020-06-03 15:22:13
Python
barswert, 2020-06-03 15:22:13

Python problem - decryption and encryption?

python course assignment

Write a program that can encrypt and decrypt a substitution cipher. The program takes two strings of the same length as input, the first line contains the characters of the source alphabet, the second line contains the characters of the final alphabet, after which there is a string that needs to be encrypted with the passed key, and another line that needs to be decrypted.

Let, for example, the following input be passed to the program:
abcd
*d%#
abacabadaba
#*%*d*% This means that the character a of the original message is replaced by the character * in the cipher, b is replaced by d, c is replaced by % and d is replaced by #.
You need to encrypt the string abacabadaba and decrypt the string #*%*d*% using this cipher. We get the following lines, which we pass to the output of the program:
*d*%*d*#*d*
dacabac

wrote a program (I took a google one written in python 2 as a basis), the actual program:
in_chars = input()
out_chars = input()
message = input()
d_message = input() 
for index, char in enumerate(in_chars):
  message = message.replace(char, out_chars[index])
print (message)
for index, char in enumerate(out_chars):
  d_message = d_message.replace(char, in_chars[index])
print (d_message)

output:
*#*%*#*#*#*
dacabac
the output does not match the required one, help me to deal with the error

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
barswert, 2020-06-18
@barswert

in general, the solution turned out to be simpler:

alphabet, cipher, encode, decode = input(), input(), input(), input()

enc_dict = {letter: char for letter, char in zip(alphabet, cipher)}
dec_dict = {char: letter for char, letter in zip(cipher, alphabet)}

print("".join([enc_dict[letter] for letter in encode]))
print("".join([dec_dict[char] for char in decode]))

G
galaxy, 2020-06-03
@galaxy

message = message.replace(char, out_chars[index])- this code will re-replace d (i.e. b -> d -> #).
Usemessage.translate(string.maketrans(from, to))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question