Hello, I’m struggling with the Vignère cypher part of this project. The first part successfully produces a keyword_string that has the message with the keyword, but the second part does not produce any comprehensible message and I cannot figure out what issue is. This is my code so far (the provided solution, commented out on the bottom, doesn’t work in the second part either):
def vig_decoderalphabet = "abcdefghijklmnopqrstuvwxyz"
punctuation = " ,!?'."
message = "dfc aruw fsti gr vjtwhr wznj? vmph otis! cbx swv jipreneo uhllj kpi rahjib eg fjdkwkedhmp!"
key = "friends"(string, keyword):
keyword_string = " "
keyword_index = 0
for letter in string:
if letter not in punctuation:
keyword_string += keyword[(keyword_index) % len(keyword)]
keyword_index += 1
else:
keyword_string += letter
decoded_message = " "
keyword_index = 0
for letter in string:
if letter not in punctuation:
decoded_message += alphabet[(alphabet.find(letter) - alphabet.find(keyword_string[keyword_index])) % 26]
keyword_index += 1
else:
decoded_message += letter
#for i in range(0, len(string)):
#if not string[i] in punctuation:
#ln = alphabet.find(string[i]) - alphabet.find(keyword_string[i])
#decoded_message += alphabet[ln % 26]
# else:
# decoded_message += string[i]
return decoded_message
print(vig_decoder(message, key))
Any help would be greatly appreciated!
The codebyte had the def in the wrong place, so I moved it just before the line that has keyword_string
and I fixed the indentations appropriately.
You added spaces and other stuff to keyword_string
, so you should increment keyword_index
in the second loop even if the current letter is a space or other punctuation (put the keyword_index += 1
outside the if-statement in the loop, but still in the loop)
Also, you did not start keyword_string
as an empty string, you initailized it to be a string that has a space in it,
so keyword_index
should start at 1
, not 0
for the second loop.
alphabet = "abcdefghijklmnopqrstuvwxyz"
punctuation = " ,!?'."
message = "dfc aruw fsti gr vjtwhr wznj? vmph otis! cbx swv jipreneo uhllj kpi rahjib eg fjdkwkedhmp!"
key = "friends"
def vig_decoder(string, keyword):
keyword_string = " "
keyword_index = 0 # used to iterate through keyword
for letter in string:
if letter not in punctuation:
keyword_string += keyword[(keyword_index) % len(keyword)]
keyword_index += 1 # increment
else:
keyword_string += letter
decoded_message = " "
keyword_index = 1 # used to iterate through keyword_string
for letter in string:
if letter not in punctuation:
decoded_message += alphabet[(alphabet.find(letter) - alphabet.find(keyword_string[keyword_index])) % 26]
else:
decoded_message += letter
keyword_index += 1 # increment outside of if - else stuff
"""
#for i in range(0, len(string)):
#if not string[i] in punctuation:
#ln = alphabet.find(string[i]) - alphabet.find(keyword_string[i])
#decoded_message += alphabet[ln % 26]
# else:
# decoded_message += string[i]
"""
return decoded_message
print(vig_decoder(message, key))