Short Python BFS

  • 8
    class Solution(object):
        def depthSum(self, nestedList):
            :type nestedList: List[NestedInteger]
            :rtype: int
            depth, ret = 1, 0
            while nestedList:
                ret += depth * sum([x.getInteger() for x in nestedList if x.isInteger()])
                nestedList = sum([x.getList() for x in nestedList if not x.isInteger()], [])
                depth += 1
            return ret

  • 1

    Very succinct solution!

    Could you explain why the sum function in the following line works?

    sum([x.getList() for x in nestedList if not x.isInteger()], [])

    It is not clear to me from the documentation in the python source code (see below).

    Signature: sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.
    Type: builtin_function_or_method

  • 1

    @ygt2016 Just to concatenate the lists that will be processed in the next iteration

  • 1

    Thanks, nice trick to flatten a list of lists.
    For those who are interested, the following article (search for "sum") gives examples.

Log in to reply

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