Question

I was wondering if the below code is an efficient way to encode/decode a string without using the built in maketrans() method. Does using the .index method slow down the process? Is there a better way to do this? Thanks.

alpha1 = ['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']

def decode(text, shift):
    alpha2 = alpha2 = alpha1[shift:] + alpha1[:shift]   
    encoded = ''
    for i in text:
        if i in alpha1:
            encoded += alpha2[alpha1.index(i)]
        else:
            encoded += i
return encoded
Was it helpful?

Solution

def decode(text, shift):
    d = {}
    for c in (65, 97):
        for i in range(26):
            d[chr(i+c)] = chr((i+shift) % 26 + c)
    return "".join([d.get(c, c) for c in text])

The eagle eyed will recognise this from the import this source code. I always thought it was a neat way of doing rot(x) encoding.

edit: this takes into account capital letters too, if you didn't want that then you could reduce it to:

def decode(text, shift):
    d = {}
    for i in range(26):
        d[chr(i+97)] = chr((i+shift) % 26 + 97)
    return "".join([d.get(c, c) for c in text])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top