Part 1
In part 1, we have a file containting a list of prices and are asked to find the sum of all prices.
After reading in the file into a list of numbers, we use the built-in function `sum` to get the total.
Part 2
In part 2, we should return the sum of the prices while excluding the 20 most expensive items.
For this, we first sort the prices and then exclude the last 20 elements. Summing the rest up returns the answer.
Part 3
In part 3, we have to total the prices while alternating between adding and subtracting the current price to the total. Starting with the first price, subtracting the second, adding the third, subtracting the fourth, ...
Alternating the operations means we can split the list into two parts. The odd indizes are all added, while the even indizes are all subtracted. The answer is obtained by summing the first part while subtracting the sum of the second part.
We used the list iterators in Python to get every second element starting with index 0 and summed it up. The same was done using every second element with index 1. The answer was then the first sum minus the second sum.
No comments:
Post a Comment