fraction knapsack problem with python it gives an error when i'm running the code, is the split function is not working for the integer values.
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
Here is the source code of a Python program to solve the fractional knapsack problem using greedy algorithm. what i'm doing wrong please tell me. thanks in advance.
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)
It seems that you try to run this code with a Python 2.x
interpreter, while your code is written in Python 3
. In order to be able to run it, you need to check that Python 3
is installed on your machine (see here for installations instructions).
To run it, run
python3 my_script.py
in a terminal.
Another possiblity is to paste
#!/usr/bin/env python3
at the top of your python script. Then if you make the file executable (by running chmod +x myscript.py
on ubuntu for instance), you can then run it simply with
./my_script.py
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.