Python program for rotation of elements of array- left and right

Python-program-for-rotation-of-elements-of-array-left-and-right

Array Rotation Left and Right

In this program we’ll be learning about rotation of elements of array towards left and right to a specified number of times.An array is said to be right rotated if all the selected elements were  moved towards right by one position. The last element of array will become the first element of array after rotation and vice versa for left rotation.

Left Rotation

Here we will be learning about Left rotation in an Array
Algorithm.

  • STEP 1: START
  • STEP 2: INITIALIZE arr[] ={10, 20, 30, 40, 50 }.
  • STEP 3: SET n =3
  • STEP 4: PRINT “Elements of Array”
  • STEP 5: REPEAT
  • STEP 6 UNTIL i<arr.length
    //for(i=0; i<arr.length; i++)
  • STEP 6: PRINT arr[i]
  • STEP 7: REPEAT
  • STEP 8 to STEP 12 UNTIL i<n
    // for(i=0; i<n; i++ )
  • STEP 8: DEFINE j, first.
  • STEP 9: first = arr[0]
  • STEP 10: REPEAT STEP 11 UNTIL j>0
    //for(j=0 ;j<arr.length-1; j++)
  • STEP 11: arr[j]= arr[j+1]
  • STEP 12: arr[j]= first
  • STEP 13: PRINT “Array after rotation”
  • STEP 14: REPEAT STEP 15 UNTIL i<arr.length
    //for(i=0; i<arr.length; i++)
  • STEP 15: PRINT arr[i]
  • STEP 16: END

Python Code For Left Rotation

Python-program-for-rotation-of-elements-of-array-left
a = list(map(int,input("ENTER ARRAY ELEMENTS ").split()))
k = int(input("ENTER NO.OF ROTATIONS "))
print("ARRAY BEFORE ROTATION ",*a)
k=k%len(a)
for i in range(k):
    x=a.pop(-1)
    a.insert(0,x)
print("ARRAY AFTER ROTATION  ",*a)

Right Rotation

Over here we will be learning how to rotate our array towards right.
Algorithm.

  • STEP 1: START
  • STEP 2: INITIALIZE arr[] ={10, 20, 30, 40, 50 }.
  • STEP 3: SET n =3
  • STEP 4: PRINT “Elements of Array”
  • STEP 5: REPEAT STEP 6 UNTIL i<arr.length
    //for(i=0; i<arr.length; i++)
  • STEP 6: PRINT arr[i]
  • STEP 7: REPEAT STEP 8 to STEP 12 UNTIL i<n
    // for(i=0; i<n; i++ )
  • STEP 8: DEFINE j, last.
  • STEP 9: last = arr[arr.length-1]
  • STEP 10: REPEAT STEP 11 UNTIL j>0
    //for(j= arr.length-1;j>0; j–)
  • STEP 11: arr[j]= arr[j-1]
  • STEP 12: arr[0]= last
  • STEP 13: PRINT “Array after rotation”
  • STEP 14: REPEAT STEP 15 UNTIL i<arr.length
    //for(i=0; i<arr.length; i++)
  • STEP 15: PRINT arr[i]
  • STEP 16: END

Python Code for right rotation

Python-program-for-rotation-of-elements-of-array-right
a = list(map(int,input("ENTER ARRAY ELEMENTS ").split()))
k = int(input("ENTER NO.OF ROTATIONS "))
print("ARRAY BEFORE ROTATION ",*a)
k=k%len(a)
for i in range(k):
    x=a.pop(0)
    a.append(x)
print("ARRAY AFTER ROTATION  ",*a)