如何在python中查找列表中最短的单词?
我希望这个函数返回列表中字符最少的单词 以下是我编写的代码:如何在python中查找列表中最短的单词?,python,Python,我希望这个函数返回列表中字符最少的单词 以下是我编写的代码: def get_shortest_name(words): shortest_word = "" shortest_length = 0 for word in words: if shortest_length > len(word): shortest_length = len(word) shortest_wo
def get_shortest_name(words):
shortest_word = ""
shortest_length = 0
for word in words:
if shortest_length > len(word):
shortest_length = len(word)
shortest_word = word
return shortest_word
def test_get_shortest_name():
print("1.", get_shortest_name(["Candide", "Jessie", "Kath", "Amity", "Raeanne"]))
产出:1。凯丝
我得到了正确的输出,但其他隐藏测试失败。请帮我找出代码中的一些问题。非常感谢 这是您的代码的正确版本。它可能会帮助您了解自己的代码出了什么问题。我已经用注释
#
表示了修改后的行。除了两条修改过的线外,所有内容都保持不变。代码中的问题是,“
是您初始化的最短单词,因此没有选择其他单词作为最短单词,因为它们都有有限的长度(大小)
输出
1. Kath
你可以按字长排序。没有人能保证列表中只有一个最短的单词
print(sorted(["Candide", "Jessie", "Kath" ,"Amity", "Raeanne"],key=lambda x: len(x)))
您的代码有几个问题:
def get_最短_名称(单词):
最短单词=“”
最短长度=0
您以最短长度0
开始,因此。。。任何单词的长度怎么可能比这个短?第一种解决方案是使用一些硬编码值,如
最短长度=999
然而,这将假定不可能存在任何长度大于999
的最短单词
另一种选择:
shortest_length=float('inf')
你肯定任何单词的长度都小于无穷大
奖金:一行 实际上,您可以将所有函数简化为一行:
shortest_word=min(words,key=lambda word:len(word))
我将让您查看python的内置函数。哪个“隐藏测试”失败?您发布的代码不返回“Kath”,而是返回一个空字符串。这根本不起作用。如果你想帮助调试你的代码,你必须发布你的实际代码。没有比
”
短的东西。你可以用列表中的第一个单词初始化最短的单词
,用它的长度初始化最短的单词
print(sorted(["Candide", "Jessie", "Kath" ,"Amity", "Raeanne"],key=lambda x: len(x)))