Python 2.7中的均衡指数

时间:2017-06-08 02:34:40

标签: python

我在Codility接受了一个演示任务,我在试图弄清楚我做错了什么时遇到了一些麻烦。任务:

在Python 2.7环境中工作

给出了由N个整数组成的零索引数组A.该阵列的平衡指数是任何整数P,使得0≤P<1。 N和较低指数的元素之和等于较高指数的元素之和,即

A [0] + A [1] + ... + A [P-1] = A [P + 1] + ... + A [N-2] + A [N-1]。< / p>

假设零元素的总和等于0.如果P = 0或P = N-1,则会发生这种情况。

例如,考虑以下由N = 8个元素组成的数组A:

A[0] = -1
A[1] =  3
A[2] = -4
A[3] =  5
A[4] =  1
A[5] = -6
A[6] =  2
A[7] =  1 

P = 1是该阵列的平衡指数,因为:

A[0] = −1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]

P = 3是该阵列的平衡指数,因为:

A[0] + A[1] + A[2] = −2 = A[4] + A[5] + A[6] + A[7]

P = 7也是一个均衡指数,因为:

A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0

并且没有索引大于7的元素。

P = 8不是平衡指数,因为它不满足条件0≤P<1。 Ñ

写一个函数:

def解决方案(A)

给定由N个整数组成的零索引数组A,返回其任何均衡指数。如果不存在均衡指数,该函数应返回-1。

作为回应,我写了以下内容:

def solution(A):
    if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there
        return "Empty list, no integers to work with"
    else:
        equi = []
        x = 0
        length = len(A)
        rightSum = []
        leftSum = []
        while x < length:
            for i in A:
                rightSum = A[1:i-1]
                leftSum = A[i+1:length-2]
                if sum(rightSum) == sum(leftSum):
                    equi.append(i)
                    return equi
                else:
                    return -1
            x += 1
    pass

solution([-1,3,-4,5,1,-6,2,1])

当我编写代码时,我在测试列表中保持-1,即使我应该得到equi [1,3,7]。

另一个问题,为什么我需要通过&#39;方法结尾的关键字?

我应该补充一点,我对Python编码和编码非常陌生。我们将非常感谢所有人提供的任何帮助。

3 个答案:

答案 0 :(得分:2)

考虑函数必须返回的数据类型。这是一份均衡指数清单。

这意味着函数中的每个return语句都必须返回一个列表。绝不是一个数字,绝不是一个字符串。

对于空列表,没有可能的均衡指数; return []

当您找到均衡指数时,您可以将其附加到equi列表中,正如您所做的那样并继续。不要return循环内的while。第一个return语句结束了函数执行。

当你的循环因为你查看了所有索引而结束时,equi列表将包含循环找到的所有均衡索引。现在,在循环之后,它的时间是return equi,而不是无用的pass

(对于奖励积分,您可以计算一次列表的总和,并注意向右移动索引会在左侧总和中添加一个元素,并从正确的总和中减去相同的元素。这样,您赢了&# 39;每次都必须sum每个子列表;算法的性能将是线性的而不是二次的。)

答案 1 :(得分:2)

你的逻辑是理智的,但是你在语言的某些语法上绊倒。

我在评论时尽力帮助您的代码:

def solution(A):
    if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there
        return "Empty list, no integers to work with"
    else:
        equi = []
        x = 0
        length = len(A)
        rightSum = []
        leftSum = []
        # while x < length: (removed)
        # When we do for i in A, we're already iterating over each element i of the list A.
        # As such, there's no need for the while loop.
        for i in A:
            # You switched right and left sum; elements at the 'left' are at the beginning of the list
            # I also switched the name of the lists to leftList and rightList, to be more descriptive
            # (a list and a sum are different things)
            # I switched the i that was in the indexes to x. i is the integer on the list we're iterating over;
            # its position on the list, on the other hand, is being counted with x.
            leftList = A[0:x]  # Go from 0, since you want to count the first element.
            # We could also ommit the first index and it would begin from the first element
            rightList = A[x+1:]  # If we ommit the second index, it'll go until the last element
            if sum(leftList) == sum(rightList):
                # I changed equi.append(i) to equi.append(x), because i is the value we're iterating over, while
                # x is the counter (index) of the number being currently evaluated
                equi.append(x)
                # return equi (removed)
                # We don't want to return here. When we call return, the function exits!

            # What this would do is exit the function if the sum of the left list wasn't equal to the sum of the right.
            # This isn't what we want, so we'll just remove this
            # else: (removed)
            #     return -1 (removed)
            x += 1

        # No pass needed; that's another thing entirely, just a nil instruction

        # Now the loop is done, we have appended to equi all the equilibrium values.
        # It's time to exit the function by returning the list of equi values.
        # Since we must return -1 if no equilibrium indices exist, then we have to check for that as well
        if len(equi) == 0:
            return -1
        else:
            return equi

sol = solution([-1, 3, -4, 5, 1, -6, 2, 1])
print(sol)  # [1, 3, 7]

还有一些其他小的东西可以提高可读性(变量命名约定,使用enumerate),但为了简洁和简单起见,我已经包括了它的工作原理。

答案 2 :(得分:0)

您只需要做的就是:

a=[-1, 3, -4, 5, 1, -6, 2, 1]

for i in range(len(a)):

     print("sum of digits at Left  side of the index {} is : {}"  .format(i, sum(a[0:i]))) 

     print("sum of digits at right side of the index {} is : {}" .format(i,sum(a[i+1:len(a)])))

     if  sum(a[0:i])==sum(a[i+1:len(a)]):
        print("My Equilibirium Index is : {} ".format(i))