library(tidyverse)
library(readxl)
path = "files/CH-187 Custom Grouping.xlsx"
input = read_excel(path, range = "B2:C19")
test = read_excel(path, range = "G2:H7")
result = input %>%
mutate(diff = difftime(lead(Date), Date, units = "days") %>% as.numeric()) %>%
mutate(Group = cumsum(lag(diff, default = 0) > 1) + 1) %>%
summarise(`Total Sales` = sum(Sales, na.rm = T), .by = Group)
all.equal(result, test)
#> [1] TRUEOmid - Challenge 187
data-challenges
advanced-exercises
🔰 Group Challenge 187: Custom Grouping!

Challenge Description
🔰 Group Challenge 187: Custom Grouping!
Solutions
Logic:
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 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
path = "CH-187 Custom Grouping.xlsx"
input = pd.read_excel(path, usecols="B:C", skiprows=1, nrows=17)
test = pd.read_excel(path, usecols="G:H", skiprows=1, nrows=5).astype('int32')
input['Group'] = (input['Date'].diff().dt.days.fillna(0).astype(int) > 1).cumsum() + 1
result = input.groupby('Group', as_index=False)['Sales'].sum().rename(columns={'Sales': 'Total Sales'}).astype({'Total Sales': 'int32'})
print(result.equals(test)) # TrueLogic:
Reads the workbook ranges needed for the challenge
Aggregates or ranks values at the relevant grouping level
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 business rule is readable, but the workbook still requires careful implementation to reach the expected layout.