Skip to main content
 首页 » 编程设计

python之在形成循环引用的列表中查找 3 对集合

2024年09月03日41JustinYoung

希望这是一个非常简单的问题,但我一直在努力解决这个问题。

我有一个通过索引确定的引用点列表。这些索引值是线的起点和终点。 EG Line 1 [1,3] Line2 [4,5] 等

我试图在 Pure Python 中执行以下操作,并且已经运行了如此多的代码迭代,我无法再思考了。我确信这是某种列表管理解决方案...

**List 1:** 
 
[1,3] 
[4,5] 
[2,1] 
[5,1] 
[3,2] 
[4,1] 

我希望从列表 1 中获得以下输出。

**List2** 
[1,3] 
[2,1] 
[3,2] 
 
**List3** 
[4,5] 
[5,1] 
[4,1] 

因此结果是数据组有效地提供了它们之间的循环/三角形关联。

请帮忙,我完全被难住了!

编辑: 我附上了我正在使用的数据结构的草图。您可以看到每条线都有起点和终点引用。并在列表中识别相应的“组”以便能够提取 3 个唯一的引用,这样我就可以生成一个三角形。

Link to Data Structure Example and Desired Output

到目前为止,我已经放弃了我的大部分代码,但尝试使用组合(我不想使用这种方法,因为会有很多数据需要迭代)

def combinations(iterable, r): 
    pool = tuple(iterable) 
    n = len(pool) 
    for indices in permutations(range(n), r): 
        if sorted(indices) == list(indices): 
            yield tuple(pool[i] for i in indices) 
 
input = IN[0] 
result = [] 
 
for i in input: 
    matrix = [] 
    matrix.append(combinations(i,3)) 
    result.append(matrix) 
 
OUT = result 

请您参考如下方法:

这样的事情怎么样?我们基本上只是检查每对相邻的顶点,看看它们是否有任何共同的邻居,如果有,那么就形成了一个三角形。我们任意对点 (x < y < z) 强制执行某种排序,这样我们就不会多次找到同一个三角形。

# given some input: 
pairs = ([ 
[1,3], 
[4,5], 
[2,1], 
[5,1], 
[3,2], 
[4,1] 
]) 
 
# compute the set of neighbors of each vertex 
from collections import defaultdict 
neighbors = defaultdict(set) 
for x, y in pairs: 
  # enforce some arbitrary ordering x < y < z so that 
  # we don't find the same triangle more than once 
  if x < y: 
    neighbors[x].add(y) 
  else: 
    neighbors[y].add(x) 
 
# for each pair of adjacent neighbors 
for (x, y) in pairs: 
  # Optional sorting 
  if x > y: 
    (y, x) = (x, y) 
 
  # (x, y, z) form a triangle if z is a common neighbor of x and y 
  common_neighbors = neighbors[x] & neighbors[y] 
  for z in common_neighbors: 
    print((x,y,z)) 

生成一组三角形(和你说的格式不太一样,但应该是相同的信息内容,你可以根据自己的需要做相应的调整):

(1, 2, 3) 
(1, 4, 5)