HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Finding an equilibrium of an index of an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
equilibriumindexarrayfinding

Problem

Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. P is an index of an array A.

Input:

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


Output:

1
3
7


1 is an equilibrium index of this array, because:

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


3 is an equilibrium index of this array, because:

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


7 is also an equilibrium index, because:

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


My solution for review:

def isEquilibrium(alist, ind):
    listLen = len(alist)
    left = getSum(0, ind, alist)
    right = getSum(ind+1, listLen, alist)
    # print left, right
    if left == right:
        return True

def getSum(start, end, lis):
    tot = 0
    for i in xrange(start, end):
        tot = tot + lis[i]
    return tot

def solution(alist):
    for i in xrange(0, len(alist)):
        result = isEquilibrium(alist, i)
        if(result):
            print i

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

Solution

You can utilize built-in features of Python to refactor the code.

-
Use the sum() function

Python already provides a sum() function to add all elements of a list that you can use.

example_list = [1, 2, 3, 4, 5]
result = sum(example_list)


-
Slicing

Python allows selecting a range of values of a list. The syntax is:

list[start:end:step]


All these are optional. By default, start is 0, end is the length of the list, and step is 1.

Using this, you can select elements before the index by list[:index] and select elements after the index using list[index+1:].

-
Idiomaticity

Here, a and b are compared for equality. If a is equal to b, the expression a == b will be True, so True is returned.

if a == b:  
    return True

# Refactored
return a == b


-
Naming conventions

snake_case is preferred over camelCase for naming in Python community. Use is_equilibrium instead of isEquilibrium.

Code Snippets

example_list = [1, 2, 3, 4, 5]
result = sum(example_list)
list[start:end:step]
if a == b:  
    return True

# Refactored
return a == b

Context

StackExchange Code Review Q#155760, answer score: 4

Revisions (0)

No revisions yet.