0

I wrote the following accepted solution for the Decode Ways problem(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]

On the last line I am capturing the case where the input string s is empty. I've seen other people doing this and it works - the code returns zero when the input is empty, otherwise it returns the calculated value l2[1]. Yet, I still don't understand why does such a construct work in python?

In my mind the expression

len(s) and l2[1]

is just a boolean and thus the function shall return true or false. Instead it returns an integer which can be different from 0 or 1.

Can someone explain why this works? Or point to the relevant location in the documentation?

Nick
  • 2,924
  • 4
  • 36
  • 43

0 Answers0