完整的问题是“编写一个函数find_longest_word(),它带有一个单词和列表 返回最长的单词和长度。您还应该编写测试函数 这将要求用户输入单词列表并打印最长的单词及其长度。“
我写了这段代码并且它有效。我只需要弄清楚如何在这段代码中添加一个函数,以便我在问题中告诉我。
def main():
text = input("Please input a list of words to evaluate: ")
longest = 0
for words in text.split():
if len(words) > longest:
longest = len(words)
longest_word = words
print("The longest word is", longest_word, "with length", len(longest_word))
main()
答案 0 :(得分:5)
只需将逻辑移动到一个函数中,就像这样
def find_longest_word(text):
for words in text.split():
if len(words) > longest:
longest = len(words)
longest_word = words
return longest_word, len(longest_word)
def main():
input_string = input("Please input a list of words to evaluate: ")
longest_word = find_longest_word(input_string)
print("The longest word is", longest_word, "with length", len(longest_word))
您尝试解决的实际问题可以像这样解决
def find_longest_word(text):
longest_word = max(text.split(), key = len)
return longest_word, len(longest_word)
注意:我们不是在find_longest_word
函数中打印结果,而是从它返回longest_word
,这样函数只会执行它应该执行的操作。现在,顾名思义,它只找到最长的单词。
答案 1 :(得分:1)
使用简短的编解码器练习....
def main():
a = sorted(input("Please input a list of words to evaluate: ").split(), key=len) [-1]
print ("You longe word ", str(a), " have this", str(len(a)), "lenghts")
main()
答案 2 :(得分:0)
您不需要longest_word = words
,但如果没有您的答案,则无法回答此练习....,谢谢!
def main ():
text = input("Please input a List of words to evaluate: ")
longest = 0
for words in text.split():
if len(words) > longest:
longest = len(words)
print ("The longest word is", words, "with lenght", longest)
main()
答案 3 :(得分:0)
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][1]
print(find_longest_word(["hasta ", "lavista", "baby"]))
答案 4 :(得分:0)
这是一个python程序,用于读取单词列表并返回最长的单词的长度:
list_words = ["PHP", "Exercises", "Backend"]<br/>
s = [(len(word),word) for word in list_words] <br/>
s.sort() <br/>
print('Longest String in list is ',s[-1][1]) <br/>
答案 5 :(得分:-1)
numberOfWordsInList = int(input("Enter number of words to be List: "))
def longestWordInList(numberOfWordsInListt):
createdList = [input("Enter any word: ") for i in range(numberOfWordsInList)]
lengthOfItems = [(len(items), items) for items in createdList]
return max(lengthOfItems)
print(longestWordInList(numberOfWordsInList))