Python: Can print answer but cannot return answer (Palindrome Partitioning) -
in python code below, when input s = "ab"
, [[]]
should [["a","b"]]
. have checked 2 functions individually , turned out right. can print out reply [["a","b"]]
in line 26, cannot reply return. quite confused here , appreciate ideas can help.
class solution: # @param s, string # @return list of lists of string def partition(self, s): ############### depth first search: utilize recursion a!!! if s == "": homecoming [[]] if len(s) == 1: homecoming [[s[0]]] self.result = [] temp = [] stack = [] # stack 2d lists k in range(len(s)): stack.append([]) in range(len(s)): j in range(i+1,len(s)+1): substr = s[i:j] if substr == substr[::-1]: stack[i].append(s[i:j]) self.dfs(temp, stack, 0, len(s)) homecoming self.result def dfs(self, temp, stack, start, end): if start == end: self.result.append(temp) print(self.result) homecoming else: in range(len(stack[start])): temp.append(stack[start][i]) self.dfs(temp, stack, start+len(stack[start][i]), end) temp.pop()
you sharing temp
between recursive calls:
temp.append(stack[start][i]) self.dfs(temp, stack, start+len(stack[start][i]), end) temp.pop()
the list object referenced temp
appended self.result
:
if start == end: self.result.append(temp)
but empty shared list object 1 time again popping after returning. removes elements shared list object after printed.
you want append copy instead:
if start == end: self.result.append(temp[:])
you don't need temp
. build new lists instead:
for item in stack[start]: self.dfs([item], stack, start + len(item), end)
you never more add together 1 item temp
, remove again; starting empty temp
list means can build new list objects recursive calls.
instead of looping on range()
indexing, loop on stack[start]
directly.
python
No comments:
Post a Comment