Python Tutorial (33) – Example: Reverse the specified number of elements in an array

Time: Column:Python views:190

Define an Integer Array and Rotate the First 'd' Elements to the End of the Array

The following Python code demonstrates how to define an integer array and rotate the first d elements of the array to the end. The process is shown through different implementations.

For example, (arr[], d, n) rotates the first d elements of an array of length n to the end.

The example rotates the first two elements of the array to the back.

Original Array:

1557040642-8986-simplearray.png

After Rotation:

1557040642-8722-arrayRotation.png

Example 1: Simple Rotation

def leftRotate(arr, d, n):
    for i in range(d):
        leftRotatebyOne(arr, n)

def leftRotatebyOne(arr, n):
    temp = arr[0]
    for i in range(n-1):
        arr[i] = arr[i+1]
    arr[n-1] = temp

def printArray(arr, size):
    for i in range(size):
        print("%d" % arr[i], end=" ")

# Array and function call
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)

Output:

3 4 5 6 7 1 2

Example 2: Rotation Using GCD

def leftRotate(arr, d, n):
    for i in range(gcd(d, n)):
        temp = arr[i]
        j = i
        while True:
            k = j + d
            if k >= n:
                k = k - n
            if k == i:
                break
            arr[j] = arr[k]
            j = k
        arr[j] = temp

def printArray(arr, size):
    for i in range(size):
        print("%d" % arr[i], end=" ")

def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)

# Array and function call
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)

Output:

3 4 5 6 7 1 2

Example 3: Reversal Algorithm for Rotation

def reverseArray(arr, start, end):
    while start < end:
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
        start += 1
        end -= 1

def leftRotate(arr, d):
    n = len(arr)
    reverseArray(arr, 0, d-1)
    reverseArray(arr, d, n-1)
    reverseArray(arr, 0, n-1)

def printArray(arr):
    for i in range(0, len(arr)):
        print(arr[i], end=' ')

# Array and function call
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2)
printArray(arr)

Output:

3 4 5 6 7 1 2

Explanation:

  1. Example 1 rotates the array by shifting each element by one position, repeatedly for d times.

  2. Example 2 uses the Greatest Common Divisor (GCD) to optimize the rotation process by reducing the number of rotations needed.

  3. Example 3 employs the reversal algorithm, where the array is reversed in parts to achieve the final rotation.