Python (data driven rather than explicit edge case checks)

  • 1

    With problems that accept arrays as input, I often try to avoid having to explicitly check for edge cases by padding my input. Personally I think it becomes more readable, but that may be debatable :) In any case, I thought I'd throw it up here.

    def plusOne(self, digits):
      if not digits: return []
      result = []
      carry  = 1
      digits = [0]+digits
      while digits and carry:
        digit  = digits[-1] + carry
        result = [digit%10] + result
        carry  = digit/10
        digits = digits[:-1]
      return digits[1:] + result

    The main idea is that I pad my digits with a 0 at the start to catch the case that all our digits were 9. I'm consuming the digits list, so digits[1:] == [] if I used the extra 0, but if I didn't use it, digits[1:] will remove it for me (and re-attach any other digits I didn't use).

    Here's another approach using the same technique, but using comprehensions to find the last non-nine element (which we increment, and set everything to right to be 0):

    def plusOne(self, digits):
      if not digits: return []
      digits = [0]+digits
      i = [i for i,d in enumerate(digits) if d < 9][-1]
      return digits[(0<i):i] + [digits[i]+1] + [0]*(len(digits)-i-1)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.