Files
CS412-Applied-Algorithms/Palindrome-Partitioning/cs412_palindrome_partition_memoized_b.py

53 lines
1.0 KiB
Python
Raw Normal View History

2025-09-13 15:36:12 -04:00
"""
name: Nicholas Tamassia
2025-09-13 15:36:12 -04:00
Honor Code and Acknowledgments:
2025-09-13 15:36:12 -04:00
This work complies with the JMU Honor Code.
2025-09-13 15:36:12 -04:00
Comments here on your code and submission.
2025-09-13 15:36:12 -04:00
"""
2025-09-17 21:29:16 -04:00
def is_palindrome(s: str, start: int, end: int) -> bool:
return s[start:end] == s[start:end][::-1]
2025-09-13 15:36:12 -04:00
def palindrome_partitions(s: str) -> int:
2025-09-17 21:29:16 -04:00
memo: list[int] = [-1] * (len(s) + 1)
2025-09-13 15:36:12 -04:00
2025-09-17 21:29:16 -04:00
def recurse(start: int) -> int:
nonlocal memo
2025-09-13 15:36:12 -04:00
2025-09-17 21:29:16 -04:00
if start == len(s):
return 1
2025-09-13 15:36:12 -04:00
2025-09-17 21:29:16 -04:00
if memo[start] != -1:
return memo[start]
2025-09-17 21:29:16 -04:00
sum = 0
2025-09-17 21:29:16 -04:00
for i in range(start + 1, len(s) + 1):
if is_palindrome(s, start, i):
sum += recurse(i)
2025-09-17 21:29:16 -04:00
memo[start] = sum
return sum
2025-09-17 21:29:16 -04:00
return recurse(0)
2025-09-13 15:36:12 -04:00
# 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 i in range(0, n):
in_str = input().strip()
print(palindrome_partitions(in_str))
if __name__ == "__main__":
main()