我有这样一个职能:
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多个bool操作很麻烦。
if (endWord not in wordList) or (beginWord not in wordList):
return 0怎样才能使它简明扼要呢?
发布于 2019-04-03 08:35:24
如果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子句通常是非常好的,但在您的情况下,您将有一个可能返回0或None的函数,这不是最佳的\推荐函数。如果可以的话,按照上面的方法重新设计它。 如果没有,我不会费心去改变条件。你所拥有的是非常可读的,没有更好的选择。你当然可以: 如果不是全部(在wordList中为x (endWord,beginWord)):返回0 但差不多就是这样了。
发布于 2019-04-03 08:35:06
我觉得这个应该管用。
if any([x not in wordList for x in [endWord, beginWord]]):
return 0发布于 2019-04-03 08:42:09
如果您希望这个函数加速一点(O(log n)而不是O(n)) --考虑更改Set[str]的wordList类型。在这种情况下,职能是:
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: Set[str]
:rtype: int
"""
return int(bool({beginWord, endWord} & wordList))https://stackoverflow.com/questions/55490414
复制相似问题