Home > Software design >  I can't solve this reverse specific items in a given array
I can't solve this reverse specific items in a given array

Time:01-12

Still I haven't been able to solve this challenge. After hours of thinking and analysing this exercise to see if it can work with different inputs, I came here to seek help.

For a given array of integers, perform operations on the array. Return the resulting array after all operations have been applied in the order given. Each operation contains two indices. Reverse the subarray between those zero-based indices, inclusive.

arr =15, 3, 2, 1, 31

operations = [[0, 1], [1, 3]]

a= [5,3,2,1,3]
o = [[0,1], [1,3]]

# Desired Outputs:
# arr1 = [3, 5, 2, 1, 3]
# arr2 = [3, 1, 2, 5, 3]


def performOperations(arr, o):

    i1 = o[0][0]
    i2 = o[0][1]
    i3 = o[1][0]
    i4 = o[1][1]

    indexes_1 = [i1, i2]
    indexes_2 = [i3, i4]

    arr_1_reversed_items = arr[i1:i2 1:1][::-1]

    arr_1 = arr
    for index in indexes_1:
        arr_1[indexes_1[index]] = arr_1_reversed_items[index]

    arr_2_reversed_items = arr_1[i3:i4 1:1][::-1]

    arr2 = arr
    for j in indexes_2:
        arr2[indexes_2[j]] = arr2[j 1]
        # The error here I gues is because the items positions are in the middle but not sure how to do this challenge to pass any kind of input
    return arr1, arr2

print(performOperations(a, o))

CodePudding user response:

you can use inplace slice assignment (note this modifies the original array)

a= [5,3,2,1,3]
o = [[0,1], [1,3]]

def performOperations(a, o):
    for start,end in o:
        if start > 0:
            a[start:end 1] = a[end:start-1:-1]
        else:
            a[start:end   1] = a[end::-1]
performOperations(a,o)
print(a)

CodePudding user response:

What you need to do is to iterate over the list of operations; in every iteration store the sublist in a temporary list, reverse it, and then assign it to the range within the original list. Note the elements of the sublists within o are accessed directly by use of tuple assignment.

a = [5, 3, 2, 1, 3]
o = [[0, 1], [1, 3]]

for x, y in o:
    rev = a[x: y 1]
    rev.reverse()
    a[x: y 1] = rev
    print(a)

This code snippet produces your desired output:

[3, 5, 2, 1, 3]
[3, 1, 2, 5, 3]

An even more simplified version that uses only slices will produce the same result:

a = [5, 3, 2, 1, 3]
o = [[0, 1], [1, 3]]

for x, y in o:
    a[x: y 1] = a[y: -len(a)-1 x: -1]
    print(a)
  •  Tags:  
  • Related