python - Caesar cipher fails when output character is beyond 'z' -
just clear, asking because have tried 1.5 hours , can't seem results. not taking programming class or have lot of free time summer , using lot of learn python book. want know how complete problem.
the problem asks create program runs "caesar cipher" shifts ascii number of character down key choose. instance, if wanted write sourpuss , chose key of 2, program spit out ascii characters shifted down two. s turn u, o turn q (2 characters down ascii alphabet...).
i part writing program.
def main(): the_word=input("what word encode? ") key=eval(input("what key? ")) message="" newlist=str.split(the_word) the_word1=str.join("",the_word) each_letter in the_word1: addition=ord(each_letter)+key message=message+chr(addition) print(message) main()
running program, following:
what word encode? sourpuss key? 2 uqwtrwuu
now, next question says issue arises if add key ascii number , results in number higher 128. asks create program implements system if number higher 128, alphabet reset , go ascii value of 0.
what tried this:
if addition>128: addition=addition-128
when ran program after doing this, didn't work , returned space instead of right character. ideas?
try using modular arithmetic instead of condition:
((ord('z') + 0 - 97) % 26) + 97 => 122 # chr(122) == 'z' ((ord('z') + 1 - 97) % 26) + 97 => 97 # chr(97) == 'a' ((ord('z') + 2 - 97) % 26) + 97 => 98 # chr(98) == 'b'
notice expression:
((ord(character) + - 97) % 26) + 97
returns correct integer representing given character
after add offset i
(the key, call it). in particular, if add 0
ord('z')
code 'z'
. if add 1
ord('z')
code a
, , on.
this works lowercase characters between a-z
, magic numbers 97
being code a
, 26
being number of characters between a
, z
; tweaking numbers can adapt code supporting greater range of characters.
Comments
Post a Comment