library(tidyverse)
library(readxl)
path = "files/CH-005.xlsx"
input = read_excel(path, range = "B2:D21")
test = read_excel(path, range = "I2:L6") %>% as.matrix()
# replace NA with 0
test[is.na(test)] = 0
result = input %>%
mutate(value = 1) %>%
select(-Quantity) %>%
pivot_wider(names_from = Product, values_from = value, values_fill = list(value = 0)) %>%
select(-c(`Invoice Num`))
prod = as.matrix(result)
prod_t = as.matrix(result) %>% t()
cooc = prod_t %*% prod
diag(cooc) = 0
rownames(cooc) = rownames(test) = colnames(test) = colnames(cooc) = colnames(result)
identical(cooc, test)
# [1] TRUEOmid - Challenge 5
data-challenges
advanced-exercises
🔰 For instance, since products B and C are bought together solely under invoice number IN-001, the highlighter cell displays a count of 1.

Challenge Description
🔰 For instance, since products B and C are bought together solely under invoice number IN-001, the highlighter cell displays a count of 1.
Solutions
Logic:
Reads the workbook ranges needed for the challenge
Reshapes the data into the grain required by the task
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 numpy as np
import pandas as pd
path = "CH-005.xlsx"
input_data = pd.read_excel(path, usecols="B:D", skiprows=1, nrows=20)
test = pd.read_excel(path, usecols="I:L", skiprows=1, nrows=4).fillna(0).astype(int).to_numpy()
prod = (
input_data.assign(value=1)
.drop(columns=["Quantity"])
.pivot_table(index="Invoice Num", columns="Product", values="value", fill_value=0, aggfunc="first")
)
cooc = prod.to_numpy().T @ prod.to_numpy()
np.fill_diagonal(cooc, 0)
print(np.array_equal(cooc, test))Logic:
Reads the workbook ranges needed for the challenge
Reshapes the data into the grain required by the task
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.