Caesar Cipher

  • + 0 comments
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    #
    # Complete the 'caesarCipher' function below.
    #
    # The function is expected to return a STRING.
    # The function accepts following parameters:
    #  1. STRING s
    #  2. INTEGER k
    #
    
    def caesarCipher(s, k):
        # Write your code here
        # time is O(n)
        # incase k is larger than 26, we % so move is between 0 - 26
        move = k % 26
        result = []
        for letter in s:
            if letter.isupper():
                # ord() converts str to ACII num, and chr converts it back
                # - 65 so it goes from 0 - 26, % 26 so after adding move it's 
                # still within 26 letter range, + 65 to go back to ACII
                letter = chr((ord(letter) - 65 + move) % 26 + 65)
            elif letter.islower():
                # lower letter a starts at 97
                letter = chr((ord(letter) - 97 + move)% 26 + 97)
            result.append(letter)
            #combind letters in the arr result with "" (nothing) in between
        return "".join(result)
        
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        n = int(input().strip())
    
        s = input()
    
        k = int(input().strip())
    
        result = caesarCipher(s, k)
    
        fptr.write(result + '\n')
    
        fptr.close()