Python program to rotate an array towards its left
Inplace Method
# Rotate Array def roateLeft(arr, size, rotate_count): array_length = len(arr) if array_length <= 0: return arr if size > array_length: size = array_length # Figure out effective roation count # eg: size = 10 and rotation_count = 15 # effective roation_count is 5 if rotate_count > size: rotate_count = rotate_count - size print ("Array Length: %d" %array_length) print ("Array Size to consider: %d" %size) print ("Effective Rotation Count: %d" %rotate_count) while rotate_count > 0: rotate_count -= 1 shiftLeft(arr, size) # Shift One Element def shiftLeft(arr, size): array_length = len(arr) # return if array is empty if array_length <= 0: return # Check and use the size passed in if size < array_length: array_length = size firstItem = arr[0] for index in range (array_length - 1): arr[index] = arr[index + 1] arr[array_length - 1] = firstItem # Tests input_array = [1,2,3,4,5,6,7,8,9] print ("Input", input_array) roateLeft(input_array, 5, 6) print ("Output", input_array) print ("") input_array = [1,2,3,4,5,6,7,8,9] print ("Input", input_array) roateLeft(input_array, 12, 14) print ("Output", input_array) print ("") input_array = [] print ("Input", input_array) roateLeft(input_array, 12, 14) print ("Output", input_array) ''' Output: Input [1, 2, 3, 4, 5, 6, 7, 8, 9] Array Length: 9 Array Size to consider: 5 Effective Rotation Count: 1 Output [2, 3, 4, 5, 1, 6, 7, 8, 9] Input [1, 2, 3, 4, 5, 6, 7, 8, 9] Array Length: 9 Array Size to consider: 9 Effective Rotation Count: 5 Output [6, 7, 8, 9, 1, 2, 3, 4, 5] Input [] Output [] '''
Split and Merge Method
# Rotate Array def roateLeft(arr, size, rotate_count): array_length = len(arr) if array_length <= 0: return arr if size > array_length: size = array_length # Figure out effective roation count # eg: size = 10 and rotation_count = 15 # effective roation_count is 5 if rotate_count > size: rotate_count = rotate_count - size print ("Array Length: %d" %array_length) print ("Array Size to consider: %d" %size) print ("Effective Rotation Count: %d" %rotate_count) return arr[rotate_count:size] + arr[:rotate_count] + arr[size:array_length] # Tests input_array = [1,2,3,4,5,6,7,8,9] print ("Input", input_array) output_array = roateLeft(input_array, 5, 6) print ("Output", output_array) print ("") input_array = [1,2,3,4,5,6,7,8,9] print ("Input", input_array) output_array = roateLeft(input_array, 12, 14) print ("Output", output_array) print ("") input_array = [] print ("Input", input_array) output_array = roateLeft(input_array, 12, 14) print ("Output", output_array) ''' Output: Input [1, 2, 3, 4, 5, 6, 7, 8, 9] Array Length: 9 Array Size to consider: 5 Effective Rotation Count: 1 Output [2, 3, 4, 5, 1, 6, 7, 8, 9] Input [1, 2, 3, 4, 5, 6, 7, 8, 9] Array Length: 9 Array Size to consider: 9 Effective Rotation Count: 5 Output [6, 7, 8, 9, 1, 2, 3, 4, 5] Input [] Output [] '''
Hope this helps.