M4) Sorted distinct values

A table contains integer measurements. The function in Listing 1 retains only values from 1 through 10, removes duplicates, and returns its result in ascending order.

Listing 1: Set membership records the retained integers; sorted returns a list in ascending order.
def bounded_distinct(table):
    found = set()
    for row in table:
        for value in row:
            if 1 <= value <= 10:
                found.add(value)
    return sorted(found)

data = [
    [7, 2, 11, 10],
    [11, 1, 2, 1],
    [9, 7, 0, -1],
]
print(bounded_distinct(data))

What is printed by Listing 1?

  • [1, 2, 7, 9, 10]
  • [7, 2, 11, 10, 1, 2, 9]
  • [2, 0, 0, 0, 0, 0, 2, 0, 1, 1]
  • [7, 2, 11, -1, 10, 1, 2, 9, 7, 0, -1]
  • bounded_distinct(table) receives a nested list of integers and returns a sorted list of distinct values in the inclusive range 1 through 10. For example, bounded_distinct([[3, 3, 12]]) returns [3], and bounded_distinct([]) returns [].
  • set() creates an empty set. found.add(value) adds a value and returns None; adding 4 twice still leaves only one 4 in the set.
  • sorted(values) returns a new list in ascending order without changing the input: sorted({4, 2}) is [2, 4].
  • print(value) displays the value and ends with a new line.