CSE 160 Section 7
Processing Data
CSE 160: Section 7
Logistics
CSE 160: Section 7
Recap Nested Lists
lst = [10, 20, 30]
# 0 1 2 <- index
lst[0] # 10
len(lst) # 3
grid = [[1, 2, 3],
[4, 5, 6]]
grid[1] # [4, 5, 6] <- a whole row
grid[1][0] # 4 <- row 1, column 0
len(grid) # 2 <- number of rows
len(grid[0]) # 3 <- number of columns
CSE 160: Section 7
Recap Nested Lists
# Making a list
lst = [item0, item1, item2]
# Using a list
lst[i]
len(lst)
lst[i] = x
lst.append(x)
lst[:]
for i in range(len(lst)):
# Nested lists
grid = [[a, b], [c, d]]
grid[i][j]
len(grid[i])
for row in grid:
for x in row:
Syntax | Description |
lst[i] | Get the element at index i |
len(lst) | Return the number of elements in lst |
lst[i] = x | Change the element at index i to x |
lst.append(x) | Add x to the end of the list |
lst[:] | Make a copy of the list |
for i in range(len(lst)): | Loop through every list index |
lst[i][j] | Get element j of the inner list at index i |
for row in lst: for x in row: | Loop through every element of a nested list |
for i in range(len(lst)): for j in range(len(lst[i])): | Loop through every index (i, j) of a nested list |
CSE 160: Section 7
Recap File I/O
f = open("data.csv") # mode "r" (read) by default
for line in f: # line = "1, 2, 5, 0\n"
line.strip() # "1, 2, 5, 0"
line.strip().split(",") # ["1", " 2", " 5", " 0"]
f.close() # close when you're done
CSE 160: Section 7
Recap File I/O
# Opening a file
f = open(path, mode)
f.close()
with open(path, mode) as f:
# Reading and writing
f.read()
for line in f:
f.write(s)
# Cleaning a line
line.strip()
line.split(",")
# Cleaning a line
line.strip()
line.strip(",")
Syntax | Description |
open(path, mode) | Open a file. Mode: "r" read (default), "w" overwrite, "a" append |
f.read() | Return the entire file as one string |
for line in f: | Loop through the file one line at a time |
f.write(s) | Write string s to the file (strings only; add "\n" yourself) |
f.close() | Close the file when you're done |
with open(path, mode) as f: | Open a file; closes it automatically |
s.strip() / s.strip(",") | Remove whitespace (like “\n”), or the given character, from both ends only |
s.split(",") / s.split() | Split s into a list of strings at each “,”; with no argument, split on whitespace |
CSE 160: Section 7
Section Handout Problems
CSE 160: Section 7
Warm-Up Problem!
Practice with lists! (Try not to use the reference sheet)
Function | Description |
lst.append(element) | |
| Adds each of the elements in sequence to the end of lst, returns None |
lst.count(element) | |
lst.insert(index, element) | |
lst.index(element) | |
| Removes and returns the element at index idx in lst. With no parameter, removes the last element in lst |
CSE 160: Section 7
Solutions
Function | Description |
lst.append(element) | Adds element to the end of lst, returns None |
lst.extend(sequence) | Adds each of the elements in sequence to the end of lst, returns None |
lst.count(element) | Returns the number of times element appears in lst |
lst.insert(index, element) | Inserts element into lst at position index, moving the later elements one spot to the right; returns None |
lst.index(element) | Returns the index of the first occurrence of element in lst; raises a ValueError if element is not in lst |
lst.pop(idx) / lst.pop() | Removes and returns the element at index idx in lst. With no parameter, removes the last element in lst |
CSE 160: Section 7
Problem 1 - Part A
You are given a list of friends and a list with the number of clubs they are in. The friend in the first element of friends participates in the number of clubs in the first element of clubs.
friends = ["Mickey", "Minnie", "Goofy", "Pluto"]
clubs = [2, 4, 3, 1]
For example, Mickey is in 2 clubs, Minnie is in 4 clubs, and so on.
Part A. Write a function called get_clubs(name, names, rso) that takes a friend's name and returns the number of clubs they are in.
get_clubs("Mickey", friends, clubs) should return 2
CSE 160: Section 7
Solution - Part A
Part A. Write a function called get_clubs(name, names, rso) that takes a friend's name and returns the number of clubs they are in.
get_clubs("Mickey", friends, clubs) should return 2
def get_clubs(name, names, rso):
for i in range(len(names)):
if names[i] == name:
return rso[i]
return None
CSE 160: Section 7
Problem 1 - Part B
Part B. Write a function called most_clubs(names, rso) that returns the name of the friend that is in the most clubs.
most_clubs(friends, clubs) should return "Minnie"
CSE 160: Section 7
Solution - Part B
Part B. Write a function called most_clubs(names, rso) that returns the name of the friend that is in the most clubs.
most_clubs(friends, clubs) should return "Minnie"
def most_clubs(names, rso):
max_name = names[0]
max_clubs = rso[0]
for i in range(len(names)):
if rso[i] > max_clubs:
max_clubs = rso[i]
max_name = names[i]
return max_name
Alternate Solution:
def most_clubs(names, rso):
max_clubs = max(rso)
max_index = rso.index(max_clubs)
return names[max_index]
CSE 160: Section 7
Problem 2 - Part A
You and your friends are planning a surprise birthday party for one of your friends. You decide that you will each bring a different item with a different quantity and of different prices (in dollars).
Name = ["Adena", "Ben", "Ciara"]
Quantity = [3, 5, 2]
Price = [9.00, 2.50, 5.50]
For example, Adena is bringing 3 of an item that costs $9.00 per item (total of $27.00).
Part A. Write a function called cost that takes in the three lists and returns the total amount of money that all friends combined will spend on the party.
CSE 160: Section 7
Solution - Part A
Part A. Write a function called cost that takes in the three lists and returns the total amount of money that all friends combined will spend on the party.
def cost(names, quantity, price):
total = 0
for i in range(len(names)):
total = total + quantity[i] * price[i]
return total
CSE 160: Section 7
Problem 2 - Part B
Part B. Another friend suggests adding a fourth list called transportation that stores the amount of money each friend spends on transportation to the party (gas money, bus fare, etc.).
transportation = [10, 5, 8]
For example, Adena spends $10 on transportation to the party.
Modify the cost function so that it returns the total amount of money all friends combined spend on supplies and getting to the party.
Hint: use the formula quantity * price + transportation.
CSE 160: Section 7
Solution - Part B
Part B. Another friend suggests adding a fourth list called transportation that stores the amount of money each friend spends on transportation to the party (gas money, bus fare, etc.).
transportation = [10, 5, 8]
For example, Adena spends $10 on transportation to the party.
Modify the cost function so that it returns the total amount of money all friends combined spend on supplies and getting to the party.
Hint: use the formula quantity * price + transportation.
def cost(names, quantity, price, transportation):
total = 0
for i in range(len(names)):
total = total + quantity[i] * price[i] + transportation[i]
return total
CSE 160: Section 7
Problem 2 - Part C
Part C. How easy was it to modify the cost function to include a new “attribute” (e.g. a new cost category)? How easy would it be to include 10 more attributes for each friend’s cost calculation?
CSE 160: Section 7
Solution - Part C
Part C. How easy was it to modify the cost function to include a new “attribute” (e.g. a new cost category)? How easy would it be to include 10 more attributes for each friend’s cost calculation?
- One attribute: easy, just one more parameter and one more term in the formula.
- 10 more attributes: hard, since the function would need 10 more parameters and lists, which gets messy and error-prone.
CSE 160: Section 7
Problem 3 - Part A
You are organizing a fun run with some friends and want to keep track of the results. You store the information in results.txt. Each line contains a participant’s name, their bib number, and their finishing time (in minutes).
results.txt:
James, 135, 35
Ruth, 202, 28
Adrian, 384, 27
Kevin, 491, 32
Part A. Write a function called names that takes the name of a file as an argument and returns a list containing the names of all the runners in the file.
names("results.txt") should return ["James", "Ruth", "Adrian", "Kevin”]
CSE 160: Section 7
Solution - Part A
Part A. Write a function called names that takes the name of a file as an argument and returns a list containing the names of all the runners in the file.
names("results.txt") should return ["James", "Ruth", "Adrian", "Kevin”]
def names(filename):
result = []
file = open(filename)
for line in file:
parts = line.split(",")
result.append(parts[0])
file.close()
return result
CSE 160: Section 7
Problem 3 - Part B
Part B. To organize this runner data, you decide to design a custom data structure. What features should this data structure have to make working with the runner data easier? In what ways would this data structure be similar to a list? In what ways would it be different?
CSE 160: Section 7
Solution 3 - Part B
Part B. To organize this runner data, you decide to design a custom data structure. What features should this data structure have to make working with the runner data easier? In what ways would this data structure be similar to a list? In what ways would it be different?
- Features: keep each runner's name, bib, and time together.
Example: {"Ruth": {"bib": 202, "time": 28}}
- Similar to a list: stores many items; we can loop over it.
- Different: access by label, not number index.
Example: runners["Ruth"]["time"]
CSE 160: Section 7
Exit Ticket!
Describe one type of problem where working with data in lists is easy? What makes a list data structure useful for this problem?
Then, describe a different problem where working with data in lists is hard(er)? What limitations do lists (or the data) pose for this type of problem?
CSE 160: Section 7
Solution
There is no one right answer!
Easy: Storing and processing an ordered collection of similar items
(e.g., exam scores).
- Keeps items in order
- Access any item by index
- Easy to loop through (sum, max, sort)
Hard: Looking up data by a label instead of a position
(e.g., a phone number by name).
- Only number indices, no labels
- Must search the whole list (slow for large data)
- Hard to keep related data paired together
- A dictionary fits better
CSE 160: Section 7
Quest Review
CSE 160: Section 7
Thanks for coming!
CSE 160: Section 7
Problem 3
Create def get_squares(number_list) that accepts a list of numbers as a parameter, and returns a dictionary mapping each number in the list to its square.
For Example:
nums = [1, 4, 4]
get_squares(nums) returns {1:1, 4:16}
CSE 160: Section 7
Problem 4
Write coldest_city(city_temperatures) that takes in a dictionary and return the city (key) with the lowest temperature (value).
For Example:
city_temperatures = {‘Seattle’: 36, ’Cupertino’:39, ‘New York’:57}
coldest_city(city_temperatures) => returns “Seattle”
CSE 160: Section 7
Problem 5 Part a
Write function def pokemon_types(pokemon_dict) that takes parameter pokemon_dict and returns a new dictionary mapping each type of pokemon to the number of pokemon in pokemon_dict with that type.
For example, when
pokemon_dict = {"pikachu": "electric", "charmander": "fire", "charizard" : "fire"}
pokemon_types(pokemon_dict) => returns {“electric” : 1, “fire” : 2}
CSE 160: Section 7
Problem 5 Part b
Write def pokemon_types(pokemon_dict) that takes parameter pokemon_dict and returns a new dictionary mapping each type of pokemon to the list of pokemon with that type.
For example, when
pokemon_dict = {"pikachu": "electric", "charmander": "fire", "charizard": "fire"}
pokemon_types(pokemon_dict) returns =>
{‘electric’ : [‘pikachu’], ‘fire’: [‘charmander’, ‘charizard’]}
CSE 160: Section 7