0

I need to generate all the arrangements of digits for a number, hopefully with itertools because it's a 15 digit number (277,777,788,888,899), and will have over 1 million permutations.

If I were to try it with itertools.permutations() I would get 1,307,674,368,000 numbers, instead of the real ones I need, wich are just 1,261,260.

Without discarding the repeated ones from itertools, is there an efficient way to just get them the first time?

Current Result:

>>> [''.join(i) for i in itertools.permutations('moon')]
['moon', 'mono', 'moon', 'mono', 'mnoo', 'mnoo', 'omon', 'omno', 'oomn', 'oonm', 'onmo', 'onom', 'omon', 'omno', 'oomn', 'oonm', 'onmo', 'onom', 'nmoo', 'nmoo', 'nomo', 'noom', 'nomo', 'noom']

Expected result:

>>> [''.join(i) for i in itertools.permutations('moon')]
['moon', 'mono', 'mnoo', 'omon', 'omno', 'oomn', 'oonm','onom', 'onmo', 'nmoo', 'nomo', 'noom']
Teivel
  • 162
  • 1
  • 3
  • 12
  • What you want are the **unique permutations**. Here is a question on it: https://stackoverflow.com/questions/11425070/algorithm-to-list-all-unique-permutations-of-numbers-contain-duplicates A few of the answers have python solutions. – FHTMitchell Mar 21 '19 at 14:48
  • Yep, totally a duplicate, my ten minutes of browsing weren't enough... – Teivel Mar 21 '19 at 14:57
  • Just finished writing my answer and saw this marked as a duplicate. I've posted my answer in the linked question then, since I think my answer is more efficient. – blhsing Mar 21 '19 at 15:14
  • 1
    Good work! Thanks – Teivel Mar 21 '19 at 15:17

1 Answers1

-1

You can avoid the duplicates with set keyword, in case you don't know what set do, it removes the duplicate from array and return a new array of elements with count of only once, so with the use of set it produce:-

>>> import itertools
>>> list(set(''.join(p) for p in itertools.permutations('moon')))
['onmo', 'oonm', 'oomn', 'onom', 'nmoo', 'moon', 'mono', 'omon', 'mnoo', 'omno', 'noom', 'nomo']
Damian Wayne
  • 1
  • 1
  • 3
  • My problem isn't removing the duplicates, it's avoiding the computation complexity. I can compute about 1.2 million permutations per second, but it'll take me 290 hours to get through the trillions of permutations I'd need to compute – Teivel Mar 21 '19 at 15:01
  • Oh, perhaps I misunderstood it. I don't know anyway of making it more efficient, sorry. – Damian Wayne Mar 21 '19 at 15:05
  • Don't worry about it, thanks anyway – Teivel Mar 21 '19 at 15:07
  • @Teivel See if this helps https://codereview.stackexchange.com/questions/132704/counting-permutations-without-repetitions-for-a-number-or-a-string – Damian Wayne Mar 21 '19 at 15:14