1

我在实施迄今为止创建真正定义程序的过程中遇到了麻烦。

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 部分的建议将不胜感激!:)

4

3 回答 3

16

我认为这对 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):

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

尽管列表对象支持类似的操作,但它们针对快速固定长度操作进行了优化,并且会为 pop(0) 和 insert(0, v) 操作带来 O(n) 内存移动成本,这些操作会改变底层数据表示的大小和位置.

于 2013-10-15T03:31:17.680 回答
4

看一下这个:

>>> 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]
于 2013-10-15T03:35:34.267 回答
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))

现在,如果您注意到这一点left并且right最后 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"))
于 2013-10-15T03:33:02.780 回答