-1

I was doing a leetcode problem and while reviewing a solution I was quite dumbfounded by a certain line in the solution. The leetcode problem in particular is https://leetcode.com/problems/binary-subarrays-with-sum/

The solution:

class Solution:
    def numSubarraysWithSum(self, A: List[int], S: int) -> int:

        res = 0
        sm = 0
        sums = collections.defaultdict(int)

        for a in A:
            sm += a
            res += sums[sm - S] + (sm == S)
            sums[sm] += 1
        return res

I understand everything that is going on besides this line:

   res += sums[sm - S] + (sm == S)

I have never seen a conditional in an addition operation before.

Throwaway
  • 1
  • 1
  • `==` yields a Boolean, which happens to behave like 1 or 0… – deceze Mar 11 '21 at 19:13
  • Try `print(0 + (sm == S))` to see what happens? – Welbog Mar 11 '21 at 19:13
  • Show us *exactly* what you don't understand from when you traced the intermediate expressions in this code. "Explain this code block to me" is out of scope for Stack Overflow: deconstruct the compound expressions and tell us what you don't understand about one or two of those operations. That is a Boolean comparison, *not* a conditional flow. – Prune Mar 11 '21 at 19:13

1 Answers1

0

Conditional expressions evaluate to booleans, which in Python are just subtypes of int. False is 0, True is 1, so adding sm == S is the same as adding 1 if sm equals S or adding 0 otherwise.

jwodder
  • 54,758
  • 12
  • 108
  • 124