python - 根据逻辑表达式计算嵌套列表的所有组合

标签 python nested logical-operators python-itertools

假设我有一个操作列表,其中可以包含三种不同类型的操作:

类型A:可以包含所有类型的操作(析取)
B 类:可以包含所有类型的操作(有序连词)
类型 C:不能包含子操作。这就是我最终想要达到的水平。

我考虑过(基于 python - representing boolean expressions with lists )析取和合取可以分别用元组和列表表示,但我不确定这是否是最佳解决方案。

对于类型 A 和 B,有一个包含类型元素的字典,例如

type_a = {
‘a1’: ('b1', 'a2'),
‘a2’: ('c1', 'c2')
}

type_b = {
‘b1’: ['c4', 'c5', 'c7'],
‘b2’:['c3', 'c4']
}

详细说明:

'a1' 等于 ('b1', 'a2'),它等于 (['c4', 'c5','c7'], 'c1 ', 'c2')

“a2”等于('c1', 'c2')

“b1”等于['c4', 'c5', 'c7']

“b2”等于['c3', 'c4']

输入示例:

['a1', 'b2', 'c6']

预期输出:

结果应仅包含类型 C 操作。

原始

[(['c4', 'c5', 'c7'], 'c1', 'c2'), 'c3', 'c4', 'c6']

所有组合

['c4', 'c5','c7', 'c3', 'c4', 'c6']

['c1', 'c3', 'c4', 'c6']

['c2', 'c3', 'c4', 'c6']

问题:

  • 元组和列表的合取和析取表示是一个好主意吗?
  • 实现这一目标的有效方法是什么?
  • 是否有可能实现计算的函数 所有组合,与 itertool? (我不太熟悉 他们,但我听说他们很强大)

感谢您的帮助。

最佳答案

遗憾的是,itertools 在这里没有多大帮助。然而,以下递归野兽似乎可以完成这项工作:

def combinations(actions):
    if len(actions)==1:
        action= actions[0]
        try:
            actions= type_a[action]
        except KeyError:
            try:
                actions= type_b[action]
            except KeyError:
                #action is of type C, the only possible combination is itself
                yield actions
            else:
                #action is of type B (conjunction), combine all the actions
                for combination in combinations(actions):
                    yield combination
        else:
            #action is of type A (disjunction), generate combinations for each action
            for action in actions:
                for combination in combinations([action]):
                    yield combination
    else:
        #generate combinations for the first action in the list
        #and combine them with the combinations for the rest of the list
        action= actions[0]
        for combination in combinations(actions[1:]):
            for combo in combinations([action]):
                yield combo + combination

这个想法是为第一个操作('a1')生成所有可能的值,并将它们与其余操作(['b2', 'c6'])。

这也消除了用列表和元组表示合取和析取的需要,老实说,我发现这相当令人困惑。

关于python - 根据逻辑表达式计算嵌套列表的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38587123/

相关文章:

python - django 中的时间戳字段

Python LDAP : The signature algorithm is not supported

C代码编码器! (数组)(嵌套循环)(fgets)(语法?)

swift - Vapor 2 OR 条件不适用于请求类型检查

python /JSON : Merge default and user configuration

从列表中删除相似项目的pythonic方法

javascript - 剑道网格 : add new row with nested object stopped working

c++ - 带有嵌套循环的标记元素 C++ 数组

Ruby:&= 和 &&= 的区别

ios - 在 reduce 中使用逻辑运算符作为组合闭包