获得整数排列的更有效方法是什么? [英] More efficient way to get integer permutations?
问题描述
我可以得到这样的整数排列:
I can get integer permutations like this:
myInt = 123456789
l = itertools.permutations(str(myInt))
[int(''.join(x)) for x in l]
是否有更有效的方法在Python中获取整数排列,省去了创建字符串的开销,然后加入生成的元组?对它进行定时,元组加入过程比 list(l)
长3倍。
Is there a more efficient way to get integer permutations in Python, skipping the overhead of creating a string, then joining the generated tuples? Timing it, the tuple-joining process makes this 3x longer than list(l)
.
添加了支持信息
myInt =123456789
def v1(i): #timeit gives 258ms
l = itertools.permutations(str(i))
return [int(''.join(x)) for 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) for x in l]
推荐答案
你可以这样做:
>>> digits = [int(x) for x in str(123)]
>>> n_digits = len(digits)
>>> n_power = n_digits - 1
>>> permutations = itertools.permutations(digits)
>>> [sum(v * (10**(n_power - i)) for i, v in enumerate(item)) for item in permutations]
[123, 132, 213, 231, 312, 321]
这避免了转换为元组和从元组转换,因为它将使用元组中的整数位置来计算其值(例如,(1,2,3)
表示 100 + 20 + 3
)。
This avoids conversion to and from a tuple as it'll use the integer's position in the tuple to compute its value (e.g., (1,2,3)
means 100 + 20 + 3
).
因为 n_digits
的值在整个过程中是已知且相同的,我认为您还可以优化计算:
Because the value of n_digits
is known and the same throughout the process, I think you can also optimize the computations to:
>>> values = [v * (10**(n_power - i)) for i, v in enumerate(itertools.repeat(1, n_digits))]
>>> values
[100, 10, 1]
>>> [sum(v * index for v, index in zip(item, values)) for item in permutations]
[123, 132, 213, 231, 312, 321]
我还认为我们不需要一直拨打 zip()
,因为我们不需要该列表:
I also think we don't need to call zip()
all the time because we don't need that list:
>>> positions = list(xrange(n_digits))
>>> [sum(item[x] * values[x] for x in positions) for item in permutations]
[123, 132, 213, 231, 312, 321]
这篇关于获得整数排列的更有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!