In Class Activity - Python - More for-loops¶
Problem 0: A more complex for-loop over a dictionary¶
Here is a dictionary purchases
that records a series of purchases, broken down into different categories. Each category is a list of the relevant purchases under that category.
purchases = {}
purchases['entertainment'] = [100., 50.50, 22.12]
purchases['food'] = [5.45, 1.20, 65.20, 5.99, 12.23]
purchases['transportation'] = [24.20, 26.11, 5.03]
Write a nested for-loop to compute the total cost of all the purchases. Alternatively, you can use the python sum
function and a single for-loop.
# your answer goes here
total = 0.
for k in purchases.keys():
mylist = purchases[k]
for l in mylist:
total += l
total
# OR
total = 0.
for k in purchases.keys():
total += sum(purchases[k])
total
Problem 1: Using numpy¶
The code below imports numpy and creates a random matrix A
with 5 rows and 4 columns. The entries in A
are uniform random samples from \(0,\dots,2\).
import numpy as np
import numpy.random as npr
A = npr.randint(0,3,size=(5,4))
A
Use numpy to compute the sum of each column (google the numpy function for sum
)
# Your answer here
np.sum(A,axis=0)
Use numpy to compute the sum of each row
# Your answer here
np.sum(A, axis=1)
Use numpy to compute the overall sum across the entirem atrix
# Your answer here
np.sum(A)