Skip to content

Graph Basics

Lesson 1 of 16 · 5 min

Graph Basics

Step 1 of 7

A graph is things plus the connections between them. That is the entire definition.

The Idea

A graph is nodes joined by edges. That is the whole definition — arrays and linked lists just add rules on top of it. Edges can be undirected (a two-way bond) or directed (one-way). A node's degree is simply how many edges touch it.

Real-World Example

A molecule is a graph you can hold. Atoms are the nodes, chemical bonds are the edges, and, where every bond is single, an atom's valence is its degree: carbon accepts four bonds, hydrogen exactly one. Chemists draw structures rather than formulas because the connections, not the atom counts, decide what the substance does.

The Code

Your turn

What does this print?

g = {"A": ["B", "C"], "B": ["A"], "C": ["A"]}
print(len(g), sum(len(v) for v in g.values()) // 2)

Mini quiz

1 / 3

What are the two ingredients of every graph?