1 of 36

CSE 160 Section 7

Sets, Tuples, Itemgetter, and Sorting!

TA1 & TA2

2 of 36

Logistics

  • HW4 Part 2 (due Friday February 21)
    • Reminder again: Hw 4 Part 1 resubmission open after Part 2 due date
    • Submitting on Gradescope
    • Wait for autograder!

  • Coding Activity 6 (due Wednesday February 26)

3 of 36

Lecture Preview: Sets

4 of 36

Sets

  • Sets are a type of data structure which is unordered and unindexed
  • There can be no duplicates
  • Imagine it as a “bag of values”

You can imagine a set that contains the values 1 through 6 like this:

1

2

3

4

5

6

5 of 36

Sets

You can imagine a set that contains the values 1 through 6 like this:

s = set([1, 2, 3, 4])

s = {1, 1, 1, 1, 1, 1, 2, 3, 4}

1

3

2

4

s = {1, 2, 3, 4}

s = set()

s.add(1)

s.add(2)

s.add(3)

s.add(4)

6 of 36

Add, Remove, and Discard

Say we have the set s that has elements 1, 2, 3, 4 inside

Add

  • adds an element to the set
  • s.add(5)

1

3

2

4

Remove

  • takes out an existing element from the set (Must exist in the set!)
  • s.remove(5)

Discard

  • takes out an element from the set (doesn’t need to be in there already)
  • s.discard(5)

Pop

  • Returns a random element
  • s.pop()
  • Could return 1, 2, 3, or 4

7 of 36

Sets

  • Although you can convert any data structure into a set, you can only add immutable types into a set (just like dict keys)
  • Data types that can not go in a set (mutable types)
    • Dictionaries
    • Lists
    • other sets
  • Data types that can go in a set (immutable types)
    • Integers
    • Floats
    • Booleans (but why would you do this?)
    • Strings
    • Tuples

8 of 36

Looping Through a Set

To see all elements in a set, we can loop through it

Would print 1, 2, 3, 4 in some random order

1

3

2

4

for element in s:

print(element)

9 of 36

Checking If Something Is In A Set

We can use in to see if an element is in a set

Returns True

Returns False

1

3

2

4

2 in s

6 in s

10 of 36

Set Operations

A | B

A & B

A - B

A ^ B

elements only in A

elements only in B

items in both

11 of 36

Set Operations

Set Operation

Code

Adding values

my_set.add(val)

Removing values

my_set.remove(val) #Value must already exist

my_set.discard(val) #Value doesn’t need to exist

Return a random element

my_set.pop()

Return all values in both sets

set_1 | set_2 Or set_1.union(set_2)

Return values found in both sets

set_1 & set_2 Or set_1.intersection(set_2)

Return values only found in set_1

set_1 - set_2 Or set_1.difference(set_2)

Return values not found in both sets

set_1 ^ set_2

12 of 36

Lecture Review: Tuples

13 of 36

Tuples

  • Tuple is a collection which is ordered and unchangeable.
  • Lists and tuples are similar, but have different properties
  • The table at the right shows what kind of things you can do with a tuple, but not a list.
  • Let the data structure be called name. A ✅ means you can do it, a 🚫 means it won’t work

Description

Example

list

tuple

indexing

name[i]

negative indexing

name[-i]

slicing

name[i:j]

checking if item exists

item in name

looping

for item in name

length

len(name)

changing items

name[i] = item

🚫

appending items

name.append(item)

🚫

put in a set

set().add(name)

🚫

use a dict keys

dict(name:val)

🚫

14 of 36

Making a Tuple

These are all ways to make tuples:

Note that to make a one element tuple you need to add a comma after the one value! (1) would not work!

t = tuple([1, 2, 3])

t = (1, 2, 3)

t = (1,)

15 of 36

Lecture Preview: Sorting

16 of 36

.sort()

listname.sort() sorts a list

Example:

Output:

lst = [2, 1, 3]

lst.sort()

print(lst)

[1, 2, 3]

17 of 36

sorted()

sorted(listname) returns a sorted copy of the list

Example:

Output:

lst1 = [2, 1, 3]

lst2 = sorted(lst1)

print(lst1)

print(lst2)

[2, 1, 3]

[1, 2, 3]

18 of 36

Note About In Place Functions

insert(), extend(), reverse(), and sort() are all called in place functions.

Example:

Output:

In-place” means that the list is modified, but the result it returns is None

lst = [2, 3, 1]

result = lst.sort()

print(result)

print(lst)

None

[1, 2, 3]

19 of 36

Lecture Preview: Itemgetter

20 of 36

Why Do We Care About Itemgetter?

  • Very easy way to sort values on multiple attributes
  • Way to sort dictionaries into a list
    • if my_dict is a dictionary, then list(my_dict.items()) will return a list of key value tuple pairs!
  • Super important for hw5!

21 of 36

Itemgetter

Itemgetter returns a function:

from operator import itemgetter

get_3rd_item = itemgetter(2)

get_3rd_item([7, 3, 8]) -> 8

# this is the same as

itemgetter(2)([7, 3, 8]) -> 8

22 of 36

Sorting with Itemgetter in General

  • Useful for when you have a list of tuples where every item inside those tuples corresponds to a particular feature
    • ex: the element at index 0 of every tuple is a name, the element at index 1 of every tuple is an age)
    • lst = [('Anne', 5), ('Bob', 6), ('Carl', 3), ('Elisa', 2), ('Diana', 2)]

  • If you want to sort with the feature in the tuple at the index i, do so like this:
    • sorted_lst = sorted(lst, key = itemgetter(i))

  • Sort by the “least important” feature first (ie a tie breaker), the more important features last

23 of 36

Sorting with Itemgetter

lst = [('Anne', 5), ('Bob', 6), ('Carl', 3), ('Elisa', 2), ('Diana', 2)]

# sort alphabetically by name

alphabetical_lst = sorted(lst, key = itemgetter(0))

# sort by the number (lowest number first)

sorted(lst, key = itemgetter(1))

# sort by the number (highest number first)

sorted(alphabetical_lst, key = itemgetter(1), reverse = True)

24 of 36

Sorting with Itemgetter Based on 2 Criteria

lst = [('Anne', 5), ('Bob', 6), ('Carl', 3), ('Elisa', 2), ('Diana', 2)]

# sort by the number (highest number first), break ties alphabetically

# alphabetize first

sorted_lst = sorted(lst, key = itemgetter(0))

# then sort by number

sorted_lst = sorted(sorted_lst, key = itemgetter(1), reverse = True)

25 of 36

Section Handout Problems

26 of 36

Problem 1

Write a function called all_unique_words(file_name) that takes in a string file_name and returns the number of unique words in the file. You may use the split() function for this problem, which takes in a string and returns a list of the words in the string separated by empty spaces.

Example:

If colors.txt has the content "red green blue green"

Your output should be: 3

27 of 36

Problem 1

def all_unique_words(file_name):

file = open(file_name):

words = file.read()

unique = set(words.split())

file.close()

return len(unique)

28 of 36

Problem 2

What output is produced after running the following piece of code?

from operator import itemgetter

data = [ ("Fred", 3, 5),

("Zeke", 5, 3),

("Sam", 5, 6),

("Mary", 3, 5),

("Ann", 7, 8) ]

def some_key(x):

return len(x[0])

print(sorted(data, key=some_key))

print(sorted(data, key=itemgetter(2), reverse=True))

29 of 36

Problem 2

[('Sam', 5, 6), ('Ann', 7, 8), ('Fred', 3, 5), ('Zeke', 5, 3), ('Mary', 3, 5)]

[('Ann', 7, 8), ('Sam', 5, 6), ('Fred', 3, 5), ('Mary', 3, 5), ('Zeke', 5, 3)]

30 of 36

Problem 3

a. Given a list of tuples in the form (name, age), using itemgetter, return a list names and ages sorted alphabetically in one line of code

b. Given a list of tuples in the form (name, age), using itemgetter, return a list names and ages sorted by increasing age in one line of code

31 of 36

Problem 3

a. alphabetical_lst = sorted(lst, key = itemgetter(0))

b. youngest_to_oldest = sorted(lst, key = itemgetter(1))

32 of 36

Problem 3

c. Using itemgetter, define a function called find_oldest that takes in a list of tuples in the form (name, age) and returns a list of tuples belonging to the oldest people. If there is a tie, return a list of the names and ages of the people sharing the same (oldest) age in a new list in alphabetical order.

For example, given age_list = [ ("Tom", 19), ("Max", 26), ("James", 12), ("Alice", 26), ("Carol", 10) ], find_oldest(age_list) would return [("Alice", 26), ("Max", 26)]

33 of 36

Problem 3

def find_oldest(age_list):

sort_name = sorted(age_list, key=itemgetter(0))

sort_age = sorted(sort_name, key=itemgetter(1), reverse=True)

oldest_age = sort_age[0][1]

ret_list = []

for pair in sort_age:

if(pair[1] == oldest_age):

ret_list.append(pair)

else:

return ret_list # return early since it is sorted

return ret_list

34 of 36

Problem 4

  1. You are given a list of dictionaries representing the scientific and common names of various plants. Write a function called unique_species(plants) that takes in a list of dictionaries and returns a list of all of the unique species by their scientific name sorted alphabetically.

cactus = [{“scientific name”: “Kroenleinia grusonii”,”common

name”: “golden barrel cactus”},

{“scientific name”: “Kroenleinia grusonii”,”common name”: “golden ball”},

{“scientific name”: “Carnegiea gigantea”,”common name”: “saguaro”}]

Should return:

[“Carnegiea gigantea”, “Kroenleinia grusonii”]

35 of 36

Problem 4

def unique_species(plants):

species = set()

for name in cactus:

species.add(name["scientific name"])

return sorted(list(species))

36 of 36

Section Code

** Note that section codes are only given in-person and are not given through email, Ed, or other mediums.