簡體   English   中英

在python中測試字典上的等價關系

[英]Testing equivalence relation on dictionary in python

給出一個關系作為元組列表

[(1,2), (1,3), (2,3), (2,1), (2,2), (3,2), (3,3)]

我有一個字典,將鍵映射到其等效類的列表

{1: [2, 3], 2: [3, 1, 2], 3: [2, 3]}

我想寫一個函數,給定這個字典檢查關系是否是傳遞和對稱的,這意味着

∀ a, b, c : if (a,b) ∈ Relation and (b,c) ∈ Relation ==> (a,c) ∈ Relation

∀ a, b : if (a,b) ∈ Relation ==> (b,a) ∈ Relation

是否有可能以有效的方式編寫它,而不會濫用嵌套循環? 使用字典對程序的其他部分很有幫助,但我不確定它是否在這里。

救命?

我不認為你需要在這里使用字典,因為這些關系已經很容易在元組列表中使用了。 如果您使用字典,您可能仍會最終將其轉換為帶有d.items()的元組列表。

由於這些是關系,它實際上應該是一組元組,而不是列表,它可以有重復:

relations = {(1,2), (1,3), (2,3), (2,1), (2,2), (3,2), (3,3)}

您可以通過創建一個檢查關系是否具有傳遞性的函數來開始:

def is_transitive(relation):
    for a, b in relation:
        for c, d in relation:
            # checks transitive property: (a, b) && (b, c) -> (a, c)
            if b == c and (a,d) not in relation:
                return False

    return True

然后你可以編寫一個函數來檢查關系是否與all()對稱:

def is_symmetric(relation):
    # checks symmetric property: (a, b) -> (b, a)
    return all(rel[::-1] in relation for rel in relation)

然后你可以做一個簡單的函數來檢查上面兩個函數的結合:

def check_relation(relation):
    # True and True -> True
    # True and False -> False
    # False and True -> False
    # False and False -> False
    return is_symmetric(relation) and is_transitive(relation)

其工作原理如下(未經過廣泛測試):

>>> relations = {(1,2), (1,3), (2,3), (2,1), (2,2), (3,2), (3,3)}
>>> print(check_relation(relations))
False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM