Missing a sequence when using itertools combonations_with_replacement

老子叫甜甜 提交于 2019-12-07 17:13:49

问题


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

I'm not sure why im missing the sequence pop here. Why does pop not show but ppo and opp do .

expected output opp ppp poo ppo ooo opo oop pop

actual output opp ppp poo ppo ooo opo oop


回答1:


Consider this:

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

The values in the sequence are irrelevant to what combinations_with_replacement does; only the positions within the sequence count. Your question is the same as asking why 'bab' and 'cac' don't show up in my example. Hint: the name of the function isn't permutations_with_replacement ;-)




回答2:


It is documented correctly 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.

Emphasis mine.



来源:https://stackoverflow.com/questions/32021016/missing-a-sequence-when-using-itertools-combonations-with-replacement

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