如何将2 for循环转换为纯递归?

时间:2020-06-04 05:27:31

标签: python recursion

我想知道如何转换这段代码,使其仅使用纯递归,因此没有for或while循环和列表理解。

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

我将基本情况设置为

def things(list1, list2):
    if not (list1 and list2):
        return []

我知道如何处理一个循环,但是如何管理嵌套的for循环?

1 个答案:

答案 0 :(得分:1)

编写递归函数的第一步是找到退出条件。 (该功能应在外部for循环结束时停止。)

尽管对于这类任务,for/while循环比递归更有效。

def th(arr, list1, list2, index1, index2):
    if index1 == len(list1):
        return 
    elif index2 == len(list2):
        th(arr,list1,list2,index1+1,0)
    else:
        if list1[index1] < list2[index2]:
            arr.append((list1[index1], list2[index2]))
        th(arr, list1, list2, index1, index2+1)

if __name__ == "__main__":
    l1 = [1,3,5]
    l2 = [2,4]
    arr =[]
    th(arr,l1,l2,0,0)
    print(arr)
# arr : [(1, 2), (1, 4), (3, 4)]