Split a Dataset Practice Problem
This data science coding problem helps you practice Decision Trees, split a dataset, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Decision Trees.
- Problem ID: 211
- Problem key: 211-split-a-dataset
- URL: https://datacrack.app/solve/211-split-a-dataset
- Difficulty: easy
- Topic: Decision Trees
- Module: Supervised Learning
Problem Statement
# 🧩 Split a Dataset
---
### 🎯 Goal
Apply one decision-tree question to split rows and labels into left and right child nodes.
A split is the operation that moves samples from one parent node into two smaller child nodes. This is the operation that creates the child nodes whose quality we measured using entropy and information gain in the previous problems.
---
### 📖 Introduction
A decision tree splits data by asking a simple question about one feature.
For example:
~~~text
Is the size smaller than or equal to 2.1?
~~~
The tree checks this question for every row:
- If the answer is **Yes**, the row goes to the **left child**.
- If the answer is **No**, the row goes to the **right child**.
The split rule can be written as:
`feature value <= threshold`
where:
- **feature value** is the value of the selected feature in the row.
- **threshold** is the value used to make the decision.
Example:
~~~text
Question:
Is size <= 2.1?
size = 1.5 → Yes → left child
size = 3.1 → No → right child
~~~
The label must move together with its row. Otherwise, the model will have incorrect feature-label pairs.
---
### 💻 Task
Implement `split_dataset(X, y, feature_index, threshold)`.
Your function should:
- Select the feature value from each row using `feature_index`.
- Compare it with `threshold`.
- Put rows with `value <= threshold` into the left child.
- Put all other rows into the right child.
- Move each label into the matching child label list.
---
### 📥 Input / 📤 Output
**Input**
- `X`: list of feature rows
- `y`: list of labels aligned with `X`
- `feature_index`: column index used for the split
- `threshold`: numeric split value
**Output**
- dictionary with `left_X`, `left_y`, `right_X`, and `right_y`
---
### 🧩 Starter Code
```python
def split_dataset(X, y, feature_index, threshold):
# Your code here
pass
```
---
### 💡 Example
```python
split_dataset([[1], [2], [3]], ["low", "mid", "high"], 0, 2)
```
Expected Output:
```python
{
"left_X": [[1], [2]],
"left_y": ["low", "mid"],
"right_X": [[3]],
"right_y": ["high"]
}
```
---
### ⚠️ Common Mistakes
- Using `< threshold` instead of `<= threshold`.
- Moving rows but forgetting to move labels.
- Accidentally changing the original input lists.
- Changing the order of rows inside the child nodes.Starter Code
def split_dataset(X, y, feature_index, threshold):
# Your code here
pass