Introduction to Computer Science
CompSci 101 : Spring 2014

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:

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.

  1. the set of first-year students taking CompSci 101
  2. the set of first-year students who are not taking CompSci 101
  3. the set of students who either are first-year students or are taking CompSci 101
  4. 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

x = set([1,2,3,1,2,3,1,2,3,1,1,1])
print len(x), x
will generate the output
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'])