Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Permutation where element can be repeated specific times and do it fast

$
0
0

I have been looking for a function like this, sadly I was not able to found it.

Here a code that do what I write:

import itertools#Repeat every element specific timesdata = {  1: 3,  2: 1,  3: 2}#Lengthn = 0to_rep = []for i in data:  to_rep += [i]*data[i]  n += data[i]#itertools will generate also duplicated onesret = itertools.permutations(to_rep, n)#clean dupsret = list(set(ret))

So, the code will show all lists of length 6, where there is 3 times "1", 1 time "2", and 2 times "3", the code works.

So.... the challenge here is time, this method is too expensive! which would be the fastest way to do this?

I have tested this with some samples of 27 times True and one time False, which is not much, in total there is 28 ways to do it, but this code takes forever... there is even more ways, but I would like to know a more efficient one.

I was able to write a code when we have two elements, like True/False, but seems a lot more complex with more than two elements.

def f(n_true, n_false):  ret = []  length = n_true + n_false  full = [True]*length  for rep in itertools.combinations(range(length), n_false):    full_ = full.copy()    for i in rep:      full_[i] = False    ret.append(full_)  return ret

Exists a function that already do this?Which is best way to run this?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>