Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rot13 function but the code can't translate if letter clue is over 122

The answers come one by one but if the value is over 122 then the following code doesn’t work.

def rotate_word13(line, num):
    for x in line:
        a = ord(x)
        a = ord(x) + num
        print(a)

        if a >= 122:
            e = a - 122
            print(e)
            x = chr(e)
            print(x)
        else:
            x = chr(a)
            print(x)

rotate_word13("hello", 13)
rotate_word13("r", 13)

Here is the result. As you can see it works only if ord is less than 122 after it’s been subtracted.

117
u
114
r
121
y
121
y
124
2
127
5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You seem to be trying to implement the ROT13 cypher.

You need to take account of upper- and lower-case letters. Simply find where the letter is in an ordered list of letters, add 13 to that index and then modulo by 26.

Like this:

from string import ascii_lowercase as L, ascii_uppercase as U

def rot13(s):
    r = []
    for c in s:
        if (i := U.find(c)) >= 0:
            r.append(U[(i + 13) % 26])
        elif (i := L.find(c)) >= 0:
            r.append(L[(i + 13) % 26])
        else:
            r.append(c)
    return ''.join(r)

print(rot13('Why did the chicken cross the road'))

Output:

Jul qvq gur puvpxra pebff gur ebnq
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading