如何在仅包含键的向后引用的有序字典中最小化距离?

问题描述

我有一个有序字典,其中包含对字典中其他元素的非周期性引用:

from collections import OrderedDict
ug = OrderedDict(a=[],b=['e'],c=['a','b'],d=['a'],e=[])

现在我想

  1. 对字典进行排序,以使引用仅指向每个键之前的键,并且
  2. 最小化有序词典中的“参考距离”。

下面显示了这种距离函数的样子:

def distance(g):
    total_distance = 0
    ordered = True
    for i,i_key in enumerate(list(g)):
        for j_index,j_key in enumerate(g[i_key]):
            j = list(g).index(j_key)
            print(str(j_key) + ' -> ' + str(i_key) + ' = ' + str(i) + ' - ' + str(j) + ' = ' + str(i-j))
            total_distance += i - j
            if (i < j):
                ordered = False
    
    if ordered:
        print('total_distance: ' + str(total_distance) + '\n')
        return (total_distance)
    else:
        print('not in order\n')
        return None

以下是测试的原始列表:

ug = OrderedDict(a=[],e=[])
distance(ug)

给予

e -> b = 1 - 4 = -3
a -> c = 2 - 0 = 2
b -> c = 2 - 1 = 1
a -> d = 3 - 0 = 3
not in order

这是两个仅具有向后引用的新命令:

og1 = OrderedDict(e=[],a=[],'b'])
distance(og1)

og2 = OrderedDict(a=[],e=[],'b'])
distance(og2)

会产生

a -> d = 2 - 1 = 1
e -> b = 3 - 0 = 3
a -> c = 4 - 1 = 3
b -> c = 4 - 3 = 1
total_distance: 8

a -> d = 1 - 0 = 1
e -> b = 3 - 2 = 1
a -> c = 4 - 0 = 4
b -> c = 4 - 3 = 1
total_distance: 7

如何在订购仅包含对键的反向引用的字典时最小化这种总距离?无需坚持使用OrderedDict数据结构。另外,如果证明其他一些数据结构更简洁,则'a','b',...,'e'键可以简单地表示为数字。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)