简体   繁体   English

Python如何在递归函数中评估'和'?

[英]How does Python evaluate 'and' in a recursive function?

Let's imagine that we want to check if all the elements of a list are positive. 让我们想象一下,我们想要检查列表中的所有元素是否都是正数。 We can define a function : 我们可以定义一个函数:

def check_positive(array):
    if not array:
        return True
    else:
        if array[0] <= 0:
            return False
        else:
            return check_positive(array[1:])

This function is tail-recursive. 这个函数是尾递归的。 Another way to write this function is the following : 编写此函数的另一种方法如下:

def check_positive(array):
    if not array:
        return True
    else:
        return (array[0] > 0) and (check_positive(array[1:])

Is this function tail-recursive as well? 这个函数也是尾递归的吗?

I guess, what i'm asking is if you ask Python to evaluate : 我猜,我问的是你是否要求Python评估:

True and (f(x))

will it evaluate f(x) and then evaluate True and (whatever is the result of f(x)) , or will it evaluate True and f(x) to be equivalent to 'f(x)' and end its evaluation of the expression by evaluating 'f(x)'? 它会评估f(x)然后评估True and (whatever is the result of f(x)) ,或者它会评估True and f(x)等于'f(x)'并结束它的评估通过评估'f(x)'来表达?

Your line: 你的路线:

return (array[0] > 0) and (check_positive(array[1:]))

will evaluate array[0] > 0 . 将评估array[0] > 0 If it is false, it will return false without calling check_positive . 如果为false,则在不调用check_positive情况下返回false。 If it is true, then it will call check_positive(array[1:]) . 如果是,则调用check_positive(array[1:]) So it has the same evaluation order as your first example. 因此它与第一个示例具有相同的评估顺序。

Note though that tail-recursive is not an interesting characteristic in Python, because Python does not do tail-call optimization. 请注意,尾递归在Python中不是一个有趣的特性,因为Python不进行尾调用优化。

You can test it like this: 你可以像这样测试它:

arr = [0]*10**6
check_positive(arr)

This ends instantly, compared with this: 与此相比,这立即结束:

arr = [1]*10**6
check_positive(arr)

which is very slow. 这很慢。

So you can conclude, that yes, it is tail recursive. 所以你可以得出结论,是的,它是尾递归的。

(its a terrible way of doing this in python tho) (这是在python中这样做的可怕方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM