Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

String slicing trong Python để xoay chuỗi


Cho một chuỗi, nhiệm vụ slicing chuỗi theo hai cách: theo chiều kim đồng hồ (clockwise) và ngược chiều kim đồng hồ (anticlockwise).

1. Xoay trái (anticlockwise) chuỗi cho trước d phần tử (d <= n).

2. Xoay phải (clockwise) chuỗi cho trước d phần tử (d <= n).

Ví dụ

Input: string = "pythonprogram"
d = 2
Output: Left Rotation: thonprogrampy
Right Rotation: ampythonprogr

Thuật toán

Bước 1: Nhập chuỗi.
Bước 2: Tách chuỗi thành hai phần first & second.
- Left rotation: Lfirst = str[0:d], Lsecond = str[d:].
- Right rotation: Rfirst = str[0:len(str)-d], Rsecond = str[len(str)-d:].
Bước 3: Nối hai phần second + first tương ứng.

Ví dụ mã

def rotate(input, d):
    # Slice chuỗi thành hai phần cho left và right
    Lfirst = input[0:d]
    Lsecond = input[d:]
    Rfirst = input[0:len(input)-d]
    Rsecond = input[len(input)-d:]
    print("Left Rotation:", (Lsecond + Lfirst))
    print("Right Rotation:", (Rsecond + Rfirst))

# Driver program
if __name__ == "__main__":
    str = input("Enter String ::>")
    d = 2
    rotate(str, d)

Kết quả

Enter String ::> pythonprogram
Left Rotation: thonprogrampy
Right Rotation: ampythonprogr