CSE 160 Section 7
Sets, Tuples, Itemgetter, and Sorting!
TA1 & TA2
Logistics
Lecture Preview: Sets
Sets
You can imagine a set that contains the values 1 through 6 like this:
1
2
3
4
5
6
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)
Add, Remove, and Discard
Say we have the set s that has elements 1, 2, 3, 4 inside
Add
1
3
2
4
Remove
Discard
Pop
Sets
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)
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
Set Operations
A | B
A & B
A - B
A ^ B
elements only in A
elements only in B
items in both
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 |
Lecture Review: Tuples
Tuples
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) | 🚫 | ✅ |
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,)
Lecture Preview: Sorting
.sort()
listname.sort() sorts a list
Example:
Output:
lst = [2, 1, 3]
lst.sort()
print(lst)
[1, 2, 3]
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]
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]
Lecture Preview: Itemgetter
Why Do We Care About Itemgetter?
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
Sorting with Itemgetter in General
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)
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)
Section Handout Problems
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
Problem 1
def all_unique_words(file_name):
file = open(file_name):
words = file.read()
unique = set(words.split())
file.close()
return len(unique)
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))
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)]
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
Problem 3
a. alphabetical_lst = sorted(lst, key = itemgetter(0))
b. youngest_to_oldest = sorted(lst, key = itemgetter(1))
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)]
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
Problem 4
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”]
Problem 4
def unique_species(plants):
species = set()
for name in cactus:
species.add(name["scientific name"])
return sorted(list(species))
Section Code
** Note that section codes are only given in-person and are not given through email, Ed, or other mediums.