






"""simple docstring"""






import numpy as np

import datasets


UpperCAmelCase_     :				Any         =				"""
Compute the Mahalanobis Distance

Mahalonobis distance is the distance between a point and a distribution.
And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.
It was introduced by Prof. P. C. Mahalanobis in 1936
and has been used in various statistical applications ever since
[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]
"""

UpperCAmelCase_     :				Any         =				"""\
@article{de2000mahalanobis,
  title={The mahalanobis distance},
  author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},
  journal={Chemometrics and intelligent laboratory systems},
  volume={50},
  number={1},
  pages={1--18},
  year={2000},
  publisher={Elsevier}
}
"""

UpperCAmelCase_     :				List[Any]         =				"""
Args:
    X: List of datapoints to be compared with the `reference_distribution`.
    reference_distribution: List of datapoints from the reference distribution we want to compare to.
Returns:
    mahalanobis: The Mahalonobis distance for each datapoint in `X`.
Examples:

    >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\")
    >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])
    >>> print(results)
    {\'mahalanobis\': array([0.5])}
"""




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION       ,	_KWARGS_DESCRIPTION				)
class 							lowerCAmelCase__       (    datasets.Metric				):






      '''simple docstring'''

      def _SCREAMING_SNAKE_CASE				(		self  :						Dict):




          '''simple docstring'''


          return datasets.MetricInfo(
              description=_DESCRIPTION		,			citation=_CITATION		,			inputs_description=_KWARGS_DESCRIPTION		,			features=datasets.Features(
                  {
                      '''X''': datasets.Sequence(datasets.Value('''float'''		,			id='''sequence''')		,			id='''X'''),
                  })		,			)



      def _SCREAMING_SNAKE_CASE				(		self  :						Union[str, Any]		,			lowercase_  :						str		,			lowercase_  :						Optional[int]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Any							=	np.array(a_)
          SCREAMING_SNAKE_CASE_   :						str							=	np.array(a_)

          # Assert that arrays are 2D
          if len(X.shape) != 2:
              raise ValueError('''Expected `X` to be a 2D vector''')
          if len(reference_distribution.shape) != 2:
              raise ValueError('''Expected `reference_distribution` to be a 2D vector''')
          if reference_distribution.shape[0] < 2:
              raise ValueError(
                  '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension''')

          # Get mahalanobis distance for each prediction
          SCREAMING_SNAKE_CASE_   :						Optional[int]							=	X - np.mean(a_)
          SCREAMING_SNAKE_CASE_   :						Dict							=	np.cov(reference_distribution.T)
          try:
              SCREAMING_SNAKE_CASE_   :						Dict							=	np.linalg.inv(a_)
          except np.linalg.LinAlgError:
              SCREAMING_SNAKE_CASE_   :						Optional[int]							=	np.linalg.pinv(a_)
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	np.dot(a_		,			a_)
          SCREAMING_SNAKE_CASE_   :						Tuple							=	np.dot(a_		,			X_minus_mu.T).diagonal()

          return {"mahalanobis": mahal_dist}










"""simple docstring"""






from __future__ import annotations

import requests



def       _A    (__a							)				-> dict:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Any							=	f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty'
    return requests.get(__a							).json()



def       _A    (__a = 10							)				-> list[dict]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Any							=	'''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'''
    SCREAMING_SNAKE_CASE_   :						Dict							=	requests.get(__a							).json()[:max_stories]
    return [get_hackernews_story(__a							) for story_id in story_ids]



def       _A    (__a = 10							)				-> str:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Tuple							=	hackernews_top_stories(__a							)
    return "\n".join('''* [{title}]({url})'''.format(**__a							) for story in stories							)


if __name__ == "__main__":
  print(hackernews_top_stories_as_markdown())


