首页 > 解决方案 > 我该如何修复这个数组?

问题描述

#!/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”时,它不会打印。谁能帮我这个

标签: arraysrecursion

解决方案


您的问题是递归调用 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?


推荐阅读