# Given a nested list of int array - calculate the sum of all the integers, while multiplying each number by its depth.

• For example:

Here's the depth sum of the nested list {1, {2, 3}}:

{1, {2, 3}} => 1*1 + 2*2 + 3*2 = 11

Here's the depth sum of the nested list {1, {2, {3}}}:

{1, {2, {3}}} => 1*1 + 2*2 + 3*3 = 14

My code:

``````class NestedList():
def __init__(self, vals):
self.content = vals

def weightSum(self):
return self.weightSumHelper(1)

def weightSumHelper(self, depth):
result = 0
for x in self.content:
try:  # or use: isinstance(x, NestedList)
result += x.weightSumHelper(depth + 1)
except AttributeError:
result += x * depth
return result
``````

My tests:

``````nl1 = NestedList([1, NestedList([2, 3])])
print nl1.weightSum()
nl2 = NestedList([1, NestedList([2, NestedList([3])])])
print nl2.weightSum()``````

• ``````import java.util.ArrayList;
import java.util.List;

public class NestedListHelper {

public static class NestedList {
private Integer value;
private List<NestedList> list;

public NestedList(Integer val) {
value = val;
}

public NestedList(List<NestedList> nestedLists) {
list = nestedLists;
}

public boolean isInteger() {
return value != null;
}

public Integer getInteger() {
return value;
}

public List<NestedList> getList() {
return list;
}
}

public int sum(List<NestedList> list, int depth) {
int sum = 0;
for(NestedList curr : list) {
if(curr.isInteger()) {
sum+= curr.value * depth;
}

else {
sum+= sum(curr.getList(), depth+1);
}
}
return sum;
}

public int sumTester() {
NestedList n1 = new NestedList(1);

NestedList n2 = new NestedList(2);
NestedList n3 = new NestedList(3);
List<NestedList> n1List = new ArrayList<NestedList>();

NestedList n4 = new NestedList(n1List);
List<NestedList> list = new ArrayList<NestedList>();

return sum(list, 1);
}

}``````

• This post is deleted!

• JavaScript

``````function sum(array, depth) {
depth = depth || 1;
return array.reduce(function (acc, current) {
var isArray = Array.isArray(current);
acc += isArray ? sum(current, depth + 1) : current * depth;
return acc;
}, 0);
}

``````

• ``````def xsum(nums,level):
res = 0
if nums:
for num in nums:
if isinstance(num,list):
res += xsum(num,level+1)
else:
res += num * level

return res
``````

first call will be

``````xsum(nums,1)
``````

• Recursive Solution in Swift:

``````final class Solution {
static func sumProduct(_ array: [Any]) -> Int {
return helper(array, idx: 0, depth: 1)
}

private static func helper(_ array: [Any], idx: Int, depth: Int) -> Int {
guard idx >= 0, idx < array.count else  { return 0 }
if let intArray = array[idx] as? [Any] {
return helper(intArray, idx: 0, depth: depth + 1)
}
if let int = array[idx] as? Int {
return helper(array, idx: idx + 1, depth: depth) + (depth * int)
}
return 0
}
}
``````

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