【问题标题】:How to get the correct order of copying files in python?如何获得在python中复制文件的正确顺序?
【发布时间】:2019-04-12 08:17:54
【问题描述】:

我正在使用 python 来复制一些文件。但我无法得到正确的复制顺序。

假设我有一堂课:

class Info:
    def __init__(self, source: str, destination: str):
        self.source = source
        self.destination = destination

我有一个Info 的列表。

复制顺序的规则是:

如果 A.destination 包含 B.source,则将 B 放在 A 后面。

例如 这里我们有三个Info

 Id        source         destination
Info1      Root/A    ->    Root/B/A
Info2      Root/B    ->    Root/D/B
Info3      Root/C    ->    Root/A/C

Info1.destination 包含 Info2.source,所以将 Info2 放在 Info1 后面,

Info3.destination 包含 Info1.source,所以将 Info1 放在 Info3 后面。

最终订单是[Info3, Info1, Info2]

我认为最大的困难是一些Info无法比较。

是否有一些有效的算法来实现这一点?谢谢!

【问题讨论】:

    标签: python algorithm sorting tree


    【解决方案1】:

    你可以通过topological sort来做,我在here找到一个版本:

    from collections import deque
    from collections import defaultdict
    
    GRAY, BLACK = 0, 1
    
    def topological(graph):
        order, enter, state = deque(), set(graph), {}
    
        def dfs(node):
            state[node] = GRAY
            for k in graph.get(node, ()):
                sk = state.get(k, None)
                if sk == GRAY: raise ValueError("cycle")
                if sk == BLACK: continue
                enter.discard(k)
                dfs(k)
            order.appendleft(node)
            state[node] = BLACK
    
        while enter: dfs(enter.pop())
        return order
    

    测试代码:

    graph = defaultdict(list)
    graph['A'].append('B')
    graph['B'].append('D')
    graph['C'].append('A')
    
    src_info = {'A': 'Info1', 'B': 'Info2', 'C': 'Info3'}
    res = [src_info[c] for c in topological(graph) if c in src_info]
    
    print(res)
    

    输出:

    ['Info3', 'Info1', 'Info2']
    

    【讨论】:

    • 谢谢告诉我topological sort,我使用包networkx 来解决这个问题。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多