在Python中有没有一种优雅的方法来跟踪连接项集?
对于某段代码,我需要找到一种方法来识别某些别名。问题是,我们事先不知道这些别名是什么 以下是我的要求: 如果A和B是别名,B和C是别名,那么A和C也应该是别名。 两组别名以任何方式连接时都应合并。 在每组别名中,一个应为主要别名。 我使用以下解决方案,利用集合字典:在Python中有没有一种优雅的方法来跟踪连接项集?,python,Python,对于某段代码,我需要找到一种方法来识别某些别名。问题是,我们事先不知道这些别名是什么 以下是我的要求: 如果A和B是别名,B和C是别名,那么A和C也应该是别名。 两组别名以任何方式连接时都应合并。 在每组别名中,一个应为主要别名。 我使用以下解决方案,利用集合字典: class Alias(object): def __init__(self, initial): self._set = {initial} self.initial = initial
class Alias(object):
def __init__(self, initial):
self._set = {initial}
self.initial = initial
def add(self, alias):
self._set.add(alias)
def merge(self, other):
self._set.update(other._set)
def __iter__(self):
return iter(self._set)
class AliasDict(object):
def __init__(self):
self._dict = {}
def add(self, one, other):
if one in self._dict:
if other in self._dict: #merge!
self._dict[one].merge(self._dict[other])
for k in self._dict[other]:
self._dict[k] = self._dict[one]
else:
self._dict[one].add(other)
elif other in self._dict:
self._dict[other].add(one)
else:
self._dict[one] = self._dict[other] = Alias(one)
self._dict[one].add(other)
def get(self, n):
return self._dict.get(n)
def __contains__(self, s):
return s in self._dict
这能改进吗?例如,通过使用我搜索过的标准库中的一个类,我可能错过了一些有用的东西。您是否考虑过使用标准库?它的速度几乎是O1,而且似乎完全符合您的要求。您考虑过使用一个吗?它的速度几乎是O1,似乎完全符合您的要求。这是您可以在图形上映射的东西,因此我要做:
from networkx import Graph
from networkx.algorithms.components.connected import connected_components
# see aliases as the edges between nodes in a graph
aliases = [('A', 'B'), ('B', 'C'), ('D','E')]
g = Graph( aliases )
# connected components are alias groups
print connected_components(g) # [['A', 'C', 'B'], ['E', 'D']]
您没有指定哪个别名应该是主别名,因此您最好从这些列表中选择第一个别名
这是可以映射到图表上的东西,所以我会:
from networkx import Graph
from networkx.algorithms.components.connected import connected_components
# see aliases as the edges between nodes in a graph
aliases = [('A', 'B'), ('B', 'C'), ('D','E')]
g = Graph( aliases )
# connected components are alias groups
print connected_components(g) # [['A', 'C', 'B'], ['E', 'D']]
您没有指定哪个别名应该是主别名,因此您最好从这些列表中选择第一个别名
它看起来很有趣,但实际上它看起来比我现在拥有的东西倒退了一步。不过,我不确定。这看起来很有趣,但实际上它看起来比我现在拥有的东西倒退了一步。不过我不确定。