When I try to implement my code an error appears, but when I use a debugger to see where the code's stuck there is no index out of range. I must miss something but I don't know what.
message = "WEATHERREPORTWINDYTODAY"
number1 = 7
def Encode(letter, number):
shift = 0
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
liste_decode = []
for i in range(len(letter)):
number_index_alphabet = alphabet.index(letter[i]) shift number
shift = 1
if number_index_alphabet <= len(alphabet):
liste_decode.append(alphabet[number_index_alphabet])
else:
number_index_alphabet -= 26
liste_decode.append(alphabet[number_index_alphabet])
return liste_decode
print(Encode(message, number1))
CodePudding user response:
Number_index_alphabet == 26 at some point. The index range for alphabet is 0-25 inclusive. You will have also problem with that line:
number_index_alphabet -= 26
Working code:
if number_index_alphabet < len(alphabet):
liste_decode.append(alphabet[number_index_alphabet])
else:
number_index_alphabet = number_index_alphabet % 26
liste_decode.append(alphabet[number_index_alphabet])
CodePudding user response:
I see here two possible mistakes
if number_index_alphabet <= len(alphabet):
should beif number_index_alphabet < len(alphabet):
- not sure what you are expecting from this
number_index_alphabet -= 26
I assume that your function should look like this
def Encode(letter, number):
shift = 0
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
liste_decode = []
for i in range(len(letter)):
number_index_alphabet = alphabet.index(letter[i]) shift number
shift = 1
liste_decode.append(alphabet[number_index_alphabet % 26])
return liste_decode
CodePudding user response:
The reason why out of range is that you incremented shift
and in one step of the loop number_index_alphabet
will be 53
, even if in the else statement you minus 26, you get 27, which is out of range.
And in the if statement number_index_alphabet <= len(alphabet)
will also probably incur out of range error, should be number_index_alphabet < len(alphabet)
.
I guess you want to encode the sentence with a shift in the alphabet. changed a little bit, hope it helps.
message = "WEATHERREPORTWINDYTODAY"
number1 = 7
def Encode(letter, number):
shift = number
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
str_encode = str()
for i in range(len(letter)):
number_index_alphabet = alphabet.index(letter[i]) shift
if number_index_alphabet >= len(alphabet):
number_index_alphabet %= len(alphabet)
str_encode = alphabet[number_index_alphabet]
return str_encode
print(Encode(message, number1))
output: DLHAOLYYLWVYADPUKFAVKHF