Partially Ordered Sets · Hasse Diagrams

Lesson 2

Nikolai Chukhin · Alexander S. Kulikov

The code below builds a Hasse diagram for all divisors of 840 with the divisibility relation.

from itertools import combinations
import pygraphviz as pgv

n = 840
divisors = [k for k in range(1, n + 1) if n % k == 0]

graph = pgv.AGraph(directed=True, rankdir='BT')
for a, b in combinations(divisors, 2):
    if b % a == 0 and not any(a < c < b and c % a == 0
                              and b % c == 0
                              for c in divisors):
        graph.add_edge(a, b)

graph.layout(prog='dot')
graph.draw('hasse.png')