首页 > 解决方案 > 为什么这个返回语句有效?(Python 3)

问题描述

我为解码方式问题编写了以下公认的解决方案(https://leetcode.com/problems/decode-ways/):

class Solution:
def numDecodings(self, s: str) -> int:
    l2 = [0, 1]
    ldig = None
    for i,val in enumerate(s):
        curr = 0
        cdig = int(val)
        if cdig: curr += l2[1]
        if ldig and 10*ldig + cdig < 27: curr += l2[0]
        del l2[0]
        l2.append(curr)
        ldig = cdig
    return len(s) and l2[1]

最后一行,我正在捕获输入字符串 s 为空的情况。我见过其他人这样做并且它有效 - 当输入为空时代码返回零,否则它返回计算值 l2[1]。然而,我仍然不明白为什么这样的构造在 python 中起作用?

在我心中的表达

镜头和 l2[1]

只是一个布尔值,因此该函数应返回真或假。相反,它返回一个可以不同于 0 或 1 的整数。

有人可以解释为什么这有效吗?或者指向文档中的相关位置?

标签: python-3.x

解决方案


推荐阅读