Python 3D Academyবাংলা

Sets in practice

🌍 In real life. A teacher checks a homework rule: "Use every vowel at least once." Another asks: "Did anyone hand in twice?" And a shop keeps the order customers came in, but only wants each customer once. These are everyday jobs where "one of each" is the whole point.

This lesson puts sets to work on jobs like these.

The idea in one sentence: compare whole sets with == and <=, find repeats by comparing len(set(x)) with len(x), and pair a seen set with a list when the order matters.

Its words:

  • subset: a <= b is True when every value of a is also in b
  • equal sets: {1, 2} == {2, 1} is True: the same values, order doesn't matter
  • order-keeping dedupe: remove repeats but keep the first-seen order, using a set and a list together

Step by step, does "hello" repeat a letter?

  1. set("hello") keeps h, e, l, o: 4 different letters.
  2. len("hello") is 5.
  3. 4 isn't 5, so some letter repeats.
print({1, 2} == {2, 1})
print({"a"} <= {"a", "b"})
print({"c"} <= {"a", "b"})

set(word) gives the different letters of a word, so it's quick to check things like "does this word repeat a letter?"

word = input("Word: ")
print(len(set(word)) == len(word))
False: hello has 5 letters but only 4 different ones.

A set forgets the order, so to remove repeats and keep the order, use a seen set together with a list:

words = ["b", "a", "b", "c", "a"]
seen = set()
order = []
for w in words:
    if w not in seen:
        seen.add(w)
        order.append(w)
print(order)
word = input("Word: ")
print({"a", "e", "i", "o", "u"} <= set(word))
True: education uses every vowel.

A set that can't change: frozenset. A set can't be a dictionary key or sit inside another set, because it can change: {{1, 2}: "x"} gives TypeError: cannot use 'set' as a dict key (unhashable type: 'set'). A frozenset is a set that never changes. It has in, len, |, & and <=, but no add or remove, so it can be a key: for example the ingredients of a dish, whatever order they are listed in.

menu = {frozenset({"rice", "dal"}): "khichuri", frozenset({"rice", "egg"}): "egg fried rice"}
have = frozenset({"dal", "rice"})
print(menu[have])
print("egg" in have, len(have))

What it costs. Turning a list into a set takes one pass over the list. After that, each in is a fast hash lookup. Compare the two ways to check a list of n names for repeats:

  • with a nested loop, comparing every name with every other: about n × n comparisons; for 10,000 names, 100 million
  • with a seen set: one pass, about 10,000 quick lookups

Mistakes and edge cases.

  • Losing the order. list(set(words)) removes repeats but scrambles the order; use the seen + list pattern above.
  • Indexing the result. set(names)[0] gives TypeError: 'set' object is not subscriptable.
  • < and <=. a < b means a is a subset and smaller than b, so {1} < {1} is False, while {1} <= {1} is True.
  • Letters, not words. set("a cat") holds the letters and the space, not the words; use set(text.split()) for words.

Quiz

  1. What does this print?

    print({3, 1} == {1, 3})
  2. What does this print?

    print({"a", "b"} <= {"a"})
  3. What does this print?

    seen = set()
    order = []
    for w in ["x", "y", "x"]:
        if w not in seen:
            seen.add(w)
            order.append(w)
    print(order)
  4. Why use a set for seen instead of a list?

    • Checking `in` a set is very fast, and repeats are dropped anyway
    • A set keeps the order of the items
    • Lists can't use `in`
  5. What does this print?

    print(len(set([1, 1, 2]) | {3}))
  6. Which line stops this program with an error?

    names = ["Bo", "Ana", "Bo"]
    unique = set(names)
    print(unique[0])

Coding tasks

  1. Ask for some words on one line. Print them without repeats, keeping the order in which each word first appeared, on one line separated by spaces.

  2. Ask for a word. Print True if no letter appears twice in it, otherwise False.

  3. Ask for a sentence in lowercase. Print True if it uses all five vowels (a, e, i, o, u) somewhere, otherwise False.