Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why am i getting None in my list in Recursion in python

my slack is getting o/p as slack=[[],[],[]] output is not appending in it why?
candidates = [10,1,2,7,6,1,5], target = 8 Output: [ [1,1,6], [1,2,5], [1,7], [2,6] ]

type here
class Solution:
    def __init__(self):
        self.slack =[]

    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        output =[]
        i =0
        def rec(i,target,output,candidates):
            if i>=len(candidates):
                if target == 0: 
                    self.slack.append(output) 
                return self.slack
            
            if candidates[i]<=target:
                output.append(candidates[i])
                rec(i+1,target-candidates[i],output,candidates)
                output.pop()
            rec(i+1,target,output,candidates)
        
        rec(i,target,output,candidates)
        return self.slack

output needs to be appended inside the slack

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this

from typing import List

class Solution:
    def __init__(self):
        self.slack = []

    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        output = []
        i = 0
        candidates.sort()  # Sort the candidates list to handle duplicates

        def rec(i, target, output, candidates):
            if i >= len(candidates):
                if target == 0:
                    self.slack.append(output.copy())  # Append a copy of 'output' to 'self.slack'
                return self.slack

            if candidates[i] <= target:
                output.append(candidates[i])
                rec(i + 1, target - candidates[i], output, candidates)

                # Skip duplicates
                while i + 1 < len(candidates) and candidates[i] == candidates[i + 1]:
                    i += 1

                output.pop()  # Remove the last element as we backtrack
            rec(i + 1, target, output, candidates)

        rec(i, target, output, candidates)
        return self.slack

Testing

candidates = [10, 1, 2, 7, 6, 1, 5]
target = 8

solution = Solution()
result = solution.combinationSum2(candidates, target)
print(result) # [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
assert result ==  [[1,1,6], [1,2,5], [1,7], [2,6]]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading