Update:
Sorry for the late reply, but thanks again for your help. I think I've somehow managed to write it the way I'm expected to, but I get a ValueError on: m = ciphertext.index(n)
Does anyone see if I've made a mistake?
def cipher (message: str, ciphertext: list, alphabet: list = ["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"]) -> str:
if len(message) == 0:
return ""
else:
n = alphabet.index(message[0])
m = ciphertext.index(n)
message = message[1:]
return m cipher(message, ciphertext)
ciphertext = ["C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A", "B"]
message = "Hello"
print(cipher(message, ciphertext))
Old: So, I'm supposed to write a function for a substitution cipher in Python. I input a message, the function compares it to a list of the alphabet, and recursively returns the corresponding letter from a second list, on the same index.
I'm given this code to start with, but I have no idea how to find the same index of the other list, or how to write it recursively to have it continue rewriting each letter of the message until it reaches len(message) == 0.
def cipher (message: str, ciphertext: list, alphabet: list = ["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"]) -> str:
if len(message) == 0:
return ""
else:
The function shall return a new text with the same size as the original, except that each letter has been replaced by the corresponding letter in the ciphertext according to its position. For example:
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"]
Sample ciphertext alphabet = ["C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A", "B"]
Sample message = "EXAMPLE"
Sample return ciphertext= "GZCORNG"
Any help is appreciated. Python is very new to me, so if you can help, please use simple terms/methods.
CodePudding user response:
Here is a starter that works.
# the cypher to be used (as a dictionary)
cypher_code = {
'a':'a', 'b':'c', 'c':'f', 'd':'f', 'e':'g',
'f':'a', 'g':'c', 'h':'f', 'i':'f', 'j':'g',
'k':'a', 'l':'c', 'm':'f', 'n':'f', 'o':'g',
'p':'a', 'q':'c', 'r':'f', 's':'f', 't':'g',
'u':'a', 'v':'c', 'w':'f', 'x':'f', 'y':'g', 'z':'a'
}
def cipher (message: str, cypher_to_use: dict) -> str:
''' function to encrypt / decrypt'''
if len(message) == 0:
return ''
decoded_word = ''
for letter in message:
decoded_letter = cypher_to_use[letter]
decoded_word = decoded_word decoded_letter
return decoded_word
x = cipher('hello', cypher_code)
print(x)
converts hello
to fgccg
.
Hope this helps !