Exceptional Python


  • 0

    To return a value from deep down... raise it :-)

    def kthSmallest(self, root, k):
        def inorder(root, k):
            if root:
                k = inorder(root.left, k)
                if k == 1:
                    raise Exception(root.val)
                k = inorder(root.right, k-1)
            return k
        try:
            inorder(root, k)
        except Exception as e:
            return e.message

  • 0
    T

    Hi Stefan, this is pretty cool! Does python has no other convenient ways of returning the value?


  • 0

    This is mostly a "creative" solution I wrote for fun :-)

    The normal way is with return, but I'm already returning the k because Python 2 doesn't have nonlocal or so. Plus I like how I decrease k by feeding k-1 to the right call. I can easily return multiple values, so I could return k as well as the wanted result, but it would be a bit messier and I just didn't feel like it here.

    Another way is writing a generator and using yield. Maybe I would use that for this if we had Python 3 here, because it has nicer syntax (yield from).


Log in to reply
 

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