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 "or" do in a return statement? It's preventing me from fully understanding the solution to this problem. Thanks.
The question is as follows: Have the function ArrayAdditionI(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.
def subsetsum(target, arr): if len(arr) == 0: return target == 0 return subsetsum(target, arr[1:]) or subsetsum(target - arr, arr[1:]) def ArrayAdditionI(arr): arr = sorted(arr) target = arr[-1] arr = arr[:-1] return 'true' if subsetsum(target, arr) else 'false' # keep this function call here # to see how to enter arguments in Python scroll down print ArrayAdditionI(raw_input())Answer1:
Here's how to break this down:
return subsetsum(target, arr[1:]) or subsetsum(target - arr, arr[1:])
This has the form
return a or b where
a = subsetsum(target, arr[1:]) and
b = subsetsum(target - arr, arr[1:]).
If bool(a) is
True, then the expression
a or b short circuits and returns whatever the value of
b must be evaluated to determine the value of the expression
a or b.
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 bAnswer2:
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 <a href="https://docs.python.org/2/reference/expressions.html#booleans" rel="nofollow">boolean expression</a> of
False or True
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.
>>> False or True True >>> False or False False