0

I am facing a confusing python problem when generating all lists summed to a number with a fixed length using DFS.

The problem is that local results (temp variable) cannot be stored in a global list (res). When I print res with print(res, y), there are numbers of lists in the res, however, there is none using return res in the last line (attached figure).

class Solution:
    def connect(self , m , n ):
        res = []
        def helper(x, y, res, temp):
            if len(temp) == y:
                temp.sort()
                print(temp, y)
                res.append(temp) #+= [temp]
                print(res, y)
                return
            if x >= 0:
                for i in range(0, x+1):
                    temp.append(i)
                    helper(x - i, y, res, temp)
                    temp.pop()
        temp = []
        helper(m, n, res, temp)
        return res #len([i for i in res if sum(i) == m])

Solution().connect(5, 3) 

enter image description here

  • 1
    Please include text, not images of text. – Aplet123 Dec 09 '20 at 14:04
  • Please read about [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). You can also use [Python-Tutor](http://www.pythontutor.com/visualize.html#mode=edit) which helps to visualize the execution of the code step-by-step. – Tomerikoo Dec 09 '20 at 14:10
  • 2
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) TL;DR you are using the same `temp` list and doing `temp.pop()`. Probably adding a `temp = []` after the `res.append` line will solve it or maybe just doing `res.append(temp[:])` (which creates a copy of `temp`) – Tomerikoo Dec 09 '20 at 14:14
  • Everything you append to `temp` eventually gets popped back off - so the final state of that list is empty. All of the references to `temp` that you appended to `res` therefore are empty as well, because *they're all the same list*. You need to append a *copy* of `temp` if you want to preserve its state as of that moment in time. – jasonharper Dec 09 '20 at 14:18
  • @Aplet123, sorry, first time using stack overflow to ask a question. – qin wang Dec 09 '20 at 15:25
  • 1
    @Tomerikoo, @jasonharper, that's it, I should have copied the `temp` instead of using it. Thanks a million! – qin wang Dec 09 '20 at 15:27

0 Answers0