<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def diag(A, k=0):
 """Extract or construct a diagonal polynomial array."""

    if isinstance(A, Poly):
        core, core_new = A.A, {}
        for key in A.keys:
            core_new[key] = numpy.diag(core[key], k)

        return Poly(core_new, A.dim, None, A.dtype)

    return numpy.diag(A, k)