Fastest possible generation of permutation with defined element values in Python

2024/10/5 15:31:58

Trying to generate permutations, could be used with generator or produced List of Lists (but maybe I need a lot of memory?) Looked on the Internet and SO, but couldn't find a version where I define the values for each element.

BTW How many permutations it will be?

8 elements with each value from 1-15

Here is my code, but maybe there is a better, faster way to generate it:

Any tips are appreciated!

import time
from tqdm import tqdm
def permutations(iterable, r=None):# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC# permutations(range(3)) --> 012 021 102 120 201 210pool = tuple(iterable)n = len(pool)r = n if r is None else rif r > n:returnindices = range(n)cycles = range(n, n-r, -1)yield tuple(pool[i] for i in indices[:r])while n:for i in reversed(range(r)):cycles[i] -= 1if cycles[i] == 0:indices[i:] = indices[i+1:] + indices[i:i+1]cycles[i] = n - ielse:j = cycles[i]indices[i], indices[-j] = indices[-j], indices[i]yield tuple(pool[i] for i in indices[:r])breakelse:returnplist = []for item in tqdm(permutations('123456789ABCDEF',8)):plist.append(item)len(plist)
Answer

You just copied the code from the itertools.permutations() documentation. That explicitly states that it is roughly equivalent, because it is only there to help you understand what itertools.permutations() does. The code is not intended to be used in production settings.

Use itertools.permutations() itself. The itertools module is designed for maximum efficiency already. The module is coded in C, and will always beat a pure Python implementation, hands down.

You are also wasting iterations on appending values to a list; each .append() expression requires an attribute lookup and a method call. You can build plist in a single expression by calling list():

plist = list(permutations('123456789ABCDEF', 8))

However, you really don't want to execute that call, because that'll take a lot of time to produce all possible permutations as separate objects, and allocating the memory for that takes time and will slow down your machine.

The number of k-permutations of n is calculated with k! / (n - k)!), with n=15 and k=8, that's 15! / (15 - 8)!, so just over a quarter billion results, 259_459_200. On a 64-bit OS that'll require about ~30GB of memory (2GB for the list object, 27G for the tuples, mere bytes for the 15 1-digit strings as they are shared).

If you really want to process those permutations, I'd just loop over the generator and use each result directly. You'll still have to iterate a quarter-billion times, so it'll still take a lot of time, but at least you don't then try to hold it all in memory at once.

Alternatively, always look for other ways to solve your problem. Generating all possible permutations will produce a very large number of possibilities. Your previous question received an answer that pointed out that for than specific problem, searching through 200kb of data for likely candidates was more efficient than to do 40k searches for every possible 8-permutation of 8. With 259 million permutations there is an even larger chance that processing your problem from another direction might keep your problem space manageable.

https://en.xdnf.cn/q/119988.html

Related Q&A

Obtain coordinates of a Polygon / Multi-polygon around a point in python [duplicate]

This question already has answers here:Draw a polygon around point in scattermapbox using python(2 answers)Closed 2 years ago.I am using plotlys scattermapbox to draw a polygon around a point object. I…

PyCuda Error in Execution

This is my pycuda code for rotation.I have installed the latest cuda drivers and I use a nvidia gpu with cuda support.I have also installed the cuda toolkit and pycuda drivers.Still I get this strange …

Python code to Download Specific JSON key value data through REST API calls

I am trying to write a code in python which download only specific key value in the Calls. So the solution might beDownloading the Raw data and later removing the unwanted through regex or 2)Applying s…

How to measure pairwise distances between two sets of points?

I have two datasets (csv files). Both of them contains latitudes-longitudes of two sets (220 and 4400) of points. Now I want to measure pairwise distances (miles) between these two sets of points (220 …

Interactively Re-color Bars in Matplotlib Bar Chart using Confidence Intervals

Trying to shade the bars in this chart based on the confidence that a selected y-value (represented by the red line) lies within a confidence interval. See recolorBars() method in the class example bel…

Unlock password protected Workbook using VBA or Python

I have a workbook name m.xlsx, but its password protected and Ive forgotten the password. How can I open it or un-protect it?The following code does not work:Unprotect workbook without password I need…

How do I make a variable detect if it is greater than or less than another one?

I am currently learning Python, and I decided to build a small "Guess the Number" type of game. I am using the random feature, and trying to make it so it will detect if the users input is eq…

Python Regular Expression from File

I want to extract lines following some sequence from a file. E.g. a file contains many lines and I want line in sequencejourney (a,b) from station south chennai to station punjab chandigarh journey (c,…

Changing the words keeping its meaning intact [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

How to create index for a SQLite3 database using SQLAlchemy?

I have multiple SQLite3 databases for which the models are not available. def index_db(name, tempdb):print(f{name.ljust(padding)} Indexing file: {tempdb})if tempdb.endswith(primary.sqlite):conn = sqlit…