Reasoning about Code
Think about the following pieces of code and diagnose them on paper rather than simply typing them into the interpreter.
Sets
A set is an unordered collection of distinct objects. The objects in a set are also called the elements or members of the set. Common operations include:
- The union of two sets A and B is the set containing elements that are either in A or in B.
- The intersection of two sets A and B is the set containing elements that are both A and B.
- The difference between two sets A and B is the set containing elements that are in A but not B.
- The complement of a set A is the set of all elements of the universal set (i.e. set containing all objects under consideration) that are not in A.
Suppose A is a set of strings representing the names of first-year students at Duke and B is a set of strings representing students taking CompSci 101 at Duke. Express each of the following sets in terms of operations on sets A and B.
- the set of first-year students taking CompSci 101
- the set of first-year students who are not taking CompSci 101
- the set of students who either are first-year students or are taking CompSci 101
- the set of students who either are not in their first-year or are not taking CompSci 101
Logic Puzzles
Try these two logic puzzles based on your understanding of these set operations.
Sets in Python
In Python a set does not store duplicates, each value is only stored once. For example, the code below
will generate the outputx = set([1,2,3,1,2,3,1,2,3,1,1,1]) print len(x), x
3, set([1,2,3])
As shown above, a set can be created from a list. Additionally elements can be added to
the set using the set method .add
, e.g.,
s = set() s.add("big") s.add("small") s.add("big") s.add("big") s.add("small") print len(s),s
will generate the output
2, set(['small','big'])