The goal is to understand how use list comprehensions and perform set.
List Comprehensions
A list comprehension allows you to create lists quickly using syntax that looks like set-builder notation.
==============================
a = [k*k for k in range(5)]
b = [k for k in range(13) if k%2 == 0]
==============================
The list a contains the squares of 0 to 4 and b contains all even numbers from 0 to 12.
Sets and Set Operations
Sets are similar to lists, but they cannot have repeated entries and have special set operations.
==============================
A = set([1,2,3,4,5])
B = set([3,4,5,6,7])
==============================
- (a)
- We can determine the membership of an element x in a set A:
==============================
x in A
============================== - (b)
- In the case of a finite set, we can compute its cardinality:
==============================
len(A)
============================== - (c)
- We can determine if a set A is a subset of another set B:
==============================
A.issubset(B)
============================== - (d)
- Unions:
==============================
A.union(B)
============================== - (e)
- Intersection:
==============================
A.intersection(B)
============================== - (f)
- Set Differences:
==============================
A.difference(B)
==============================
Problems
- (a)
- Use list comprehensions to create the following lists:
- (i)
- The list of all of the odd numbers from 1 to 100.
- (ii)
- The list of all letters in your name that are not ‘e’. (Hint: a string can be iterated over.)
- (b)
- Suppose and
- (i)
- Compute .
- (ii)
- Compute .
- (iii)
- Compute .
- (iv)
- Compute .