Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Using sets to compute unique elements
Set operations
7. Set operations – review
Simulating machines
Summary

Instruction

Great! Let's have a quick review of basic set operations in Python before we learn more about them:

  1. To find elements that are both in set A and set B (in other words, to find the intersection of sets A and B), you can use the .intersection() method or an & operator:
    A.intersection(B)
    A & B
    
  2. To find elements that are either in set A or set B (in other words, to find the union of sets A and B), you can use the .union() method or a | operator:
    A.union(B)
    A | B
    
  3. To find elements that are in set A but not in set B (in other words, to find the difference of sets A and B), you can use the .difference() method or a - operator:
    A.difference(B)
    A - B
    
  4. To find elements that are either in set A or set B but not in both sets (in other words, to find the symmetric difference of sets A and B), you can use the .symmetric_difference() method or an ^ operator:
    A.symmetric_difference(B)
    A ^ B
    
  5. You can also check if set A is a subset of set B. Use the .issubset() method or a <= operator:
    A.issubset(B)
    A <= B
    
  6. Similarly, to check if set A is a superset of set B, you can use the .issuperset() method or an >= operator:
    A.issuperset(B)
    A >= B
    

Note: set A is a superset of set B if and only if set B is a subset of set A.

Exercise

Write a function named check_words(word1, word2) that accepts two strings and checks if we can create one of these strings using the letters from the other string (using each letter as many times as we need to). The function should return True if we can create word1 from the letters in word2 or if we can create word2 from the letters in word1. Otherwise, it should return False.

Stuck? Here's a hint!

For each string, create a set of letters in that string. Then, check if the first set of letters is a subset or superset of the other string.