Python练习题答案: 中可能包含多个列表列表编号的平方和【难度:1级】--景越Python编程实例训练营,1000道上机题等你来挑战

标签: python面试题库和答案  python编程练习  编程基础  递归算法

中可能包含多个列表列表编号的平方和【难度:1级】:

答案1:

def sumsquares(l):
    return sum([ i**2 if type(i) == int else sumsquares(i) for i in l ])

答案2:

def sumsquares(l):
    if not isinstance(l, list):
        return l * l
    return sum(sumsquares(x) for x in l)

答案3:

import re
def sumsquares(l):
    result_arr = [int(i) for i in re.sub('\D', ' ', str(l)).split()]
    return sum(i**2 for i in result_arr )

答案4:

def sumsquares(l):
    if isinstance(l, int): return l**2
    return sum(map(sumsquares, l))

答案5:

def sumsquares(l):
    return sum(el**2 if isinstance(el, int) else sumsquares(el) for el in l)

答案6:

def sumsquares(lst):
    try:
        return sum(sumsquares(a) for a in lst)
    except TypeError:
        return lst ** 2

答案7:

def sumsquares(l):
    def g(l):
        if isinstance(l,int):
            return l*l
        else:
            return sum(g(x) for x in l)
    return g(l)

答案8:

sumsquares=s=lambda l:sum(n<[]and n*n or s(n)for n in l)

答案9:

def sumsquares(l):
    result = 0
    for e in l:
        result += sumsquares(e) if isinstance(e, list) else e*e
    return result​

答案10:

def sumsquares(l):
    return sum(sumsquares(el) if isinstance(el, list) else el ** 2 for el in l)



Python基础训练营景越Python基础训练营QQ群

在这里插入图片描述
欢迎各位同学加群讨论,一起学习,共同成长!

原文链接:加载失败,请重新获取