Palindrome-Partitioning: Added memoization

This commit is contained in:
2025-09-15 11:25:53 -04:00
parent d1dead52e1
commit 4ddf200373

View File

@@ -1,11 +1,11 @@
"""
name: Nicholas Tamassia
name: Nicholas Tamassia
Honor Code and Acknowledgments:
Honor Code and Acknowledgments:
This work complies with the JMU Honor Code.
This work complies with the JMU Honor Code.
Comments here on your code and submission.
Comments here on your code and submission.
"""
@@ -14,19 +14,30 @@ def is_palindrome(s: str) -> bool:
def palindrome_partitions(s: str) -> int:
if len(s) == 0:
return 1
sum = 0
memo: dict[str, int] = {}
for i in range(1, len(s) + 1):
left = s[:i]
right = s[i:]
def recurse(s: str) -> int:
nonlocal memo
if is_palindrome(left):
sum += palindrome_partitions(right)
if len(s) == 0:
return 1
return sum
sum = 0
for i in range(1, len(s) + 1):
left: str = s[:i]
right: str = s[i:]
if is_palindrome(left):
if right not in memo:
memo[right] = palindrome_partitions(right)
sum += memo[right]
return sum
return recurse(s)
# All modules for CS 412 must include a main method that allows it