Python guy - 7 months ago 36

Python Question

This is a simple function but it is giving me a hard time. I'm trying to calculate the mode in a list, and if there are > 1 modes (with the same frequency), then they need to be displayed.

`def compute_mode(numbers):`

mode = 0

count = 0

maxcount = 0

for number in numbers:

count = numbers.count(number)

if count >= maxcount:

maxcount = count

mode = number

print("Mode: ", mode, "Count: ", maxcount)

Function call:

`print(compute_mode([0,1,3,5,7,3,0]))`

Output:

`Mode: 0 Count: 2`

Mode: 3 Count: 2

Mode: 3 Count: 2

Mode: 0 Count: 2

I can't seem to make the function not repeat the last two lines. I'm not sure why it is repeating again for 0 and 3.

Any ideas?

Answer

The reason you get the modes twice is that your for-loop loops over every element in the list. Therefore, when it encounters the second instance of a previously seen element, it prints it out again.

In other news, your function will fail for a different reason - try removing the first `0`

and see what happens.

This is how I would fix it:

```
from collections import Counter
def compute_mode(numbers):
counts = Counter(numbers)
maxcount = max(counts.values())
for num,count in counts:
if count == maxcount:
print(num, count)
```

If you want to do all the heavy lifting yourself:

```
def compute_mode(numbers):
counts = {}
maxcount = 0
for number in numbers:
if number not in counts:
counts[number] = 0
counts[number] += 1
if counts[number] > maxcount:
maxcount = counts[number]
for number, count in counts.items():
if count == maxcount:
print(number, count)
```