'Cesar Cispher Logic Issue(python)
wordList = ["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"]
wordListLen = len(wordList)
word = input("Hello do you wish to Encode or Decode a word?\n")
def encode(word, shift):
shift = int(shift)
lettersInNum = []
finalWord = ""
word = list(word)
wordLen = len(word)
for position in range(wordListLen):
alphabetLetter = wordList[position]
for index in range(wordLen):
wordLetter = word[index]
if(wordLetter == alphabetLetter):
lettersInNum.append(position)
for n in range(len(lettersInNum)):
lettersInNum[n] +=shift
if(lettersInNum[n] >26):
lettersInNum[n] = 0 + (lettersInNum[n] -27)
finalWord += wordList[lettersInNum[n]]
print(finalWord)
def decode(word,shift):
print("TODO")
if(word.lower() == "encode"):
enWord = input("What is the word you wish to encode?\n")
shift = input("By how many letters do you wish to shift?\n")
encode(enWord,shift)
if(word.lower() == "decode"):
deWord = input("What is the word you wish to decode?\n")
shift = input("By how many letters do you wish to shift?\n")
decode(deWord,shift)
I believe the error in this code revolves around the following line:
if(wordLetter == alphabetLetter):
because the word Apples is being converted to 0 4 11 15 15 IN CHRONOLOGICAL ORDER and not letter order. I believe this is happening because the statement is evaluating to true because E comes before P and L in the alphabet and is thus translated first.
If you know how to fix this please let me know.
Solution 1:[1]
You just need to change the order of the for loop.
for index in range(wordLen):
wordLetter = word[index]
for position in range(wordListLen):
alphabetLetter = wordList[position]
if wordLetter == alphabetLetter:
lettersInNum.append(position)
This should fix the bug. Try to dry run your code to better understand how the order of loops changes the output.
You can also write your encode function like this:
def encode(word, shift):
shift = int(shift) % 26
finalword = ''
for letter in word:
finalword += chr(ord(letter) + shift)
print(finalword)
Resources for ord, chr and modulo operator %
Feel free to comment in case of any doubt.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
