3

Suppose I have an object called Node

Node has two properties, name and age

I have a set of Nodes called set1 and another called set2

I want to get the intersection of set1 and set2.

However I want the comparisons within the intersection method to be purely based on the name property.

This is done by overriding the __eq__ method.

This means if Node("Jenna", 54) existed in set1 and Node("Jenna", 29) existed in set2 then one of those Nodes will exist in the instersection.

How do I force the intersection to keep the Node from set1 if it exists in the intersection with set2.

I.e - in the above example, how do I force the intersection to contain Node("Jenna", 54) and NOT Node("Jenna", 29) ?

Any ideas?

Greg Peckory
  • 7,700
  • 21
  • 67
  • 114
  • Later sets will always replace items in earlier sets, I think, so you could order the intersection on that basis (i.e. `set2.intersection(set1)`). But it seems like you aren't really using sets semantically if you care which element is in the output. – jonrsharpe Nov 12 '17 at 12:17
  • I've tried reversing the order of the operation.. it made no difference. – Greg Peckory Nov 12 '17 at 12:18

1 Answers1

0

Take a look at: What's the algorithm of 'set.intersection()' in python?

If you override __eq__ and __hash__ it could work, but intersection will keep elements of the shortest set.

Another way to do that is this:

s2_names = {n.name for n in s2}
inter = {n for n in s1 if s1.name in s2_names}
ptitpoulpe
  • 684
  • 4
  • 17