1-liner in Ruby / Python


  • 17

    Ruby

    def first_bad_version(n)
      (1..n).bsearch { |i| is_bad_version(i) }
    end
    

    Or:

    def first_bad_version(n)
      (1..n).bsearch(&method(:is_bad_version))
    end
    

    Python

    In Python I was only able to do it with a rather ugly wrapper:

    def firstBadVersion(self, n):
        return bisect.bisect(type('', (), {'__getitem__': lambda self, i: isBadVersion(i)})(), False, 0, n)
    

    Nicer, more readable version:

    def firstBadVersion(self, n):
        class Wrap:
            def __getitem__(self, i):
                return isBadVersion(i)
        return bisect.bisect(Wrap(), False, 0, n)

  • 1
    I

    For the nicer, more readable one, isn't the versions start from 1?

    return bisect.bisect(Wrap(), False, 1, n)
    

  • 2

    Nice for Wrapper. I was wondering how to use bisect and I found your solution.

    Here is my 1-liner recursion solution.

    def firstBadVersion(self, right, left = 1):
            return right if right == left \
                else self.firstBadVersion((left + right) / 2, left) if isBadVersion((left + right) / 2) \
                else self.firstBadVersion(right, (left + right) / 2 + 1)

  • 0

    @lee215 How about a 1-liner using reduce?


Log in to reply
 

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