Back to General discussions forum
So after lots and lots of 'Googling' and browsing Stack Overflow, I've finally managed to put together a working algorithm which generates permutations. The problem is, whenever I try to build a list of permutations, I get "MemoryError" (I'm using Python 3). This makes sense, considering the amount of permutations possible. My question is, if I cannot generate some sort of list, how else can I solve this problem? Or, is there some kind of method I can use to create the list in a memory-efficient way?
Thank you in advance for your help,
Christopher P. Matthews
Christopher, Hi!
You are right, with N=12
the total amount of possible permutations is over 400
millions and if we multiply
it by at least 12
bytes for each, this yields at least 5
Gb of memory.
So probably building the full list (with the aim of sorting it then?) is bit tricky.
One idea is that we need not full list. If you simply
generate them in lexicographic order
(starting from very first which is ABCDE...
)
you at each step only need previous one to build the next one. So memory is only necessary to keep one permutation
and its index.
This approach has one sad property - building these millions of permutations will take significant time. With
modern hardware I believe in Python it is possible to do about a million of such iterations per second - so
it may take few minutes. (But for larger N
this will become a real problem)
So yet another approach is simply to convert the required index into permutation. This could be done if you
represent index in factorial
system rather decimal or hexadecimal. The same wiki article has a link
to this page which, I believe, can help if you are
curious about this approach.
Hope this helps - and feel free to ask more about details or anything!
Rodion
Thanks for your help, Rodion, and Sergey as well... I have just solved the problem! Thank you for pointing me in the right direction, I'm glad that I took the time to study the factorial number system!
Always,
Christopher P. Matthews