Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬으로 문자열에서 미러 문자 찾기


사용자로부터 입력받은 문자열과 특정 위치가 주어졌을 때, 해당 위치부터 문자열 끝까지의 문자를 알파벳 역순으로 변환하는 것이 이 프로그램의 목표입니다. 이 연산에서는 'a'를 'z'로, 'b'를 'y'로, 'c'를 'x'로, 'd'를 'w'로 바꾸는 식으로 진행됩니다. 즉, 알파벳 순서에서 첫 번째 문자가 마지막 문자로 매핑되는 거울(mirror) 방식입니다.

입력: p = 3
   입력 문자열 = python
출력 : pygslm

위 예시에서 위치 3부터 시작하는 't', 'h', 'o', 'n'이 각각 'g', 's', 'l', 'm'으로 변환되었음을 확인할 수 있습니다.

알고리즘

Step 1: 문자열과 미러 변환을 시작할 위치를 입력받습니다.
Step 2: 알파벳 역순으로 저장된 문자열을 생성합니다.
Step 3: 빈 문자열을 하나 생성합니다.
Step 4: 지정된 위치까지의 각 문자를 순회하며 원본 그대로 유지합니다.
Step 5: 해당 위치부터 문자열 끝까지는 알파벳 역순으로 변환합니다.
Step 6: 최종 결과 문자열을 반환합니다.

예제 코드

# Python program to find mirror characters in string
 
def mirror(str1, n):
   # Creating a string having reversed
   # alphabetical order
   alphaset = "zyxwvutsrqponmlkjihgfedcba"
   l = len(str1)

   # The string up to the point specified in the
   # question, the string remains unchanged and
   # from the point up to the length of the 
   # string, we reverse the alphabetical order
   result = ""
   for i in range(0, n):
      result = result + str1[i];

   for i in range(n, l):
      result = (result +
      alphaset[ord(str1[i]) - ord('a')]);
   return result;
 
# Driver function
str1 = input("Enter the string ::>")
n = int(input("Enter the position ::>"))
result = mirror(str1, n - 1)
print("The Result ::>",result)

코드 설명

이 코드의 핵심은 alphaset 변수에 저장된 알파벳 역순 문자열입니다. ord(str1[i]) - ord('a') 계산을 통해 현재 문자가 알파벳에서 몇 번째 위치인지 구한 뒤, 그 인덱스를 역순 문자열에 적용하면 자동으로 미러 문자가 됩니다. 예를 들어 'a'의 경우 인덱스 0이므로 역순 문자열의 첫 번째 문자인 'z'로 변환됩니다.

또한 위치 n 이전의 문자들은 변환 없이 그대로 유지되며, 오직 지정된 위치부터 문자열 끝까지만 미러 변환이 적용됩니다.

실행 결과

Enter the string ::> python
Enter the position ::> 3
The Result ::> pygslm