2016-07-26 75 views
1

假设我有一个动作列表,它可以包含三种不同类型的动作:计算嵌套列表的所有组合基于逻辑表达式

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'] 

问题:

  • 与合取和析再想法元组的介绍并列出一个好主意?
  • 什么是有效的实现方式?
  • 是否有可能实现的功能,其中计算 所有组合,与itertools? (我不是很熟悉 他们,但我听说他们是非常强大的)

感谢您的任何帮助。

回答

1

不幸的是,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'])将它们结合起来。

这也消除了表示与列表和元组的联合和分离的需要,老实说,我发现相当混乱。

+0

非常好,谢谢你。作为一个扩展,我想也接受列表元素,其中包含提到的字符串作为第一个元素,例如 '[['a1',{'param':'something'}],['b2',{'param':'something'}]'。第二个元素(字典)应该通过。 – eljobso

0

Python中还有一个支持集合操作的set type - 如果你不关心排序。