def numberOfTriangles (G): ''' Returns the number of triangles in $G$ by using the fact that the $(i,i)$ entry of the cube of the adjacency matrix of $G$ indicates the number of closed walks of length $3$ that start and end at vertex $v_i$ (\textit {i.e.\} the number of triangles that $v_i$ participates in). To get the total number of triangles in the whole graph, we must note that if three vertices $v_1, v_2, v_3$ form a triangle, the trace counts this six times. So, we correct for this by dividing by $6$. ''' A = adjacencyMatrix (G) return (A**3).trace() / 6
def eigenvalues (G): ''' Returns the eigenvalues of the adjacency matrix of $G$. ''' eigenvals = adjacencyMatrix(G).eigenvals() # The following is necessary because the dictionary returned by # \code{sympy.Matrix.eigenvals()} uses \code{sympy.Integer}s as # keys rather than ordinary integers. Thus, we get the annoying # situation where (for example), eigenvals() might return the # dict \code{\{4: 1, -2: 2, 0: 3\}}, but the expression # \code {4 in eigenvals} would fail. return dict ( [ (int (k), eigenvals [k]) for k in eigenvals.keys() ] )
def is_triangleFree (G): ''' Returns True if $G$ is triangle-free, otherwise False. ''' # By Mantel's Theorem (West, p. 41), the maximum number of edges in # an $n$-vertex triangle-free simple graph is the floor of $n^2 / 4$. n = order (G) if size (G) > floor (n**2 / 4.0): return False # Otherwise, recall that the $(i,j)$ entry of the $n$-th power of the # adjacency matrix of a graph indicates the number of closed walks # of length $n$ that begin at $v_i$ and end at $v_j$. (West, p. 455, # Proposition 8.6.7.) # A triangle is a closed walk of length $3$ starting and ending at # the same vertex. Thus, we see that $G$ is triangle-free if and # only if $\trace (A^3) = 0$, where $A$ is the adjacency matrix of $G$. A = adjacencyMatrix (G) return (A**3).trace() == 0