[英]Want to reverse subarray from the indices given in another 2d array?
我有一個數組說A1=[5,3,2,1,3]
,另一個二維數組說A2 = [[0,1],[1,3]]
。 我想要的是通過A2
中每個數組中提到的索引來反轉A1
的子數組
像這兒,
在 A2 的第一個操作中,即[0,1]
,它將 A1 從A1[0] to A1[1]
,因此A1 becomes = [3,5,2,1,3].
在 A2 的第二個操作中,即[1,3]
,它將 A1 從A1[1] to A1[3]
,因此A1 becomes = [3,1,2,5,3].
所以ANS is [3,1,2,5,3]
任何人都可以告訴我如何解決這個問題,因為我是編碼初學者。? 我在 python 工作。
import math
import os
import random
import re
import sys
#function
def reversubarray(arr,start,end):
def performOperations(arr, operations):
answerarray = arr
x = oprations.size();
for i in range(x):
answerarray = reverseSubarray(arr,operations[x][0],operations[x][1])
return answerarray;
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr_count = int(input().strip())
arr = []
for _ in range(arr_count):
arr_item = int(input().strip())
arr.append(arr_item)
operations_rows = int(input().strip())
operations_columns = int(input().strip())
operations = []
for _ in range(operations_rows):
operations.append(list(map(int, input().rstrip().split())))
result = performOperations(arr, operations)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()
我已經想出了蠻力方法,但我怎么能在這里寫reverseSubArray
function。?
任何人都可以分享這個方法
您可以使用列表切片輕松反轉您的子列表 -
def reversubarray(arr,start,end):
arr[start:end+1] = arr[start:end+1][::-1]
a = [5,3,2,1,3]
reversubarray(a, 0, 1)
print(a)
輸出 -
[3, 5, 2, 1, 3]
解釋 -
arr[start:end+1]
將創建一個包含start
和end
索引的arr
片段arr[::-1]
返回arr
的反向切片>>> a = [5,3,2,1,3]
>>> a[0:2]
[5, 3]
>>> a[0:2][::-1]
[3, 5]
>>> a[0:-2]
[5, 3, 2]
忽略代碼的 rest,以下是實現“反向”功能的方法:
A1 = [5,3,2,1,3]
A2 = [[0,1],[1,3]]
def swap(a1, a2):
for i, j in a2:
a1[i], a1[j] = a1[j], a1[i]
return a1
print(swap(A1, A2))
Output:
[3, 1, 2, 5, 3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.