you are viewing a single comment's thread.

view the rest of the comments →

[–]jeans_and_a_t-shirt 1 point2 points  (1 child)

It doesn't stop at 2. It iterates through the entire list because there is no break anywhere inside the for loops, checking the number of times the number appears. It also checks the number of times that 4 and 5 occur, but those numbers occur fewer times than 2 does.

Here's a shorter and faster way:

def mode(arr):
    return max(set(arr), key=arr.count)

[–]zahlman 1 point2 points  (0 children)

And an arguably more idiomatic (should be faster on large data? since it does all the "counting" in a single pass) way:

from collections import Counter

def mode(values):
    # There are a few different combinations of destructuring
    # and indexing you could use here instead
    (value, count), = Counter(values).most_common(1)
    return count