Search code examples
pythonpython-3.xpython-2.7palindrome

Get all possible string's partitions in which each partition is a palindrome


I am having a hard time debugging the error i am making here

Given a string s, partition s such that every string of the partition is a palindrome. Return all possible palindrome partitioning of s. For example, given s = "aab", Return [ ["a","a","b"] ["aa","b"], ]

def ispalindrome(self,s,i,j):
    while (i < j):
        if (s[i] != s[j]):
            return False
        i+=1
        j-=1
    return True
def helper(self,i,current,s,ans):
    if(i==len(s)):
        ans.append(current)
        return
    for j in range(i,len(s)):
        if(self.ispalindrome(s,i,j)):
            current.append(s[i:j+1])
            self.helper(j + 1, current, s, ans)
            current.pop()
def partition(self, A):
    current=[]
    ans=[]
    self.helper(0, current, A, ans)
    return ans

by calling the partition function this returns an empty list don't know why, Any help would be appreciated


Solution

  • You can get the results you want by changing:

    ans.append(current)

    To:

    ans.append(current[:])

    Or:

    ans.append([] + current)

    I think the problem was that you were appending the list current to ans and elsewhere in your code, you were popping off values in current (which affected the list you had stored in ans).

    By appending a list slice, current[:], it is sort of a copy of the current list and not the list itself :-)

    The second solution does in effect what the first does. It appends a fresh list address, [], to ans and concatenates the values from current to the fresh address.

    I got the results [['a', 'a', 'b'], ['aa', 'b']] running your code with the change.