【发布时间】:2014-02-17 16:39:42
【问题描述】:
我正在尝试创建一个函数,该函数接收元素列表并递归返回包含该列表的所有排列(长度为 r)的列表。但是,如果列表中有-1,应该可以重复。
例如,对于 r = 2 的列表 [0, -1, 2],我希望返回 [0, -1], [-1, 0], [0, 2], [2, 0] , [-1, 2], [2, -1] 和 [-1, -1]。
到目前为止,这是我的功能:
def permutations(i, iterable, used, current, comboList, r):
if (i == len(iterable):
return
if (len(current) == r):
comboList.append(current)
print current
return
elif (used[i] != 1):
current.append(iterable[i])
if (iterable[i][0] != -1):
used[i] = 1
for j in range(0, len(iterable)):
permutations(j+1, iterable, used, current, comboList, r)
used[i] = 0
return comboList
如您所见,我错误地尝试使用“已访问列表”来跟踪列表中的哪些元素已访问和未访问。
【问题讨论】:
-
-1是在 Python 中给予特殊处理的丑陋值。你真正想做什么?这些数字代表什么?
标签: python list permutation