简体   繁体   中英

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 :

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)'?

Your line:

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

will evaluate array[0] > 0 . If it is false, it will return false without calling check_positive . If it is true, then it will call 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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