I am trying to create a complete graph in a Python Dictionary in 1 line. But when creating the list comprehension for the values I can not figure out how to specify that the key_value can not appear in the list of values (in graph speak, no self loop).
for n nodes
G = {k:[v for v in range(n)] for k in range(n) }
results in this (example n = 3)
{0: [0, 1, 2], 1: [0, 1, 2], 2: [0, 1, 2]}
but what I want is this
{0: [1, 2], 1: [0, 2], 2: [0, 1]}
But trying something similar to this
G = {k:[v for v in range(n) for v !=k] for k in range(n) }
will throw an error at the k in the list comprehension. So k must be out of scope for the list comprehension, which makes sense.
Can G be defined in this method?
To ignore the key's value
from the value
list, you just have to put a validation in your list comprehension.
G = { k: [v for v in range(n) if v != k] for k in range(n) }
So for n = 3
you graph G
would return :-
{0: [1, 2], 1: [0, 2], 2: [0, 1]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With