【发布时间】:2011-01-07 02:57:23
【问题描述】:
我需要找到所有共享任何相互元素的子数组并将它们合并到一个子数组中。 (用 Python 实现,但任何算法想法都会有所帮助)
多维数组结构:
categories = {'car':['automobile','auto'],
'bike':['vehicle','motorcycle','motorbike','automobile'],
'software':['computer','macbook','apple','microsoft','mozilla'],
'firefox':['internet','mozilla','browser']
'bicycle':['vehicle']}
我想将“汽车”、“自行车”和“自行车”合并到一个列表中(保留第一个列表的键新列表的键可以是任何相关键)和“软件” ' 和 'firefox' 也合并到一个列表中。
性能至关重要。
到目前为止,我能想到的最佳解决方案是保持 element => list_key 的扁平一维数组(例如,'automobile ' => 'car') 然后对多维数组中的每个列表运行以下递归函数(伪代码):
function merge_similar(list_key):
For each element in categories[list_key]:
If flatten_array.has_key(element):
list_to_merge = flatten_array[element]
merge_similar(list_to_merge) /* merge other lists which share an element with our newly found similar list */
categories[list_key] = merge(categories [list_key], categories[list_to_merge])
delete categories[list_to_merge]
知道如何提高它的性能吗?
谢谢!
【问题讨论】:
-
不确定“保留第一个列表的键”是否有意义,因为它们是字典键,因此是无序的。 “第一”在该语句中没有任何意义。
-
新列表的键实际上并不重要 - 已修复。谢谢
标签: python performance algorithm arrays