首页 > 解决方案 > Python 与元组集的传递关系

问题描述

我无法弄清楚如何确定此列表是否可传递

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

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

到目前为止我所拥有的

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.

标签: python

解决方案


鉴于 Mark Dickinson 的评论澄清,

您可以遍历列表并一次性解压缩子数组for a,b in s

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

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

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.')

推荐阅读