元组集合的Python传递关系



我有麻烦弄清楚如何确定这个列表是否可传递

D1 = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21}

我必须确定r在D1的定义域内是否可传递。我必须检查每一个可能的元组

到目前为止我有什么

def r(x, y):
R = [[9, 7], [9, 5], [9, 3], [9, 1], [7, 5], [7, 3], [7, 1], [5, 3], [3, 1]]
return([x, y] in R)
rIsTransitive = True
for a in D1:
for b in D1:
for c in D1:
for d in D1:
if(r(a, b) and b == c):
rIsTransitive = False
print('The triple (' + str(a) + ',' + str(b) + ',' + str(c) + ') shows that r is not transitive')

if (rIsTransitive):
print('The relation r on domain D1 is transitive.')
else:
print('The relation r on domain D1 is not transitive.')
print(' ')

输出应该是

The triple (5,3,1) shows that r is not transitive
The relation r on domain D1 is not transitive.

我当前的输出

The triple (9,5,5) shows that r is not transitive
The triple (9,5,5) shows that r is not transitive
The triple (9,5,5) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The triple (9,7,7) shows that r is not transitive
The relation r on domain D1 is not transitive.

通过定义R中X>Y中所有的[X,Y],并且希望输出为(5,3,1),可以修改条件并添加语句来停止循环

def r(x, y):
R = [[9, 7], [9, 5], [9, 3], [9, 1], [7, 5], [7, 3], [7, 1], [5, 3], [3, 1]]
return([x, y] in R)
rIsTransitive = True
for a in D1:
for b in D1:
for c in D1:
if(r(a, b) and b > c):
rIsTransitive = False
print('The triple (' + str(a) + ',' + str(b) + ',' + str(c) + ') shows that r is not transitive')
break
if rIsTransitive == False:
break

if (rIsTransitive):
print('The relation r on domain D1 is transitive.')
else:
print('The relation r on domain D1 is not transitive.')
print(' ')

鉴于Mark Dickinson的评论澄清,

你可以迭代你的列表和解包你的子数组在一次使用for a,b in s

则需要2个循环(见下文),一个用于第一对,一个用于第二对。因为你的集合是有序的,你只需要检查b == c和数组[a,d]在集合中,然后你需要输出a,b,d否则你会看到一个带有b==c的三元组

假设你想在第一个不可传递项(5,3,1)之后停止,那么你可以跳出for循环(需要一个标志和条件break)…或者您可以使用生成器函数)

s = [[9, 7], [9, 5], [9, 3], [9, 1], [7, 5], [7, 3], [7, 1], [5, 3], [3, 1]]
def my_non_transitivity_genenerator(value_set):
for a,b in s:
for c,d in s:
yield (b==c and [a,d] not in s,a,b,c,d)
checker = my_non_transitivity_genenerator(s)
for t,a,b,c,d in checker:
if t:
print(f'The triple ({a},{b},{d}) is not transitive')
break
else:
print('The relation r on domain D1 is transitive.')

最新更新