In this simple python program, we need to left shift elements in an array. It's an intermediate-level python program.
To understand this example, you should have knowledge of the following Python programming topics:
In this simple python program, we need left rotate the elements of the array n times. An array in python is a set of elements of the same type indexed by a common variable. Array elements are stored in the sequential list as array= the first element, array = second, like that.
For example, consider an array A contains elements 1,2,3,4,5 Array A = [ 1, 2, 3, 4, 5 ] So we assume we want to rotate the elements by two times left.
like this, we can rotate any number of times.
Let us take the basic python program logic, we open a
for loop, then save the array's first element into a variable. Open inner for loop to left-shift the elements by one and append the last element from the saved variable. The outer for loop in python will continue until the number of times we need to left rotate the elements.
STEP 1: Initialize an array using some elements. And assign a value to n as the number of times we want to left rotate the array in python language.
STEP 2: Now we display the original array using a
for loop from zero to the length of an array using the
len() method and
range() method in python programming.
STEP 3: Open the outer for loop till the number n from zero using the range method.
STEP 4: Store the first element arr[i] to a variable.
STEP 5: Open the inner loop to traverse from the first element of the array to the length of the array minus one. We have to use less than one to append the last element from the variable.
STEP 6: Apply the left shift by using the method arr[j] = arr[j+1] and it will change the first element as the second element.
STEP 7: Append the last element of the array from the variable we stored the original array's first element.
STEP 8: Use a
for loop and
arr = [1, 2, 3, 4, 5]; n = 1; # how many times array should be shifted print("Original array: "); for i in range(0, len(arr)): # displaying the first or real array print(arr[i]), for i in range(0, n): # rotate the element of array using for loop first = arr; # saving the first element to a variable for j in range(0, len(arr)-1): arr[j] = arr[j+1]; #shifting to left by one arr[len(arr)-1] = first; # adding the first element to array from the variable print(); print("Array after left rotation: "); for i in range(0, len(arr)): print(arr[i]),
Original array: 1 2 3 4 5 Array after left rotation: 2 3 4 5 1