The Python Book
 
shortcut formula
20151015

Combinations of array elements

Suppose you want to know how many unique combinations of the elements of an array there are.

The scenic tour:

a=list('abcdefghijklmnopqrstuvwxyz')
n=len(a)
stack=[]

for i in xrange(n):
    for j in xrange(i+1,n):
        stack.append( (a[i],a[j]) )

print len(stack) 

The shortcut:

print (math.factorial(n)/2)/math.factorial(n-2)

From the more general formula:

n! / r! / (n-r)!  with r=2. 

(see itertools.combinations(iterable, r) on docs.python.org/2/library/itertools.html )

Add up from 1 to n

Add up all numbers from 1 to n.

The straight-n-simple solution:

result = 0
for i in xrange(n):
        result += (i + 1)
print (result)

The fast solution:

result = n * (n+1) / 2
print (result)

Here's the explanation (thanks codility)

 
Notes by Willem Moors. Generated on momo:/home/willem/sync/20151223_datamungingninja/pythonbook at 2019-07-31 19:22