
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Nested List Weight Sum II in Python
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. Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.
So, if the input is like [[1,1],2,[1,1]], then the output will be 8, as four 1's at depth 1, one 2 at depth 2.
To solve this, we will follow these steps −
Define a function depthSumInverse() . This will take nestedList
flats:= a new list
maxd:= 0
Define a function flatten() . This will take nlst,dist
dist := dist + 1
maxd:= maximum of maxd, dist
for each node in nlst, do
if node is an integer is non-zero, then
insert (node,dist) at the end of flats
otherwise,
flatten(node, dist)
flatten(nestedList, 0)
summ:= 0
for each v,d in flats, do
summ := summ + v*(maxd+1-d)
return summ
Example
Let us see the following implementation to get a better understanding −
class Solution(object): def depthSumInverse(self, nestedList): flats=[] self.maxd=0 def flatten(nlst,dist): if isinstance(nlst,list): nlst=nlst dist+=1 self.maxd=max(self.maxd,dist) for node in nlst: if isinstance(node,int): flats.append((node,dist)) else: flatten(node,dist) flatten(nestedList,0) summ=0 for v,d in flats: summ+=v*(self.maxd+1-d) return summ ob = Solution() print(ob.depthSumInverse([[1,1],2,[1,1]]))
Input
[[1,1],2,[1,1]]
Output
8
- Related Articles
- Weight sum of a nested array in JavaScript
- Nested list comprehension in python
- Flatten Nested List Iterator in Python
- Python - Convert given list into nested list
- Python Program to Find the Total Sum of a Nested List Using Recursion
- Python - Convert List to custom overlapping nested list
- Convert a nested list into a flat list in Python
- Find maximum length sub-list in a nested list in Python
- Python program to Flatten Nested List to Tuple List
- Python How to copy a nested list
- Python - Prefix sum list
- Last Stone Weight II in C++
- Python - Create nested list containing values as the count of list items
- Python - Convert list of nested dictionary into Pandas Dataframe
- Python Program to Flatten a Nested List using Recursion
