library(tidyverse)
library(readxl)
path = "files/CH-127 Add Index Column.xlsx"
input = read_excel(path, range = "B2:C13")
test = read_excel(path, range = "E2:G13")
compute_index <- function(price_vector) {
idx <- rep(1, length(price_vector))
for (i in 2:length(price_vector)) {
if (price_vector[i] > price_vector[i - 1]) {
idx[i] <- idx[i - 1] + 1
} else {
idx[i] <- 1
}
}
return(idx)
}
result <- input %>%
group_by(Stock) %>%
mutate(index = compute_index(Price))
all.equal(result$index, test$index, check.attributes = FALSE)
#> [1] TRUEOmid - Challenge 127
data-challenges
advanced-exercises
🔰 Result Stock Price A B Question Table index Challenge 127:

Challenge Description
🔰 Result Stock Price A B Question Table index Challenge 127:
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
Applies the rule iteratively until the output stabilizes
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 itertools
path = "CH-127 Add Index Column.xlsx"
input = pd.read_excel(path, usecols="B:C", skiprows=1, nrows=12)
test = pd.read_excel(path, usecols="E:G", skiprows=1, nrows=12).rename(columns=lambda x: x.replace('.1', ''))
input = input.sort_values(by='Stock')
input["index"] = input.groupby(['Stock', (input.groupby('Stock')['Price'].diff() < 0).cumsum()]).cumcount() + 1
print(input.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 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.