Home > Software design >  Function to reverse every sub-array group of size k in python
Function to reverse every sub-array group of size k in python

Time:09-05

I did this code so I reverse sub array group of integers but actually it only reverse the first sub array only and I don't know why this is happening!!! Here is the code:

def reverseInGroups(self, arr, N, K):
    rev=list()
    count=0
    reach=K
    limit=0
    while limit<N-1:
        rev[limit:reach]=reversed(arr[limit:reach])
        limit=limit K
        reach=reach K
        
        if reach==N-1 or reach<N-1:
            continue
           
        elif reach>N-1:
            reach=N-1
            
                
    return rev

This is the the input,excpected output and my output:

For Input: 
5 3
1 2 3 4 5
Your Output: 
1 2 3 4 5 
Expected Output: 
3 2 1 5 4 

CodePudding user response:

You don't have to create new list rev, you can reverse items in list arr. For example:

def reverseInGroups(arr, N, K):
    limit = 0
    while limit < N:
        arr[limit : limit   K] = reversed(arr[limit : limit   K])
        limit  = K
    return arr


l = [1, 2, 3, 4, 5]
print(reverseInGroups(l, 5, 3))

Prints:

[3, 2, 1, 5, 4]

CodePudding user response:

I tried your code online and its fine, but you have one logic error in your function to get your desired output.

while limit<N-1:
rev[limit:reach]=reversed(arr[limit:reach])
limit=limit K  #3
reach=reach K  #6
if reach==N-1 or reach<N-1:
    continue
elif reach>N-1:
    reach=N  #5 

this is an image to see what I mean image description

  • Related