Home > database >  Want to reverse subarray from the indices given in another 2d array?
Want to reverse subarray from the indices given in another 2d array?

Time:02-22

I have an array say A1=[5,3,2,1,3] , and another 2D array say A2 = [[0,1],[1,3]]. What I want is to reverse the subarrays of A1 by indices mentioned in each array in A2

Like here,

In first operation of A2 i.e. [0,1], it reverses A1 from A1[0] to A1[1] so A1 becomes = [3,5,2,1,3].

In second operation of A2 i.e. [1,3], it reverses A1 from A1[1] to A1[3] so A1 becomes = [3,1,2,5,3].

So ANS is [3,1,2,5,3]

Can anyone tell me how to do it this problem since I am beginner to coding.? I am working in 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()

I had figured out the brute force approach but how can I write the reverseSubArrayfunction here.?

Can anyone share the approach

CodePudding user response:

You can use list slices to easily reverse your sublist -

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)

outputs -

[3, 5, 2, 1, 3]

Explanation -

  • arr[start:end 1] would create a slice of arr inclusive of start and end index
  • arr[::-1] returns a reversed slice of arr
>>> a = [5,3,2,1,3]
>>> a[0:2]
[5, 3]
>>> a[0:2][::-1]
[3, 5]
>>> a[0:-2]
[5, 3, 2]

CodePudding user response:

Ignoring the rest of your code, here's how you could implement the 'reverse' functionality:

A1 = [5,3,2,1,3]
A2 = [[0,1],[1,3]]

def swap(a1, a2):
    for e in a2:
        i, j = e
        a1[i], a1[j] = a1[j], a1[i]
    return a1

print(swap(A1, A2))

Output:

[3, 1, 2, 5, 3]
  • Related