Question presented to candidate: "What operations does a Python set support? Show me how you would find what two collections have in common, what is missing from one of them, and explain when a set is the right data structure in the first place."
What a strong answer should cover:
- A set is an unordered collection of unique, hashable items backed by a hash table, so
x in sis O(1) on average versus O(n) for a list. - The four operations with their operators and methods: union
|, intersection&, difference-, symmetric difference^; the methods accept any iterable (and several of them), the operators need sets. - Comparisons are containment tests:
<=subset,<proper subset,>=/>superset,isdisjointβ sets are only partially ordered, soa < bandb < acan both be False. - In-place forms (
|=,&=,-=,^=,update,intersection_update, ...) and single-itemadd,remove(raisesKeyError) versusdiscard(silent). frozensetis the immutable, hashable variant (usable as a dict key or set element);{}is an empty dict;1,1.0andTruecount as one element; dedup withset()loses order,dict.fromkeyskeeps it.
Code / implementation expected: Yes β a short snippet comparing two collections (common, missing, extra items).