首页 > 解决方案 > 单词列表中的两个元素

问题描述

我有这样的功能:

def ladderLength(self, beginWord, endWord, wordList):
    """
    :type beginWord: str
    :type endWord: str
    :type wordList: List[str]
    :rtype: int
    """
    if (endWord not in wordList) or (beginWord not in wordList):
        return 0

多个布尔操作很麻烦。

    if (endWord not in wordList) or (beginWord not in wordList):
        return 0

如何将其简化为清晰简洁?

标签: python

解决方案


如果您的所有if-block 都是这样的:

  if (endWord not in wordList) or (beginWord not in wordList):
    return 0
  else:  # <- I am assuming this, see Note 1
    return 1

然后您可以将整个内容替换为:

return int(all(x in wordList for x in (endWord, beginWord)))

注1

没有else子句通常很好,但在您的情况下,您将有一个可能返回0None不是最佳\推荐的函数。如果可以,请按照上面的方法重新设计它。

如果不是,我不会费心改变条件。您拥有的那个可读性很强,没有比这更好的替代品了。当然你可以这样做:

if not all(x in wordList for x in (endWord, beginWord)):
    return 0

但仅此而已。


推荐阅读