<a id="ch-11"></a>

## Chapter 11 — The rank key is a pair

<!-- open-cyber-academy:lesson-figures:start ch-11 -->
### Lesson map

Lesson 11. Map, example, EX057.

```mermaid
flowchart TD
  T["Tuple: id, title, likelihood, impact"] --> K["Key: minus product, then id"]
  K --> S["sorted walks that key"]
  S --> O["F1, F3, F4, F2"]
```

The title is printed. It is not part of the key.

### Logical drawing

```text
key
  (- likelihood * impact, id)
F1  (-6, "F1")
F3  (-6, "F3")
F4  (-4, "F4")
F2  (-2, "F2")
```
<!-- open-cyber-academy:lesson-figures:end ch-11 -->

### Learning outcomes

After this chapter, you should be able to:

1. Name the two parts of the sort key.
2. Say which tuple indexes supply the product.
3. Refuse a sort that uses the title text.

### 11.1 Unary minus on the product, then the id string.

Each finding is `(id, title, likelihood, impact)`. `sorted` receives `key=lambda f: (-f[2] * f[3], f[0])`. Index 2 is likelihood. Index 3 is impact. Their product is the score. The unary minus makes a larger product sort first, because `-6` is less than `-4`, and `sorted` goes low to high. The second key component is `f[0]`, the id, with no minus, so ids go in ordinary string order when products match.

The title sits at index 1. The key never reads it. "Staff portal" does not outrank "Shared admin" because of those words. The printed order of this file is F1, F3, F4, F2, which is the order of the four keys `(-6, "F1")`, `(-6, "F3")`, `(-4, "F4")`, `(-2, "F2")`.

| Id | Likelihood | Impact | Key |
|---|---:|---:|---|
| F1 | 3 | 2 | `(-6, "F1")` |
| F3 | 2 | 3 | `(-6, "F3")` |
| F4 | 2 | 2 | `(-4, "F4")` |
| F2 | 2 | 1 | `(-2, "F2")` |

### 11.2 Worked example

| Offered claim | What the lambda reads | Decision |
|---|---|---|
| "High products first, and the minus is why." | `-f[2] * f[3]` | Keep |
| "The title's topic sets the order." | Index 1 is unread by the key | Refuse |
| "F2 is last because it was typed last." | F2 is second in the list and last in the print | Refuse |

> **Synthetic case.** The four tuples are the whole ranking input.

### Errors and limits

Do not sort on the title when the lambda does not read it.

### Apply

- **EX057 — Key pair.** What does the ranking lambda return, and which part of the tuple does it ignore? *Rubric:* 3 = it returns the negated product of indexes 2 and 3, then the id; the title is not in the key;; 2 = score descending, then id; title unused;; 1 = one fact;; 0 = none.

<!-- open-cyber-academy:chapter-navigation:start ch-11 -->
### Continue studying — lesson 11 (chapter 11 of 20)

[← Chapter 10](#ch-10) · [Course chapter index](../SUBJECTS.md) · [Chapter 12 →](#ch-12)

Continue to the next authored lesson.
<!-- open-cyber-academy:chapter-navigation:end -->

## Worked answers

<a id="answer-ex057"></a>
**EX057.** The lambda returns the negated product of likelihood and impact, then the id. The title is not in the key.
