Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 759
Shilo Avatar asked Jun 05 '26 14:06

Shilo


2 Answers

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

like image 164
Tim Peters Avatar answered Jun 08 '26 00:06

Tim Peters


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.

like image 36
Anand S Kumar Avatar answered Jun 08 '26 00:06

Anand S Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!