Python 中的字串切片旋轉字串
給定一個字串,我們的任務是對字串進行兩種型別的切片操作。一是順時針,另一個是逆時針。
1. 逆時針(或逆時針)旋轉給定的字串 d 個元素(其中 d <= n)。
2. 順時針(或順時針)旋轉給定的字串 d 個元素(其中 d <= n)。
示例
Input: string = "pythonprogram" d = 2 Output: Left Rotation: thonprogrampy Right Rotation: ampythonprogr
演算法
Step 1: Enter string. Step 2: Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ]. Step 3: Now concatenate these two parts second + first accordingly.
示例程式碼
def rotate(input,d):
# Slice string in two parts for left and 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)輸出
Enter String ::> pythonprogram Left Rotation: thonprogrampy Right Rotation: ampythonprogr
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP