python - python程序报错(分数背包问题)
问题描述
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
^
SyntaxError: invalid syntax
这是使用贪心算法解决分数背包问题的 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)
解决方案
似乎您尝试使用Python 2.x
解释器运行此代码,而您的代码是用Python 3
. 为了能够运行它,您需要检查Python 3
您的机器上是否安装了它(有关安装说明,请参见此处)。
要运行它,运行
python3 my_script.py
在一个终端。
另一种可能是粘贴
#!/usr/bin/env python3
在你的 python 脚本的顶部。然后,如果您使文件可执行(chmod +x myscript.py
例如通过在 ubuntu 上运行),您可以简单地运行它
./my_script.py
推荐阅读
- angular - 如何在表单提交时显示验证错误
- assembly - 如何访问堆栈上为函数调用传递的未知数量的参数?
- spring - 如何解决这个错误 Servlet.init() for servlet [dispatcher] 抛出异常
- mysql - 如何为开发目的复制 Google Cloud MySQL 数据库?
- kubernetes - 主机名使用 traefik 跨越不同的命名空间?
- javascript - 将 Angular 组件输入参数传递给 CSS 的子 div
- javascript - jQuery:if语句选择一个选项值
- angular - 取消 ngx-datatable 中的编辑行并返回以前的数据
- excel - 对象不支持此属性或方法,如果我声明具有正确类型的变量
- python - Keras - 使用大量功能