Search code examples
pythoncaesar-cipher

How can I make my Caesar cipher more efficient?


I have made a Caesar cipher program to be assessed but I was wondering if I could make it more efficient?

#A Caesar cipher program

##Defines the alphabet
abc = ['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']

##Collects the infomation from the user
task = input("Would you like to encrypt or decrypt?: ")
word = input("Please enter your word: ")
offset = int(input("Please enter your offset: ")) % 26

##The function to work out the answer
def workout(offset):
    final = []
    for i in word:
        try:
            if i.isupper():
                final.append(abc[abc.index(i.lower()) + offset].upper())
            else:
                final.append(abc[abc.index(i.lower()) + offset])
        except:
            final.append(i)

    print(''.join(final))

##Displays the final result
if task == "encrypt":
    workout(offset)
else:
    workout(-offset)

I appreciate all replies :) Thanks!


Solution

  • Here is an example of how to use str.translate

    >>> offset = 5
    >>> abc = ['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']
    >>> trns = str.maketrans(''.join(abc), ''.join(abc[offset:] + abc[:offset]))
    >>> "dog".translate(trns)
    'itl'
    

    You'll have to add a little extra code to handle negative offsets

    so your function can become

    def workout(offset):
        trns = str.maketrans(''.join(abc), ''.join(abc[offset:] + abc[:offset]))
        print(words.translate(trns))
    

    consider passing words as a parameter and abc a string instead of a list

    import string
    abc = string.ascii_lowercase
    ABC = string.ascii_uppercase
    
    def workout(offset, words):
        trns = str.maketrans(abc + ABC, abc[offset:] + abc[:offset] + ABC[offset:] + ABC[:offset])
        print(words.translate(trns))
    

    note, you'll still need some extra logic to make negative offsets work