题目描述
基于关系的矩阵表示,实现关系的自反闭包、对称闭包、传递闭包运算,并计算A上的关系R={<a,b>,<b,a>,<b,c>,<c,d>}的自反闭包、对称闭包、传递闭包,其中A={a,b,c,d}.
编写程序,基于关系的矩阵表示,实现关系的自反闭包、对称闭包、传递闭包运算;利用编写的程序,计算并输出A上的关系R={<a,b>,<b,a>,<b,c>,<c,d>}的自反闭包、对称闭包、传递闭包,其中A={a,b,c,d}.
闭包输出格式示例:
------------------
自反闭包
------------------
{<a,a>,<b,b>,<c,c>,<d,d>,<a,b>,<b,a>,<b,c>,<c,d>}
------------------
Python代码实现:
# 打印自反闭包
def print_reflexive(A, R):
with open("closure.txt", "a") as f:
f.writelines(["------------------\n", "自反闭包\n",
"------------------\n", "{"])
for i in A:
# 形成<i, i>
temp = "<" + i + "," + i + ">"
# 统计<i, i>的个数
number = R.count(temp)
if number == 0:
# 如果<i, i>个数为0,则输出
with open("closure.txt", "a") as f:
f.writelines([temp, ","])
# 打印剩余的序偶
for i in R:
if i == R[-1]:
with open("closure.txt", "a") as f:
f.write(i)
else:
with open("closure.txt", "a") as f:
f.writelines([i, ","])
with open("closure.txt", "a") as f:
f.writelines(["}", "\n", "------------------\n"])
# 打印对称闭包
def print_symmetric(R):
with open("closure.txt", "a") as f:
f.writelines(["------------------\n", "对称闭包\n",
"------------------\n", "{"])
for i in R:
temp = list(i)
# 交换2个元素的位置
temp[1], temp[3] = temp[3], temp[1]
result = ""
# 形成一个元素交换了位置的序偶
for i in temp:
result += i
# 统计其个数
number = R.count(result)
# 如果其个数为0,则输出
if number == 0:
with open("closure.txt", "a") as f:
f.writelines([result, ","])
# 打印剩余序偶
for i in R:
if i == R[-1]:
with open("closure.txt", "a") as f:
f.write(i)
else:
with open("closure.txt", "a") as f:
f.writelines([i, ","])
with open("closure.txt", "a") as f:
f.writelines(["}", "\n", "------------------\n"])
# 打印传递闭包
def print_transitive(R):
with open("closure.txt", "a") as f:
f.writelines(["------------------\n", "传递闭包\n",
"------------------\n", "{"])
r = R
while True:
# 统计新生成序偶的个数
number = 0
for i in r:
temp1 = list(i)
# 如果序偶不是<i, i>型
if temp1[1] != temp1[3]:
for j in r:
temp2 = list(j)
# 如果满足条件,则生成序偶
if temp1[3] == temp2[1]:
result = "<" + temp1[1] + "," + temp2[3] + ">"
# 如果其个数为0,则添加进关系
if r.count(result) == 0:
r.append(result)
number += 1
# 如果新生成序偶的个数为0,说明传递闭包生成完成
if number == 0:
break
for i in r:
if i == r[-1]:
with open("closure.txt", "a") as f:
f.write(i)
else:
with open("closure.txt", "a") as f:
f.writelines([i, ","])
with open("closure.txt", "a") as f:
f.writelines(["}", "\n", "------------------\n"])
if __name__ == "__main__":
# 集合A
A = ["a", "b", "c", "d"]
# 关系R
R = ["<a,b>", "<b,a>", "<b,c>", "<c,d>"]
# 调用函数打印自反 对称 传递闭包
print_reflexive(A, R)
print_symmetric(R)
print_transitive(R)
运行结果:
------------------
自反闭包
------------------
{<a,a>,<b,b>,<c,c>,<d,d>,<a,b>,<b,a>,<b,c>,<c,d>}
------------------
------------------
对称闭包
------------------
{<c,b>,<d,c>,<a,b>,<b,a>,<b,c>,<c,d>}
------------------
------------------
传递闭包
------------------
{<a,b>,<b,a>,<b,c>,<c,d>,<a,a>,<a,c>,<b,b>,<b,d>,<a,d>}
------------------