Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Decision Tree in Python

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Decision Tree in Python. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Airbus Americas Customer Services can use a compact decision tree to classify service records from numeric signals such as aircraft age or delay duration. Implement a deterministic CART-style classifier that chooses binary splits using Gini impurity.

Given feature matrix X, class labels y, a maximum tree depth, and a minimum split size, return the trained tree as nested dictionaries.

Formal Specification

  • X is a non-empty list of n rows, each containing d numeric features.
  • y is a list of n labels. Labels may be integers or strings.
  • max_depth is a non-negative integer. The root has depth 0.
  • min_samples_split is a positive integer.
  • An internal node must have the form {"type": "node", "feature": f, "threshold": t, "left": left_tree, "right": right_tree}.
  • A leaf must have the form {"type": "leaf", "class": label}.
  • Use x <= threshold for the left branch and x > threshold for the right branch.

At each node, consider every feature and every midpoint between adjacent distinct sorted feature values. Select the split with the lowest weighted Gini impurity. Break equal-score ties by feature index, then by threshold order. Stop when the node is pure, reaches max_depth, has fewer than min_samples_split records, or has no valid split. A leaf predicts the majority class, breaking class ties by first appearance in the node.

Constraints

  • 1 <= n <= 200
  • 1 <= d <= 20
  • 0 <= max_depth <= 20
  • 1 <= min_samples_split <= n
  • Feature values are finite numbers
  • Every row has the same number of features

Function Signature

def decision_tree(X, y, max_depth, min_samples_split):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output