Module 13: Tuples, Sets, and Dictionaries | CMSC 105 Elementary Programming - Fall 2024

Module 13: Tuples, Sets, and Dictionaries

Note: Create a text file called module13.txt where you will store you answers to exercise questions. The questions that are not related to changing code. You will submit this file on Blackboard along with your code.

Objectives

By the end of this module you will be able to:

Tuples

Suppose we want to write a function that computes both the square and cube of a number:

Tuples are similar to lists in many ways, but different in one crucial aspect:

Thus, you can replace a list element but you cannot replace a tuple element.

Once the tuple is instantiated (that’s the technical term for “made”) then the tuple’s value cannot be changed.

Here, we’re simply replacing one fixed-value tuple with another.

Groups of tuples can be combined into lists and other data structures.


Exercise 1: Type up the above in my_tuple_example.py. Then trace through the iteration in your module13.txt.


Exercise 2: Consider the following:

import math

def distance(p, q):
    return math.sqrt( (p[0]-q[0])**2 + (p[1]-q[1])**2 )

def find_closest_point(p, L):
    # Write your code here to find the closest point in L to p
    # and to return both the point and the distance to it from p.

list_of_points = [(3,4), (1,2), (3,2), (4,3), (5,6)]
query_point = (5,4)
(c, d) = find_closest_point(query_point, list_of_points)
print('closest:',c,' at distance', d)
# Should print: 
# closest: (4, 3)  at distance 1.4142135623730951

In my_tuple_example2.py, fill in the missing code to find the closest point in a list of points to a given query point. Return both the closest point and the distance to the query point as a tuple.


Sets

The general mathematical term set means a “collection of like things but without duplicates”.

Python has special syntax and operations to support this mathematical notion:

The first set contains five numbers, whereas the second contains four strings.

Consider this variation

A = {2, 4, 5, 6, 8}
B = {'hello', 'hi', 'hey', 'howdy'}

C = {8, 5, 4, 6, 2, 4, 5, 5}
print(C)

if A == C:
    print('they are equal')
else:
    print('they are not equal')

Given what we’ve said about sets, what will be printed?


Exercise 3: Type up the above in my_set_example.py to find out.


Note:

What can we do with sets?

Here, D contains every element across both sets.

Dictionaries

Consider this problem:

Download the file here: fruits.txt

fruits.txt

apple
banana
apple
pear
banana
banana
apple
kiwi
orange
orange
orange
kiwi
orange

This might represent, for example, a record of sales at a fruit stand.


Exercise 4: Type up the above in my_fruits.py and use the data file fruits.txt to confirm. Next, in my_fruits2.py, change the program to accommodate the additional fruits in fruits2.txt.

Download the file here: fruits2.txt

fruits2.txt

apple
banana
apple
pear
banana
banana
apple
kiwi
orange
plum
orange
orange
kiwi
plum
orange
peach

Aside from being tedious, this approach has other issues:

Fortunately, the use of dictionaries will make it easy:

# Make an empty dictionary
counters = dict()

with open('fruits.txt','r') as data_file:
    line = data_file.readline()
    while line != '':
        fruit = line.strip()
        if fruit in counters.keys():
            # If we've seen the fruit before, increment.
            counters[fruit] += 1
        else:
            # If this is the first time, set the counter to 1
            counters[fruit] = 1
        line = data_file.readline()

print(counters)

Exercise 5: Type up the above in my_fruits3.py and first apply it to fruits.txt and then to fruits2.txt. (Submit your program with the latter file as the input file.) In your module13.txt, describe what you had to change in the code to make it work for the second file.

Now let’s explain:

With this understanding we can now revisit the code in the fruit example: