Exercise

Merging months into quarters

Now we saw what to do when we wanted to split quarters into months for more detailed monthly information. But what happens when the opposite is true and we wish to combine data into fewer columns? This is typical when dealing with historical data, when monthly details may not be necessary, or when we need a highly consolidated version of the data for a report.

The key here is to create an index, and then only add to the quarter total quarter in cycles of 3, or until the length of the list. We can do this with the following code:

if index % 3 == 0 or index == len(months):

This code checks whether the index divided by three yields a remainder of 0, or if the index is at the end of the list months. Thus, in a loop it will execute the specified code every three months or when it reaches the end of the list.

The monthly sales are already provided in the code as months, containing the sales from the first two quarters, as well as the first month of Q3. Your task is to generate a new list called quarters that contains the quarterly totals from the first three months (which includes the partial total of Q3).

Instructions

100 XP
  • Initialize an empty list quarters to contain the new quarterly values, and an index variable index set to 1.

  • Create a for loop to find the monthly sales in months:

    • Add the monthly sales to quarter.
    • If it's the end of the quarter or the end of the list months, append your quarterly total to quarters.
    • Reset the quarterly total quarter to 0, increment the index by 1 (this has been done for you).
  • Print the quarterly totals.