If $\{x:f(x) > a\}$ and $\{x:f(x) < a\}$ are open$\forall~a\in\mathbb{R}$ then f is continuous. We have the function $f: \mathbb{R} \to \mathbb{R}$.

Question: Show that if the sets $\{x:f(x) > a\}$ and $\{x:f(x) < a\}$ are open for every $a\in\mathbb{R}$, then $f$ is continuous.

My attempt:$f$ is continuous if $A \subset \mathbb{R}$ is open, then $f^{-1}(A) \subset \mathbb{R}$ is open. I can show that the image of $\{x:f(x) >a\}$ is open. Namely $\{f(x) > a\} = (a,\infty)$ is open in $\mathbb{R}$. But this doesn't prove that for any open set $A \subset \mathbb{R}$, we have that $f^{-1}(A)\subset\mathbb{R}$ open as well.  
Thanks in advance!
 A: Let $\varepsilon >0$ Then let $a=f(x) +\varepsilon$ and  $b=f(x) -\varepsilon$
By assumption, since  $\{x:f(x) > b\}$ and $\{x:f(x) < a\}$ are open,  there exist $\delta_a>0 ~~and~~~\delta_b>0 $ such that 
$$(x-\delta_a, x+\delta_a) \subset \{x:f(x) <a\}~~~and ~~~~(x-\delta_b, x+\delta_b)\subset \{f(x) >b \} $$
that is 
$$\forall~~y\in \Bbb R~~|y-x|< \delta_a, \implies f(y) < f(x) +\varepsilon$$ and 
$$\forall~~y\in \Bbb R ~~ |y-x|< \delta_b\implies f(y) > f(x) -\varepsilon $$
Therefore taking $\delta =\min(\delta_a,\delta_b)$ we have 
$$\forall~~y\in \Bbb R, ~~ |y-x_|< \delta\implies |f(y)-f(x)|\lt \varepsilon $$
this prove the continuity.
A: You can write $\{x\in X : f(x)>a\}$ as $\{x\in X : f(x)\in(a,\infty)\}=f^{-1}(a,\infty)$, and similarly you can write $\{x\in X : f(x)<a\}$ as $f^{-1}(-\infty,a)$.
Recall that a function $f$ is continuous if and only if the pre-image of an open set $U$ is open.
Moreover, the set of intervals $(a,b)$ is a basis for the topology on $X$ and therefore a function $f$ is continuous if and only if $f^{-1}(a,b)$ is open. (you can use for example, in the case of $\mathbb{R}$, that every open set is a countable union of open intervals)
Now, $(a,b) = (-\infty,b)\cap (a,\infty)$ Hence, $f^{-1}(a,b) = f^{-1}(-\infty,b)\cap f^{-1}(a,\infty)$ we conclude that $f^{-1}(a,b)$ is a finite intersection of open sets and so it is open.
This completes the proof.
Edit: Apparently this question was asked before in here
