The Python Book
shortcut formula

Combinations of array elements

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

The scenic tour:


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 )

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