wk1.4

warm-up

Instructions: For each of the following problems, fill out the answer underneath and submit the finished quiz to me via personal slack message. You may consult your notes but please do not use the internet.

  • assign the number 8 to a variable eight.

  • set b equal to eight.

  • print b.

  • Write a boolean expression that will return true if x is 'a' or 'b' and false otherwise.

  • Write a boolean expression that returns true if and only if x is greater than ten and x is odd.

  • write a function that takes a parameter, n, and then returns n (unchanged).

  • write a function that takes a string, str_, and prints the string three times (once per line).

  • Write a program to prompt the user for hours and rate per hour to compute gross pay.

Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
  • given a str1 = "Hello " and a str2 = "World", how can we concatenate (join together) str1 to str2?

  • given a str1 = "Hello", how can we index str1 to get the 'o'? Give two different ways.

  • given a str1 = "Hi", what operation can we do to the string to output "HiHiHiHi"?

  • make a list, lst, containing the numbers 0 through 10.

  • append the string 'hi' to the list
  • remove the 4 from the lst
  • how can you check if 5 is in the lst (your expression should return True if 5 is in the lst, and False otherwise)

  • write a loop that prints each element from 0 through 9

  • write a loop that prints each element from your lst.

  • write a loop that prints out the element multiplied by two for each element from 0 through 9.

  • write a loop that will count from 0 to infinity.

  • write a statement that checks if a variable var is empty.

  • make a tuple containing a single element 'a'

  • make a tuple containing two elements, 'a' and 'b'

  • given a tuple containing 'Dicaprio' and 43, unpack the tuple with the variables name and age.

  • make an empty dictionary, dct.

  • add the key value pairs 'one'/1, 'two'/2, 'three'/3, 'four'/4

  • change the value of three to 'tres'
  • delete the key value pair 'two'/2.

  • write the following loops over dct:

    • a loop that gets the keys
    • a loop that gets the values
    • a loop that prints the key value pairs (not tuple)
    • a loop that prints tuples of the key value pairs.
  • why might we use a dictionary over a list of tuples?

  • Give a definition of the following:

    • mutability/immutability
    • homogeneous/heterogenous datatypes
    • overflow
    • abstraction
    • modularization
  • For each of the following datatypes, write M for mutable or I for immutable, HO for homogeneous or HE for heterogenous: ex. blub: MHO (note blub is not a datatype we will be going over in this class)

    • string
    • list
    • tuple
    • dictionary
  • what is the difference between printing output from a function vs. returning output from a function?

  • what is a variable?
  • what is the difference between aliasing and copying? What type of datatypes does aliasing apply to? Why do we prefer to copy?

Sets and frozen sets

A big difference: sets are mutable, frozen sets are not


In [4]:
# How to make a set

a = {1, 2, 3}

type(a)

# Getting a set from a list
b = set([1, 2, 3])

a == b

# How to make a frozen set

a = frozenset({1, 2, 3})


# Getting a set from a list
b = frozenset([1, 2, 3])


Out[4]:
True

In [12]:
# Getting a set from a string
set("obtuse")


Out[12]:
{'b', 'e', 'o', 's', 't', 'u'}

In [6]:
# Getting a set from a dictionary
c = set({'a':1, 'b':2})
type(c)


Out[6]:
set

In [8]:
# Getting a set from a tuple
c = set(('a','b'))
type(c)


Out[8]:
set

In [7]:
# Sets do not contain duplicates
a = {1, 2, 2, 3, 3, 3, 3}
a


Out[7]:
{1, 2, 3}

In [10]:
# Sets do not support indexing (because they don't preserve order)
a[2]


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-e403a3609bef> in <module>()
      1 # Sets are immutable
      2 
----> 3 a[2]

TypeError: 'set' object does not support indexing

In [ ]:
# Sets cannot be used for dictionary keys because they are mutable but frozensets can be used for dictionary keys.

In [14]:
# Adding elements to a set
s = set([12, 26, 54])
s.add(32)
s # If we try to add 32 again, nothing will happen


Out[14]:
{12, 26, 32, 54}

In [15]:
# Updating a set using an iterable
s.update([26, 12, 9, 14]) # once again, note that adding duplicates has no effect.
s


Out[15]:
{9, 12, 14, 26, 32, 54}

In [ ]:
# making copies of sets
s2 = s.copy()

Testing membership


In [16]:
32 in s


Out[16]:
True

In [17]:
55 in s


Out[17]:
False

Subsets and supersets


In [18]:
s.issubset(set([32, 8, 9, 12, 14, -4, 54, 26, 19]))


Out[18]:
True

In [19]:
s.issuperset(set([9, 12]))


Out[19]:
True

In [20]:
# Note that subset and superset testing works on other iterables

s.issuperset([32, 9])


Out[20]:
True

In [ ]:
# We can also use <= and >= respectively for subset and superset testing
set([4, 5, 7]) <= set([4, 5, 7, 9])
set([9, 12, 15]) >= set([9, 12])

Removing items


In [21]:
s = set([1,2,3,4,5,6])
s.pop()


Out[21]:
1

In [ ]:
s.remove(3)

In [ ]:
s.remove(9) # Removing an item that isn't in the set causes an error

In [22]:
s.discard(9) # discard is the same as remove but doesn't throw an error

In [24]:
s.clear() # removes everything
s


Out[24]:
set()

Iterating over sets

Big takeaway: you can do it but good luck guessing the order


In [25]:
s = set("blerg")
for char in s:
    print(char)


l
e
r
g
b

Set operations

Intersection

Any element which is in both $S_1$ and $S_2$ will appear in their intersection.


In [27]:
s1 = set([4, 6, 9])
s2 = set([1, 6, 8])
s1.intersection(s2)


Out[27]:
{6}

In [28]:
s1 & s2


Out[28]:
{6}

In [29]:
s1.intersection_update(s2) # updates s1 with the intersection of s1 and s2
s1


Out[29]:
{6}

Union

The union is the merger of two sets. Any element in $S_1$ or $S_2$ will appear in their union.


In [30]:
s1 = set([4, 6, 9])
s2 = set([1, 6, 8])
s1.union(s2)


Out[30]:
{1, 4, 6, 8, 9}

In [31]:
s1 | s2


Out[31]:
{1, 4, 6, 8, 9}

In [ ]:
# To update using union, simply use update

Symmetric difference (xor)

the set of elements which are in one of either set, but not in both.


In [48]:
s1 = {8, 1, 6, 5, 3}
print(s1)
s2.update([7])
print(s2)


{8, 1, 3, 5, 6}
{8, 1, 6, 7}

In [49]:
s1.symmetric_difference(s2)


Out[49]:
{3, 5, 7}

In [56]:
(s1 | s2) - (s1 & s2) == s1 ^ s2


Out[56]:
True

In [33]:
s1 ^ s2


Out[33]:
{1, 4, 8, 9}

In [37]:
s1.symmetric_difference_update(s2)
s1


Out[37]:
{1, 4, 8, 9}

Set Difference

Elements in $S_1$ but not in $S_2$


In [35]:
s1 = set([4, 6, 9])
s2 = set([1, 6, 8])

s1.difference(s2)


Out[35]:
{4, 9}

In [36]:
s1 - s2


Out[36]:
{4, 9}

In [38]:
s1.difference_update(s2)
s1


Out[38]:
{4, 9}

Important points

Union, intersection and difference also work with more than two sets

Everything except for the update methods work with frozen sets

Set - Exercises

  • Create the set {'cat', 1, 2, 3}, call it s.
  • Create the set {'c', 'a', 't', '1', '2', '3'}.
  • Create the frozen set {'cat', 1, 2, 3}, call it fs.
  • Create a set containing the frozenset fs, it should look like {frozenset({'cat', 2, 3, 1})}.

  • create two new sets a and b such that

    • The symmetric difference contains 'a', 'b', 'c'
    • the intersection contains 1, 3, and 5
    • the difference between a and b (note the ordering) contains 'a'.
    • the union contains 1, 3, 5, 'a', 'b', 'c'

Just for fun:

  • is the set of even integers a subset of integers?
  • Is the set of even integers a superset of integers?
  • is the set of even integers the same size as the set of integers?

In [ ]: