Coloring a random graph in python
I have a script that implements greedy coloring in python, in other words it colors a graph with four colors. I wanted to generate a random graph and then pass it into the script found on the link above to color it. This is how I generate a random graph (in the shape of a dictionary):
list = [1,2,3,4,5]
d = {i: sample([j for j in q if i != j], randrange(1, len(q) - 1))
for i in q}
So what i need now is some kind of function that passes the created dictionary into the greedy coloring script, because if i enter the graph d in the function in the script called greedycoloring I get the following error:
Traceback (most recent call last):
File "/private/var/mobile/Containers/Shared/AppGroup/9244016A-6D10-4627-B39B-6D63D3F9D22C/Pythonista3/Documents/nuovaprova.py", line 88, in <module>
greedyColoring(d, 5)
File "/private/var/mobile/Containers/Shared/AppGroup/9244016A-6D10-4627-B39B-6D63D3F9D22C/Pythonista3/Documents/nuovaprova.py", line 33, in greedyColoring
if (result[i] != -1):
IndexError: list index out of range
Solution 1:
Start list
q from 0 as shown below:
q = [0, 1, 2, 3, 4]
d = {i: sample([j for j in q if i != j], randrange(1, len(q) - 1))
for i in q}
Then, you can directly pass dictionary d
into the script as :
greedyColoring(d, 5)
The given script represents graph as list of lists
where index of list represents the node and its corresponding value represents its adjacent nodes, so you can also convert d
into list of list as [node for node in d.values()]
and then pass into the function as:
greedyColoring([node for node in d.values()], 5)