Implementation of set reconciliation algorithm

后端 未结 3 2001
别跟我提以往
别跟我提以往 2021-02-04 18:56

I\'m looking for implementations of set reconciliation algorithm. The problem is following: there are two sets with elements identified by some relatively compact value (e.g. UU

3条回答
  •  温柔的废话
    2021-02-04 19:10

    This code is out of my head, and thus covered by whatever license applies for code samples in this site.

    # given two finite sequences of unique and hashable data,
    # return needed opcodes and data needed for reconciliation
    
    def set_reconcile(src_seq, dst_seq):
        "Return required operations to mutate src_seq into dst_seq"
        src_set= set(src_seq) # no-op if already of type set
        dst_set= set(dst_seq) # ditto
    
        for item in src_set - dst_set:
            yield 'delete', item
    
        for item in dst_set - src_set:
            yield 'create', item
    

    Use as follows:

    for opcode, datum in set_reconcile(machine1_stuff, machine2_stuff):
        if opcode == 'create':
            # act accordingly
        elif opcode == 'delete':
            # likewise
        else:
            raise RuntimeError, 'unexpected opcode'
    

提交回复
热议问题