Last active
October 28, 2022 04:43
-
-
Save jednano/1718adf6355dcba76ec001a126854032 to your computer and use it in GitHub Desktop.
Summation (i.e., ∑)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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