最近在写运筹学作业,找不到求所有基解的代码,于是花了一点时间写完,分享给各位不想手算的同学,太痛苦了,只能找出所有
from sympy import symbols, diff, Rational,simplify,ratsimp,Eq,Contains,solve
from itertools import combinations
def enumerate_combinations(n, m,add=0):
# 检查输入参数的有效性
if n < m:
raise ValueError("Number of variables must be greater than or equal to the combination size.")
# 创建一个包含所有变量下标的列表
indices = list(range(n))
indices = [i+add for i in indices]
# 使用combinations函数生成所有可能的下标组合
index_combinations = combinations(indices, m)
# 返回所有组合的下标
return list(index_combinations)
#-----------------------
# x1,x2,x3,x4,x5,x6 = symbols('x1 x2 x3 x4 x5 x6')
# ex1 = 12*x1+3*x2+6*x3+3*x4
# ex2 = 8*x1+x2-4*x3+2*x5
# ex3 = 3*x1-x6
# z = 3*x1+x2+2*x3
# b = [9,10,0]
# tx = [x1,x2,x3,x4,x5,x6]
# tst = [ex1,ex2,ex3]
# x1,x2,x3,x4,x5 = symbols('x1 x2 x3 x4 x5')
# tx = [x1,x2,x3,x4,x5,]
# ex1 = x1+x3
# ex2 = x1+2*x2+x4
# ex3 = x2+x5
n = 5 # 未知数个数
tx = []
tst = []
A = [[1,0,1,0,0],
[1,2,0,1,0],
[0,1,0,0,1]] #约束方程系数
b = [5,10,4] #约束方程右边
zb = [2,3,1] #目标函数系数
for i in range(n):
tx.append(symbols('x'+str(i+1)))
for i in range(len(A)):
shizi = 0
for j in range(len(A[i])):
shizi += A[i][j]*tx[j]
tst.append(shizi)
z = 0
for i in range(len(zb)):
z += tx[i]*zb[i]
m = n - len(tst)
print(tx,tst,z)
#------------------------
m = n - len(tst)
print(m,n)
combinations_indices = enumerate_combinations(n, m)
print(len(combinations_indices))
count = 0
for combination in combinations_indices:# 获取每种组合
count += 1
print("\n---------------------------",count)
st = tst.copy()
x = tx.copy()
tempx = [i for i in range(n)]
for index_combinations in combination:# 将公式的数值替换为0
for _st in range(len(st)):
if x[index_combinations] in st[_st].free_symbols:
st[_st] = st[_st].subs(x[index_combinations],0)
# 求解方程
#print(x,combination)
for i in sorted(list(combination),reverse=True):
x.pop(i)
print("st=",st)
if 0 in st:
print("ERROR")
continue
for i in range(len(st)): #等式和对应关联
st[i] = Eq(st[i],b[i])
print(st,x)
results = solve(tuple(st),tuple(x))
print("令",end="")
for i in combination:
print(tx[i],end=",")
print("= 0")
tempx = [0 for i in range(n)]
for i in range(len(tx)):
if tx[i] in results.keys():
print(tx[i],"=",results[tx[i]],end="\t")
tempx[i] = results[tx[i]]
else:
print(tx[i],"=",0,end="\t")
print()
for i in results.keys():
print(i,"=",results[i])
#计算目标函数
zz = z.copy()
for i in range(n):
if tx[i] in z.free_symbols:
zz = zz.subs(tx[i],tempx[i])
print("z=",zz)