551. 嵌套列表的加权和

551. 嵌套列表的加权和

中文English

给一个嵌套的整数列表, 返回列表中所有整数由它们的深度加权后的总和. 每一个元素可能是一个整数或一个列表(其元素也可能是整数或列表)

样例

例1:

输入: the list [[1,1],2,[1,1]], 
输出: 10. 
解释:
four 1's at depth 2, one 2 at depth 1, 4 * 1 * 2 + 1 * 2 * 1 = 10

例2:

输入: the list [1,[4,[6]]], 
输出: 27. 
解释:
one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4 * 2 + 6 * 3 = 27

class Solution:
    '''
    大致思路:
    1.无法确定有多少层,只能循环嵌入,一直到[]的时候停止
    2.设置全局变量,self.res,self.depth
    3.单独写一个方法returnsamelist,返回同级的列表,以及将所有同级的列表合并,[1,4,5,5],[[2,4],[42,[43,3]],[24,6,[4,2]]]
    4.在单独写一个方法returnsamelistsum,计算当前列表同级的加权和
    '''
    def __init__(self):
        self.res = 0
        self.depth = 0

    def depthSum(self,nestedList):
        while  True:
            if nestedList == []:
                break
            self.depth += 1
            same_list,nestedList = self.returnsamelist(nestedList)
            self.res = self.res + self.returnsamelistsum(same_list)
        return self.res

    def returnsamelist(self,l):
        other_l = []
        same_l = []
        for column in l:
            if isinstance(column,list) == True:
                ##这里注意一下,需要extend,去掉一层,否则上面会一直while true下去,返回[1,1,1,1]这样才对,而不是[[1,1],[1,1]]
                other_l.extend(column)
            else:
                same_l.append(column)
        return same_l,other_l

    def returnsamelistsum(self,l_same):
        ##这里确定传进的列表一定是单层的,例如[4,2,5,67,6]这种形式
        res = 0
        for num in l_same:
            res += num*self.depth
        return res

 

posted @ 2020-03-14 04:18  风不再来  阅读(297)  评论(0编辑  收藏  举报