我应该使用 sympy.utilities.iterables.variations() 来获取 permutations_with_replacement 吗? [英] Should I use sympy.utilities.iterables.variations() to get permutations_with_replacement?
问题描述
我正在试验 sympy 的排列没有替换
I'm experimenting with sympy's permutations without replacement
from sympy.functions.combinatorial.numbers import nP
from sympy.utilities.iterables import permutations
nP('abc', 2)
# >>> 6
list(permutations('abc', 2))
# >>> [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
接下来,我不想尝试置换替换.似乎没有类似于 combinations_with_replacement()
方法的 permuations_with_replacement()
方法,但是有一个 variations()
方法:
Next, I wan't to try permutations with replacement. It seems that there isn't a permuations_with_replacement()
method similar to the combinations_with_replacement()
method, but there is a variations()
method:
from sympy.utilities.iterables import variations
nP('abc', 2, replacement=True)
# >>> 9
list(variations('abc', 2, repetition=True))
# >>>
[('a', 'a'),
('a', 'b'),
('a', 'c'),
('b', 'a'),
('b', 'b'),
('b', 'c'),
('c', 'a'),
('c', 'b'),
('c', 'c')]
variations()
方法是否执行与我期望的 permutations_with_replacement()
相同的功能?
Does the variations()
method perform the same function as I am expecting with permutations_with_replacement()
to do?
另见:sympy.utilities.iterables.combinations() 替换?
推荐答案
variations
方法完全按照您的想法执行,即计算笛卡尔积,恰当地命名为 product
,包的方法.
The variations
method does exactly what you think it does, which is to calculate the Cartesian product, aptly named product
, method of the package.
这意味着 list(sympy.utilities.iterables.product('abc', repeat=2)
将产生相同的结果.使用 repetition=False
,variations
等于 permutations
.
This means that list(sympy.utilities.iterables.product('abc', repeat=2)
will yield the same results.
With repetition=False
, variations
is equal to permutations
instead.
这也可以从variations
的内部代码看出:
This can also be seen from the internal code of variations
:
if not repetition:
seq = tuple(seq)
if len(seq) < n:
return
for i in permutations(seq, n):
yield i
else:
if n == 0:
yield ()
else:
for i in product(seq, repeat=n):
yield i
这篇关于我应该使用 sympy.utilities.iterables.variations() 来获取 permutations_with_replacement 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!