对我而言,不使用sum()来计算数组之和的更有效方法是什么?

时间:2018-10-05 10:00:14

标签: python arrays sum

因此,我的代码如下所示。本质上,我想做的是将函数calculateSumX,calculateSumY和calculateSumZ最小化为一个函数。我该怎么做?现在忽略案例。

def calculateSumX(x):
    theSumX = 0

    for i in x:
        theSumX = theSumX + 1
        return theSumX;

def CalculateSumY(y):
    theSumY = 0

    for i in y:
        theSumY = theSumY + 1
        return theSumY;

def calculateSumZ(z):
    theSumZ = 0

    for i in z:
        theSumZ = theSumZ + 1
        return theSumZ;

def question5(x, y, z):

    case = 5

    #tests whether the sum of each array is equal 

    x = calculateSumX(x)
    y = calculateSumY(y)
    z = calculateSumZ(z)

    if x == y == z:
        print("The sum of all three arrays have equal values ")
        case = 1
        return case

    # if x and y equal
    elif x == y:
        print("The sum of x and y hold equal values ")
        case = 2
        return case

    # if x and z equal 
    elif x == z:
        print("The sum of x and z hold equal values ")
        case = 3
        return case

    # if y and z equal 
    elif y == z:
        print("The sum of y and z hold equal values ")
        case = 4
        return case

    # if all three different
    else:
        print("No sum of each array hold equal values ")
        return case

1 个答案:

答案 0 :(得分:2)

这个;

def calculateSumX(x):
    theSumX = 0

    for i in x:
        theSumX = theSumX + 1
        return theSumX;

def CalculateSumY(y):
    theSumY = 0

    for i in y:
        theSumY = theSumY + 1
        return theSumY;

def calculateSumZ(z):
    theSumZ = 0

    for i in z:
        theSumZ = theSumZ + 1
        return theSumZ;


x = calculateSumX(x)
y = calculateSumY(y)
z = calculateSumZ(z)

可以简单地变成这个;

def calculate_sum(ls):
    total = 0
    for value in ls:
        total += value
    return total


sum_x = calculate_sum(x)
sum_y = calculate_sum(y)
sum_z = calculate_sum(z)

顺便说一句,您原来的calculateSum函数将不计算总和,但将返回列表中元素的数量,实际上甚至不会这样做,因为它们在第一个元素之后返回。