Find the maximum frequency of an element in a given Array

Question:

Problem outline

This is the solution I have come up with but I’m unsure whether this is the best possible solution as far as Big (O) notation is concerned…

def solution(A):
    B = [0, 0, 0, 0, 0]
    for i in range (len(A)):
        if A[i] == "Cardiology":
            B[0] += 1
        elif A[i] == "Neurology":
            B[1] += 1
        elif A[i] == "Orthopaedics":
            B[2] += 1
        elif A[i] == "Gynaecology":
            B[3] += 1
        elif A[i] == "Oncology":
            B[4] += 1
    max_patients = max(B)
    return max_patients
Asked By: da2ksentine7

||

Answers:

Because you know all of the possible values, you could use a dict with department names as keys and counts as values.

You could initialize it as:

departments = {"Cardiology": 0, "Neurology": 0, "Orthopaedics": 0, "Gynaecology": 0, "Oncology": 0}

As a style suggestion, since you’re iterating over the elements of a list, you don’t need to access them by index, instead you can loop over the list directly. Combining that with the dictionary, you can do:

for dept in A:
    departments[dept] += 1

max_patients = max(departments)
return max_patients

Of course, if you’re willing to explore the documentation a little, the collections.Counter object does the same thing (but probably a little faster)

Answered By: Dash

You can solve this very easily with collections.Counter. You don’t want or need dictionaries, side lists or anything else extra. Everything you add is another thing to break. Keep it as simple as possible.

from collections import Counter

def solution(A):
    return max(Counter(A).values())

I only stuck this in a function to give you context. There’s no reason for this to be a function. Wrapping this in a function is basically just giving the operation an alias. Unfortunately, your alias doesn’t give any indication of what you aliased. It’s better to just put the one line in place.

Answered By: OneMadGypsy

Based on assumptions and the return value:

def solution(A):
    A = [A.count(A[i]) for i in set(range(len(A)))]
    return max(A)

A = ["Cardiology", "Neurology", "Oncology", "Orthopaedics", "Gynaecology", "Oncology", "Oncology"]
print(solution(A))

# 3
Answered By: Arifa Chan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.