gpt4 book ai didi

python - 在 python 中查找对称对

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:46 25 4
gpt4 key购买 nike

我有以下代码可以从给定的输入中查找并打印所有对称对。

'''
Given a list of number pairs.
If pair(i,j) exist, and pair(j,i) exist report all such pairs.
'''

def find_all_symmetric_pairs(inp_dic):

for key in inp_dic:
val = inp_dic[key]

if inp_dic[val] == key:
return key,val
return -1,-1


inp_dic = {'1':'3','2':'6','3':'5','7':'4','5':'3','8':'7'}

print type(inp_dic)
key,value = find_all_symmetric_pairs(inp_dic)

print "key:"+str(key)
print "value:"+str(value)

输出:

 key:3
value:5

但是如果我将输入更改为

inp_dic = {(1,3),(2,6),(3,5),(7,4),(5,3),(8,7)}

inp_dic = {{1,3},{2,6},{3,5},{7,4},{5,3},{8,7}}

我很难迭代。我如何实现相同的目标?

最佳答案

这似乎是一个有用的解决方案:

d = {'1':'3','2':'6','3':'5','7':'4','5':'3','8':'7'}
pairs = [(key, value) for key, value in d.items()]
answer = [(x, y) for (x, y) in pairs if (y, x) in pairs]
print(answer)

输出

[('3', '5'), ('5', '3')]

如果我们将 pairs 设为 set 而不是 list 也可能会更快:

d = {'1':'3','2':'6','3':'5','7':'4','5':'3','8':'7'}
pairs = {(key, value) for key, value in d.items()}
answer = [(x, y) for (x, y) in pairs if (y, x) in pairs]
print(answer)

输出

[('3', '5'), ('5', '3')]

关于python - 在 python 中查找对称对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34795434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com