-1

For example in while A and B, if A is False, it's not necessary to evaluate B. Then will B be evaluated in this case? Similarly, in if A or B, if A is True, it's not necessary to evaluate B.

Specific context is this problem, I wrote

def summaryRanges(self, nums):
    """
    :type nums: List[int]
    :rtype: List[str]
    """
    output = []

    i = 0

    while ( i < len(nums) ):

        head = nums[i]


        while ( i <= len(nums)-2 ) and (nums[i+1] == nums[i] + 1): ### question here
                i += 1

        tail = nums[i]

        if head == tail:
            output.append(str(head))
        else:
            output.append(str(head) + '->' + str(tail))

        i += 1

I don't know if it works yet (troubled by other bugs). In the line commented with 'question here', (nums[i+1] == nums[i] + 1) will cause index exceeding string length if i==len(nums)-1, so I added ( i <= len(nums)-2 ) trying to prevent that.

Any suggestions on how to fix/avoid/circumvent this is appreciated.

YJZ
  • 3,934
  • 11
  • 43
  • 67
  • https://docs.python.org/2/reference/expressions.html#boolean-operations – BrenBarn Aug 30 '15 at 05:56
  • @BrenBarn nice thanks! that's what i was looking for. If you could put the answer as an answer, i'll accept it. – YJZ Aug 30 '15 at 05:59

1 Answers1

1

and and or do short-circuit. Note that the value of the expression will always be that of one of the operands, and not necessarily True or False.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358