[英]Permutation with Limiting
I want to permute each a set of elements.. However, for each element in the set.我想对每个元素进行排列。但是,对于集合中的每个元素。 I want to limit the times its going to be repeated.我想限制它重复的次数。
Here is a snip of code to understand:这是一段代码以供理解:
_list_ = [0,1,3]
limit_dict = {
0 : [0, 1],
1 : [0, 3],
3 : [0, 1]
}
def main(position=0, length=5, genlist=[]):
if position == length:
print (genlist)
else:
for element in _list_:
if limit_dict[element][0] != limit_dict[element][1]:
limit_dict[element][0] += 1
main(position + 1, length, genlist + [element])
limit_dict[element][0] -= 1
main()
This is the general idea, is there a faster way to implement this?这是一般的想法,有没有更快的方法来实现这个?
I want to do something like this for a large number of integers and therefore cannot use itertools to achieve this since it uses a lot of memory.我想为大量整数做这样的事情,因此不能使用 itertools 来实现这一点,因为它使用了很多 memory。
That's what distinct_permutations
from more-itertools does.这就是more-itertools中的distinct_permutations
所做的。
from more_itertools import distinct_permutations
limit_dict = {
0 : [0, 1],
1 : [0, 3],
3 : [0, 1]
}
elements = (k for k, v in limit_dict.items() for _ in range(*v))
for permutation in distinct_permutations(elements):
print(permutation)
Output: Output:
(0, 1, 1, 1, 3)
(0, 1, 1, 3, 1)
(0, 1, 3, 1, 1)
(0, 3, 1, 1, 1)
(1, 0, 1, 1, 3)
(1, 0, 1, 3, 1)
(1, 0, 3, 1, 1)
(1, 1, 0, 1, 3)
(1, 1, 0, 3, 1)
(1, 1, 1, 0, 3)
(1, 1, 1, 3, 0)
(1, 1, 3, 0, 1)
(1, 1, 3, 1, 0)
(1, 3, 0, 1, 1)
(1, 3, 1, 0, 1)
(1, 3, 1, 1, 0)
(3, 0, 1, 1, 1)
(3, 1, 0, 1, 1)
(3, 1, 1, 0, 1)
(3, 1, 1, 1, 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.