-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathNested_Integer.py
50 lines (39 loc) · 1.51 KB
/
Nested_Integer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
#####From NC QQ group and mitbbs, Linkedin Second round phone interview
This is the interface that represents nested lists.
You should not implement it, or speculate about its implementation.
```
public interface NestedInteger
{
/** @return true if this NestedInteger holds a single integer, rather than a nested list */
boolean isInteger();
/** @return the single integer that this NestedInteger holds, if it holds a single integer
* Return null if this NestedInteger holds a nested list */
Integer getInteger();
/** @return the nested list that this NestedInteger holds, if it holds a nested list
* Return null if this NestedInteger holds a single integer */
List<NestedInteger> getList();
}
/**
* Given a nested list of integers, returns the sum of all integers in the list weighted by their depth
* For example, given the list {{1,1},2,{1,1}} the function should return 10 (four 1's at depth 2, one 2 at depth 1)
* Given the list {1,{4,{6}}} the function should return 27 (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3)
*/
// null || empty: 0
// 1*2
//
public int depthSum (List<NestedInteger> input)
```
"""
def depthSum(input):
if isInteger(input):
return getInteger(input)
return get_depth_recur(input, 1)
def get_depth_recur(input, depth)
if isInteger(input):
return depth * getInteger(input)
nested_list = getList(input)
sum = 0
for element in nested_list:
sum += get_depth_recur(element, depth + 1)
return sum