265. Python Program to Total Each Column of a Mini Spreadsheet
HardPhase 3 · Challenge
This one has a few steps, and you know all the tools: try and except, lists, split() and :.2f. Add up Example 1 on paper first.
Overview
Spreadsheet apps add up columns for you, and they must not stop when someone types a word where a number should be. A careful program skips the bad row, says why, and carries on.
Problem Statement
Ilya keeps a small table of numbers. The first line has the column names. Each line after it is one row of numbers, and the last line is end. Rows are numbered from 1, starting with the first line after the names.
Check each row in this order:
- If the row does not have exactly one cell for each column, print
Skipped row <n>: wrong number of cells. - Else, if any cell is not a number, print
Skipped row <n>: <cell> is not a number, with the first bad cell of the row.
A skipped row adds nothing to any column, not even its good cells. Every other row is used.
After end, print Rows used: <count>. Then, for each column in order, print <name>: total <total>, average <average>. The average is the total divided by the number of rows used. Print the totals and averages with 2 decimal places. If no row was used, print only the Rows used: 0 line.
Examples
Example 1. Input:
Mon Tue Wed
10 20 30
5 abc 15
3 4
1.5 2 2.5
end
gives:
Skipped row 2: abc is not a number
Skipped row 3: wrong number of cells
Rows used: 2
Mon: total 11.50, average 5.75
Tue: total 22.00, average 11.00
Wed: total 32.50, average 16.25
Why: row 2 has the word abc, so none of its cells count, not even 5 and 15. Row 3 has only 2 cells. Rows 1 and 4 are used: Mon is 10 + 1.5 = 11.5, and 11.5 ÷ 2 = 5.75.
Example 2. Input:
Sales
7
x
-2
end
gives:
Skipped row 2: x is not a number
Rows used: 2
Sales: total 5.00, average 2.50
Why: 7 and -2 are used. 7 + (-2) = 5, and 5 ÷ 2 = 2.5.
Input
The first line has 1 to 5 column names, with one space between them. Then one row per line, with one space between the cells, and a last line end. A number can be whole, negative or have a decimal point, like -2 or 1.5. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line for each skipped row, as soon as it is read. Then the Rows used: line and one line per column. The tests try 7 different inputs, also a table with no rows, a row with two bad cells, a bad cell at the end of a row, and 1,5 written with a comma.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.