I have pairs of items (in Python), with one list holding the first half and a second list holding the second half. Each pair appears twice, in the form of a -> b
and also b -> a
.
Every value that is paired up has a corresponding 2D coordinate that is stored in a third array and I want to graph every pair as dots on a scatter plot and then graph a line joining their coordinates together. How do I avoid plotting the same 2 items twice?
The nieve solution is to check whether both a
and b
have already been plotted as dots but this won't work if pairs like c -> b
and a -> c
both appear earlier.
That means I'll need to check whether specifically the pair of coordinates have been plotted before.
I believe both of these solutions run in O(n^2)
time. Is there a solution that runs in O(n)
time?
Here's an example:
import torch
# Each use of `torch.randn` is a placeholder for actual values but imitates the shape
t_a = torch.randn(3, 256, 256)
t_b = torch.randn(3, 256, 256)
t_c = torch.randn(3, 256, 256)
t_d = torch.randn(3, 256, 256)
a = [t_a, t_b, t_c]
b = [t_b, t_a, t_d]
c_keys = [t_a, t_b, t_c]
c_values = [torch.randn(2), torch.randn(2), torch.randn(2)]
CodePudding user response:
Keep track of all of the drawn coordinates in a set.
plotted_lines = set()
for single_a, single_b in zip(a, b):
if (single_a, single_b) not in plotted_lines and (single_b, single_a) not in plotted_lines:
plot(single_a, single_b)
plotted_lines.add((single_a, single_b))