Morningstar Interview Question

optimize a certain part of the code from the assignment