forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem_181.py
27 lines (18 loc) · 770 Bytes
/
problem_181.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def is_palindrome(string):
return bool(string) and string == string[::-1]
def split_into_pals(string, curr="", prev_pals=[]):
if not string and not curr:
return prev_pals
elif not string:
return prev_pals + list(curr)
candidate = curr + string[0]
alt_1 = []
if is_palindrome(candidate):
alt_1 = split_into_pals(string[1:], "", prev_pals + [candidate])
alt_2 = split_into_pals(string[1:], candidate, prev_pals)
return alt_1 if bool(alt_1) and len(alt_1) < len(alt_2) else alt_2
# Tests
assert split_into_pals("racecarannakayak") == ["racecar", "anna", "kayak"]
assert split_into_pals("abc") == ["a", "b", "c"]
assert split_into_pals("madam") == ["madam"]
assert split_into_pals("madama") == ["madam", "a"]