Skip to main content
1 of 2
Andrea Ciufo
  • 579
  • 1
  • 5
  • 12

Python Combinatory Algorithm - A Binomial Coefficient application with n mutable and k fixed to 2

This question came from a real use case. I had a data frame with different columns each one containing data from a data source and I wanted to design a hypothesis test to prove or not if the data had the same mean. So I had to compute the Kolmogorov-Smirnov test for each couple of columns.

Now the problem can be generalized to any combinatory task.

It follows that I had to implement a Binomial Coefficient like

$$ \binom{n}{k} $$

Where n is the number of columns

and k is = 2

My question is: if exists a more efficient way to compute this.

I created an algorithm to solve this issue, but I am wondering if there is a better way to do that in Python.

In my algorithm, I simply multiply each n element in an explanatory array with another element i of the same array, with n!=i, instead of computing the statistical test.

to_do=[1,2,3,4,5]
#done will store information on the elements already combined
done=[]
#j will store information on the results of the combination  
j=[]


#iterating over the to_do array
for n in to_do:

  #checking if we already computed the n element  
  if n not in done:
    print(n)
    #taking another i element from the array
    #where n!=i    
    for i in to_do: 
      print(i)
      #if the condition is satisfied       
      if i!=n:
        #combine the two elements        
        m=n*i

        #append the result on the "j" array 
        j.append(m)
    #updating the array with the "done" elements        
    done.append(n)    

print(len(done))
print(len(j))
Andrea Ciufo
  • 579
  • 1
  • 5
  • 12