[Python] How can I optimize a Python loop that counts maximum frequency of elements?...

Discussão em 'Python' iniciado por Stack, Julho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a Python function to find the most frequent element in a list and handle ties in a specific way.

    a = [1, 2, 2, 3, 3, 3, 4]
    s = 0
    count = 1
    for i in set(a):
    if a.count(i) == s:
    count += 1
    elif a.count(i) > s:
    s = a.count(i)
    count = 1
    print("YES" if count == 1 else "NO")


    The code works as expected — it prints "YES" if only one number has the highest frequency and "NO" if there's a tie. However, I’m concerned about performance because a.count(i) is being called multiple times inside the loop, which could be inefficient for larger lists.

    Continue reading...

Compartilhe esta Página