Reputation: 1874
I am trying to generate all 5 digit numbers out of {1,2,3,4,5,6,7,8,9}
such that any digit can be repeated at most twice. That is, numbers like 12345, 11267, 11226
are allowed but 11134 or 11115
are not allowed.
I can write a code with multiple for loops perhaps, but I was wondering if there are shorter, more elegant methods available.
For example, itertools.product('123456789', repeat=5)
will generate all such 5 tuples (9^5
in total) or itertools.permutations(''123456789',5)
will generate all 5
tuples with no repetitions (9x8x7x6x5
in total). I am wondering is there a way to use these tools to generate all numbers of the form 11235 and 11224
but nothing else without going through multiple for loops and the like.
Upvotes: 0
Views: 585
Reputation: 56
Unless I've misunderstood the question, just using
itertools.permutations('112233445566778899',5)
should do the trick.
Edit: that included repeats, since it had two of each digit. Wrapping it in a set seems to solve that:
set(itertools.permutations('112233445566778899',5))
Upvotes: 4