def decode(coded_message, keyword):
keywordphrase = ""
for i in range(0, len(coded_message)):
for nums in range(0, len(keyword)):
if len(keywordphrase) < len(coded_message):
if coded_message[i] not in alphabet:
keywordphrase += coded_message[i]
keywordphrase += keyword[nums]
print(decode("fff f a f a", "dog"))
What am I doing wrong here? I thought this would copy anything if it wasn’t in the alphabet, and then cycle through the keyword if it was. Thanks in advance
I’m not that great at explaining stuff so see this (what it says in the exercise):
Consider the message
barry is the spy
If we want to code this message, first we choose a keyword. For this example, we'll use the keyword
Now we use the repeat the keyword over and over to generate a _keyword phrase_ that is the same length as the message we want to code. So if we want to code the message "barry is the spy" our _keyword phrase_ is "dogdo gd ogd ogd". Now we are ready to start coding our message. We shift the each letter of our message by the place value of the corresponding letter in the keyword phrase, assuming that "a" has a place value of 0, "b" has a place value of 1, and so forth. Remember, we zero-index because this is Python we're talking about!
message: b a r r y i s t h e s p y
keyword phrase: d o g d o g d o g d o g d
resulting place value: 4 14 15 12 16 24 11 21 25 22 22 17 5
So we shift "b", which has an index of 1, by the index of "d", which is 3. This gives us an place value of 4, which is "e". Then continue the trend: we shift "a" by the place value of "o", 14, and get "o" again, we shift "r" by the place value of "g", 15, and get "x", shift the next "r" by 12 places and "u", and so forth. Once we complete all the shifts we end up with our coded message:
eoxum ov hnh gvb
As you can imagine, this is a lot harder to crack without knowing the keyword! So now comes the hard part. I'll give you a message and the keyword, and you'll see if you can figure out how to crack it! Ready? Okay here's my message:
dfc aruw fsti gr vjtwhr wznj? vmph otis! cbx swv jipreneo uhllj kpi rahjib eg fjdkwkedhmp!
and the keyword to decode my message is
Because that's what we are! Good luck friend!
I’m just trying to figure out how to get the keyword to fit a given string lol
For each index in coded_message, the next for loop will run through each index of keyword. Technically it’s setting up loops the length of each string, but this description fits the usage in the program. So when your program starts at i=0, and finds coded_message is f, it finds the else statement true once for each index in keyword (nums = 0, 1, 2). Thus you add ‘dog’ to keywordphrase three times, then three spaces, another dog, then three spaces.
I don’t want to just give you the answer right away, but I will say that you only want one output per index in coded message, so you only want one for loop. As to iterating through the letters in dog, you need track that ‘variable’ without a loop.