Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để tìm các ký tự nhân bản trong một chuỗi

Cho một chuỗi nhập của người dùng và vị trí từ vị trí đó, chúng ta cần sao chép các ký tự lên đến chiều dài của chuỗi theo thứ tự bảng chữ cái. Trong thao tác này, chúng ta thay đổi 'a' thành 'z', 'b' thành 'y', 'c' thành 'x', 'd' thành 'w', v.v. có nghĩa là ký tự đầu tiên trở thành ký tự cuối cùng trên.

Inpu t: p = 3
   Input string = python
Output : pygslm

Thuật toán

Step 1: Input the string and position from we need to mirror the characters.
Step 2: Creating a string which is stored in alphabetical order.
Step 3: Create an empty string.
Step 4: Then traverse each character up to the position from where we need a mirror and up to this sting is unchanged.
Step 5: From that position up to the length of the string, we reverse the alphabetical order.
Step 6: Return the string.

Mã mẫu

# 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)

Đầu ra

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