library(tidyverse)
library(readxl)
path <- "300-399/369/CH-369 Custom Grouping.xlsx"
input <- read_excel(path, range = "B3:E10")
test <- read_excel(path, range = "H3:I5")
result = input %>%
mutate(rn = row_number()) %>%
mutate(
group = case_when(
row_number() < ceiling(n() / 2) ~ "Group 1",
row_number() > ceiling(n() / 2) ~ "Group 2",
TRUE ~ "Middle"
)
) %>%
group_by(group) %>%
summarise(sum_value = sum(`Total Sales`, na.rm = TRUE)) %>%
pivot_wider(names_from = group, values_from = sum_value) %>%
mutate(
`Group 1` = `Group 1` + if_else(`Group 1` < `Group 2`, Middle, 0),
`Group 2` = `Group 2` + if_else(`Group 2` <= `Group 1`, Middle, 0)
) %>%
select(`Group 1`, `Group 2`) %>%
pivot_longer(everything(), names_to = "IDs", values_to = "Sales")
all.equal(result, test)
## [1] TRUEOmid - Challenge 369

Challenge Description
🔰 Group 1 Group 2 Grouping Group the rows in the question table into two sets from midle, and allocate the middle row to the group with the lower total sales.
Solutions
Logic:
Reads the workbook ranges needed for the challenge
Reshapes the data into the grain required by the task
Aggregates or ranks values at the relevant grouping level
Builds the intermediate columns that drive the final result
Strengths:
- The R solution stays close to the workbook rule and keeps the transformation compact.
Areas for Improvement:
- The code assumes the sheet structure and source ranges remain stable.
Gem:
- The strongest part of the solution is choosing the right intermediate representation before shaping the final output.
import pandas as pd
import numpy as np
path = "300-399/369/CH-369 Custom Grouping.xlsx"
input = pd.read_excel(path, usecols="B:E", skiprows=2, nrows=8)
test = pd.read_excel(path, usecols="H:I", skiprows=2, nrows=2)
n = len(input)
mid = int(np.ceil(n / 2))
g = (
input
.assign(rn=lambda d: np.arange(1, n + 1))
.assign(group=lambda d: np.select(
[d.rn < mid, d.rn > mid],
["Group 1", "Group 2"],
default="Middle"
))
.groupby("group")["Total Sales"]
.sum()
)
g1, g2, m = g.get("Group 1", 0), g.get("Group 2", 0), g.get("Middle", 0)
result = pd.DataFrame({
"IDs": ["Group 1", "Group 2"],
"Sales": [g1 + (m if g1 < g2 else 0),
g2 + (m if g2 <= g1 else 0)]
})
print(result.equals(test))
# Output: TrueLogic:
Reads the workbook ranges needed for the challenge
Aggregates or ranks values at the relevant grouping level
Builds the intermediate columns that drive the final result
Strengths:
- The Python version follows the same rule in a direct dataframe-oriented implementation.
Areas for Improvement:
- The code assumes the workbook layout remains stable, so any sheet redesign would require small adjustments.
Gem:
- The implementation stays close to the original workbook rule instead of adding unnecessary abstraction.
Difficulty Level
This task is moderate:
The core logic is clear, but the correct transformation pattern is not obvious from the raw input.
The challenge combines multiple reshaping, grouping, or parsing steps.