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[0], 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())
解决方案
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