Cryptography: ciphering in python

Viewed 81

Problem statement: Every upper case alphabet shifts to the left, for example if the alphabet D was left shifted by 3, it will become A, and E would become B, and so on..

I got the first two test cases correctly, but I got stuck at the third one that had a pound sign.

My trial:

sh = int(input())
s = input()
n = ""
for char in s:
    val = ord(char)-sh
    if char != " ":
        if 65 <= val <= 90:
            n += chr(val)
        else:
            if val < 65:
                if '0' <= char <= '9':
                    n += char
                else:
                    n += chr(90 - (65 - val - 1))
    else:
        n += char
print(n)

Test case 1:

(in1)>> 3
(in2)>> H3LL0 W0RLD
(out)>> E3II0 T0OIA

Test case 2:

(in1)>> 6
(in2)>> THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
(out)>> NBY KOCWE VLIQH ZIR DOGJM IPYL NBY FUTS XIA

Test case 3:

(input_num_1)>> 2
(input_num_2)>> H4IGDFDNO£PJNHVDKHZPDOPG2
(ExpectedOut)>> F4GEBDBLM\-62\-93NHLFTBIFXNBMNE2
(My_output_.)>> F4GEBDBLMNHLFTBIFXNBMNE2

Your help & and time to review this is seriously appreciated. Thank you.


Edit: To add more clarity, I've added what my code yields as an output under the expected output, and to be specific, how/why is £ mapped to \-62\-93 ?

1 Answers

Can't beat a good Caesar Cipher question. You're on the right track but I would use inbuilt checks on the character to quickly decide what to do with it.

sh = int(input())
s = input()
n = ""
for char in s:
    val = ord(char)-sh
    if char.isupper() and char.isalpha():
        if 65 <= val <= 90:
            n += chr(val)
        else:
            n += chr(90 - (65 - val - 1))
    else:
        n += char
print(n)
Related