Python 确定列表是否反对称

Python 确定列表是否反对称,python,list,relation,Python,List,Relation,我试图写一个函数,这样当给出一个关系列表时,无论它是否反对称,我都会返回true或false。 如果(a,b)在关系中且(b,a)在关系中,则a必须等于b i、 e.给定[“A”、“A”]、[“A”、“C”]、[“A”、“B”]、[“C”、“C”]]将返回true [[“A”,“A”],[“A”,“D”],[“D”,“A”]]将返回false,因为[A,D]和[D,A]都处于关系中,但并不相等 我的想法是: def is_antisymmetric(relation): for a, b

我试图写一个函数,这样当给出一个关系列表时,无论它是否反对称,我都会返回true或false。 如果(a,b)在关系中且(b,a)在关系中,则a必须等于b

i、 e.给定[“A”、“A”]、[“A”、“C”]、[“A”、“B”]、[“C”、“C”]]将返回true

[[“A”,“A”],[“A”,“D”],[“D”,“A”]]将返回false,因为[A,D]和[D,A]都处于关系中,但并不相等

我的想法是:

def is_antisymmetric(relation):
    for a, b in relation:
        if (a,b) in relation and (b,a) in relation and a == b:
            return True
        else:
            return False
但这似乎不起作用。任何帮助都将不胜感激

def is_antisymmetric(relation):
    for a, b in relation:
        if (a,b) in relation and (b,a) in relation and a != b:
            return False
    return True

print is_antisymmetric([("A","A"), ("A","C"), ("A","B"), ("C","C")]) # True
print is_antisymmetric([("A","A"), ("A","C"), ("C","A"), ("C","C")]) # False
或者如果您使用的是方括号

def is_antisymmetric(relation):
    for a, b in relation:
        if [a,b] in relation and [b,a] in relation and a != b:
            return False
    return True

print is_antisymmetric([["A","A"], ["A","C"], ["A","B"], ["C","C"]]) # True
print is_antisymmetric([["A","A"], ["A","C"], ["C","A"], ["C","C"]]) # False

您的方法的一个问题是
列表中
的成本相对较高
O(n)
,这使得您当前的方法是
O(n^2)
。一种简单而有效的方法是将
O(n)
中看到的每个项目添加到
set()
对于
set()
O(1)
,例如:

def is_antisymmetric(relation):
    seen = set()
    for a, b in relation:
        if a == b:
            continue
        if (b, a) in seen:
            return False
        seen.add((a, b))
    return True

In []:
is_antisymmetric([["A","A"], ["A","C"], ["A","B"], ["C","C"]])
Out[]:
True

In []:
is_antisymmetric([["A","A"], ["A","D"], ["D","A"]])
Out[]:
False
一些时间安排

import string
import itertools

rels = list(itertools.combinations(string.ascii_letters, 2))
当前方法(由@Xin Huang确定):

使用上面的
set()
方法:

In []:
%timeit is_antisymmetric_set(rels)
Out[]:
329 µs ± 2.99 µs per loop

>>>(1,2)in[[1,2]
False
也许我很愚蠢,但我不明白为什么
[[“A”,“A”,“C”,“A”,“B”,“C”,“C”]
应该返回
True
。请解释一下你所说的反对称是什么意思……你能提供一个例子,说明你希望它何时返回
False
?还有,为什么你要短路你的循环,你将在列表中最多检查一个值。需要更多
任何
所有
。非常感谢你,我的问题是没有使用方括号
In []:
%timeit is_antisymmetric_set(rels)
Out[]:
329 µs ± 2.99 µs per loop