Pyth0nicPenguin Pyth0nicPenguin - 2 months ago 18
Python Question

Make basic cipher function more readable

I have this basic cipher function:

def encrypt_decrypt(data, in_or_out):
pass_lst = list(data)
return_list = []

if in_or_out == "in":
for i in pass_lst:
num = ord(i) + 10
return_list.append(chr(num))
else:
for i in pass_lst:
num = ord(i) - 10
return_list.append(chr(num))

return ''.join(return_list)


I want to make this cipher a little more readable and a little
DRY
er.. Is there a way I can shorten this function successfully?

Answer

You ca make it DRYer by computing the ±10 from the in_or_out parameter. Eg,

def encrypt_decrypt(data, in_or_out):
    delta = {'in': 10, 'out': -10}[in_or_out]
    return_list = []
    for i in list(data):
        num = ord(i) + delta
        return_list.append(chr(num))
    return ''.join(return_list)

And that can be made more compact by using a list comprehension:

def encrypt_decrypt(data, in_or_out):
    delta = {'in': 10, 'out': -10}[in_or_out]
    return ''.join([chr(ord(i) + delta) for i in data])

Notice that I'm directly iterating over data. That will work if data is a string, list or tuple.

However, you should be aware that your code isn't safe: it doesn't handle char codes where ord(i) + delta is outside the 0-255 range.