intersection of 2 list of pairs

les_ander at yahoo.com les_ander at yahoo.com
Sun Feb 20 12:24:36 EST 2005


Hi,
I have 2 lists of tuples that look like:
E1=[('a','g'),('r','s')] and
E2=[('g','a'),('r','q'),('f','h')].
In this tuple, the ordering does not
matter, i.e. (u,v) is the same as (v,u).

What I want to do is the following:
given 2 list of tuples, E1 and E2, I want to create another list with
tuples that are common to both. So in the above example I would like
to return ('a','g') as being common.
So far I have the code below but it does not work out properly, I would
be grateful if someone can help me out .
thanks

def list_of_tuples_intersect(E1,E2):

	S1=Set()
	S2=Set()
	for e in E1:
		S1.add((e[0],e[1]))
		S1.add((e[1],e[0]))
	for e in E2:
		S2.add((e[0],e[1]))
		S2.add((e[1],e[0]))
	S= S1 & S2
	SS=Set()
	done=Set()

	for e in S:
		if ((e[0],e[1])  in done) or ((e[1],e[0])  in done):
			continue
		else:
			SS.add((e[0],e[1]))
			done.add((e[0],e[1]))
			done.add((e[1],e[0]))
	return SS




More information about the Python-list mailing list