给定两组,如何对一组中的每个元素与另一组的每个元素进行成对比较.
我想获得初始集中每个元素的前3个结果.
有没有更快的方法来解决任务.我正在寻找一种更加pythonic的方式来完成任务.
set1 = set([str(item) for item in range(100)]) # Pls. note originally set contains strings
set2 = set([str(item) for item in range(50,150)]) # set([str(item) for item in range(50,100)])
for item in set1:
max = [-1,-1,-1]
for stuff in set2:
val = magicComp(item,stuff)
if val > max[0]:
max[2] = max[1]
max[1] = max[0]
max[0] = val
elif val > max[1]:
max[2] = max[1]
max[1] = val
elif val > max[2]:
max[2] = val
Run Code Online (Sandbox Code Playgroud)
你的答案还不错,它比每次迭代时对数组进行排序要好,但它仍然是 O(N^2)。
由于您知道所需的数组索引,因此您可以使用快速选择算法根据 magicComp 函数在 O(log n) 时间内查找索引 0,1,2。这会将您的运行时间减少到 O(n*log n)
根据该链接中的代码,您的代码将类似于:
results = {}
ls2 = list(set2)
for el in set1:
results[el] = [select(ls2, ii) for ii in [0,1,2]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
429 次 |
| 最近记录: |