I have made the following function that gives the combinations permuted of n elements with a constrain/rule. This consist on creating a dataframe with all combination of numbers from 0 to n that sums n.
Function
import pandas as pd
import itertools
import numpy as np
def combinations_permuted(n_elm):
items = list(range(0,n_elm+1,1))
combinations = pd.DataFrame(list(filter(lambda x: np.sum(x)==n_elm,list(itertools.combinations_with_replacement(items, n_elm)))))
comb_permuted = pd.DataFrame()
for index, combination in combinations.iterrows():
comb_permuted=comb_permuted.append(list(filter(lambda x: np.sum(x)==n_elm,list(itertools.permutations(combination.tolist(), n_elm)))))
return(comb_permuted.drop_duplicates().as_matrix())
Example
array([[0, 0, 3],
[0, 3, 0],
[3, 0, 0],
[0, 1, 2],
[0, 2, 1],
[1, 0, 2],
[1, 2, 0],
[2, 0, 1],
[2, 1, 0],
[1, 1, 1]], dtype=int64)
The problem is that is taking a long time when n_elm is "big" for example 9. I think this code can be improving in terms of time performance.
Maybe by replacing the for loop with a map function.
Any help to get it?