0

How to make this program give proper output and shift elements in list properly using for loop and one board e.g given numbers 0 1 2 3 4 number of shifts 2 then 2 3 4 0 1

numquantity = int(input("enter the number"))
board = []

for number in range(numquantity):
    board.append(input())
numberofrotations = int(input("number of shifts"))

for index in range(numberofrotations):
    taken = board.pop(0)
    board.insert(-1, taken)

print(board)

3 Answers3

0

insert(-1, taken) doesn't insert at the last position, but just before. (See the official doc quote at the end of the post)

If you take the initial list [1, 2, 3] and 2 rolls:

['2', '1', '3']
['1', '2', '3']

You should replace this with append and it's ok:

['2', '3', '1']
['3', '1', '2']

So here is the code:

for _ in range(number_of_rotations):
    board.append(board.pop(0))

Or, as insert inserts at the index BEFORE:

for index in range(numberofrotations):
    board.insert(len(board), board.pop(0))

Here is from the Python official doc:

list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

Metapod
  • 415
  • 2
  • 11
  • How to make it shift to right not to left? – Stefan Kelp Oct 29 '21 at 15:11
  • @StefanKelp You mean ```[1,2,3] => [3,1,2]``` ? If so, you just need to pop the last element of the list & insert it at the very beginning of the list (Note that the post of Kirushikesh gives some details for the insert method) – Metapod Nov 02 '21 at 16:53
0

For future reference, you should provide more information on what happens and what should happen, just copy pasting the console output of the program would already be hugely helpful.

But anyway, I'd like to point you to this stack overflow question to see what you are doing wrong:

Why does list.insert[-1] not work in python?

Ou Tsei
  • 470
  • 7
  • 24
0

To shift right you need to pop the last element from the array and insert it into the front since inserting element in front of the array will cost O(N) in when using list so its better to use deque because insertion at front will cost O(1). Here is the code

from collections import deque

numquantity = int(input("enter the number"))
board = deque()

for number in range(numquantity):
    board.append(input())
numberofrotations = int(input("number of shifts"))

for index in range(numberofrotations):
    board.appendleft(board.pop())

print(board)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Kirushikesh
  • 578
  • 5
  • 8