Skip to content

Instantly share code, notes, and snippets.

@SamuraiT
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SamuraiT/9054089 to your computer and use it in GitHub Desktop.
Save SamuraiT/9054089 to your computer and use it in GitHub Desktop.
a random graph: G(n,p) which generates graphs with n nodes and edges between any two nodes with the probability (p)
from Graph import (
Graph,
Edge,
Vertex,
)
import random
class RandomGraph(Graph):
"""
create a random graph with the probability (p)
"""
def add_random_edges(self, p):
vs = self.vertices()
max = len(vs)
for i in xrange(max):
for j in xrange(i+1, max):
if random.random() <= p:
e = Edge(vs[i],vs[j])
self.add_edge(e)
def create_graph_with(vertices):
vs = [Vertex(word) for word in vertices]
return RandomGraph(vs)
def friendship_graph():
vertices = ['Tatsu','Jack','Mack','Alex','Allen','Bob','Paul']
g = create_graph_with(vertices)
g.add_random_edges(0.3)
draw_graph(g)
def draw_graph(g):
from GraphWorld import *
layout = CircleLayout(g)
# draw the graph
gw = GraphWorld()
gw.show_graph(g, layout)
gw.mainloop()
if __name__ == '__main__':
import sys
friendship_graph()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment