Number of Combinations (Python)

Updated vegaseat 3 Tallied Votes 458 Views Share

If you want to know the number of combinations of x things taken n at a time, you can use the Python module gmpy. The module gmpy is a C-coded Python extension module that supports fast multiple-precision arithmetic, very handy if x things reach a large number.

''' gmpy2_combinations_number.py
comb(x, n) returns the number of combinations of x things,
taken n at a time, n must be >= 0

gmpy is a C-coded Python extension module that supports fast
multiple-precision arithmetic, download Windows installers from:
http://code.google.com/p/gmpy/

tested with Python27/33 and GMPY2 2.0.0b4  by  vegaseat  27feb2013
'''

import gmpy2


print("gmpy2.comb(3, 2) = {}".format(gmpy2.comb(3, 2)))

print("gmpy2.comb(100, 20) = {}".format(gmpy2.comb(100, 20)))

print('-'*60)

print("Is gmpy2.comb(100000, 1000) == gmpy2.comb(100000, 99000)?")
print(gmpy2.comb(100000, 1000) == gmpy2.comb(100000, 99000))

print('-'*60)

print("""\
There are 100 printable characters on a computer keyboard.
How many different 10 character passwords can you make?""")
print("{:,}".format(int(gmpy2.comb(100, 10))))

''' result ...
gmpy2.comb(3, 2) = 3
gmpy2.comb(100, 20) = 535983370403809682970
------------------------------------------------------------
Is gmpy2.comb(100000, 1000) == gmpy2.comb(100000, 99000)?
True
------------------------------------------------------------
There are 100 printable characters on a computer keyboard.
How many different 10 character passwords can you make?
17,310,309,456,440
'''