Skip to content
Snippets Groups Projects
Commit fa59b7c0 authored by Valtteri Virta's avatar Valtteri Virta
Browse files

made node class

parents
No related branches found
No related tags found
No related merge requests found
node.py 0 → 100644
from typing import Dict, Any, Iterator, Tuple
class Node:
"""
Represents a node in a graph for Dijkstra's algorithm visualization.
Attributes:
id: Unique identifier for the node.
neighbors: Dictionary mapping neighbor nodes to edge weights.
"""
def __init__(self, id: int):
self.id = id
# Map each neighbor Node to the weight of the connecting edge
# Dict insted of dict gives type hints -> better in this case
self.neighbors: Dict['Node', int] = {}
def add_neighbor(self, neighbor: 'Node', weight: int = 1) -> None:
"""
Connect node to a neighbor with the given weight.
"""
self.neighbors[neighbor] = weight
def remove_neighbor(self, neighbor: 'Node') -> None:
"""
Remove the connection to a neighbor, if it exists.
"""
self.neighbors.pop(neighbor, None)
def get_neighbors(self) -> Iterator[Tuple['Node', int]]:
"""
Return an iterator of (neighbor, weight) pairs.
"""
return iter(self.neighbors.items())
def __hash__(self) -> int:
# Allow Node to be used as a key in dictionaries or elements in sets
return hash(self.id)
def __equal__(self, other: Any) -> bool:
# Nodes are equal if IDs match
# Can compare even wiht other types -> gives False
return isinstance(other, Node) and self.id == other.id
def __repr__(self) -> str:
return f"Node({self.id})"
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment