shift_right python using for loops

前端 未结 3 1898
自闭症患者
自闭症患者 2021-01-26 04:18

The question is to write a shift_right function so that it shifts every element in the list to the right. For instance, if the list is

L = [\'a\',\         


        
相关标签:
3条回答
  • 2021-01-26 04:22

    I just figured out the answer for the question. Its as follows.

    def shift_right(L):
        last_item = L[-1]
        for i in range(1, len(L)):
            L[len(L) - i] = L[len(L) - i - 1]
        L[0] = last_item
    
    0 讨论(0)
  • 2021-01-26 04:36

    I'd implement it like this:

    def shift_right(L):
        if len(L) > 0:
            L.insert(0, L.pop())
    

    As Lee correctly comments, this is a rotate operation rather then a shift.

    0 讨论(0)
  • 2021-01-26 04:43

    I'll add this in for completeness.

    If you are shifting several at at time you can use something like

    def rotate(L, n):
        if len(L) is not 0:
            shift = n % len(L)
            L[:shift], L[shift:] = L[-shift:], L[:-shift]
    

    If you are doing this often throughout your program, it could be worthwhile to use a deque. You can convert your list to a deque like this:

    from collections import deque
    L = deque(L)
    

    then to rotate it n spaces to the right, you can use

    L.rotate(n)
    

    If you want to convert it back into a list, you can do

    L = list(L)
    

    It is better to avoid converting back and forth, since it takes as much time as several rotations in the list. Deques work best when you are accessing, adding, and deleting around their beginnings and ends.

    0 讨论(0)
提交回复
热议问题