只有在Python3.x中添加另一个返回值时,才能获得正确的输出

2024-05-15 02:48:58 发布

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

对不起,这个不具体的标题,但我无法更好地解释它。你知道吗

我有这个python代码:

def longestWord_with_recursion(wrds):
    if type(wrds) == str:
        return len(wrds),wrds
    return max([longestWord_with_recursion(x) for x in wrds])

(…)

words = [list of words]
print(longestWord_with_recursion(words))

带有len(wrds),wrds的返回给我以下信息:

(11, 'programming') #programming is the correct answer

但是,由于我只想返回单词,因此我将返回替换为return wrds,它给出了以下内容:

you #another word in the list, but the wrong one

为什么会这样?如果我加上另一个返回值,但如果我只返回这个值,为什么它会给我正确的单词?怎么能解决这个问题呢?你知道吗

E:单词列表是:

['The', 'Scandal', 'of', 'education', 'is', 'that', 'every', 'time', 'you', 'teach', 'something', 'you', 'deprive', 'a', 'student', 'of', 'the', 'pleasure', 'and', 'benefit', 'of', 'discovery', 'Seymour', 'Papert', 'born', 'February', '29', '1928', 'died', 'July', '31', '2016', 'If', 'debugging', 'is', 'the', 'process', 'of', 'removing', 'bugs', 'then', 'programming', 'must', 'be', 'the', 'process', 'of', 'putting', 'them', 'in', 'Edsger', 'W', 'Dijkstra']


Tags: oftheinyoulenreturniswith
3条回答

如果只返回单词,则使用递归语句形成的列表只是单词列表。”“你”是列表中最伟大的单词(按字母顺序排列的最后一个)。您必须返回长度,才能使上一个调用级别对该数据进行操作。你知道吗

请注意,这不是递归,而是语法意义上的递归。您的函数有两个完全不同的操作,它们实际上没有交互作用:如果用字符串调用它,它只做一件事;如果用任何其他数据类型调用它,它会迭代。这不是真正的“基本情况”和“递归情况”,除非您有嵌套的单词列表。你知道吗

这看起来不像是正确使用递归。看起来更像是试图用两个功能重载longestWord_with_recursion函数:

  • (word_length, word)
  • 返回基于元组列表的最大单词。你知道吗

您可以将整个函数重写为:

def longest_word(iterable):
    return max([(len(x), x) for x in iterable])

它还将返回最长的单词,同时仍然使用内置的max函数。这将返回一个(word_length, word)元组,因此如果您只希望返回单词,可以执行以下操作:

def longest_word(iterable):
    return max([(len(x), x) for x in iterable])[1]

注意结尾的[1]。你知道吗

编辑:

再看一下max的文档,以及@Kenny在评论中的评论,可以更简单一些:

def longest_word(iterable):
    return max(iterable, key=len)

在这一点上,它真的值得成为它自己的功能吗?你知道吗

试试这个:

def longestWord_with_recursion(wrds):
if type(wrds) == str:
    return len(wrds),wrds
return max([longestWord_with_recursion(x) for x in wrds])[1]

print(longestWord_with_recursion(words))

它返回一个包含两个元素的列表,所以您只需指出要打印的元素是第二个!你知道吗

相关问题 更多 >

    热门问题