Find The Mode

Finding the mode of a few numbers isn't too hard, but if you have a very long list, you'll probably need some code!

To find the mode, you use the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
current_count = 0   
mode_count = 0      
for position in range(len(array)):
    if array[position] == array[position-1]:
        current_count += 1
    if array[position] != array[position-1] \
       or position == len(array)-1:
        if current_count > mode_count:
            mode = array[position-1]
            mode_count = current_count
        current_count = 1
print mode

For this approach to be successful, which of the following must be true about your array?

I. It is sorted.

II. It is unimodal.

Details

  • The mode is defined as the element which appears most often in a set. If more than one element appears most often, the mode is that set of elements which appear most often.
I and II II only Neither I only

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Arulx Z
Oct 4, 2015

The statement (line 4)

1
array[position] == array[position-1]

will only work if the array is sorted.


Uni modal means something that has only one mode.

If there was more than one mode, an list would have been used to store the modes. However, in the code, a int variable is used to store the mode. Hence it's unimodal.

Additionally, the following statement (line 8)

1
current_count > mode_count:

only works when current_count is greater than mode_count .

However, if there was more than one mode, then something like this -

1
current_count >= mode_count:

would have been required.

Moderator note:

Great explanation for why both conditions are necessary.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...