Majority Voting Practice Problem
This data science coding problem helps you practice K-Nearest Neighbors, majority voting, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of K-Nearest Neighbors.
- Problem ID: 190
- Problem key: 190-majority-voting
- URL: https://datacrack.app/solve/190-majority-voting
- Difficulty: easy
- Topic: K-Nearest Neighbors
- Module: Supervised Learning
Problem Statement
# 🧩 Majority Voting
---
### 🎯 Goal
Predict one class label from the labels of the nearest neighbors.
---
### 📖 Introduction
KNN now has the `k` nearest training samples. Each neighbor already has a known class label, so KNN uses those labels to make a prediction for the query.
In KNN classification, every neighbor gets one vote. The label with the most votes is the predicted class. This is called **majority voting**.
For example, if the nearest neighbors have labels `["cat", "dog", "cat"]`, then `cat` gets 2 votes and `dog` gets 1 vote. The prediction is `cat`.
---
### 💻 Task
Implement `majority_vote(neighbor_labels)`.
Your function should:
- Count how often every label appears.
- Return the label with the largest count.
- Return the alphabetically smaller label when two or more labels tie.
---
### 📥 Input / 📤 Output
**Input**
- `neighbor_labels`: labels from already-selected nearest neighbors.
**Output**
- One predicted label.
---
### 🧩 Starter Code
```python
def majority_vote(neighbor_labels):
# Your code here
pass
```
---
### 💡 Example
```python
majority_vote(["cat", "dog", "cat"])
```
Expected output:
```python
"cat"
```
---
### ⚠️ Common Mistakes
- Returning the closest neighbor instead of counting all `k` labels.
- Returning the first label that appears rather than the most common label.
- Ignoring tied counts.
Starter Code
def majority_vote(neighbor_labels):
# Your code here
pass