Python - 用前缀交换 K 后缀
给定一个列表,执行 K 前缀和后缀的交换。
例子:
Input : test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9], K = 2
Output : [7, 9, 3, 1, 0, 1, 3, 5, 5, 6]
Explanation : Rear 2 and Front 2 elements swapped.
Input : test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9], K = 1
Output : [9, 6, 3, 1, 0, 1, 3, 5, 7, 5]
Explanation : Rear 1 and Front 1 element swapped.
方法#1:使用切片和范围交换
在这里,我们使用列表切片执行获取所需切片的任务,并执行范围交换以交换元素。这是解决此问题的就地方法。
Python3
# Python3 code to demonstrate working of
# Swap K suffix with prefix
# Using range swap + slice()
# initializing list
test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# performing range swap
test_list[:K], test_list[len(
test_list) - K:] = test_list[len(test_list) - K:], test_list[:K]
# printing result
print("After prefix suffix swap : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Swap K suffix with prefix
# Using slice notation
# initializing list
test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# joining parts using slice
res = test_list[len(test_list) - K:] + \
test_list[K: len(test_list) - K] + test_list[:K]
# printing result
print("After prefix suffix swap : " + str(res))
输出
The original list is : [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
After prefix suffix swap : [5, 7, 9, 1, 0, 1, 3, 5, 6, 3]
方法#2:使用切片符号
在此,我们使用切片执行切片的每个列表来执行列表元素的重建。
蟒蛇3
# Python3 code to demonstrate working of
# Swap K suffix with prefix
# Using slice notation
# initializing list
test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# joining parts using slice
res = test_list[len(test_list) - K:] + \
test_list[K: len(test_list) - K] + test_list[:K]
# printing result
print("After prefix suffix swap : " + str(res))
输出
The original list is : [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
After prefix suffix swap : [5, 7, 9, 1, 0, 1, 3, 5, 6, 3]