我试图在不使用itertools的情况下在
python中生成排列.到目前为止,这是我的代码:
def generatePermutations(minVal, maxVal, arrayLength, depth = -1, array = []):
if(depth == -1): # set all values to minVal initially
for i in range(arrayLength):
array.append(minVal)
depth += 1
generatePermutations(minVal, maxVal, arrayLength, depth, array) # recurse
elif depth < arrayLength:
a.append(array[:]) # a is a list declared above the function
current = 0
while current <= depth:
if array[current] < maxVal:
array[current] += 1
break
else:
if current < depth:
array[current] = minVal
else:
depth += 1
array[current] = minVal
if depth < arrayLength:
array[depth] += 1
break
current += 1
generatePermutations(minVal, maxVal, arrayLength, depth, array)
该功能适用于足够小的数字.例如,generatePermutations(1,2,2)使用以下内容填充列表a:
[1, 1]
[2, 1]
[1, 2]
[2, 2]
但是,当我尝试创建长度为9的数组(generatePermutations(1,9,9))的排列时,我会在函数完成之前很久就遇到堆栈溢出错误.有没有办法阻止这种情况?