def ring_edges(n, triples):
    """Let there be n*r vertices grouped into r ordered rings of n vertices each.
    Each triple (a, b, k) in triples corresponds to the statement "for 0 <= i <= n, vertex i
    in ring a is connected to vertex i+k in ring b, all indices taken modulo n".
    Return all the edges implied by these statements."""
    L = []
    for (a, b, k) in triples:
        limit = k if a == b and 2*k == n else n
        L.extend([(i+a*n, (i+k)%n + b*n) for i in range(limit)])
    return L