python - More efficient way to get integer permutations? -


i can integer permutations this:

myint = 123456789  l = itertools.permutations(str(myint)) [int(''.join(x)) x in l] 

is there more efficient way integer permutations in python, skipping overhead of creating string, joining generated tuples? timing it, tuple-joining process makes 3x longer list(l).

added supporting information

myint =123456789 def v1(i): #timeit gives 258ms     l = itertools.permutations(str(i))     return [int(''.join(x)) x in l]  def v2(i): #timeit gives 48ms     l = itertools.permutations(str(i))     return list(l)  def v3(i): #timeit gives 106 ms     l = itertools.permutations(str(i))     return [''.join(x) x in l] 

you can do:

>>> digits = [int(x) x in str(123)] >>> n_digits = len(digits) >>> n_power = n_digits - 1 >>> permutations = itertools.permutations(digits) >>> [sum(v * (10**(n_power - i)) i, v in enumerate(item)) item in permutations] [123, 132, 213, 231, 312, 321] 

this avoids conversion , tuple it'll use integer's position in tuple compute value (e.g., (1,2,3) means 100 + 20 + 3).

because value of n_digits known , same throughout process, think can optimize computations to:

>>> values = [v * (10**(n_power - i)) i, v in enumerate(itertools.repeat(1, n_digits))] >>> values [100, 10, 1] >>> [sum(v * index v, index in zip(item, values)) item in permutations] [123, 132, 213, 231, 312, 321] 

i think don't need call zip() time because don't need list:

>>> positions = list(xrange(n_digits)) >>> [sum(item[x] * values[x] x in positions) item in permutations] [123, 132, 213, 231, 312, 321] 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -