python - 用于合并和展平树结构的集合合并

标签 python data-structures merge tree-traversal

我有一组这样的数据:

data = { 1: {"root": [2],
             "leaf": [10, 11, 12],
             },
         2: {"root": [1,3],
             "leaf": [13, 14, 15],
             },
         3: { "root": [2],
              "leaf": [16, 17],
            },
         4: {"root": [],
             "leaf": [17, 18, 19],
             },
         5: { "root": [],
              "leaf": [20, 21]
             },
       }

从这个数据来看,初始键是一个根节点索引,它包含一个解释哪些根节点和叶节点与其相关的字典。

我想将所有索引合并到相关列表中。

  • 一个根索引由一个根索引连接,两者/所有根索引和所有叶索引合并到结果列表中。
  • 根索引可以通过叶连接到另一个根,根索引和所有叶索引都合并到结果列表中。

我在找出遍历和合并数据的最佳方法时遇到了一些麻烦。从上面的数据集中,预期输出是:

[[1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [5, 20, 21]]

Fixed Attempt,好像行得通,有没有更有效的方法?

class MergeMachine(object):
    processed = []

    def merge(self, idx, parent_indexes, existing):
        if idx not in self.processed:
            parent_indexes.append(idx)
            if self.data[idx]["root"]:
                for related_root_idx in self.data[idx]["root"]:
                    if related_root_idx not in self.processed and related_root_idx not in parent_indexes:
                        existing.extend(self.merge(related_root_idx, parent_indexes, existing))
                        self.processed.append(related_root_idx)
            existing.append(idx)
            existing.extend(self.data[idx]["leaf"])
            self.processed.append(idx)
        return existing

    def process(self, data):
        results = []
        self.data = data
        for root_idx in self.data.keys():
            r = set(self.merge(root_idx, [], []))
            if r:
                combined = False
                for result_set in results:
                    if not r.isdisjoint(result_set):
                        result_set.union(r)
                        combined = True
                if not combined:
                    results.append(r)
        return results

mm = MergeMachine()
mm.process(data)

是否有一种有效的方法可以将数据合并到预期的输出中?

最佳答案

我不知道这是否有效,但它似乎有效:

data = #your data as posted

data = [set ( [k] ) | set (v ['root'] ) | set (v ['leaf'] ) for k, v in data.items () ]
merged = []
while data:
    e0 = data [0]
    for idx, e in enumerate (data [1:] ):
        if e0 & e:
            data [idx + 1] = e | e0 #idx is off by 1 as I enumerate data [1:]
            break
    else: merged.append (e0)
    data = data [1:]

print (merged)

我猜想在最坏的情况下(即不可能合并)成本应该是 O(n**2)。而且它是串行的,没有递归。

关于python - 用于合并和展平树结构的集合合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14971652/

相关文章:

python - 使用Application Factory实现Flask-WhooshAlchemy

python - Django:ModelSerializer 的自定义字段映射

c - linux内核模块中的每个任务数据结构

javascript - JS(ES6): Merge arrays based on id and concatenating sub arrays

Git merge 不获取新文件

python - 如何将默认值插入缺失的 csv 字段?

python - 更快地将列表居中的方法

apache-flex - Flash ActionScript 3 中使用的标准映射/关联数组结构?

python 嵌套列表和字典,无法访问和设置

python - pandas:如何通过与另一个面板合并来沿短轴延伸