在python字典中计算“唯一对”的数字?

2024-10-17 08:36:56 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:编辑过的打字错误;字典的键值应该是字典,而不是集合。在

我将保留这里的打字错误,因为下面的问题解决这个问题。我很抱歉给你添麻烦。在

问题是:

假设我有一个不重复的整数列表:

list1 = [2, 3]   

在这种情况下,有一个唯一的对2-3和3-2,因此字典应该是:

^{pr2}$

也就是说,有1对2-3和1对3-2。在

对于较大的列表,配对是相同的,例如

list2 = [2, 3, 4]

有双亲吗

{2:{3: 1}, 3:{2: 1}, 3:{4: 1}, 4:{3: 1}, 2:{4: 1}, 4:{2: 1}}

(1)一旦列表的大小变得更大,如何使用python数据结构在算法上找到这种格式的“唯一对”?在

(2)我提到列表不能有重复的整数,例如

[2, 2, 3]

不可能,因为有两个2

但是,可能有一个列表:

list3 = [[2, 3], [2, 3, 4]] 

因此字典必须是

{2:{3: 2}, 3:{2: 2}, 3:{4: 1}, 4:{3: 1}, 2:{4: 1}, 4:{2: 1}}

因为有两对2-3和3-2。如果给定一个列表中有多个列表,那么如何“更新”字典?在

这是一个算法问题,我不知道最有效的解决方案。我的想法是以某种方式将值缓存在一个列表中并枚举对…但这太慢了。我猜itertools中有一些有用的东西。在


Tags: 算法编辑数据结构列表字典格式错误情况
2条回答

{g}每一个问题的复杂度都取决于第一个问题列表的复杂度,将这些插入到输出dict(恒定复杂性)。在

import os 
import sys 


def update_results(result_map, tup):
    # Update dict inplace
    # Don't need to keep count here
    try:
        result_map[tup] += 1
    except KeyError:
        result_map[tup] = 1
    return


def algo(input):
    # Use dict to keep count of unique pairs while iterating
    # over each (key, v[i]) pair where v[i] is an integer in 
    # list input[key]
    result_map = dict()
    for key, val in input.items():
        key_pairs = list()
        if isinstance(val, list):
            for x in val:
                if isinstance(x, list):
                    for y in x:
                        update_results(result_map, (key, y))
                else:
                    update_results(result_map, (key, x))
        else:
            update_results(result_map, (key, val))
    return len(result_map.keys())


>>> input = { 1: [1, 2], 2: [1, 2, [2, 3]] }
>>> algo(input)
>>> 5

我很确定有一种更精细的方法来做这件事(同样,这取决于你问题的确切规格),但这可能会让你开始(没有进口)

你要做的是对列表中的组合产生的对进行计数。你可以找到那些带有Countercombinations的。在

from itertools import combinations
from collections import Counter

list2 = [2, 3, 4]

count = Counter(combinations(list2, 2))

print(count)

输出

^{pr2}$

至于列表列表,我们用每个子列表的结果更新Counter。在

from itertools import combinations
from collections import Counter

list3 = [[2, 3], [2, 3, 4]]

count = Counter()

for sublist in list3:
    count.update(Counter(combinations(sublist, 2)))

print(count)

输出

Counter({(2, 3): 2, (2, 4): 1, (3, 4): 1})

相关问题 更多 >