如何解决如何在仅包含键的向后引用的有序字典中最小化距离?
我有一个有序字典,其中包含对字典中其他元素的非周期性引用:
from collections import OrderedDict
ug = OrderedDict(a=[],b=['e'],c=['a','b'],d=['a'],e=[])
现在我想
- 对字典进行排序,以使引用仅指向每个键之前的键,并且
- 最小化有序词典中的“参考距离”。
下面显示了这种距离函数的样子:
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'
键可以简单地表示为数字。
解决方法
一个可选的解决方案可以是:
-
创建给定
OrderDict
的所有可能排列, -
map
每个元素具有您提供的用于测量距离的功能, -
过滤所有
None
,这意味着它们不满足后退条件 参考 -
最终选择带来最小距离的排列
实现:
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]):
# print(j_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
from collections import OrderedDict
import itertools
ug = OrderedDict(a=[],b=['e'],c=['a','b'],d=['a'],e=[])
all_permutations = list(itertools.permutations(ug.items()))
all_permutations = [OrderedDict(item) for item in all_permutations]
mapped = map(distance,all_permutations)
mapped = [(item,iter) for iter,item in enumerate(mapped) if item is not None]
minimal_permutation = min(list(mapped))
print("minimal distance is: " + str(minimal_permutation[0]))
print(all_permutations[minimal_permutation[1]])
输出:
minimal distance is: 6
OrderedDict([('e',[]),('b',['e']),('a',('c',['a','b']),('d',['a'])])
请注意,此解决方案存在风险,因为排列的数量可能因len(ug)
而异,但是另一方面,我无法找到另一种方法来找到最佳排列,而无需逐一检查他们至少一次。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。