Python 中的 XOR 线性方程组求解器

问题描述 投票:0回答:2

我有 n 行 n+1 列矩阵,需要构建这样的系统 例如矩阵是

x4 x3 x2 x1 result
1  1  0  1  0
1  0  1  0  1
0  1  0  1  1
1  0  1  1  0

然后等式将是 (+ is XOR)

x4+x3+x1=0
x4+x2=1
x3+x1=1
x4+x2+x1=0

我需要将答案作为 x1 的列表返回,..... 我们如何在 python 中做到这一点?

python equation xor
2个回答
3
投票

您可以使用微软 Z3 求解器的 Python 接口pyz3

from z3 import *

def xor2(a, b):
    return Xor(a, b)

def xor3(a, b, c):
    return Xor(a, Xor(b, c))

#  define Boolean variables
x1 = Bool('x1')
x2 = Bool('x2')
x3 = Bool('x3')
x4 = Bool('x4')

s = Solver()

#  every equation is expressed as one constraint
s.add(Not(xor3(x4, x3, x1)))
s.add(xor2(x4, x2))
s.add(xor2(x3, x1))
s.add(Not(xor3(x4, x2, x1)))

#  solve and output results
print(s.check())
print(s.model())

结果:

sat
[x3 = False, x2 = False, x1 = True, x4 = True]

您可以将软件包安装为:

python -m pip install z3-solver

1
投票

学习高斯,也可以用来异或。然后写一个高斯python程序

© www.soinside.com 2019 - 2024. All rights reserved.