Python 与元组集的关系 [英] Python Relations with Sets of Tuples
本文介绍了Python 与元组集的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试确定元组集是否具有某种类型的关系.我试图找出传递关系和复合关系.
对于传递关系:
# 关系Relation"在以下情况下被称为可传递的:# ∀ (a, b) ∈ Relation, (b, c) ∈ Relation ==>(a, c) ∈ 关系
例如:
<预><代码>>>>{(1,1), (1,2), (1,4), (2,1), (2,2), (3,3), (4,1), (4,4)} #应该是假的>>>{(1,1), (2,1), (3,1), (3,2), (4,1), (4,2), (4,3)} # 应该为真对于复合关系:
#关系'R1'和'R2'的复合是组成的关系# 元组 (a,c),使得 (a,b) ∈ R1 和 (b,c) ∈ R2
例如:
{(1,0), (1,1), (2,1), (2,2), (3,0), (3,1)} == R1={(1),1), (1,4), (2,3), (3,1), (3,4)}, R2={(1,0), (2,0), (3,1),(3,2), (4,1)}# 应该返回真
我不确定如何开始编写这些函数.任何让我开始的帮助将不胜感激.谢谢!
以下是我能够成功编码的其他一些关系:
# 自反关系# 集合 'Set' 上的关系 'Relation' 在以下情况下称为自反:# ∀ a ∈ 集合,(a,a) ∈ 关系def is_reflexive(Set, Relation):newSet = {(a, b) for a in Set for b in Set if a == b}如果关系 >= newSet:返回真返回错误# 对称关系# 关系Relation"在以下情况下称为对称关系:# ∀ (a, b) ∈ Relation, (b, a) ∈ Relation定义是_对称(关系):if all(tup[::-1] in Relation for tup in Relation):返回真返回错误
解决方案
对于传递测试,只需转换 Python 中的数学定义:
def is_transitive(relation):对于 a,b 的关系:对于 c,d 的关系:如果 b == c 和((a,d)不相关):# 打印 (a,b),(c,d) # 取消注释测试...返回错误返回真
I'm trying to determine whether or not sets of tuples have a certain type of relation. I'm trying to figure out the transitive relation, and the composite relation.
For the transitive relation:
# A relation 'Relation' is called transitive when:
# ∀ (a, b) ∈ Relation, (b, c) ∈ Relation ==> (a, c) ∈ Relation
For example:
>>> {(1,1), (1,2), (1,4), (2,1), (2,2), (3,3), (4,1), (4,4)} # Should be False
>>> {(1,1), (2,1), (3,1), (3,2), (4,1), (4,2), (4,3)} # Should be True
For the composite relation:
# The composite of relations 'R1' and 'R2' is the relation consisting
# of tuples (a,c), such that (a,b) ∈ R1 and (b,c) ∈ R2
For example:
{(1,0), (1,1), (2,1), (2,2), (3,0), (3,1)} == R1={(1,1), (1,4), (2,3), (3,1), (3,4)}, R2={(1,0), (2,0), (3,1), (3,2), (4,1)}
# Should return True
I am uncertain on how to start coding these functions. Any help to get me started would be greatly appreciated. Thank you!
EDIT: Here are some other relations I was able to successfully code:
# Reflexive Relation
# A relation 'Relation' on a set 'Set' is called reflexive when:
# ∀ a ∈ Set, (a,a) ∈ Relation
def is_reflexive(Set, Relation):
newSet = {(a, b) for a in Set for b in Set if a == b}
if Relation >= newSet:
return True
return False
# Symmetric Relation
# A relation 'Relation' is called symmetric when:
# ∀ (a, b) ∈ Relation, (b, a) ∈ Relation
def is_symmetric(Relation):
if all(tup[::-1] in Relation for tup in Relation):
return True
return False
解决方案
For the transitive test, just convert the math definition in Python:
def is_transitive(relation):
for a,b in relation:
for c,d in relation:
if b == c and ((a,d) not in relation):
# print (a,b),(c,d) # uncomment for tests...
return False
return True
这篇关于Python 与元组集的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文