zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Sum Arrays

2023-04-18 15:43:57 时间

Instructions
Write a function that takes an array of numbers and returns the sum of the numbers. The numbers can be negative or non-integer. If the array does not contain any numbers then you should return 0.
Examples
Input: [1, 5.2, 4, 0, -1]
Output:9.2

Input:[]
Output: 0

Input: [-2.398]
Output: -2.398
Solution

# 个人解法
def sum_array(array):
    """求数组之和"""
    
    # 空数组时返回0
    if len(array) == 0:
        return 0;
    
    # 使用列表解析求数组之和
    return sum(value for value in array)
# 最优解法
def sum_array(array):
    return sum(array)