Source code for data_structures.graphs.vertex
# -*- coding: utf-8 -*-
"""Vertex node used within graph data structures."""
import sys
from typing import Dict, List
if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self
[docs]
class Vertex:
"""Represents a node in a graph with weighted connections to neighbors."""
[docs]
def __init__(self, key):
""" Initialize the vertex with a key and no connections. """
self._id = key
self._connections = {}
def __str__(self):
return f"{self.id} connectedTo: {[x.id for x in self._connections]}"
@property
def id(self):
""" The vertex identifier. """
return self._id
@id.setter
def id(self, value):
self._id = value
[docs]
def get_weight(self, vertex: Self):
""" Retrieve the weight to reach the neighbor """
return self._connections[vertex]
[docs]
def get_connections(self) -> Dict:
""" Return the connections """
return self._connections
[docs]
def get_connections_ids(self) -> List:
""" Return the connections ids """
return [vertex.id for vertex in self.get_connections()]
[docs]
def add_neighbor(self, vertex: Self, weight=0):
""" Add or update a connection """
self._connections[vertex] = weight