Bart Bart - 1 year ago 59
Python Question

My ascii value dictionary doesn't work

I got an assignment yesterday about Rot and I was told to write all 26 of them in code, or atleast a program that did, so I thought I'd start with the dictionary, since I wanted to also call for a certain rot I came up with this.

def generate_rotated_dictionary(n):
for i in range(0, 26):
letter = alphabet_list[i]
new_let = ord(letter) + n
new_let = chr(new_let)
rot_dic.update({letter: new_let})

Unfortunately, this doesn't work and results in:

{'a': 'b', 'c': 'd', 'b': 'c', 'e': 'f', 'd': 'e', 'g': 'h', 'f': 'g', 'i':
'j', 'h': 'i', 'k': 'l', 'j': 'k', 'm': 'n', 'l': 'm', 'o': 'p', 'n': 'o',
'q': 'r', 'p': 'q', 's': 't', 'r': 's', 'u': 'v', 't': 'u', 'w': 'x', 'v':
'w', 'y': 'z', 'x': 'y', 'z': '{'}

{'a': 'c', 'c': 'e', 'b': 'd', 'e': 'g', 'd': 'f', 'g': 'i', 'f': 'h', 'i':
'k', 'h': 'j', 'k': 'm', 'j': 'l', 'm': 'o', 'l': 'n', 'o': 'q', 'n': 'p',
'q': 's', 'p': 'r', 's': 'u', 'r': 't', 'u': 'w', 't': 'v', 'w': 'y', 'v':
'x', 'y': 'z', 'x': 'z', 'z': '|'}

{'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': '|', 'x': 'z', 'z': '}'}

{'a': 'e', 'c': 'g', 'b': 'f', 'e': 'i', 'd': 'h', 'g': 'k', 'f': 'j', 'i':
'm', 'h': 'l', 'k': 'o', 'j': 'n', 'm': 'q', 'l': 'p', 'o': 's', 'n': 'r',
'q': 'u', 'p': 't', 's': 'w', 'r': 'v', 'u': 'y', 't': 'x', 'w': 'z', 'v':
'z', 'y': '}', 'x': '|', 'z': '~'}

How do I fix it with the ending, I know that it is because of my use of Ascii values, but how do i get this to start with the a again (number 97)

Answer Source

Hardly worth a full answer, but you want to take the modulo 26 of new_let before you convert to a character. by doing remainder division, you get how far past 26 the index has gone


>>>26 + 13 # rot13 for z
>>>39 % 26
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download