【每日一题0812】Mean Square

:woman_mage:我们的任务是编写一个python函数,实现计算均值。函数接收两个等长的整数列表nums_1nums_2,将它们索引相同的两个元素的差值分别进行平方运算,然后汇总求和并返回平均值。

示例:
输入:[1, 2, 3], [4, 5, 6] ,输出:9 ,因为(9 + 9 + 9) / 3

题目难度:简单
题目来源:codewars

def mean_square(nums_1:list, nums_2:list):
    pass
  
assert mean_square([1,2,3], [4,5,6]) == 9
assert mean_square([10, 20, 10, 2], [10, 25, 5, -2]) == 16.5
assert mean_square([10, 10], [10, 10]) == 0
def mean_square(nums_1: list, nums_2: list):
    return sum(list(map(lambda x: x ** 2, [nums_2[i] - nums_1[i] for i in range(len(nums_1))]))) / len(nums_1)


assert mean_square([1, 2, 3], [4, 5, 6]) == 9
assert mean_square([10, 20, 10, 2], [10, 25, 5, -2]) == 16.5
assert mean_square([10, 10], [10, 10]) == 0

面试题要是都这个难度就好了

def mean_square(num1:list,num2:list):
    if len(num1)==0:
        return 0
    else:
        nums=0
        for i in range(len(num1)):
            nums=nums+(num1[i]-num2[i])**2
        return nums/(len(num1))
def mean_square(nums_1:list, nums_2:list):
    return sum(list(map(lambda x: (x[0]-x[1])**2, zip(nums_2, nums_1)))) / len(nums_1)

assert mean_square([1,2,3], [4,5,6]) == 9
assert mean_square([10, 20, 10, 2], [10, 25, 5, -2]) == 16.5
assert mean_square([10, 10], [10, 10]) == 0

image

image

参考题解

def mean_square(nums_1:list, nums_2:list):
    return sum(map(lambda x, y: (x - y) ** 2, nums_1, nums_2)) / len(nums_1)

assert mean_square([1,2,3], [4,5,6]) == 9
assert mean_square([10, 20, 10, 2], [10, 25, 5, -2]) == 16.5
assert mean_square([10, 10], [10, 10]) == 0

解题思路:利用python3内置函数map()和sum()函数实现。

map()函数语法:map(function, iterable, ...),接收一个函数对象,以及任意个可迭代对象。这里我们是用lambda匿名函数定义处理传入的可迭代对象的计算逻辑。

sum()函数的语法:sum(iterable[, start]),用来对序列进行求和计算。其中iterable表示可迭代对象,可以是列表、元组、集合;start 表示指定相加的参数,如果没有设置这个值,默认为0。

参考题解

def mean_square(nums_1:list, nums_2:list):
    return sum((x-y)**2 for x,y in zip(nums_1, nums_2)) / len(nums_1)


assert mean_square([1,2,3], [4,5,6]) == 9
assert mean_square([10, 20, 10, 2], [10, 25, 5, -2]) == 16.5
assert mean_square([10, 10], [10, 10]) == 0

解题思路:利用python3内置函数zip()和sum()函数实现。
zip()函数接收可迭代的对象作为参数,将对象中对应的元素对应打包成一个个元组,返回的是zip对象。
例如zip([1,2,3], [4,5,6])的结果是<zip object at 0x10c399880>,转成列表则是[(1, 4), (2, 5), (3, 6)]

关闭