The following problem may be trivial but I am not an expert in programming.
Language to be used : python 3
The problem: You have been given a list, 'a = [a1,a2,a3,a4]'. The objective is to check whether a specific number say, 'S' can be expressed as a sum of the numbers from the list 'a'. Note one can take a number from the list as many times as needed.
The problem is dubbed as 'HowSum'.
My code:
def hs_slow(tsum,ar):
if tsum==0:
return []
if tsum<0:
return None
for i in ar:
ntsum=tsum-i
hsResult=hs_slow(ntsum,ar)
if hsResult!=None:
hsResult.append(i)
return hsResult.append(i)
return None
Logic of my code:
If 'tsum' is negative for a specific set of numbers, that does not lead to the correct number and hence we should get a null return.
If 'tsum' is zero, it means, we have found a specific set of numbers from the list that leads up to the correct sum. Hence, we should get this set of numbers as result. For this purpose, I return an empty array i.e. [] when a '0' is hit. Then, the number 'i' should contribute to the list of correct numbers. Hence appebd it to the result.
Somehow, this works at basic level for say, if I have hs_slow(3,[2,3]). But it fails for hs_slow(7,[2,3]). While I get back [3] for the former case, I get [] for the latter.
I don't understand, why the list is not being appended for cases other tha the basic one.
Help will be highly appreciated. If you can explain the problem it will be even better.
Thanks in advance.
Please note, the problem is similar to the one described in :
Finding a sequence from given numbers that sum to given value?
But I need to understand what is going wrong with my approach.
CodePudding user response:
The hsResult=' str(hsResult) '\n' lines are not valid Python syntax. It looks like you are trying to concatenate strings, but you are not using the operator correctly.
The hsResult.append(i) line is indented incorrectly. It should be inside the if block, not after it.
The return hsResult.append(i) line will not work as expected. The append method modifies the list in place and does not return anything, so the return statement will not return the modified list. Instead, you can just return hsResult after appending the element.
def hs_slow(tsum, ar):
if tsum == 0:
return []
if tsum < 0:
return None
for i in ar:
ntsum = tsum - i
hs_result = hs_slow(ntsum, ar)
if hs_result is not None:
hs_result.append(i)
return hs_result
return None