Skip to content

Commit 1e30f5c

Browse files
authored
Update longest_palindrome
1 parent 8837180 commit 1e30f5c

File tree

1 file changed

+41
-14
lines changed

1 file changed

+41
-14
lines changed

strings/longest_palindrome

+41-14
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import timeit
2+
13
def longest_palindrome(s: str) -> str:
24
if s == s[::-1] or len(s) == 1:
35
return s
@@ -11,27 +13,52 @@ def longest_palindrome(s: str) -> str:
1113
return output
1214

1315

14-
# test cases with longer strings containing multiple palindromes
16+
# Test cases with longer strings containing multiple palindromes
1517
test_data = {
16-
"abacdfgdcaba": "abacdcbadca", # Multiple palindromes, longest is "abacdcbadca"
17-
"abcdcbacdcba": "abcdcbacdcba", # The entire string is a palindrome
18-
"aabbcbbaaaab": "aabbcbbaaaab", # The entire string is a palindrome
19-
"racecarlevelcivic": "racecar", # "racecar" is the longest palindrome
20-
"madamimadam": "madamimadam", # The entire string is a palindrome
21-
"abccbaabcdcb": "abccba", # "abccba" is the longest palindrome
22-
"noonracecar": "racecar", # "racecar" is the longest palindrome
23-
"aabbcccbbbaa": "bbb", # "bbb" is the longest palindrome
24-
"detartrated": "detartrated", # The entire string is a palindrome
25-
"civicradarlevel": "civic" # "civic" is the longest palindrome
18+
"abacdfgdcaba": "aba",
19+
"abcdcbacdcba": "abcdcba",
20+
"aabbcbbaaaab": "aabbcbbaa",
21+
"racecarlevelcivic": "racecar",
22+
"madamimadam": "madamimadam",
23+
"abccbaabcdcb": "abccba",
24+
"noonracecar": "racecar",
25+
"aabbcccbbbaa": "bbcccbb",
26+
"detartrated": "detartrated",
27+
"civicradarlevel": "civic",
28+
29+
# Additional complex cases
30+
"babad": "bab",
31+
"cbbd": "bb",
32+
"forgeeksskeegfor": "geeksskeeg",
33+
"abacabadabacaba": "abacabadabacaba",
34+
"a": "a",
35+
"bb": "bb",
36+
"pqrzzzzzyxwvutsrqponmlkjihgfedcba": "zzzzz",
37+
"abcdefg": "a",
38+
"noonracecarlevel": "racecar",
39+
"abcdedcbaefg": "abcdedcba",
40+
"abacabad": "abacaba",
41+
"aaaaaaa": "aaaaaaa",
42+
43+
# Additional large test cases
44+
"a" * 1000: "a" * 1000,
2645
}
2746

2847

29-
# Main code block
30-
if __name__ == "__main__":
48+
def benchmark():
3149
for key, value in test_data.items():
50+
start_time = timeit.default_timer()
3251
result = longest_palindrome(key)
33-
print(f"{key:<35} -> Longest Palindrome: {result}")
52+
end_time = timeit.default_timer()
53+
elapsed_time = end_time - start_time
54+
55+
print(f"{key[:30]:<35} -> Longest Palindrome: {result} (Time: {elapsed_time:.6f} seconds)")
3456
assert result == value, f"Test failed for {key}. Expected {value}, but got {result}"
3557

3658
# If all tests pass
3759
print("All tests passed!")
60+
61+
62+
# Main code block
63+
if __name__ == "__main__":
64+
benchmark()

0 commit comments

Comments
 (0)