2
我已經使用PuLP庫編寫了以下Python代碼,用於使用Integer編程公式解決揹包問題。我使用字符串來生成LpVariable命令並添加約束,然後使用eval執行它們。有沒有辦法做到這一點,而不使用eval?如何在不使用exec的情況下生成PuLP變量和約束?
from pulp import *
#Knapsack problem
items = input ('Enter the number of items :')
items = int(items)
#print('Enter %d items one by one')
print ('Enter {0} items profit one by one'.format(items))
obj = []
weight = []
knapweight = 0
for i in range(0,items):
print('Enter {0} item profit : '.format(i+1))
obj.append(input())
for i in range(0, items):
print('The profit at {0} is {1}'.format(i, obj[i]))
print ('\nEnter {0} items weights one by one'.format(items))
for i in range(0, items):
print('Enter {0} item weight'.format(i+1))
weight.append(input())
for i in range(0, items):
print('The profit at {0} is {1}'.format(i, weight[i]))
print ('\nEnter the weight of the knapsack :')
knapweight = input()
print ('The weight of the knapsack is : {0}'.format(knapweight))
#generating variables
for i in range(0, items):
str = 'x{0} = LpVariable("x{1}", cat=\'Binary\')'.format(i+1,i+1)
print (str)
exec(str)
prob = LpProblem('Knapsack', LpMaximize)
print ('\nDynamic Generaion\n')
#weight constraint generation
str = "prob += "
for i in range(0, items):
if i == (items-1):
str = str + weight[i] + '*x{0}'.format(i+1)
else:
str = str + weight[i] + '*x{0}'.format(i+1) + '+'
str = str + '<=' + knapweight
exec(str)
print(str)
#objective function generation
str = "prob += "
for i in range(0, items):
if i == (items-1):
str = str + obj[i] + '*x{0}'.format(i+1)
else:
str = str + obj[i] + '*x{0}'.format(i+1) + '+'
exec(str)
print(str)
status = prob.solve()
print(LpStatus[status])
print ('\nThe values of the variables : \n')
for i in range(0, items):
print('x{0} = {1}'.format(i+1, value(eval('x{0}'.format(i+1)))))