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

Find the index of the element with maximum absolute deviation

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

Problem

I just completed a Codility test. The question presented was pretty simple but I may have over thought it.

Question:


Find the element which has the highest absolute deviation from the mean. E.g. Array = [1,1,-1,1].The average is 0.5, so the absolute deviation for each element in the array is [0.5,0.5,1.5,0.5] (note that the -1.5 goes to 1.5 after taking the absolute values of each deviation value) and thus the index with the max absolute deviation is 2 (the index starts from 0).

My code was:

def solution(A):
    if len(A) > 0:
        average = sum(A)*1.0/len(A)
        max_avg = 0
        pos = 0            
        for i in range(len(A)):
            if abs(A[i] - average) > max_avg:
                max_avg = abs(A[i] - average)
                pos = i
        return pos
    else:
        return -1


If there's a tie between the max deviation elements i.e. two or more indexes have the same absolute deviation then either of them can be given. The required time-complexity is \$O(N)\$ and space-complexity is \$O(1)\$. In theory, this problem should be really easy but this was my first technical test and I might have overlooked something. Did I possibly miss anything?

Solution

Note that in Python 3, you don't need * 1.0 to get floating-point division. On the other hand, in Python 2, range(len(A)) would use O(N) space.

I recommend three changes:

  • Put the special case first, to reduce the separation between return -1 and the reason for returning -1.



  • Rename max_avgmax_deviation.



  • Use enumerate() to iterate over the array.



The revised solution would be:

def solution(A):
    if not A:
        return -1
    average = sum(A) * 1.0 / len(A)
    max_deviation = 0
    pos = 0
    for i, a in enumerate(A):
        if abs(a - average) > max_deviation:
            max_deviation = abs(a - average)
            pos = i
    return pos

Code Snippets

def solution(A):
    if not A:
        return -1
    average = sum(A) * 1.0 / len(A)
    max_deviation = 0
    pos = 0
    for i, a in enumerate(A):
        if abs(a - average) > max_deviation:
            max_deviation = abs(a - average)
            pos = i
    return pos

Context

StackExchange Code Review Q#82340, answer score: 3

Revisions (0)

No revisions yet.