使用 itertools 时缺少序列 combonations_with_replacement

Missing a sequence when using itertools combonations_with_replacement

from itertools import combinations_with_replacement

x = 'opo'
v = combinations_with_replacement(x, len(x))
ans = [''.join(map(str, x)) for x in v]
print(" ".join(set(ans)))

我不确定为什么我在这里遗漏了序列 pop。为什么 pop 不显示,但 ppoopp 显示。

预期输出opp ppp poo ppo ooo opo oop pop

实际产量opp ppp poo ppo ooo opo oop

考虑一下:

>>> x = 'abc'
>>> v = itertools.combinations_with_replacement(x, len(x))
>>> ans = [''.join(map(str, x)) for x in v]
>>> ans
['aaa', 'aab', 'aac', 'abb', 'abc', 'acc', 'bbb', 'bbc', 'bcc', 'ccc']

序列中的combinations_with_replacement的作用无关;只有序列中的位置才算数。您的问题与询问为什么 'bab''cac' 没有出现在我的示例中是一样的。提示:函数的名称不是 permutations_with_replacement ;-)

记录正确here -

itertools.combinations_with_replacement(iterable, r)

Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, the generated combinations will also be unique.

强调我的。