What is difference between temp and temp[:] ?


  • 0
    W
    class Solution:
    # @param s, a string
    # @return a list of lists of string
    def partition(self, s):
        if not s or len(s)==0:
            return []
        res,temp=[],[]
        self.helper(res,temp,s)
        return res
    
    def isPalindrome(self,s):
        i=0
        j=len(s)-1
        while i<j:
            if s[i]!=s[j]:
                return False
            i+=1
            j-=1
        return True
    def helper(self,res,temp,s):
        if len(s)==0:
            res.append(temp[:])   
    
        for i in xrange(1,len(s)+1):
            if self.isPalindrome(s[:i]):
                temp.append(s[:i])
                self.helper(res,temp,s[i:])
                temp.pop()
    

    why I have to write code like res.append(temp[:]) instead of res.append(temp)? What is the difference between temp and temp[:]?


  • 0
    F

    temp[:] creates a new copy of the list, rather than passing the list itself.


  • 0
    W

    Why I append(temp) to res but only get empty list like [[],[]] ?


  • 0
    P

    I ran into a similar problem before. Apparently, when they test your code, the input, such as temp, is created outside as a global variable. When you do something with temp, it uses the reference or a pointer type of thing that points to the real temp, but its value were not changed. When you do temp[:], now it accessed the real value of temp and copied it over. In general, I learned in this scenario, unless you are modifying temp, you should always use temp[:] for things such as assign it to something else. I am not an expert, so I could be inaccurate.


Log in to reply
 

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