1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I still don't understand how it works in my case. How do I know my recursive function with which input will be returned? I don't see how this works, specifically in a recursive case
You don't know which one will be returned. The first one will be called. If its return value is truthy, this value will be returned. Otherwise, the output of the second term will be returned, no matter what that output is
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.