Omid - Challenge 207

data-challenges
advanced-exercises
🔰 Group Challenge 207: Custom Grouping!
Published

March 24, 2026

Illustration for Omid - Challenge 207

Challenge Description

🔰 Group Challenge 207: Custom Grouping!

Solutions

library(tidyverse)
library(readxl)

path = "files/CH-207 Custom Grouping.xlsx"
input = read_excel(path, range = "B2:C18")
test  = read_excel(path, range = "B2:D18")

initial_threshold <- 100
threshold_step <- 50

result = input %>%
  mutate(
    Group = accumulate(
      Sales,
      .init = list(total = 0, Group = 1),
      .f = function(acc, x) {
        threshold <- initial_threshold + (acc$Group - 1) * threshold_step
        if (acc$total + x > threshold) {
          list(total = x, Group = acc$Group + 1)
        } else {
          list(total = acc$total + x, Group = acc$Group)
        }
      }
    )[-1] %>%
      map_int("Group")
  )

all.equal(result, test)
#> [1] TRUE
  • Logic:

    • Reads the workbook ranges needed for the challenge

    • 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-207 Custom Grouping.xlsx"
input = pd.read_excel(path, usecols="B:C", skiprows=1, nrows=17)
test = pd.read_excel(path, usecols="B:D", skiprows=1, nrows=17)

def accumulate_groups(sales, threshold=100, step=50):
    total, group, groups = 0, 1, []
    for x in sales:
        if total + x > threshold:
            group, total = group + 1, x
            threshold += step
        else:
            total += x
        groups.append(group)
    return groups

input["Group"] = accumulate_groups(input["Sales"])

print(input["Group"].equals(test["Group"])) # True
  • Logic:

    • Reads the workbook ranges needed for the challenge

    • Applies the rule iteratively until the output stabilizes

  • 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.