Q#51: Reorder an array by x elements in Python
Published in
Oct 1, 2021
Given an array of size n, write a function to move x elements from the front to the end of the array.
For example:
#Given the following:array = [2,4,6,8,10]x = 3#To shift 3 elements you would return:[8,10,2,4,6]
TRY IT YOURSELF
ANSWER
This question tests our understanding of Python programming, specifically writing a function and understanding array/list structures.
Luckily for us in python we can adjust arrays in place if we index through every element using [:]. So the solution will just be to index through the whole array by the partitions [x:] and [:x].
def shift_array(array, x):
array[:] = array[x:] + array[:x]
return array