Problem 288930 · medium · Level 02 Linear Data Structures

Is It a Valid Transition Table?

py-any-all · validation · probability

A weather model moves between n states (say sunny, cloudy, rainy) once a day. Its transition table is an n × n list of lists: table[i][j] is the probability of moving from state i to state j. A table is valid when:

  1. it has at least one row and is square: every row has exactly n entries, where n is the number of rows;
  2. every entry is between 0 and 1 inclusive;
  3. every row adds up to 1, allowing a rounding error of at most 1e-9.

A state i is absorbing when table[i][i] == 1: once there, the model never leaves.

Write check_table(table) that returns None if the table is not valid, and otherwise the list of absorbing states in increasing order.

Examples

Input:  table = [[0.5, 0.3, 0.2],
                 [0.1, 0.6, 0.3],
                 [0.0, 0.0, 1.0]]
Output: [2]

Input:  table = [[0.1, 0.2, 0.7], [0.3, 0.3, 0.4], [0.2, 0.2, 0.6]]
Output: []
Explanation: 0.1 + 0.2 + 0.7 is 0.9999999999999999 in floating point, which is close enough.

Input:  table = [[0.5, 0.5], [1.2, -0.2]]
Output: None
Explanation: The second row adds up to 1 but contains entries outside 0..1.

Input:  table = [[1.0], [1.0]]
Output: None
Explanation: Two rows of one entry each is not square.

Constraints

  • 0 <= len(table) <= 300; rows may have any length.
  • Entries are floats or integers.

Goals

  • State every-item conditions with `all` and a generator expression
  • Compare floating-point sums with a tolerance instead of `==`
  • Check the shape of the data before looking at its values
Starting Python…