Files
CS412-Applied-Algorithms/Palindrome-Partitioning/cs412_palindrome_partition_memoized_a.py
2025-09-18 09:06:07 -04:00

55 lines
1.0 KiB
Python

"""
name: Nicholas Tamassia
Honor Code and Acknowledgments:
This work complies with the JMU Honor Code.
Comments here on your code and submission.
"""
def is_palindrome(s: str) -> bool:
return s == s[::-1]
def palindrome_partitions(s: str) -> int:
memo: dict[str, int] = {}
def recurse(s: str) -> int:
nonlocal memo
if len(s) == 0:
return 1
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] = recurse(right)
sum += memo[right]
return sum
return recurse(s)
# All modules for CS 412 must include a main method that allows it
# to imported and invoked from other python scripts
def main():
n: int = int(input())
for _ in range(0, n):
in_str = input().strip()
print(palindrome_partitions(in_str))
if __name__ == "__main__":
main()