Complete the code to check if a substring is a palindrome.
def is_palindrome(s): return s == s[[1]]
The slice s[::-1] reverses the string s. Comparing s with its reverse checks if it is a palindrome. The step -1 means traverse backwards.
Complete the code to add a partition to the current path.
def backtrack(start, path): if start == len(s): result.append(path[:]) return for end in range(start + 1, len(s) + 1): if is_palindrome(s[start:end]): path[1](s[start:end]) backtrack(end, path) path.pop()
We use append to add the current palindrome substring to the path list.
Fix the error in the backtracking function call to avoid infinite recursion.
def backtrack(start, path): if start == len(s): result.append(path[:]) return for end in range(start + 1, len(s) + 1): if is_palindrome(s[start:end]): path.append(s[start:end]) backtrack([1], path) path.pop()
We must call backtrack with end as the new start index to move forward and avoid infinite loops.
Fill both blanks to create the palindrome partitioning function and initialize variables.
def partition(s): global result result = [] def backtrack([1], path): if [2] == len(s): result.append(path[:]) return for end in range(start + 1, len(s) + 1): if is_palindrome(s[start:end]): path.append(s[start:end]) backtrack(end, path) path.pop() backtrack(0, []) return result
The function backtrack uses start as the index to track the current position in the string.
Fill both blanks to complete the palindrome partitioning solution with backtracking.
def partition(s): result = [] def is_palindrome(sub): return sub == sub[::-1] def backtrack([1], path): if start == len(s): result.append(path[:]) return for end in range(start + 1, len(s) + 1): if is_palindrome(s[start:end]): path.append(s[start:end]) backtrack(end, path) path.pop() backtrack(0, []) return result
The palindrome check uses slicing with [::-1] to reverse the substring. The backtrack function uses start as the current index and end to move forward.
