Skip to content

Instantly share code, notes, and snippets.

@ChadSki
Created November 18, 2016 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChadSki/22d561fca6101703b5df75c4fb5edca4 to your computer and use it in GitHub Desktop.
Save ChadSki/22d561fca6101703b5df75c4fb5edca4 to your computer and use it in GitHub Desktop.
class Node(object):
"""A node in the road graph. Node functionality doesn't matter, we just
need something to refer to by name."""
def __lt__(self, other):
"""Use the object ID Just so we have a canonical way to sort Nodes."""
id(self) < id(other)
class Edge(object):
"""Connection between two Nodes."""
def __init__(self, node_pair):
"""Calculate the edge's length."""
pass # TODO
def weight(self):
"""How long does it take to traverse this edge? Used for pathing."""
return 1000 # TODO
class Graph(object):
"""Collection of Nodes and the Edges that connect them."""
def __init__(self):
self.nodes = set()
# type: set[Node]
"""For easy reference to the Nodes themselves."""
self.edges = {}
# type: Dict[ Tuple[Node, Node], Edge ]
"""Each connection between nodes. Because an edge works both ways
(this is a normal graph, not a directional graph), sort the two Nodes
before using them as a key. That way, we only have to store edges once.
Ergo, (a, b) and (b, a) should mean the same thing."""
def add_node(self, n):
"""Add a new node to the graph."""
for other in nodes:
node_pair = tuple(sorted([n, other]))
edges[node_pair] = Edge(node_pair)
nodes.add(n)
def path(self, a, b):
"""Find a path from a to b.
Returns a list of Nodes beginning with `a` and ending with `b`."""
pass # TODO do A* pathing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment