Hello,
I have been following the algorithm lectures dealing with recursion on Freecodecamps’ youtube page delivered by Alvin. One of the examples involved finding out if a given set of numbers , say [1,4,5,2] could add up to 10.
def cansum(target,values):
if target==0:
return True
if target<0:
return False
for i in values:
rem=target-i
if cansum(rem,values)==True:
return True
if cansum(rem,values)==False:
return False
cansum(1,[2,1])
The function should theoretically give similar answers if we test
cansum(1,[1,2]) but in my case its not. If someone could point out what is wrong .
Thanks
the remainder here is supposed to check for us if our number eventually reaches the base case[0 which gives True].
For example:
cansum(3,[1,4]) will evaluate as:
first iteration 3-1=2 not yet zero so we will continue
second iteration 2-4=-2 which according to our base case returns false.
if we try (1,[1,2]) we have rem=1-1=0 as our first iteration, which returns True,
the second iteration will be 1-2=-1 which according to our conditions will be False.
I found my error to be due to indentation at the last code
{if cansum(rem,values)==False:
return False} I have shifted it and its now in line with the for statement. Its working though I cant explain why
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
Now I understand why on printing out rem in your code, prints only 1-2!
It’s because of the ‘if statement’ inside the for loop, it issues a return statement which comes out of the cansum() function.
if cansum(rem,values)==False:
return False
I was assuming the if statements to be outside the for loop, noticed it now when your code was indented.
target = target - i ← this should work - as mentioned above