code: def ordqz(A, B, sort='lhp', output='real', overwrite_a=False,
            overwrite_b=False, check_finite=True):
      import warnings
      import numpy as np
      from numpy import asarray_chkfinite
      from scipy.linalg.misc import LinAlgError, _datacopied
      from scipy.linalg.lapack import get_lapack_funcs
      from scipy._lib.six import callable
      from scipy.linalg._decomp_qz import _qz, _select_function
      lwork = None
      result, typ = _qz(A, B, output=output, lwork=lwork, sort=None,
                        overwrite_a=overwrite_a, overwrite_b=overwrite_b,
                        check_finite=check_finite)
      AA, BB, Q, Z = result[0], result[1], result[-4], result[-3]
      if typ not in 'cz':
          alpha, beta = result[3] + result[4]*1.j, result[5]
      else:
          alpha, beta = result[3], result[4]
      sfunction = _select_function(sort)
      select = sfunction(alpha, beta)
      tgsen, = get_lapack_funcs(('tgsen',), (AA, BB))
      if lwork is None or lwork == -1:
          result = tgsen(select, AA, BB, Q, Z, lwork=-1)
          lwork = result[-3][0].real.astype(np.int)
          lwork += 1
      liwork = None
      if liwork is None or liwork == -1:
          result = tgsen(select, AA, BB, Q, Z, liwork=-1)
          liwork = result[-2][0]
      result = tgsen(select, AA, BB, Q, Z, lwork=lwork, liwork=liwork)
      info = result[-1]
      if info < 0:
          raise ValueError("Illegal value in argument %d of tgsen" % -info)
      elif info == 1:
          raise ValueError("Reordering of (A, B) failed because the transformed"
                           " matrix pair (A, B) would be too far from "
                           "generalized Schur form; the problem is very "
                           "ill-conditioned. (A, B) may have been partially "
                           "reorded. If requested, 0 is returned in DIF(*), "
                           "PL, and PR.")
      if typ in ['f', 'd']:
          alpha = result[2] + result[3] * 1.j
          return (result[0], result[1], alpha, result[4], result[5], result[6])
      else:
          return result[0], result[1], result[2], result[3], result[4], result[5]