[英]Calculating number of edges between tuples in Python
如果我有元組a
和b
,則嘗試計算元組之間的邊數
例如,如果a = ((0,1),(0,2),(0,3))
和b = (((0),(1,2,3)), ((0,1),(2,3)), ((0,1,2),(3)))
理想的 output 是[3,2,1]
,因為 a - 代表我們擁有的所有邊,b - 我們擁有的所有可能的圖切割。
得出計算此類邊緣總量的解決方案(在我們的示例中為 6):
def cnt_edges(a,b):
edge_cnt = 0
for i in range(len(a)):
node1 = a[i][0]
node2 = a[i][1]
for j in range(len(b)):
inner_node1 = b[j][0]
inner_node2 = b[j][1]
if (node1 in inner_node1 and node2 in inner_node2) or (node1 in inner_node2 and node2 in inner_node1):
edge_cnt += 1
return edge_cnt
a = ((0, 1),(0, 2), (0,3))
b = (((0),(1,2,3)), ((0,1),(2,3)), ((0,1,2),(3)))
cnt_edges(a,b)
我如何為 b 中的每個特定元組計算它?
您正在描述一個圖,您希望以不同的方式對其進行分區,然后計算分區之間有多少條邊。
所以我寫了一個compute_partitions
function,它給定了一些邊緣,會給你根據你的規則對它們進行分區的不同方式。 然后調用一個方法來計算兩個分區之間的“交叉點”。
from typing import List, Tuple
Edge = Tuple[int, int]
Edges = List[Edge]
edges: Edges = [
(0, 1),
(0, 2),
(0, 3),
]
Nodes = List[int]
def compute_partitions(edges: Edges) -> List[Tuple[Nodes, Nodes]]:
# we want to list all the nodes
all_unique_nodes = set(node for edge in edges for node in edge)
# then sort them in ascending order
sorted_nodes = sorted(all_unique_nodes)
# and return a sliding partition
for left_count in range(1, len(sorted_nodes)): # from 1 to len()-1 inclusive
left_nodes = sorted_nodes[0:left_count] # include up to left_count exclusive
right_nodes = sorted_nodes[left_count:] # the rest
yield left_nodes, right_nodes # could be appended into a list otherwise
def count_edges_between(left_nodes: Nodes, right_nodes: Nodes, edges: Edges) -> int:
crossings = 0
for node_a, node_b in edges:
if node_a in left_nodes:
if node_b in left_nodes:
pass
elif node_b in right_nodes:
crossings += 1
else:
raise ValueError("node not in edges")
elif node_a in right_nodes:
if node_b in left_nodes:
crossings += 1
elif node_b in right_nodes:
pass
else:
raise ValueError("node not in edges")
else:
raise ValueError("node not in edges")
return crossings
print(list(compute_partitions(edges)))
for nodes_left, nodes_right in compute_partitions(edges):
print(count_edges_between(nodes_left, nodes_right, edges), nodes_left, nodes_right)
[([0], [1, 2, 3]), ([0, 1], [2, 3]), ([0, 1, 2], [3])]
3 [0] [1, 2, 3]
2 [0, 1] [2, 3]
1 [0, 1, 2] [3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.