我想到的是:
我使用linsolve来解线性方程组而不限制域。然后,解集可能是空的,完全确定的,或者依赖于一些自由变量。然后,我尝试对{0,1}中的自由变量进行每种替换,并只收集那些导致解决方案的变量,使每个变量都在{0,1}中。在from sympy import *
def eval_solution(concrete_solution):
concrete_solution_eval = list(map(lambda x: x == 1 or x == 0,concrete_solution))
if sum(concrete_solution_eval) == len(concrete_solution):
return True
return False
def enumerate_solutions(Sols):
if Sols.free_symbols == set(): # no free variables. see if all variables belong to {0,1}
concrete_solution = Sols.args[0]
if concrete_solution == set(): # no solutions
return []
if eval_solution(concrete_solution):
return [concrete_solution]
else:
return []
# create a list of tuples of free variables, one for each valid value
free_vars = []
for i in range(2**len(Sols.free_symbols)):
free_vars.append(tuple(Sols.free_symbols))
# generate values to substitute for free variables
free_vals = [list(bin(i))[2:] for i in range(2**len(Sols.free_symbols))]
free_vals = [tuple(map(int, list('0'*(len(Sols.free_symbols)-len(s)))+s )) for s in free_vals]
# zip twice to generate lists of pairs of variable and value
free_zip = zip(free_vars,free_vals)
free_zip_fin = list([list( zip( x[0], x[1] )) for x in free_zip ] )
correct_solutions = []
for substitution in free_zip_fin:
concrete_solution = list(map(lambda x: x.subs(substitution),Sols.args[0]))
if eval_solution(concrete_solution):
correct_solutions.append(concrete_solution)
return correct_solutions
x1,x2,x3,x4,x5,x6 = symbols('x1,x2,x3,x4,x5,x6')
res=linsolve([x1+x2+x3+x4-1, x3+x4-1, x4+x5-1, x4+x5+x6-2],[x1,x2,x3,x4,x5,x6])
l = enumerate_solutions(res)
print (l)
这可能比你的想法快,也可能不会快。你自己看看这对你有没有用