Reputation: 2698
I have a code that checks if a given list of integers can sum up to a specified target. If any combination of the integers in a list can sum up to a target value, it returns True. The input 'start' is the index of the list that I want to start from and continue until the end of the list
def groupSum(start, nums, target):
if start >= len(nums):
return target == 0
else:
return groupSum(start + 1, nums, target - nums[start]) or groupSum(start + 1, nums, target);
So, if I put
groupSum(0, [2,4,8], 10)
it will return True, and, if I put
groupSum(0, [2,4,8], 9)
it will return False
QUESTION: I don't understand how they can put 'or' in the return statements, in a recursive case. I don't see how that's actually working. Is it passing multiple functions simultaneously to check every combination or what?
I'm pretty new to Recursion method and would appreciate it if you can explain the technique used here. Thanks
Upvotes: 1
Views: 410
Reputation: 2167
Why it's True
for 10 is because there's an exact match for 10 (8+2); which your recursive function reduces to 0 for the target variable.
So, groupSum(start + 1, nums, target - nums[start])
this becomes True
- so the comparison will be True or False, which will turn out to True!
Now, for the value of 9, there's no such match and hence it'll always remain False
.
You can try for 12 and 6 as well. It'll return True.
Whereas, for any other value the comparison will always be False or False.
Upvotes: 0
Reputation: 29099
In python and
and or
operators, do not return boolean values. They return the last thing evaluated. So, when you
return a or b
if a
is a truthy value, a
will be returned. Otherwise, the truthness of the expression depends on b
, and so b
will be returned.
Upvotes: 2