📘
Decision Tree Prediction
MediumDecision Trees
Traverse a decision tree to make predictions.
A decision tree is represented as nested dictionaries. Each internal node has:
- "feature": index of the feature to check
- "threshold": split value
- "left": subtree for feature_value <= threshold
- "right": subtree for feature_value > threshold
Each leaf node has:
- "class": the predicted class label
Given a tree and a list of data points (each a list of feature values), return the predicted class for each point.
Example:
Input:
tree = {"feature": 0, "threshold": 5, "left": {"class": 0}, "right": {"class": 1}}
X = [[3], [7], [5]]Output:
[0, 1, 0]
Reasoning:
- The decision tree is traversed for each data point in
X. For the first point[3], we check the feature value at index0(3) against the threshold (5). - Since 3≤5, we move to the left subtree and predict class
0. The same process applies to the third point[5], as 5≤5 also leads to the left subtree. - For the second point
[7], the feature value (7) is greater than the threshold (5), so we move to the right subtree and predict class1. - The predicted classes for all points are collected to form the output list:
[0, 1, 0].
Constraints:
- tree: nested dict with feature/threshold/left/right or class keys
- X: 2D list of feature values
- Return list of predicted class labels
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.