2016-07-26 43 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 - 如果你不關心排序。