Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing itertools permutations in Python

In context of memory management i face a lot of issues while using itertools permutations specially when the length of list is more than 10.

Is there any better way of generating permutations for any list such that memory is not much utilized ?

Below is the way how i am using it.

     num_list = [i for i in range(0,18)]
     permutation_list = list(permutations(num_list,len(num_list)))

     for p_tuples in permutation_list:
          print(p_tuples)
like image 940
HelloWorld Avatar asked Jan 30 '26 02:01

HelloWorld


1 Answers

If all you need to do is iterate over the permutations, don't store them. Iterate directly over the object returned by itertools.permutations. In other words do this:

permutations = permutations(num_list,len(num_list))
for perm in permutations:
    doSomethingWith(perm)

Calling list on an iterator is exactly the way to say "give me all of the elements right now in memory at the same time". If you don't want or need all of them in memory at once, don't use list. If you just want to use one element at a time, just iterate over what you want to iterate over.

Note that your code will still take a long time to run if you really try to go through all the permutations, because 18! is a really big number.

like image 130
BrenBarn Avatar answered Feb 01 '26 14:02

BrenBarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!