Python function that will show Caesar cipher dictionary


I am writing a function that will print out a dictionary for Caesar cipher in this format, where the argument is how much we want to shift the letter:

buildCoder(3)
{'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'B', 'X': 'A', 'Z': 'C', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'b', 'x': 'a', 'z': 'c'}

Here is my code:

import string
def buildCoder(shift):
    small = string.ascii_lowercase
    capital = string.ascii_uppercase
    mainDict = {}
    for i in range(0, len(capital)):
        mainDict[capital[i]] = capital[i+shift]
    for i in range(0, len(small)):
        mainDict[capital[i]] = capital[i+shift]
    return mainDict

But the problem is, that when it loops through letters in capital variable, string index of this variable gets out of range. What can I do to solve it?


Answer

The problem is that at some point i + shift is greater than len(small) or len(capital), you need to use the modulo operator:

import string

def build_coder(shift):
    small = string.ascii_lowercase
    capital = string.ascii_uppercase
    main_dict = {}
    for i in range(0, len(capital)):
        main_dict[capital[i]] = capital[(i+shift) % len(capital)]
    for i in range(0, len(small)):
        main_dict[small[i]] = small[(i + shift) % len(small)]
    return main_dict


result = build_coder(3)
print(result)

Output

{'B': 'E', 'w': 'z', 'e': 'h', 's': 'v', 'C': 'F', 'K': 'N', 'Z': 'C', 'v': 'y', 'I': 'L', 'r': 'u', 'S': 'V', 'R': 'U', 'X': 'A', 'l': 'o', 'N': 'Q', 'J': 'M', 'b': 'e', 'i': 'l', 'E': 'H', 'G': 'J', 'x': 'a', 'L': 'O', 'h': 'k', 'c': 'f', 'm': 'p', 'u': 'x', 'H': 'K', 'd': 'g', 'U': 'X', 'Y': 'B', 'F': 'I', 't': 'w', 'z': 'c', 'M': 'P', 'V': 'Y', 'p': 's', 'f': 'i', 'D': 'G', 'O': 'R', 'W': 'Z', 'q': 't', 'P': 'S', 'T': 'W', 'j': 'm', 'y': 'b', 'a': 'd', 'g': 'j', 'n': 'q', 'A': 'D', 'o': 'r', 'k': 'n', 'Q': 'T'}