Morningstar interview question

optimize a certain part of the code from the assignment