I have been experimenting around with generating all the n-combinations of an array. This code quickly generates all \$\text{k-combinations}\$ of a given array. I am testing my own implementation because of some restrictions in coding competitions (also, knowing the basics never hurts).
"""
Generates 3-combinations of an array.
A B C D E F G H
^ ^ ^
i j k
A B C D E F G H
^ ^ ^
i j k
A B C D E F G H
^ ^ ^
i j k
"""
from itertools import combinations
import time
def combinations_3(ary):
l = len(ary)
for i in xrange(l-2):
for j in xrange(i+1, l-1):
for k in xrange(j+1, l):
yield (ary[i], ary[j], ary[k])
start = time.time()
for combination in combinations_3([1, 2, 3, 4]):
print combination
print time.time() - start
print("===========Library Implementation============")
start = time.time()
for combination in combinations([1, 2, 3, 4], 3):
print combination
print time.time() -start
Output
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
0.00043797492981
===========Library Implementation============
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
6.19888305664e-05
It seems that my implementation is a lot slower than the library code. How can I improve performance of my code.