【算法】递归

本文深入探讨了递归算法的应用,通过两个具体实例展示了如何将常见的循环结构转换为递归调用,包括创建元组列表及筛选配对元素,旨在帮助读者理解并掌握递归思维。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Q1:

输入:
print(tupleise(7, [10, 99, 35, 40]))
输出:
[(7, 10), (7, 99), (7, 35), (7, 40)]

参考代码:

def tupleise(value, items):
    if len(items) == 1:
        return [(value, items[0])]
    return [(value, items[0])] + tupleise(value, items[1:])

print(tupleise(7, [10, 99, 35, 40]))

Q2:将下述代码用递归的方式写出来(不允许使用for-loop以及while-loop)

def things(list1, list2):
    stuff = []
    for thing1 in list1:
        for thing2 in list2:
            if thing2 > thing1:
                stuff.append((thing1, thing2))
    return stuff

参考代码:

def sub(item, list2):
    if len(list2) == 0:
        return []
    if item < list2[0]:
        return [(item, list2[0])] + sub(item, list2[1:])
    else:
        return []+sub(item, list2[1:])

    
def things(list1, list2):
    if len(list1) == 0:
        return []
    else:
        return sub(list1[0], list2)+things(list1[1:], list2)

list1 = [1, 3, 45, 2]
list2 = [2, 31, 32, 1]
print(things(list1, list2))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值