Circular Shifting Programmatically in Python

thumbnail

In this tutorial, you will learn create program to circular shifting array programmatically in python. You don’t need to import anything. Below is the python code to do circular shifting array.

# Created by inpows
# Visit inpows.com for more python tutorials

# define circShift() with parameter arr and k
# arr: Input Array
# k: Total shifting
def circShift(arr, k):
    n = len(arr)
    if(k<0):
        k = k + n
    for i in range(0,k):
        x = arr[0]
        for j in range(0, n-1):
            arr[j] = arr[j+1]
        arr[n-1] = x

if __name__ == "__main__" :
    # Initialize the Array
    arr = [1,2,3,4,5,6]
    # Determine the total number to shift the array
    # I choose the middle position to shift
    print("Initial:"+str(arr)+"\n")
    shiftNumber = -3
    circShift(arr, shiftNumber)
    print("Shift to right 3 times")
    print("Result:"+str(arr)+"\n")
    shiftNumber = 2
    circShift(arr, shiftNumber)
    print("Shift to left 2 times")
    print("Result:"+str(arr))

When you run the program, the output will be:

Initial:[1, 2, 3, 4, 5, 6]

Shift to right 3 times
Result:[4, 5, 6, 1, 2, 3]

Shift to left 2 times
Result:[6, 1, 2, 3, 4, 5]

Read another python tutorial through this link.

Back To Top