I have a list with numbers that are an integer: candidates = [1, 2 ,3, 4 , 5, 16, 20]. This list can contain > 1 million items.
I have a dictionary number_ranges that has as key an integer, with a list as value that contains object with a minimum and maximum range. This dictionary consists now of about 500k keys.
{
{5: [{"start": 0, "end": 9}]},
{16: [{"start": 15, "end": 20}, {"start": 16, "end": 18}]}
}
I am now looping through the list:
for candidate in candidates:
number = search_in_range(candidate, number_ranges)
where I check if there is a match of a number of candidates in the ranges of number_ranges, and if so, I return the key which will be used further on.
def search_in_range(candidate, number_ranges):
for number_range_key in number_ranges:
for number in number_ranges[number_range_key]:
if int(number['start']) <= candidate <= int(number['end']):
return {"key": number_range_key, "candidate": candidate}
When I run this, I see that it takes about 40 seconds to process 1000 numbers from the list. This means that if I have 1 million numbers, I need more than 11 hours to process.
('2018-12-19 16:22:47', 'Read', 1000)
('2018-12-19 16:23:30', 'Read', 2000)
('2018-12-19 16:24:10', 'Read', 3000)
('2018-12-19 16:24:46', 'Read', 4000)
('2018-12-19 16:25:26', 'Read', 5000)
('2018-12-19 16:25:59', 'Read', 6000)
('2018-12-19 16:26:39', 'Read', 7000)
('2018-12-19 16:27:28', 'Read', 8000)
('2018-12-19 16:28:15', 'Read', 9000)
('2018-12-19 16:28:57', 'Read', 10000)
The expected output is returning the keys from number_ranges that are matching within the range and the candidate number used to find that key, i.e. return {"key": number_range_key, "candidate": candidate} in function search_in_range.
What are the recommended ways in Python to optimize this algorithm?