Problem 105042 · medium · Level 01 Prerequisites & Setup

Which Total Do You Divide By?

two-way tables · percentages · nested dictionaries · reading a table

A cinema counted tickets by day (the rows) and film (the columns). The table is a dictionary from day to a dictionary from film to the number of tickets; every day lists the same films. The same table answers three different questions, depending on which total a count is divided by:

  • by = "row": of the tickets sold on that day, what percentage were for each film?
  • by = "column": of the tickets sold for that film, what percentage were sold on each day?
  • by = "total": what percentage of all tickets does each cell hold?

Write table_percentages(table, by) that returns a new table of the same shape, with every count replaced by 100 * count / total for the chosen total. A cell whose total is 0 becomes 0.0. Do not round, and do not change table.

Examples

Input:  table = {"Fri": {"Robots": 30, "Ponies": 10},
                 "Sat": {"Robots": 20, "Ponies": 40}}
by = "row"     ->  {"Fri": {"Robots": 75.0, "Ponies": 25.0}, "Sat": {"Robots": 33.33333333333333, "Ponies": 66.66666666666667}}
by = "column"  ->  {"Fri": {"Robots": 60.0, "Ponies": 20.0}, "Sat": {"Robots": 40.0, "Ponies": 80.0}}
by = "total"   ->  {"Fri": {"Robots": 30.0, "Ponies": 10.0}, "Sat": {"Robots": 20.0, "Ponies": 40.0}}
Explanation: 75% of Friday's tickets were for Robots, but only 60% of Robots tickets were sold on Friday.

Constraints

  • 1 <= number of rows, number of columns <= 200
  • every count is a whole number with 0 <= count <= 10**6
  • by is "row", "column" or "total"; percentages are compared with a small tolerance

Goals

  • Read a two-way table of counts stored as nested dictionaries
  • Compute row, column and overall totals
  • Choose the right total for the question being asked
Starting Python…