python程序给出错误(分数背包问题)
python的分数背包问题当我运行代码时会出现一个错误,就是split函数不适用于整数值python程序给出错误(分数背包问题),python,algorithm,greedy,Python,Algorithm,Greedy,python的分数背包问题当我运行代码时会出现一个错误,就是split函数不适用于整数值 Traceback (most recent call last): File "C:/Users/Akshay/Desktop/python/kapsack_problem.py", line 49, in <module> .format(n)).split() File "<string>", line 1 60 100 120 ^ S
Traceback (most recent call last):
File "C:/Users/Akshay/Desktop/python/kapsack_problem.py", line 49, in <module>
.format(n)).split()
File "<string>", line 1
60 100 120
^
SyntaxError: invalid syntax
回溯(最近一次呼叫最后一次):
文件“C:/Users/Akshay/Desktop/python/kapsack_problem.py”,第49行,在
.format(n)).split()
文件“”,第1行
60 100 120
^
SyntaxError:无效语法
下面是一个Python程序的源代码,该程序使用贪婪算法解决分数背包问题。我做错了什么请告诉我。
提前谢谢
def fractional_knapsack(value, weight, capacity):
index = list(range(len(value)))
# contains ratios of values to weight
ratio = [v/w for v, w in zip(value, weight)]
# index is sorted according to value-to-weight ratio in decreasing order
index.sort(key=lambda i: ratio[i], reverse=True)
max_value = 0
fractions = [0]*len(value)
for i in index:
if weight[i] <= capacity:
fractions[i] = 1
max_value += value[i]
capacity -= weight[i]
else:
fractions[i] = capacity/weight[i]
max_value += value[i]*capacity/weight[i]
break
return max_value, fractions
n = int(input('Enter number of items: '))
value = input('Enter the values of the {} item(s) in order: '
.format(n)).split()
value = [int(v) for v in value]
weight = input('Enter the positive weights of the {} item(s) in order: '
.format(n)).split()
weight = [int(w) for w in weight]
capacity = int(input('Enter maximum weight: '))
max_value, fractions = fractional_knapsack(value, weight, capacity)
print('The maximum value of items that can be carried:', max_value)
print('The fractions in which the items should be taken:', fractions)
def分数_背包(价值、重量、容量):
索引=列表(范围(长度(值)))
#包含值与权重的比率
比率=[v/w代表v,拉链中的w(值、重量)]
#索引按值与权重之比降序排序
sort(key=lambda i:ratio[i],reverse=True)
最大值=0
分数=[0]*len(值)
对于索引中的i:
如果weight[i]似乎您试图使用python2.x
解释器运行此代码,而您的代码是用python3
编写的。为了能够运行它,您需要检查机器上是否安装了python3
(有关安装说明,请参阅)。
跑,跑
python3 my_script.py
在终端中。
另一种可能是粘贴
#!/usr/bin/env python3
在python脚本的顶部。然后,如果您使该文件可执行(例如在ubuntu上运行chmod+xmyscript.py
),那么您只需使用
./my_script.py
你的代码在我的机器上运行得很好。我运行它,输入一些值,它会返回一些答案。