Problem 332170 · easy · Level 03 Linear Management & Searching

The Header Comes First

py-iterators · iter and next · tables

A field team sends its bird counts as a stream of text lines, like an open file: the first line is a header of comma-separated column names, and every later line is one row. The stream can only be read once, from the front: it cannot be indexed, sliced or measured with len.

Write column_total(lines, name) that returns the sum of the values in the column called name, as a float. Empty cells are skipped, and so are completely blank lines. A line may end with "\n". If the stream is empty (not even a header), return 0.0.

The tests build their streams with two helpers you can also use with Run: stream(list_of_lines) hands out the given lines one at a time, and survey(n, seed) generates a survey with n rows and the header site,species,count,weight.

Examples

Input:  lines = stream(["name,score", "ana,7", "ben,9", "chen,8"]), name = "score"
Output: 24.0

Input:  lines = stream(["a,b", "1,", "2,5.5"]), name = "b"
Output: 5.5
Explanation: The first row's b cell is empty and is skipped.

Constraints

  • Fields never contain commas or quotes; name is always one of the header's columns.
  • Up to 10**5 rows; non-empty cells of the column are valid numbers.

Goals

  • Take one item from a stream by hand with `next`, then loop over the rest
  • Use `next(it, default)` to handle an empty stream
  • Find a column by its name in the header instead of by a fixed position
Starting Python…