Skip to content

Commit 6204ab0

Browse files
committed
simplified the code following reviews
1 parent cf7dc21 commit 6204ab0

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

graphs/random_graph_generator.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
URL: https://en.wikipedia.org/wiki/Random_graph
77
"""
88

9-
import numpy as np
9+
import random
1010

1111

1212
def random_graph(
@@ -16,33 +16,33 @@ def random_graph(
1616
Function that generates a random graph
1717
@input: vertices_number (number of vertices),
1818
probability (probability that a generic edge (u,v) exists),
19-
directed (if True: g will be a directed graph,
19+
directed (if True: graph will be a directed graph,
2020
otherwise it will be an undirected graph)
2121
@examples:
2222
>>> random_graph(4, 1)
2323
{0: [1, 2, 3], 1: [0, 2, 3], 2: [0, 1, 3], 3: [0, 1, 2]}
2424
>>> random_graph(4, 1, True)
2525
{0: [1, 2, 3], 1: [0, 2, 3], 2: [0, 1, 3], 3: [0, 1, 2]}
2626
"""
27-
g = dict(zip(range(vertices_number), [[] for _ in range(vertices_number)]))
27+
graph = {i: [] for i in range(vertices_number)}
2828

2929
# if probability is greater or equal than 1, then generate a complete graph
3030
if probability >= 1:
3131
return complete_graph(vertices_number)
3232
# if probability is lower or equal than 0, then return a graph without edges
3333
if probability <= 0:
34-
return g
34+
return graph
3535

3636
# for each couple of nodes, add an edge from u to v
3737
# if the number randomly generated is greater than probability probability
3838
for i in range(vertices_number):
3939
for j in range(i + 1, vertices_number):
40-
if np.random.random() < probability:
41-
g[i].append(j)
40+
if random.random() < probability:
41+
graph[i].append(j)
4242
if not directed:
4343
# if the graph is undirected, add an edge in from j to i, either
44-
g[j].append(i)
45-
return g
44+
graph[j].append(i)
45+
return graph
4646

4747

4848
def complete_graph(vertices_number: int) -> dict:
@@ -54,13 +54,9 @@ def complete_graph(vertices_number: int) -> dict:
5454
>>> print(complete_graph(3))
5555
{0: [1, 2], 1: [0, 2], 2: [0, 1]}
5656
"""
57-
g = {}
58-
for i in range(vertices_number):
59-
g[i] = []
60-
for j in range(0, vertices_number):
61-
if i != j:
62-
g[i].append(j)
63-
return g
57+
return {
58+
i: [j for j in range(vertices_number) if i != j] for i in range(vertices_number)
59+
}
6460

6561

6662
if __name__ == "__main__":

0 commit comments

Comments
 (0)