arrays - 我该如何修复这个数组?
问题描述
#!/bin/python3
b = []
def rotate(d,a):
if d == 0:
return a
b = []
for i in range(len(a)):
b.insert(i-1,a[i])
a = b
rotate(d-1,b)
if __name__ == '__main__':
d = 4
a = ['1','2','3','4','5']
print(rotate(d,a))
我不知道为什么,但是当我返回“a”时,它不会打印。谁能帮我这个
解决方案
您的问题是递归调用 rotate 时缺少 return 语句:
def rotate(d,a):
if d == 0:
return a
#....
rotate(d-1,b) # <---- here
如果您在 d > 0 的情况下调用 rotate(d, a),则输入递归 rotate(d-1,b)...但是您丢弃了结果,python 反而返回 None。这是因为在 python 中,任何没有显式返回值的方法调用,总是返回 None ...并且您对 d > 0 的初始调用 rotate(d, a) 从未通过 return 语句传递(只有递归调用d = 0 确实如此,但你丢弃了那个结果)......所以它返回 None。
这应该可以解决您的问题:
def rotate(d,a):
if d == 0:
return a
#....
return rotate(d-1,b) # propagate the calculated value back up
另请参阅:为什么我的递归函数返回 None?
推荐阅读
- c# - Selenium C# - Find All Links Inside an IFrame in a complex web page
- javascript - 视图中的 Asp.net Master-Detail 对象与 actionresult 中的视图模型不完全匹配
- r - For 和 If/else 循环不按我想要的方式循环
- ruby - Ruby AJAX 请求删除表行
- react-native - 使用 redux-persist 的对象的 React-Native Persist 对象
- visual-studio-2017 - VS2017 - 工具 > 选项 > 测试中缺少常规选项卡
- c# - 我想在 behnd 代码中使 datagrid 只读,但看不到该选项
- r - 使用 mle 在 R 中拟合具有潜在负基数的指数函数
- batch-file - 使用 netsh 添加 DNS 然后找不到错误元素
- javascript - 计算每个值在数组中有多少个对象