vinicius de novaes
vinicius de novaes

Reputation: 421

Is there a way to define a compare function to issubset in Python

I want to use an approximate comparison to check if two sets are equal. More exactly, if there is a bijection of approximate elements on two sets.

As a toy example, consider the following function

def my_compare(a, b):
    ep = 0.1
    return a>=b-ep and a<=b+ep

I would like to do something like

a = {1, 2, 3}
b = {1.05, 2, 3}
c = {1.2, 2, 3}

print(a.issubset(b) and b.issubset(a))

print(a.issubset(c) and c.issubset(a))

Have output

True
False

PS: I know that I am subverting the mathematical definition of set by doing that. Even so. Is there?

Upvotes: 0

Views: 56

Answers (1)

yulkes
yulkes

Reputation: 210

To keep these comparisons efficient, you may want to consider an alternate underlying data structure, such as an Interval Tree.

The Python portion library at https://github.com/AlexandreDecan/portion could help you out here.

Define each element in the set as an interval sized [x - 0.1, x + 0.1], and look for intersections between the two sets: https://github.com/AlexandreDecan/portion#interval-operations

Upvotes: 2

Related Questions