0

Task is find number of equal elements in 2 lists,which are contain lists. I have 2 lists which looks like

DNF1=[[4], [12], [20], [28,32], [36], [44], [52,54], [60,4],[60,24]]
DNF2=[[16], [20,60], [24], [28,32], [48], [52], [56,58], [60,4]]

This code does not work cause arguments are lists:

 count=sum(1 for k in DNF1 if k in DNF2)

How can I write

func(DNF1,DNF2)

which will return

[[28,32],[60,4]]

or just '2' (amount of elements in intersection)

2 Answers2

5

You could do something like this:

DNF1 = [[4], [12], [20], [28, 32], [36], [44], [52, 54], [60, 4], [60, 24]]
DNF2 = [[16], [20, 60], [24], [28, 32], [48], [52], [56, 58], [60, 4]]


intersection = set(map(tuple, DNF1)) & set(map(tuple, DNF2))
result = [list(e) for e in intersection]
print(result)

Output

[[60, 4], [28, 32]]

The idea is to convert DNF1 and DNF2 to sets, but as list are not hashable you need to convert them to tuples. Once you have DNF1 and DNF2 as sets find the intersection and convert back to list each element in the intersection. The complexity of this approach is O(n).

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
2

Using list comprehension:

[DNF1[i] for i in range(len(DNF1)) if len(DNF1[i]) > 1 and DNF1[i] in DNF2 ]

[[28, 32], [60, 4]]
meW
  • 3,832
  • 7
  • 27