Python's math.comb in TypeScript

✓ Verified: Python 3.12
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { comb } from 'locutus/python/math/comb'.

Or with CommonJS: const { comb } = require('locutus/python/math/comb')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1comb(5, 2)10
2comb(10, 0)1
3comb(10, 3)120

Notes

  • Returns the number of ways to choose k items from n without repetition.

Here's what our current TypeScript equivalent to Python's math.comb looks like.

export function comb(n: number | string, k: number | string): number {
// discuss at: https://locutus.io/python/comb/
// parity verified: Python 3.12
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Returns the number of ways to choose k items from n without repetition.
// example 1: comb(5, 2)
// returns 1: 10
// example 2: comb(10, 0)
// returns 2: 1
// example 3: comb(10, 3)
// returns 3: 120

const nn = Math.trunc(Number(n))
const kk = Math.trunc(Number(k))

if (!Number.isFinite(nn) || !Number.isFinite(kk) || nn < 0 || kk < 0) {
throw new Error('comb() only accepts non-negative integers')
}
if (kk > nn) {
return 0
}

const r = Math.min(kk, nn - kk)
let result = 1
for (let i = 1; i <= r; i += 1) {
result = (result * (nn - r + i)) / i
}

return Math.trunc(result)
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 34 Python functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Python math functions


Star