source: tools/pytools/combinatorics.py @ 361

Last change on this file since 361 was 18, checked in by ole, 20 years ago

Added old pytools module from CVS

File size: 780 bytes
Line 
1"""
2  Combinatorial function using NumPy
3  OMN, 2001
4""" 
5       
6import Numeric
7
8def factorial(n):
9  v = Numeric.arange(n)+1
10  return Numeric.multiply.reduce(v)
11
12def binom (n,k):
13  """ Compute the binomial coefficient n!/(k! (n-k)!)
14  """
15 
16  if k > n or n < 0 or k < 0:
17    raise Exception
18  elif k==n or n==0 or k==0:
19    return(1)
20  else:
21    v = Numeric.arange(k) + n-k+1 #[n-k+1, ..., n-1, n]
22    nom = Numeric.multiply.reduce(v)
23    denom = factorial(k)
24   
25    return nom/denom
26
27def bitvector(i, n):
28    """Compute binary representation of positive integer i in a word of size n
29    """
30   
31    b=[0]*n
32    k=0
33    while i > 0:
34        d = i%2
35        b[k] = d
36        i = i/2
37        k = k+1
38        if k > n: break
39    return b
40
41
Note: See TracBrowser for help on using the repository browser.