【BUG分析】递归返回值

功能说明


构造了一个函数,可以接收一个任意的多维list对象,再接收一个位置list对象,从多维list对象中返回位置list指定的元素。比如get_list_elm(list, [1, 2, 3])就是返回list[1][2][3],这个函数其实是之前写的一个函数(传送门)的逆函数。

问题代码


def get_list_elm(list_0: list, position: list):
    list_1 = None
    index = None
    for num in range(len(position)):
        if type(position[num]) != int:  # 验证position元素是否全为int
            return 'Only int is available!'
    if not(position != []):  # 验证首次输入的position是否为[]
        return '[] is not available!'
    else:
        index = position[0]
        position.pop(0)
        if index >= len(list_0):  # 验证指定的元素位置是否超过list长度
            return 'position wrong!'
        else:
            list_1 = list_0[index]
            if not(position != []):  # position元素耗尽,输出元素
                return list_1
            elif type(list_1) != list:  # 当前元素非list类型,无法提取下一维的元素,position指定位置错误
                return 'position wrong!'
            else:
                get_list_elm(list_1, position)

问题分析


print(get_list_elm([[1, 2], 3, 4, 5], [0]))
print(get_list_elm([[1, 2], 3, 4, 5], [0, 0]))
print(get_list_elm([[1, 2], 3, 4, 5], [0, 1]))
print(get_list_elm([[1, 2], 3, 4, 5], [0, 0, 0]))
print(get_list_elm([[1, 2], 3, 4, 5], [1]))
print(get_list_elm([[1, 2], 3, 4, 5], [1, 0]))
print(get_list_elm([[1, 2], 3, 4, 5], [1, None]))
[1, 2]
None
None
None
3
position wrong!
Only int is available!

测试结果显示函数中对格式验证的部分都运行正常,对list的一维元素的提取也正常。而问题都出在提取高维list元素的时候,初步推测是和函数递归有关系。
最终确认问题在于最后一个else的执行语句中,而正常情况下也只有需要进行递归的时候才需要执行这个else语句,也和问题的情况吻合。
问题主要是这里没有设置return出口,最里层的递归函数找到指定元素后只会return给上一层的函数,并不是直接return给最表层函数。从倒数第二层函数开始就要靠最后一个else执行语句中的return层层往上传递。因此从倒数第三层函数开始get_list_elm(list_1, position)就接收不到值了,因此最表层print出来的就是None

修改方案


def get_list_elm(list_0: list, position: list):
    list_1 = None
    index = None
    for num in range(len(position)):
        if type(position[num]) != int:  # 验证position元素是否全为int
            return 'Only int is available!'
    if not(position != []):  # 验证首次输入的position是否为[]
        return '[] is not available!'
    else:
        index = position[0]
        position.pop(0)
        if index >= len(list_0):  # 验证指定的元素位置是否超过list长度
            return 'position wrong!'
        else:
            list_1 = list_0[index]
            if not(position != []):  # position元素耗尽,输出元素
                return list_1
            elif type(list_1) != list:  # 当前元素非list类型,无法提取下一维的元素,position指定位置错误
                return 'position wrong!'
            else:
                return get_list_elm(list_1, position)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值