Chris - 10 months ago 50

Python Question

I am trying to solve the equlibrium problem presented in Codility. I wrote a solution (probably not the most efficient one, but this is just for exercise purposes). The solution works on my PC but returns an error in the Codility environment. How this is possible? Where am I making a mistake?

The problem

To find the equilibrium index of a sequence such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes.

My Solution

`A=[-1, 3, -4, 5, 1, -6, 2, 1]`

def solution(A):

results=[]

n=len(A)

P = [0] * (n)

P[0] = A[0]

for k in xrange(1, n):

P[k] = P[k - 1] + A[k]

for p in xrange(1,n):

if P[p-1]==P[n-1]-P[p-1]-A[p]:

results.append(p)

if len(results) <> 0:

return results

else:

return -1

Compilation successful. Example test: [-1, 3, -4, 5, 1, -6, 2, 1]

Output (stderr): Invalid result type, int expected,

found. RUNTIME ERROR (tested program terminated unexpectedly)

Answer Source

It looks like you are supposed to return an integer in all cases, while your code returns a list in some cases and -1 in some other.

I think you may just return the fist result as the algorithm description doesn't seem to consider cases where solution isn't unique. So `return results[0]`

instead of `return results`

might fix it.