[Solved] how to rewrite a function to recursive [closed]


Use lengths of the lists to terminate the recursion.
In this example implementation, if length of either of the lists is 0, we have either mapped it all, or it is an empty list to begin with, thus we terminate the recursion. Also worth noting that l1[1:] is the slice of the list we haven’t mapped yet.

def map3(func, l1, l2):
    if (len(l1) == 0 or len(l2) == 0):
        return []

    return [func(l1[0], l2[0])] + map3(func, l1[1:], l2[1:])

Let’s test it:

Test function:

def func(a, b):
     return a * b

Test lists:

l1 = [1, 2, 3]
l2 = [4, 5, 6]

Run it:

print(map3(func, l1, l2))

Output:

[4, 10, 18] 

0

solved how to rewrite a function to recursive [closed]