Different effect between list.pop() and list = list[:-1] ? with right answer


  • 0
    Y
    class Solution:
        # @param s, a string
        # @return a list of lists of string
        def partition(self, s):
            if not s:
                return []
            res = []
            temp = []
            self.calRes(s, res, temp)
            return res
        
        def calRes(self, s, res, temp):
        	# print s, res, temp
            if not s:
                res.append(temp[:])
            for i in range(len(s)):
                if self.isPalindrome(s[0:i+1]):
                    temp.append(s[0:i+1])
                    self.calRes(s[i+1:], res, temp)
                    # temp=temp[:-1]  will get wrong answer
                    temp.pop() # will get the right answer
                    
        def isPalindrome(self, s):
            for n in range( len(s)/2 ):
                if s[n] != s[-n-1]:
                    return False
            return True
    

    Ah, when I use temp=temp[:-1], it actually create a new object and it's not the one in the method parameters anymore.


Log in to reply
 

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