Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

python - Prevent memory error in itertools.permutation

Firstly I would like to mention that i have a 3 gb ram.

I am working on an algorithm that is exponential in time on the nodes so for it I have in the code

perm = list( itertools.permutations(list(graph.Nodes))) # graph.Nodes is a tuple of 1 , 2 , ... n integers

which generates all the combinations of vertices in a list and then i can work on one of the permutation.

However when i run the program for 40 vertices , it gives a memory error.

Is there any simpler way in implementation via which i can generate all the combinations of the vertices and not have this error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try to use the iterator generated by the permutations instead of recreating a list with it :

perm_iterator = itertools.permutations(list(graph.Nodes))

for item in perm_iterator:
   do_the_stuff(item)

by doing this, python will keep in memory only the currently used permutation, not all the permutations (in term of memory usage, it is really better ;) )

On the other side, once the memory problem solved, the time to treat all the permutations will be growing exponentially with the number of vertices....


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...