Solution (source code)

= Solution

Both $Z\otimes Z$ and $X\otimes I$ are unitary and Hermitian, so their expectations are real. Run the real-part <Hadamard test> twice, once with controlled $Z\otimes Z$ and once with controlled $X\otimes I$. If the respective ancilla outcome-one probabilities are $p_{ZZ}$ and $p_{XI}$, then
$$
\langle\psi|Z\otimes Z|\psi\rangle=1-2p_{ZZ},\qquad
\langle\psi|X\otimes I|\psi\rangle=1-2p_{XI}.
$$
The identity in part (b) implements each controlled tensor product by gates on its two target wires with the common control. By <linearity>,
$$
\langle\psi|W|\psi\rangle=2-2(p_{ZZ}+p_{XI}).
$$