python - 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.
解决方案
鉴于 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.')
推荐阅读
- javascript - 为函数参数赋值,重用函数参数是否安全?
- jquery - Woocommerce 截断类别描述;我如何重用代码创建“少读”按钮
- c# - 在 Windows 窗体中运行时更改 EF 6 连接字符串
- python - python服务访问ajax调用,CORS错误
- python - 如何使用机器学习和 LSTM 确定价格预测中的层数和单位数?
- reactjs - 如何在反应涟漪上使用 onClick?
- angular - Matomo - Angular:跟踪页面视图和事件仅部分工作
- angular-cli - 架构验证失败并出现以下错误:数据路径“”应该具有必需的属性“browserTarget”
- python-3.x - 在 Tkinter 中使用 VGA 字体
- list - Arrow-kt:如何转动 Either
>> 进入 >