Sobes.tech
Junior — Middle

How can you compare two objects represented in the form of an edge?

sobes.tech AI

Answer from AI

If an edge is represented as an object with two vertices (for example, source and target), then comparing two such objects may depend on whether the edge is directed or not.

Example for an undirected edge (an edge between vertices A and B is equal to an edge between B and A):

class Edge:
    def __init__(self, source, target):
        self.source = source
        self.target = target

    def __eq__(self, other):
        if not isinstance(other, Edge):
            return False
        return {self.source, self.target} == {other.source, other.target}

    def __hash__(self):
        return hash(frozenset([self.source, self.target]))

# Example usage
edge1 = Edge('A', 'B')
edge2 = Edge('B', 'A')
print(edge1 == edge2)  # True

For a directed edge, comparison will consider the order of vertices:

def __eq__(self, other):
    if not isinstance(other, Edge):
        return False
    return self.source == other.source and self.target == other.target

Thus, the comparison depends on the context of the task and the type of edge.