Having the following problem. I'm reading the data from stdin and save it in list that I convert to tuple the following way:
x = int(input())
f = []
for i in range(x):
a, b = map(int, input().split())
f.append([a,b])
def to_tuple(lst):
return tuple(to_tuple(i) if isinstance(i, list) else i for i in lst)
After this I receive two tuples of tuples looking something like that:
f = ((0, 1), (1, 2), (0, 2), (0, 3))
s = (((0,), (1, 2, 3)), ((0, 1), (2, 3)), ((0, 1, 2), (3,)))
What I'm trying to do is to find the number of intersections between all inner tuples of f
and each tuple of s
. In my case "intersection" should be considered as an "edges" between tuples (so in f
we have all possible "edges" and checking if there will be an edge between inner tuples in particular tuple of s
). So for the example it should print [3,2,1]
.
Basically, I know how to do in the simple case of intersection - so one can just use set()
and then apply a.intersection(b)
But how should I proceed in my case?
Many thanks and sorry if the question was already asked before :=)
CodePudding user response:
I am sure this can be solve by different ways. but I believe this is the easiest.
out = set() # holds the output
for ff in f: # loop through f tuple
ff = set(ff) # convert to set
for ss1,ss2 in s: # loop through s tuple
ss1 = set(ss1) # convert to set
ss2 = set(ss2)
out.add(x for x in ff.intersection(ss1)) # intersection and add to out
out.add(x for x in ff.intersection(ss2)) # intersection and add to out
#if you want your output to be in list format
out = list(out)
CodePudding user response:
This is an example of how you can proceed
a = ((1,1),(1,2))
b = (((1,2),(3,1)),((3,2),(1,2)),((1,4),))
for t in b:
c=[i for i in a for j in t if i==j]