【问题标题】:Write a function longestWord() which receives a list of words, then returns the longest word ending with "ion"编写一个函数longestWord(),它接收一个单词列表,然后返回以“ion”结尾的最长单词
【发布时间】:2020-07-22 05:28:51
【问题描述】:

编写一个函数longestWord(),它接收一个单词列表,然后返回以“ion”结尾的最长单词。

这是我目前得到的:

def longest(listTest):
  word_len = [] 
  for n in listTest: 
    word_len.append((len(n), n)) 
    word_len.sort() 
  return word_len[-1][1] 

print(longest(["ration","hello","exclamation"])) 

【问题讨论】:

  • 到目前为止你尝试过什么?
  • 嗨,这是我目前得到的 deflongest(listTest): word_len = [] for n in listTest: word_len.append((len(n), n)) word_len.sort() return word_len[-1][1] print(longest(["ration","hello","exclamation"]))
  • 这是我第一次使用这个所以我不知道为什么写在同一行
  • 我编辑了您的问题,请稍后再详细说明您的问题:您尝试过的内容、预期输入、预期输出等。
  • 没问题,不客气,看看这个stackoverflow.com/help/how-to-ask

标签: python python-3.x list function


【解决方案1】:

我认为你需要:

longestWord = max([i for i in listTest if i.endswith("ion")], key=len)
print(longestWord)

【讨论】:

  • 不需要 lambda,只需传递 len
【解决方案2】:
In [9]: listTest
Out[9]: ['ration', 'hello', 'exclamation']

In [10]: def longest(lst):
    ...:     return sorted([(len(i),i) for i in lst if i.endswith("ion")], key=lambda x:x[0])[-1][1]
    ...:

In [11]: longest(listTest)
Out[11]: 'exclamation'

【讨论】:

    【解决方案3】:

    下面的函数通过列表解析和max 函数完成了这个任务。你也可以在这里传递你喜欢的任何后缀。

    def longest(words, suffix="ion"):
        # Filter the passed words
        words_with_suffix = [w for w in words if w.endswith(suffix)]
    
        # Return the longest word in the filtered list
        return max(words_with_suffix, key=len)
    
    
    list_test = ["ration","hello","exclamation"]
    
    print(longest(list_test))
    

    【讨论】:

      【解决方案4】:
      longest = ''
      for word in listTest:
          if word.endswith('ion') && (longest.size() < word.size() ):
               longest= word
      
      print(longest);
      

      【讨论】:

        【解决方案5】:

        由于到目前为止似乎没有一个答案能够处理具有相同长度(并以“ion”结尾)的两个不同单词的边缘情况,这是我的简单方法:

        filteredWords = [word for word in listTest if word.endswith("ion")]
        wordLenghts = [len(word) for word in filteredWords]
        maxLength = max(wordLenghts)
        longestWordsIndices = [i for i, j in enumerate(wordLenghts) if j == maxLength]
        
        print( [filteredWords[w] for w in longestWordsIndices] )
        

        【讨论】:

          【解决方案6】:

          您可以创建一个新列表,其中包含所有以“ion”结尾的字符串,然后您可以对列表进行排序以获得以“ion”结尾的longest word

          在给定的代码中,考虑到列表很小,我使用Bubble sort 对列表进行排序,如果您必须为此处理更大的数据,那么我建议您使用更好的排序算法,因为冒泡排序性能是 O(n^2)。

          s = ["ration","hello", "test", 'why', 'call', 'ion', "exclamation", 'cation', 'anion']
          word = []
          for i in s:
              if i.endswith('ion'):
                  word.append(i)
          
          #using bubble sort considering the list is small
          for i in range(len(word) - 1):
              for j in range(len(word) - (i+1)):
                  if len(word[j]) < len(word[j+1]):
                      temp = word[j]
                      word[j] = word[j+1]
                      word[j+1] = temp
          
          print(word[0])  #the longest word
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-01-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-06-16
            • 2021-02-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多