I know there are a lot of ways to write a ROT(n) function. But I don't want to have some table with chars.
So, I've tried to write a simple ROT(n) with decoder, as practice project. The encode function works fine. But the decoder keeps changing the 'a' into a 'z'.
Could somebody please explain to me what I'm doing wrong?
The (Python3) code below changes everything into lowercase ignoring any special chars.
import random
import string
shift = random.randint(1, 20)
# Encoder:
def encode(string):
coded_string = []
string = string.lower()
for c in string:
if ord(c) >= 97 and ord(c) <= 122:
c = (ord(c) + shift) % 122
if c <= 97:
c += 97
coded_string.append(chr(c))
continue
coded_string.append(c)
return ''.join(coded_string)
# Decoder:
def decode(string):
decoded_string = []
for c in string:
if ord(c) >= 97 and ord(c) <= 122:
if ord(c) - shift <= 97:
c = (ord(c) % 97) + (122 - shift)
decoded_string.append(chr(c))
continue
c = ord(c) - shift
decoded_string.append(chr(c))
continue
decoded_string.append(c)
return ''.join(decoded_string)
# Test Function:
def tryout(text):
test = decode(encode(text))
try:
assert test == text, 'Iznogoedh!'
except AssertionError as AE:
print(AE, '\t', test)
else:
print('Yes, good:', '\t', test)
# Random text generator:
def genRandomWord(n):
random_word = ''
for i in range(n):
random_word += random.choice(string.ascii_lowercase)
return random_word
# Some tests:
print(f'Shift: {shift}')
tryout('pokemon')
tryout("chip 'n dale rescue rangers")
tryout('Ziggy the Vulture or Zurg')
tryout('Fine # (*day%, to* code@ in Pyth0n3!')
tryout(genRandomWord(10))
tryout(genRandomWord(20))
Example output:
Shift: 7
Yes, good: pokemon
Iznogoedh! chip 'n dzle rescue rzngers
Iznogoedh! ziggy the vulture or zurg
Iznogoedh! fine # (*dzy%, to* code@ in pyth0n3!
Yes, good: qrwmfyogjg
Yes, good: ihrcuvzyznlvghrtnuno
but, ignoring the random string tests, I expected:
Shift: 7
Yes, good: pokemon
Yes, good: chip 'n dale rescue rangers
Yes, good: ziggy the vulture or zurg
Yes, good: fine # (*day%, to* code@ in pyth0n3!