This is a problem from Real Analysis - Modern Techniques and Their Applications, by Folland. I'm trying my best here, but it's hard to solve.
PS: The measurable space is $(X,\mathcal{M})$.
To me, the function should be $f(x) = \inf\{\alpha: x\in E_\alpha \} = \sup\{\alpha: x\in E_\alpha^c \}$. I'm not entirely sure about this last equality, but I guess it's ok (I would prove this for last if all goes well, which is not the case). Anyway, the point is that $E_\alpha \subset f^{-1}((-\infty, \alpha])$, for any $\alpha\in\mathbb{R}$. My hope was to prove that $f^{-1}((-\infty, \alpha])\backslash E_\alpha = \emptyset$, therefore $f^{-1}((-\infty, \alpha]) = E_\alpha \in \mathcal{M}$. But this is not necessarily true because it's possible to have points $x\in E_\alpha^c$ such that $f(x) = \alpha$.
In addition to this problem, my idea is not using exercise 4, given below.
I need to know how to fix this or what is the correct solution, if mine is wrong. Thanks a lot!