Something weird happend to my code. (py)


  • 1
    E

    My code:

    class Solution:
      def combine(self, n, k):
        return self.combine2(n, k)
        
      def combine2(self, n, k, offset=1, collects=[], prev=[]):
        if k == 0:
            return collects.append(prev)
        for i in range(offset, n-k+2):
            me = list(prev)
            me.append(i)
            self.combine2(n, k-1, i+1, collects, me)
        return collects
    

    http://codepad.org/lJXQlJTf

    I think it is correct anwser.

    BUT I always got this result:

    Submission Result: Wrong Answer
    
    Input:	2, 1
    Output:	[[1],[1],[2]]
    Expected:	[[1],[2]]
    

    I have no idea what just happened.....


  • 2
    W

    Hi e39a562r:

    When a function takes an argument with default parameter, it is immediately re-evaluated when the function returns. So, when you call ‘combine2’ multiple times, the value of 'collects' is always changing, even it is set default. In your case, the first ‘[1]’ in your answer is the result of last test case (input may be (1,1) I guess).

    So when calling combine2, use self.combine2(n, k, 1, [], []) instead, and change the definition of combine2 to def combine2(self, n, k, offset, collects, prev): will work.

    Your may refer to the Python Manual for more details.


  • 0
    E

    I got it. Thanks!
    It seems dict and list shouldn't assign to default parameter......


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.