Python Array Problem Solution
Verfasst: Dienstag 29. März 2022, 14:01
Hey,
I Newly Joined this community, hope all are staying well.
A little background: I am a noob in python programming and for the last few weeks had been practising a few Python programs on Arrays. I need help understanding this very problem, it would really mean a lot if someone could comment across each code line and share the code snippet using any online compiler.
Problem Statement:
Q) Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements.
Input : arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2
Output : arr[] = [3, 4, 5, 6, 7, 1, 2]
Thanks..!
I Newly Joined this community, hope all are staying well.
A little background: I am a noob in python programming and for the last few weeks had been practising a few Python programs on Arrays. I need help understanding this very problem, it would really mean a lot if someone could comment across each code line and share the code snippet using any online compiler.
Problem Statement:
Q) Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements.
Input : arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2
Output : arr[] = [3, 4, 5, 6, 7, 1, 2]
Code: Alles auswählen
# Python program for reversal algorithm of array rotation
# Function to reverse arr[] from index start to end
def rverseArray(arr, start, end):
while (start < end):
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start += 1
end = end-1
# Function to left rotate arr[] of size n by d
def leftRotate(arr, d):
n = len(arr)
rverseArray(arr, 0, d-1)
rverseArray(arr, d, n-1)
rverseArray(arr, 0, n-1)
# Function to print an array
def printArray(arr):
for i in range(0, len(arr)):
print (arr[i])
# Driver function to test above functions
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2) # Rotate array by 2
printArray(arr)