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

后端 未结 15 1832
你的背包
你的背包 2020-12-03 09:38

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 ch

15条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 10:01

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

    def palindromes(text):
        text = text.lower()
        results = []
    
        for i in range(len(text)):
            for j in range(0, i):
                chunk = text[j:i + 1]
    
                if chunk == chunk[::-1]:
                    results.append(chunk)
    
        return text.index(max(results, key=len)), results
    

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

提交回复
热议问题