Mogelijke duplicaten:
Statistieken: combinaties in Python
combinaties en permutaties efficiënt tellen
Project euler-probleem in python (probleem 53)
Ik ben aan het kijken of de functie nCr (n Kies r) is ingebouwd in de wiskundebibliotheek in python:
Ik begrijp dat dit kan worden geprogrammeerd, maar ik dacht dat ik zou controleren of het al is ingebouwd voordat ik het doe.
Antwoord 1, autoriteit 100%
Het volgende programma berekent nCr
op een efficiënte manier (vergeleken met het berekenen van faculteiten enz.)
import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom # or / in Python 2
Vanaf Python 3.8 zijn binomiale coëfficiënten beschikbaar in de standaardbibliotheek als math.comb
:
>>> from math import comb
>>> comb(10,3)
120
Antwoord 2, autoriteit 73%
Wilt u herhaling? itertools.combinations. Algemeen gebruik:
>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
Als u alleen de formule moet berekenen, gebruikt u Math.Factorial :
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
print nCr(4,2)
Gebruik in Python 3 de Integer Division //
in plaats van /
om overloop te voorkomen:
return f(n) // f(r) // f(n-r)
Uitgang
6