Python slicing | Reverse array in groups of a given size

Python Methods and Functions | reverse array

Examples:

 Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] k = 3 Output: [3, 2, 1, 6, 5 , 4, 9, 8, 7] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 Output: [5, 4, 3, 2, 1, 8, 7, 6] Input: arr = [1, 2, 3, 4, 5, 6] k = 1 Output: [1, 2, 3, 4, 5, 6] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 10 Output: [8, 7, 6, 5, 4, 3, 2, 1] 

We have a solution to this problem. Refer to function list slicing and

# function for inverse array in groups of given size

 

def reverseGroup ( input , k):

 

# set starting index to 0

start = 0

 

# start loop while len (input) / k times

# because there will be len (input) / k number

number of groups size k

result = []

while (start & lt; len ( input )):

 

  # if the group length is less than k

  # this means we only have the last one left

  # group inverse remaining elements

if len ( input [start:]) & lt; k:

result = result + list ( reversed ( input [start:]))

break

 

# select the current size group k

# flip it and merge it

result = result + list ( reversed ( input [start: start + k]))

  start = start + k

print (result)

 
# Driver program

if __ name__ = = "__ main__" :

input = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]

k < / code> = 5

reverseGroup ( input , k)

Output:

 [5, 4, 3, 2, 1, 8, 7, 6 ] 




Python slicing | Reverse array in groups of a given size: StackOverflow Questions

Tutorials