isefire

GraphEnumeration

Dec 11th, 2014
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. """
  2. Write a function answer(N, K) which returns the number of ways to connect N
  3. distinctly labelled Nodes with exactly K Edges, so that there is a path
  4. between any two Nodes.
  5.  
  6. The return value must be a string representation of the total number of
  7. ways to do so, in base 10.
  8. N will be at least 2 and at most 20.
  9. K will be at least one less than N and at most (N * (N - 1)) / 2
  10. """
  11.  
  12. def binomial(n, k):
  13.     result = 1
  14.     for i in range(1, k+1):
  15.         result = result * (n-i+1) / i
  16.     return result
  17.  
  18. def answer(N, K):
  19.     placeholder = 0
  20.     for i in xrange(N-1, (N*(N-1)/2), 1):  
  21.         placeholder += qq(N,K)*(1**K)
  22.     return placeholder
  23.  
  24. def qq(N, K):
  25.    
  26.     if K < N-1 or K > N*(N-1)/2:
  27.         return 0;
  28.     if K == N-1:
  29.         return N^(N-2)
  30.    
  31.     res = binomial(N*(N-1)/2, K)
  32.    
  33.     for m in xrange(0, N-2):
  34.         res1 = 0
  35.         for p in xrange(K-1/2*(m+1)*m,K-m,1):
  36.             res1 += binomial((N-1-m)*(N-2-m)/2, p)*qq(m+1, K-p)
  37.         res -= binomial(N-1, m)*res1
  38.     return res
  39.            
  40. def test():
  41.     print answer(2,1) #should be 1
  42.     print answer(4,3) #should be 16
  43.     print answer(3,2) #should be 3
  44.     print answer(4,6) ##should be 1
  45. test()
Advertisement
Add Comment
Please, Sign In to add comment