Solution (source code)

= Solution

With the pivot as origin and upward vertical coordinate,
$$
\mathbf r_1=l(\sin\theta_1,-\cos\theta_1),
\qquad
\mathbf r_2=\mathbf r_1+l(\sin\theta_2,-\cos\theta_2).
$$
Therefore
$$
|\dot{\mathbf r}_1|^2=l^2\dot\theta_1^2,
$$
$$
|\dot{\mathbf r}_2|^2=l^2\left[\dot\theta_1^2+\dot\theta_2^2
+2\cos(\theta_1-\theta_2)\dot\theta_1\dot\theta_2\right].
$$
The potential energy is
$$
V=-(M+m)gl\cos\theta_1-mgl\cos\theta_2.
$$
Thus $L=T-V$ is
$$
\boxed{
L=\frac12Ml^2\dot\theta_1^2
+\frac12ml^2\left[\dot\theta_1^2+\dot\theta_2^2
+2\cos(\theta_1-\theta_2)\dot\theta_1\dot\theta_2\right]
+Mgl\cos\theta_1+mg l(\cos\theta_1+\cos\theta_2).}
$$