Edwinner Edwinner - 8 days ago 7
Python Question

How to return the most common items in a list that are closely related in value in Python?

Suppose I have a list:

lst = [2.2, 2.23, 2.24, 3, 4, 5, 3.8]


I would like to know if there is a function out there that figures out that my most common and related numbers are:

most_common = [2.2, 2.23, 2.24]


From there i can return the smallest of the list or do whatever other operation i want.

This is the function i am using so far and i am not pleased with the results

max(set(lst), key=lst.count)


Thanks in advance.

Answer

It depends on what you mean by most common. You can use this algorithm and set precision with eps variable:

a = [2.2, 2.23, 2.24, 3, 4, 5, 3.8]
eps = 0.5


def find_relative(values, eps):
    minimum, maximum = 0, 0
    result = []
    temp = []
    for v in sorted(values):
        if not temp:
            minimum = maximum = v
            temp.append(v)
        else:
            if abs(v - minimum) < eps and abs(v - maximum) < eps:
                temp.append(v)
                if v < minimum:
                    minimum = v
                elif v > maximum:
                    maximum = v
            else:
                if len(temp) > 1:
                    result.append(temp)
                minimum = maximum = v
                temp = [v]
    return result


print(find_relative(a, eps))  # [[2.2, 2.23, 2.24], [3.8, 4]]
Comments