Skip to content

Instantly share code, notes, and snippets.

@leikahing
Last active October 31, 2017 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leikahing/2a03390ea8ea61841da0666ccbb1ca6f to your computer and use it in GitHub Desktop.
Save leikahing/2a03390ea8ea61841da0666ccbb1ca6f to your computer and use it in GitHub Desktop.
Nested list summation
def depthSum(nestedList):
"""
:type nestedList: List[Things] where Things can be an int or more List[Things]
:rtype: int
"""
# This is a depth-first search as we need to find the deepest level and return sum
# at each depth
return dfs(nestedList, 1)
def dfs(items, depth):
weighted_sum = 0
for item in items:
if not isinstance(item, list):
weighted_sum += depth * item
else:
weighted_sum += dfs(item, depth+1)
return weighted_sum

Given a nested list of integers, return the sum of all integers in the list weighted by their depth.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1: Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1)

Example 2: Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment