Reputation: 3218
If I understand itertools
"combinatoric iterators" doc correctly, the idea is to provide a set of standard functions for every common combinatory iteration.
But I miss one today. I need to iterate over every ordered combinations of items with repetitions.
combination_with_replacement('abcd', 4)
yields
('a', 'a', 'a', 'a')
('a', 'a', 'a', 'b')
('a', 'a', 'a', 'c')
('a', 'a', 'a', 'd')
('a', 'a', 'b', 'b')
('a', 'a', 'b', 'c')
('a', 'a', 'b', 'd')
('a', 'a', 'c', 'c')
('a', 'a', 'c', 'd')
... etc
but (even though the results are sorted tuples), these combinations are not ordered.
I expect more results from an ideal ordered_combination_with_replacement('abcd', 4)
for I need to distinguish between
('a', 'a', 'a', 'a')
('a', 'a', 'a', 'b')
('a', 'a', 'b', 'a')
('a', 'b', 'a', 'a')
('b', 'a', 'a', 'a')
('a', 'a', 'a', 'c')
('a', 'a', 'c', 'a')
... etc
In other words: order matters today.
Does itertool provide such an iteration? Why not, or why have I missed it?
What's a standard way to iterate over those?
Do I need to write this generic iterator myself?
Upvotes: 1
Views: 91
Reputation: 12523
To wrap up some of the comments, there are (at least) two ways to do that:
itertools.combinations_with_replacement("abcd", 4)
and
itertools.product("abcd", repeat=4)
Both produce the required results of:
[('a', 'a', 'a', 'a'),
('a', 'a', 'a', 'b'),
('a', 'a', 'a', 'c'),
('a', 'a', 'a', 'd'),
('a', 'a', 'b', 'a'),
...
Upvotes: 1