Extract Upper Triangle Practice Problem
This data science coding problem helps you practice Indexing, Slicing & Filtering, extract upper triangle, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Indexing, Slicing & Filtering.
- Problem ID: 51
- Problem key: 51-extract-upper-triangle
- URL: https://datacrack.app/solve/51-extract-upper-triangle
- Difficulty: medium
- Topic: Indexing, Slicing & Filtering
- Module: NumPy Foundations
Problem Statement
# 🧩 Extract Upper Triangle
---
### 🎯 Goal
The upper triangle of a matrix appears in covariance matrices, correlation matrices, and attention scores. `np.triu()` extracts it — zeroing out all elements below the diagonal. This problem teaches you to work with triangular matrices, a critical structure in statistics and deep learning (transformers use upper-triangular masking for causal attention).
---
### 🔍 Upper Triangle
```
Input: Output (upper triangle):
[[1, 2, 3], [[1, 2, 3],
[4, 5, 6], → [0, 5, 6],
[7, 8, 9]] [0, 0, 9]]
```
Elements on and above the main diagonal are kept. Elements below are set to 0.
---
### 💻 Task
Implement `upper_triangle(matrix)` using `np.triu()`.
---
### 📥 Input
- `matrix`: 2D square list
### 📤 Output
- The upper triangular matrix as a nested Python list
---
### 🧩 Starter Code
```python
import numpy as np
def upper_triangle(matrix):
"""
Extract the upper triangle of a square matrix (zeros below diagonal).
Args:
matrix (list[list]): Square 2D matrix
Returns:
list[list]: Upper triangular matrix
"""
arr = np.array(matrix)
# 🧠 TODO
pass
```
---
### 🔑 Key Concepts
- `np.triu(arr)` — keeps upper triangle + diagonal
- `np.tril(arr)` — keeps lower triangle + diagonal
- `np.triu(arr, k=1)` — excludes the diagonal too (`k=0` includes it, `k=1` excludes it)
- Correlation matrices are symmetric — their upper triangle contains all unique pairwise correlationsStarter Code
import numpy as np
def upper_triangle(matrix):
"""
Extract the upper triangle of a square matrix (zeros below diagonal).
Args:
matrix (list[list]): Square 2D matrix
Returns:
list[list]: Upper triangular matrix
"""
arr = np.array(matrix)
# 🧠 TODO
pass