Having some trouble decoding below, I have been trying to return to the original string. Is there anyone who could assist?
def encode(n, i=0, key=5):
if i >= len(n):
return n
chars = list(n)
chars[i] = chr(ord(list(n)[i]) + key)
return encode("".join(chars), i=i+1)
The function probably has an unintended behaviour when a key is provided to the call that is different from 5. In that case the recursive calls will not get that key and still work with the default 5.
The recursive call should logically be return encode("".join(chars), i=i+1, key=key)
If the code is fixed like that, you can call it with a negative value for k
and it will work:
def encode(n, i=0, key=5):
if i >= len(n):
return n
chars = list(n)
chars[i] = chr(ord(list(n)[i]) + key)
return encode("".join(chars), i=i+1, key=key)
# ^^^^^^^^^ fix
s = "What's another year"
s2 = encode(encode(s), 0, -5)
print(s == s2) # True
Note that the function is unnecessarily using recursion. It also turns the given string to a list and back to a string, repeatedly. It is an example of how not to do it.
Use this function instead:
def encode(s, key=5):
return "".join(chr(ord(ch) + key) for ch in s)
And use as:
s = "What's another year"
s2 = encode(encode(s), -5) # Without the i-argument.
print(s == s2) # True