Coding/Basic Skills(Python)

[Programmers, Level 1] Caesar cipher

xeohyuni 2023. 8. 21. 23:25

Description:

The Caesar method that shifts each letter of a given sentence by a fixed distance to replace it with another letter is called the Caesar cipher. For example, shifting "AB" by 1 would result in "BC", and by 3 would result in "DE". Shifting "z" by 1 would result in "a". Given a string s and a distance n, please complete the function called "solution" to create an encrypted text of s shifted by n units.

Restrictions:

  • Spaces remain spaces no matter how much you shift them.
  • The string "s" consists only of uppercase letters, lowercase letters, and spaces.
  • The length of string "s" is up to 8000 characters.
  • The value of "n" is a natural number between 1 and 25 inclusive.

Input/Output Exmaple:

s n result
"AB" 1 "BC"
"z" 1 "a"
"a B z" 4 "e F d"

 

Code:

def solution(s, n):
    ans = ""
    low = "abcdefghijklmnopqrstuvwxyz"
    up = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for alpha in s:
        if alpha in up:
            idx = up.find(alpha)+n
            ans += up[idx%26]
            
        elif alpha in low:
            idx = low.find(alpha)+n
            ans += low[idx%26]
            
        else:
            ans += " "
            
    return ans

Discussion:

The provided Python code implements the Caesar password method, which involves shifting each letter in a given input string s by a fixed distance n in the alphabet. The code processes each character in the input string, identifying whether it's an uppercase or lowercase letter. For uppercase letters, the code calculates the new shifted index, wraps it around within the range of 26 using modulo division, and replaces the letter with the shifted letter from the uppercase alphabet. Similarly, for lowercase letters, the code performs the same shifting and wrapping process using the lowercase alphabet. Symbols and whitespace are preserved as they are.