Skip to content Skip to sidebar Skip to footer

What Does "or" Do In A Python Return Statement / Explanation Of List Subset Sum

I was doing coderbyte's Python Array Addition I challenge, but I couldn't get it quite right. I saw another user's correct code, and I'm kind of puzzled by it. Mainly, what does 'o

Solution 1:

Here's how to break this down:

return subsetsum(target, arr[1:]) or subsetsum(target - arr[0], arr[1:])

This has the form return a or b where a = subsetsum(target, arr[1:]) and b = subsetsum(target - arr[0], arr[1:]).

If bool(a) is True, then the expression a or b short circuits and returns whatever the value of a is. If bool(a) is False, then b must be evaluated to determine the value of the expression a or b.

Thus, return a or b is shorthand for the following, with the benefit that b is not evaluated (if it's a function) if bool(a) is True, thanks to short-circuiting logic.

if bool(a):
    return a
else:
    return b

Solution 2:

It's not doing anything special in the context of "return", so that's kind of confusing. Take away return and just look at a boolean expression of

FalseorTrue

Will evaluate to True because one of the statements evaluates to True. The example with return is just taking the result of evaluating the boolean expression and returning it. So True if any of the subsetsum() calls return True, otherwise False.

>>> FalseorTrueTrue>>> FalseorFalseFalse

Post a Comment for "What Does "or" Do In A Python Return Statement / Explanation Of List Subset Sum"