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

55 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
"""
def is_palindrome(s: str) -> bool:
return s == s[::-1]
def palindrome_partitions(s: str) -> int:
memo: dict[str, int] = {}
2025-09-13 15:36:12 -04:00
def recurse(s: str) -> int:
nonlocal memo
2025-09-13 15:36:12 -04:00
if len(s) == 0:
return 1
2025-09-13 15:36:12 -04:00
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:
2025-09-17 21:29:16 -04:00
memo[right] = recurse(right)
sum += memo[right]
return sum
return recurse(s)
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())
2025-09-18 09:06:07 -04:00
for _ in range(0, n):
2025-09-13 15:36:12 -04:00
in_str = input().strip()
print(palindrome_partitions(in_str))
if __name__ == "__main__":
main()