【发布时间】:2018-01-25 12:16:56
【问题描述】:
我正在尝试使用 list = [0,1,2,3,4,5,6] 计算所有排列,并遵守一些约束。
- 位置 0 必须 > 3
- 位置 3 + 位置 5
使用我当前的代码,我确定所有排列和迭代,并应用约束。
import itertools
Used_permutations = []
numbers = [0,1,2,3,4,5,6]
all_permutations = list(itertools.permutations(numbers)) #Determine all permutations
for permutation in all_permutations:
if permutation[0] > 3 and permutation[3] + permutation[5] < permutation[4]: #Constraints applied to permutations
Used_permutations.append(permutation)
####################################################
### Apply calculations to current permutation ###
####################################################
这段代码的问题是我浪费时间寻找所有可能的排列,只是为了再次过滤掉它们。有人可以协助在确定排列时应用约束的方法,因此并非全部为 N!确定了吗?
【问题讨论】:
-
位置 0 为 > 3 表示位置 0 是 4,因为 4 是唯一满足该条件的候选者。
-
假设位置 3、4 和 5 是指 2、3 和 4,那么满足您的条件的 只有四个排列。
[4, 2, 0, 3, 1]、[4, 2, 1, 3, 0]、[4, 3, 0, 2, 1]和[4, 3, 1, 2, 0] -
忘记了这两个
[4, 1, 0, 3, 2]和[4, 1, 2, 3, 0]。所以总共6个 -
抱歉,复制了错误的列表。编辑以更正列表。
-
@Pierre 现在太晚了,伙计..
标签: python permutation