1

I have written a code where the user enters a code and the program rotates it by the desired amount but each time it rotates by two and not one. E.g. 1 2 3 4 5 rotated by one would turn into 4 5 1 2 3 My code is:

    arSize = int(input("Please enter the size of the list "))
    arr = []
    d = int(input("How many times do you want to rotate it to the right? :"))
    for i in range(0, arSize) :
     number = int(input("Please enter array[" + str(i) + "] value: "))
     arr.append(number)

    n = arSize

    def rightRotate(arr, d, n): 
      for i in range(d): 
        rightRotatebyTwo(arr, n) 

    def rightRotatebyTwo(arr, n):
      temp = arr[0]
      temp1 = arr[1]
      arr[1] = arr[n-1]
      arr[0] = arr[n-2]
      for i in range(2, n-1):
        temp2 = arr[i]
        temp3 = arr[i+1]
        arr[i] = temp
        arr[i+1] = temp1
        temp = temp1
        temp1 = temp2


    def printArray(arr, size): 
      for i in range(size): 
        print (arr[i]) 

    rightRotate(arr, d, n) 
    printArray(arr, n)

This is the outcome:

    Please enter the size of the list 6
    How many times do you want to rotate it to the right? :1
    Please enter array[0] value: 1
    Please enter array[1] value: 2
    Please enter array[2] value: 3
    Please enter array[3] value: 4
    Please enter array[4] value: 5
    Please enter array[5] value: 6
    5
    6
    1
    2
    3
    2
S.Dileep
  • 13
  • 3

1 Answers1

1

Your approach is a bit too convoluted. You should try a different approach.

For eg: A simple slicing operation would work just fine here.

def rotateRight(no_of_rotations):
    arr = [1, 2, 3, 4, 5] 
    arr = arr[no_of_rotations:] + arr[:no_of_rotations] 
    return arr 

All the best! :)

Sameer Pusegaonkar
  • 123
  • 1
  • 3
  • 13