Skip to content

Instantly share code, notes, and snippets.

@jednano
Last active October 28, 2022 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jednano/1718adf6355dcba76ec001a126854032 to your computer and use it in GitHub Desktop.
Save jednano/1718adf6355dcba76ec001a126854032 to your computer and use it in GitHub Desktop.
Summation (i.e., ∑)
from functools import reduce
def summate(startingAt, endingWith, callback):
"""
Returns the sum of the result values of `callback` starting at `startingAt` and ending with `endingWith`.
Example: sigma(1, 6, lambda n: 3 * n)
See: https://replit.com/@jedmao/SuperSigma#main.py
"""
return sum([callback(x) for x in range(startingAt - 1, endingWith + 1)])
/**
* @returns the sum of the result values of `callback` starting at `startingAt` and ending with `endingWith`.
* @example sigma(1, 6, (n) => 3 * n)
* @see https://replit.com/@jedmao/SuperSigmaTS#index.ts
*/
export function summate(
startingAt: number,
endingWith: number,
callback: (i: number) => number
) {
return [...range(startingAt, endingWith)].reduce(
(accumulator, i) => accumulator + callback(i)
)
}
function* range(start: number, end: number, step = 1) {
for (let i = start - 1; i <= end; i += step) {
yield i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment