如何使用Python快速找到最大的对称词?

2024-10-03 06:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个文本:

a ab aba bob dod doood zoroz rar goog bnb

我想找出这篇文章中最大的对称词。我怎么做

我在寻找最快的方法


Tags: 方法文本abgoogbobrar篇文章aba
2条回答

既然我不想把整个代码都交给你,让我把它分解一下:

Break the sentence down into a list of words 
Initialise a variable to hold the maximum length of the pallindrome (maxlen = 0)
Initialise a variable to hold the word with this lenght ( result = "" )
For word in list :
    if word is a pallindrome and length(word) > maxlen
        maxlen = length(word)
        result = word

像这样的东西可以做到:

Python 3.7.5 (default, Oct 17 2019, 12:16:48) 
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> words = 'a ab aba bob dod doood zoroz rar goog bnb'
>>> max((word for word in words.split() if word == word[::-1]), key=len)
'doood'
>>>

相关问题 更多 >