optimize python solution