【问题标题】:Generate pairs having the same attributes from list从列表中生成具有相同属性的对
【发布时间】:2016-05-28 14:07:09
【问题描述】:

假设您有一个项目列表,每个项目都有一组属性。

从具有相同属性的列表中生成所有对的有效算法是什么?

例如,给定一个列表:

[('item1', {'a','b'}), ('item2', {'a'}), ('item3', {'c','b'}), ('item4', {'b'})]

我们应该返回以下四对列表,总共可能六对:

('item1', 'item2') # both have attribute 'a'
('item1', 'item3') # both have attribute 'b'
('item1', 'item4') # both have attribute 'b'
('item3', 'item4') # both have attribute 'b'

现在,最简单的方法是首先生成所有可能的n(n+1)/2 对的列表,然后过滤掉那些没有相似属性的列表,但我怀疑这种方法效率低下,尤其是在对的数量非常大的情况下。

有什么建议吗?

【问题讨论】:

  • 任何编程语言要求?
  • @trincot - 我目前正在使用 python,但这是我真正追求的算法。
  • 我想到的第一个想法是构造一个 HashMap,可能在 O(numberOfAttributes) 中。

标签: algorithm reduction


【解决方案1】:

我建议采用两阶段算法:

arr = [('item1', {'a','b'}), ('item2', {'a'}), ('item3', {'c','b'}), ('item4', {'b'})]

# 1. create map with for each attribute the list of items that have it
mp = {}
for lst in arr:
    for prop in lst[1]:
        if prop not in mp: mp[prop] = []
        mp[prop].append(lst[0])

# 2. for each attribute: add the pairs of items to the result set
result = set()
for prop in mp:
    items = mp[prop]
    # collect all pairs in items list
    for p1 in range(len(items)):
        for p2 in range(p1+1,len(items)):
            result.add((items[p1],items[p2]))

print (result)

输出:

{('item1', 'item4'), ('item1', 'item2'), ('item3', 'item4'), ('item1', 'item3')}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多