Should I use sympy.utilities.iterables.variations() to get permutations_with_replacement?

痴心易碎 提交于 2020-01-15 10:13:05

问题


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')]

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')]

Does the variations() method perform the same function as I am expecting with permutations_with_replacement() to do?


See also: sympy.utilities.iterables.combinations() with replacement?


回答1:


The variations method does exactly what you think it does, which is to calculate the Cartesian product, aptly named product, method of the package.

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.

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


来源:https://stackoverflow.com/questions/54128621/should-i-use-sympy-utilities-iterables-variations-to-get-permutations-with-rep

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!