Skip to content
Advertisement

Python: search longest palindromes within a word and palindromes within a word/string

So here is a code i have written to find palindromes within a word (To check if there are palindromes within a word including the word itself) Condition: spaces inbetween characters are counted and not ignored Example: A but tuba is a palindrome but technically due to spaces involved now it isn’t. so that’s the criteria.

Based on above, the following code usually should work. You can try on your own with different tests to check out if this code gives any error.

JavaScript

And here is a defunct version of it. What I mean is I have tried to start out from the middle and detect palindromes by iterating from the beginning and checking for each higher and lower indices for character by checking if they are equal characters. if they are then i am checking if its a palindrome like a regular palindrome check. here’s what I have done

JavaScript

findlet() fun:

JavaScript

Sometimes it works:

JavaScript

And based on the Criteria/Condition i have put:

JavaScript

Sometimes, it doesn’t work at all:

JavaScript

Now considering madam is a very nice palindrome it should work and there are many cases which i haven’t tested myself to find out what other legitimate palindromes it doesn’t detect.

Q1: Why is it sometimes not detecting?

Q2: I would like to optimize my second code for that matter. Any inputs?

Q3: What better approach is there for a much much more efficient code than my First code which iterates many a times?

Advertisement

Answer

Your solution seems a bit complicated to me. Just look at all of the possible substrings and check them individually:

JavaScript

text.index() will only find the first occurrence of the longest palindrome, so if you want the last, replace it with text.rindex().

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement