Omid - Challenge 60

data-challenges
advanced-exercises
🔰 : Match Payments!
Published

March 24, 2026

Illustration for Omid - Challenge 60

Challenge Description

🔰 : Match Payments!

Solutions

library(tidyverse)
library(readxl)

input1 = read_excel("files/CH-060 Match payments.xlsx", range = "B2:D14")
input2 = read_excel("files/CH-060 Match payments.xlsx", range = "F2:H7")
test   = read_excel("files/CH-060 Match payments.xlsx", range = "K2:P14")
names(test)[1] = "ID"

receipts = input1 %>%
  mutate(rec_cum = cumsum(Cost),
         prev_rec_cum = lag(rec_cum, default = 0))

payments = input2 %>%
  mutate(pay_cum = cumsum(Payment),
         prev_pay_cum = lag(pay_cum, default = 0))

matched = receipts %>%
  left_join(payments, by = join_by(overlaps(prev_rec_cum, rec_cum, prev_pay_cum, pay_cum, bounds = "()")))

matched = matched %>%
  mutate(match = pmin(rec_cum, pay_cum),
         match = c(first(match), diff(match))) %>%
  group_by(ID.x) %>%
  mutate(match = ifelse(prev_rec_cum < pay_cum, match, 0)) %>%
  ungroup() %>%
  fill(Date.y)

result = matched %>%
  select(ID.x, ID.y, match) %>%
  mutate(match = as.character(match)) %>%
  pivot_wider(id_cols = ID.x, names_from = ID.y, values_from = match) %>%
  rename(ID = ID.x) %>%
  select(-`NA`) %>%
  mutate(check = if_else(reduce(across(2:6, ~is.na(.x)), `&`), "No", "Yes")) %>%
  rowwise() %>%
  mutate(across(2:6, ~if_else(check == "No", "NP", .))) %>%
  ungroup() %>%
  select(-check)

identical(result, test)
# [1] TRUE
  • 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

input1 = pd.read_excel("CH-060 Match payments.xlsx", usecols="B:D", skiprows=1, nrows=13)
input2 = pd.read_excel("CH-060 Match payments.xlsx", usecols="F:H", skiprows=1, nrows=6)
test = pd.read_excel("CH-060 Match payments.xlsx", usecols="K:P", skiprows=1, nrows=13)
test.columns = ["ID"] + list(test.columns[1:])

receipts = input1.copy()
receipts["rec_cum"] = receipts["Cost"].cumsum()
receipts["prev_rec_cum"] = receipts["rec_cum"].shift(fill_value=0)

payments = input2.copy()
payments["pay_cum"] = payments["Payment"].cumsum()
payments["prev_pay_cum"] = payments["pay_cum"].shift(fill_value=0)

matches = []
for _, r in receipts.iterrows():
    row_matches = []
    for _, p in payments.iterrows():
        if r["prev_rec_cum"] < p["pay_cum"] and p["prev_pay_cum"] < r["rec_cum"]:
            overlap = min(r["rec_cum"], p["pay_cum"]) - max(r["prev_rec_cum"], p["prev_pay_cum"])
            if overlap > 0:
                row_matches.append((r["ID"], p["ID"], overlap))
    matches.extend(row_matches)

matched = pd.DataFrame(matches, columns=["receipt_id", "payment_id", "match"])
result = matched.pivot_table(index="receipt_id", columns="payment_id", values="match", aggfunc="sum")
result = result.reindex(receipts["ID"]).reset_index().rename(columns={"receipt_id": "ID"})
result.columns.name = None
result = result.astype(object)
value_cols = [c for c in result.columns if c != "ID"]
result[value_cols] = result[value_cols].where(result[value_cols].notna(), None)
mask = result[value_cols].isna().all(axis=1)
for col in value_cols:
    result.loc[mask, col] = "NP"

print(result.equals(test))
  • Logic:

    • Reads the workbook ranges needed for the challenge

    • Reshapes the data into the grain required by the task

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