Search code examples
pythonpython-itertools

Python : defining function that returns summation of all permutations


I have a python function a(i,j,k,l). For 0<i<100, 0<j<100, 0<k<100, 0<l<100, i get a single value with this function.

eg. a(1,4,5,3) = 5.

Now what I want is a function b(i,j,k,l) that can give me the sum of a(i,j,k,l) for all the permutations of i,j,k,l.

eg b(1,4,5,3) = a(1,4,5,3) + a(1,4,3,5) + a(1,5,4,3) + a(1,5,3,4) + ...... (as it is a permutations, so there will be 4!=24 such terms).

I saw itertools.permutations but I do not know how to use it to get the indices. Any elegant way?


Solution

  • You can use itertools.permutations and then unpack the values, like this

    sum(a(*perm) for perm in permutations((j, j, k, l)))
    

    For example,

    >>> from itertools import permutations
    >>> from random import randint
    >>> def a(*args):
    ...    return args[randint(0, len(args) - 1)]
    >>> sum(a(*perm) for perm in permutations((1, 2, 3, 4)))
    57
    

    We are passing a generator expression to sum, which means that all the computed permutations are not stored in memory.