我在实施迄今为止创建真正定义程序的过程中遇到了麻烦。
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 部分的建议将不胜感激!:)