Skip to content

maths: add weighted_average function#14850

Open
liyana3572 wants to merge 1 commit into
TheAlgorithms:masterfrom
liyana3572:add-weighted-average
Open

maths: add weighted_average function#14850
liyana3572 wants to merge 1 commit into
TheAlgorithms:masterfrom
liyana3572:add-weighted-average

Conversation

@liyana3572

Copy link
Copy Markdown

Description

I added a weighted_average function to maths/weighted_average.py that computes the weighted arithmetic mean of a list of values given corresponding weights, with input validation.

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

@algorithms-keeper algorithms-keeper Bot added the awaiting reviews This PR is ready to be reviewed label Jun 23, 2026

@zuhairkazmi14 zuhairkazmi14 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation is clean and follows PEP8 style conventions perfectly. The inclusion of doctests for empty lists, mismatching lengths, and zero-sum weights is excellent. One minor optimization: instead of if not values and not weights:, since you check length mismatch immediately after, you could simplify this by checking if the values list is empty first: if not values: raise ValueError('Inputs cannot be empty'). This is cleaner and correctly catches empty lists even if one of them was passed with elements. Otherwise, great work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants