import networkx as nx # for drawing graphs
# vertex list
V = [0,1,2,3,4]
E = [(0,2), (1,3)]
G= nx.Graph()
G.add_nodes_from(V)
G.add_edges_from(E)
nx.draw(G)
# make a tree
V = [0,1,2,3,4,5,6]
E = [(0,1), (0,2), (1,3), (1,4), (2,5), (2,6)]
G = nx.Graph()
G.add_nodes_from(V)
G.add_edges_from(E)
nx.draw(G)
# adjacency matrix
# A[i,j] = 1 if i,j connected by edge
# = 0 otherwise
# edge lists are more convenient
import numpy as np
A = np.array([[0, 1, 1], [1,0,0], [1,0,0]])
H = nx.from_numpy_matrix(A) # create graph from adjacency matrix
nx.draw(H)
def rand_walk(A, v, steps):
"""Given graph correspoding to adj matrix A
(represented) as numpy array,
starting vertex v, traverse
the graph by choosing an edge randomly from
the possible choices at each vertex."""
w = v # current vertex
for n in range(steps):
num_vert = len(A[w]) # number of vertices total
neigh_list = [i for i in range(num_vert) if A[w,i]==1]
# above is list of neighbors of w
num_neigh = len(neigh_list)
# choose an edge randomly, make this the new w
w = neigh_list[randint(0,num_neigh-1)]
return w
A = np.array([[0, 1, 1], [1,0,0], [1,0,0]])
rand_walk(A,0,1)
A = np.array([[0, 1, 1], [1,0,0], [1,0,0]])
rand_walk(A,0,2)