1

I was doing some competitive programming and stumbled upon a ROT13 question that required me to increment each alphabet by 13.

This was my attempt

def rot13(message):
    l2 = []
    l1 = list(message)
    for i in l1:
        i = str(i)
    for i in l1:
        if ord('a') <= ord(i) <= ord('z'):
            i = chr((ord(i) + 13) % 26 + ord('a'))
            l2.append(i)
        elif ord('A') <= ord(i) <= ord('Z'):
            i = chr((ord(i) + 13) % 26 + ord('A'))
            l2.append(i)
    return l2

It was returning wrong outputs such as

For input - test , it gave output - zkyz while correct is "grfg"

For input - Test , output was Tkyz while it should be Grfg

I haven't joined the list yet as I was first trying to get the right answer.

3
  • 2
    You forget to subtract the initial value from the characters so 'A' starts out as 65, not 0. Commented Jan 27, 2020 at 7:32
  • 1
    @shawnin damnen If you are looking for a reference take a look at the this module implementation. Commented Jan 27, 2020 at 7:33
  • @usr2564301 Which is why I have added it at the end to give it the unicode integer value Commented Jan 27, 2020 at 7:34

1 Answer 1

2

Here's the corrected code:

def rot13(message):
    l2 = []
    l1 = list(message)
    for i in l1:
        if ord('a') <= ord(i) <= ord('z'):
            i = chr((ord(i) - ord('a') + 13) % 26 + ord('a'))  # <== changed
            l2.append(i)
        elif ord('A') <= ord(i) <= ord('Z'):
            i = chr((ord(i) - ord('A') + 13) % 26 + ord('A'))  # <== changed
            l2.append(i)
    return l2

and a test run:

>>> rot13('Test')
['G', 'r', 'f', 'g']

The issue was that ord('a') or ord('A') needed to be subtracted from the initial ord() call. You were pretty close. Except for this nit, it all worked :-)

Sign up to request clarification or add additional context in comments.

4 Comments

@shawnindamnen Please mark the answer as the selected answer. Thx.
Why the first for-loop?
@FredrikHedman I just took that out. It was there because it was in the OP's code and I wanted to make the minimal edits required to make it work. But, yes, that loop was likely superfluous.
Yes. However, this solution will drop any charachter that is not [a-zA-Z]. For example rot13('Smörgåsbord').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.