High School Reunion Solution¶
(dailywts[5::7] + dailywts[6::7])/2
# array([183.9, 182.5, 181.1, 179.7, 178.3])
Explanation¶
We can use slicing to get the weights for every Saturday. (Keep in mind, index 0 represents a Monday, so the first Saturday occurs at index 5.)
dailywts[5::7] # (1)!
# array([184. , 182.6, 181.2, 179.8, 178.4])
- This is like telling NumPy "give me every value from index 5 to the end of the array, stepping by 7"
Similarly, we can use dailywts[6::7]
to select the weights for every Sunday.
dailywts[6::7]
# array([183.8, 182.4, 181. , 179.6, 178.2])
We can calculate the total weight per weekend by adding these same-sized arrays.
dailywts[5::7] + dailywts[6::7] # (1)!
# array([367.8, 365. , 362.2, 359.4, 356.6])
- Here, NumPy uses element-wise addition.
Lastly, we can get the average weight per weekend by dividing by the previous array by 2.
(dailywts[5::7] + dailywts[6::7])/2 # (1)!
# array([183.9, 182.5, 181.1, 179.7, 178.3])
- NumPy divides each element of the array by 2, thanks to broadcasting.