Pandas interview question: detect dirty product names by group
Problem
Shared data rulesFor each “category — is_active” pair, count products and how many have a dirty name. Also find the share of dirty ones. Pairs with no dirty names stay in the answer with 0.
Formulas
- a dirty name has a leading or trailing space, two spaces in a row, or all letters in one case
dirty_share = dirty_products / products
Example
products| product_id | product_name | category | is_active | Row note |
|---|---|---|---|---|
| 1 | Whole milk 1 qt | Dairy | 1 | |
| 2 | Oat milk 1 qt | Dairy | 1 | ← leading spaces |
| 3 | SOUR CREAM 16 OZ | Dairy | 1 | ← all caps |
| 4 | Yukon Gold potatoes 2 lb | Produce | 1 | ← capital inside — fine |
| 5 | quinoa 28 oz | Pantry | 1 | ← all lowercase |
| 6 | Jasmine rice 2 lb | Pantry | 1 | ← two spaces inside |
| 7 | Clover honey 12 oz | Pantry | 0 |
- Product 2: leading spaces
- Product 3: all caps
- Product 4: capital inside — fine
- Product 5: all lowercase
- Product 6: two spaces inside
| category | is_active | products | dirty_products | dirty_share |
|---|---|---|---|---|
| Dairy | 1 | 3 | 2 | 0.6667 |
| Produce | 1 | 1 | 0 | 0 |
| Pantry | 1 | 2 | 2 | 1 |
| Pantry | 0 | 1 | 0 | 0 |
Dairy on sale: 2 of 3 names are dirty — 0.6667. Produce · 1 and Pantry · 0 have none, so their rows show 0.
Solve it free
Your code runs on real pandas in your browser. No sign-up needed.