递归代码失败

时间:2016-06-29 01:46:34

标签: python recursion

python的新手 - 感谢帮助让函数点工作并理解我做错了什么。

 def dot(l,k):  """multiply each elements in list l with each element from list k and return the total
    """
    total = 0


    if l == [] or '':
        return
    else:
        last_l = l[-1]
        last_2 = k[-1]
        total += last_2 * last_l
        return total + dot(l[:-1], k[:-1])

 l = [1, 2]
 k = [3, 4]

 print(dot(l,k))

1 个答案:

答案 0 :(得分:0)

您可以使用map和reduce以更简单的方式执行此操作:

l1=[1,2]
l2=[2,3]

mult = lambda l1,l2: [x*y for x,y in zip(l1,l2)]

print reduce(lambda x,y: x+y,mult(l1,l2))