How to Reverse an array in groups in python?

Question:

I am trying to reverse the array in groups but I am getting this error:

:----  for i in arr: TypeError: 'NoneType' object is not iterable. 

What’s wrong with my code?

   def reverseSubarray(arr,n,k):
      if k == 1:
        return
      i = 0
      while i < n:
        l = i
        r = min(i+k-1, n-1)
        while l < r:
          temp = arr[l]
          arr[l] = arr[r]
          arr[r] = temp
          l += 1
          r -= 1
        i += k
      return arr
    
    def main():
        n = int(input().strip())
        string  = input().strip().split()
        arr=[]
        for j in string:
            arr.append(int(j.strip()))
        k=int(input().strip())
        arr = reverseSubarray(arr,n,k)
        for i in arr:
            print(i,end=' ')
    
    if __name__ == "__main__":
        main()
Asked By: Puneet Sharma

||

Answers:

So the problem is that you’re actually returning None. This happens because most likely you’re giving k=1 so it will go to that line where you return nothing, which will return this error when trying to iterate.

You can treat the problem with a try-catch block on arr=reverseSubarray(arr,n,k) that will return a message like k cannot be 1

Answered By: Alexandru DuDu

You can reverse an array in groups in python as given below,

def reverseSubarray(arr, N, K):
    for i in range(0, len(arr),K):
        l=arr[i:i+K]
        l.reverse()
        arr[i:i+K] =l
    return arr
Answered By: Vivesh Kumar

While your error was indeed coming from the fact that your function is returning None as other answers have pointed out, you have also written the function in a very non-pythonic style. Here is an example of how you could rewrite it more succintly:

def reverseInGroups(self, arr, N, K):
    for i in range(0, N, K):
        arr[i:i+K] = reversed(arr[i:i+K])
    return arr
  • range(0, N, K) will return an iterator that goes from 0 to N-1 in steps of K. In other word, i will successively have value: 0, K, 2K, 3K, 4K, etc. until the last multiple of K that is less than N. Here is the documentation for more details.
  • arr[i:i+K] will refer to the slice of arr between indices i and i+K-1 or, put another way, [arr[i], arr[i+1], arr[i+2], ..., arr[i+K-1]]. It stops at i+K-1 so that you can naturally use arr[i:i+K] and arr[i+K:] without counting arr[i+K] twice.
  • reversed… reverses an iterator. Here’s the doc.
Answered By: Neha Sharma
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.