The Island's Spending Ledger

GDP · expenditure approach · net exports · dictionaries · loops

Gross domestic product (GDP) is the market value of all final goods and services newly produced in a country in a year. One way to measure it is to add up who spent on that production:

\text{GDP} = C + I + G + (X - M)

The statistics office of the island of Pellora keeps a ledger of the year's purchases, in millions of crowns. Each entry is a pair (kind, amount), and the kind says how it counts:

kind meaning counts as
"consumption" households buy new goods and services C
"investment" firms buy new machines and buildings; new houses I
"government" the government buys goods and services G
"export" foreigners buy goods made on Pellora X
"import" the foreign-made part of spending already listed above M (subtracted)
"intermediate" a firm buys inputs it uses up making something else not counted
"transfer" pensions and benefits: money paid with nothing produced in return not counted
"secondhand" used goods change hands not counted
"financial" shares and bonds are bought not counted

Intermediate goods are left out because their value is already inside the price of the final goods they went into; counting them too would count it twice.

Write gdp_by_spending(purchases) that returns a dict with the keys "C", "I", "G", "NX" (net exports, X - M) and "GDP". A kind with no entries contributes 0.

Examples

Input:  purchases = [("consumption", 120), ("investment", 30), ("government", 45),
                     ("export", 25), ("import", 40), ("intermediate", 60),
                     ("transfer", 15), ("secondhand", 8)]
Output: {"C": 120, "I": 30, "G": 45, "NX": -15, "GDP": 180}
Explanation: net exports are 25 - 40 = -15, and 120 + 30 + 45 - 15 = 180.
The flour bought by bakeries, the pensions and the used cars add nothing.

Input:  purchases = []
Output: {"C": 0, "I": 0, "G": 0, "NX": 0, "GDP": 0}

Constraints

  • numbers are compared with a tolerance of 1e-6

Goals

  • Add up GDP as $C + I + G + (X - M)$ from a list of purchases
  • Leave out spending that is not on newly produced final goods
  • Subtract imports instead of adding them
Starting Python…