转移列表循环python

时间:2013-10-15 03:24:08

标签: python

我很难实现我迄今为止创建一个真正的定义程序。

def left():
    listL = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    k=4
    right = listL[k::]
    left = listL[:k:]
    print(right + left)


def right():
    listL = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    k=len(listL)-4
    right = listL[k::]
    left = listL[:k:]
    print(right + left)

我的代码根据左移或右移k来确定重新创建原始listL的位置,在本例中为4.但是我的练习问题要求......

Given a list of N numbers, write a function to shift the numbers circularly by some integer k (where k < N). The function should take the list and k as arguments and return the shifted list. 
a) Write a function that assumes the shifting is to the left. It should not print anything. 
b) Write a function that takes a third argument that specifies shifting left or right. It should not print anything. Perform whatever error-checking you consider necessary. 
c) Write a main() function that calls the above functions. It should print the lists both before and after shifting. Perform whatever error-checking you consider necessary. 

我对A部分感到满意​​,但我对如何构建B部分和C部分以完全复制问题提出了疑问。

解决方案示例运行:

Sample run 
>>> ================================ RESTART ================================
>>> 
original list:  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
shifted by 4, to the left: [4, 5, 6, 7, 8, 9, 0, 1, 2, 3]
shifted by 4, to the right: [6, 7, 8, 9, 0, 1, 2, 3, 4, 5]

关于如何解决b和c部分的任何建议将不胜感激! :)

3 个答案:

答案 0 :(得分:15)

我认为这不适用于OP,因为它听起来像CS课程作业,但对于寻找解决方案的其他人来说,只需使用:

from collections import deque

d = deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
d.rotate(3)  # to the right
d.rotate(-3)  # back to the left

*修改

跟进您的评论(来自deque docs):

  

Deques是堆栈和队列的概括(名称是   发音为“deck”,是“双端队列”的缩写。双端   支持线程安全,内存高效的附加和弹出   deque的一侧具有大致相同的O(1)性能   任何方向。

     

虽然列表对象支持类似的操作,但它们已经过优化   快速固定长度操作并导致O(n)内存移动成本   pop(0)和insert(0,v)操作,它们改变了大小和   基础数据表示的位置。

答案 1 :(得分:3)

检查出来:

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

循环移位4:

>>> b = a[4::] + a[:4:]
>>> b
[4, 5, 6, 7, 8, 9, 0, 1, 2, 3]

并采用两种函数格式:

def shiftLbyn(arr, n=0):
    return arr[n::] + arr[:n:]

def shiftRbyn(arr, n=0):
    return arr[n:len(arr):] + arr[0:n:]

打电话给他们:

print shiftLbyn([1,2,3,4,5,6,7,8], 3)
print shiftRbyn([1,2,3,4,5,6,7,8], 4)

将给出输出:

[4, 5, 6, 7, 8, 1, 2, 3]
[5, 6, 7, 8, 1, 2, 3, 4]

答案 2 :(得分:2)

首先更改函数以获取参数并返回结果。例如

def left(listL, k):
    right = listL[k::]
    left = listL[:k:]
    return right + left # is this the usual meaning of left and right?

# This is how you call the function
print(left([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4))

现在,如果您注意到leftright具有相同的最后3行。你可以像这样组合它们

def shift(listL, k, direction):
    if direction == "right":
        k = len(listL) - k
    right = listL[k::]
    left = listL[:k:]
    return right + left

我猜main会是这样的

def main(listL):
    print(listL)
    print(shift(listL, 4, "left"))
    print(shift(listL, 4, "right"))