optimize python solution of q036