Reputation: 123
I have a list of objects that are Network Devices so they have attributes such as name and methods such as connected_neighbors. I want to find all objects that are connected with each other to create link objects. I am doing something like below but it is turning out to be very slow
for ref_device in iter(devices):
for device in iter(devices):
if ref_dev.name in device.connected_neighbor_devices():
print ref_dev.name + ' <--> ' + device.name
Update: my data is basically a list of network device objects. These objects are generated from json which itself represents these network devices, their interfaces and neighbors on these interfaces. I have a very large list of network device objects each with several interfaces. I want to create link objects from this list where a link object will have two network device objects that are connected via any number of interfaces (or basically are neighbor of each other)
I have updated my code as follows
class Link(object):
def __init__(self, dev_a, dev_b):
self.dev_a = dev_a
self.dev_b = dev_b
def __repr__(self):
return '{} - {}'.format(dev_a.name, dev_b.name)
links = []
names = {dev.name for dev in devices}
for ref_device in devices:
for neigh in ref_device.connected_neighbor_devices():
if neigh in names:
neigh_device = [d for d in devices if d.name == neigh][0]
links.append(Link(ref_device, neigh_device))
Upvotes: 0
Views: 189
Reputation: 155438
The double-loop followed by membership test in results of connected_neighbor_devices
seems unnecessary, since the method itself seems to get a sequence of connected device names. Surely you could do something like:
names = {dev.name for dev in devices}
for ref_device in devices:
for connected_name in ref_device.connected_neighbor_devices():
if connected_name in names:
print ref_device.name + ' <--> ' + connected_name
The creation of that initial set
and the test for membership is just to ensure that connected devices not part of your devices
collections are not included in the output. This might not match the ordering of your existing code, but that can be changed if needed; assuming connected_neighbor_devices
returns all the names of connected devices, this should get what you want, but with O(n)
calls to and scans of the results from connected_neighbor_devices
, not O(n ** 2)
.
Upvotes: 2