please roast my code, I hope this is the good place to look for some advice on where I can improve.
Problem definition:
Apply modifications on values depending on date ranges.
Data:
Base array - holds dictionaries in the following format:
[{'date': 20200101, 'value': 1}, {'date': 20200102, 'value': 2}]
Modifier array - holds dictionaries with similar format:
[{'date': 20200101, 'value': 1}, {'date': 20200201, 'value': 2}]
Edit: Both arrays are holding values with dates sorted in ascending order.
Goal: Add the respective value of the modifier array to the base array lining up the date ranges. Dates are exclusive, for example when the modifier array contains 2020-01-01 you have to add the value '1' to all values in the base array that have a date less than 2020-01-01. Base array has a lot of elements while modifier array relatively few. In practice this splits the base array into a couple of date ranges. If the last modification date is less than the date in base array no modification is required.
My solution:
This is assuming the comparing of dates will work, I have translated this from perl for an easier read.
mod_index = 0
mod_size = len(mod_arr)
for elem in base_arr:
if elem['date'] > mod_arr[mod_size - 1]['date']:
break
else:
if elem['date'] < mod_arr[mod_index]['date']:
elem['value'] += mod_arr[mod_index]['value']
else:
elem['value'] += mod_arr[mod_index + 1]['value']
mod_index += 1