簡體   English   中英

python程序報錯(分數背包問題)

[英]python program give error(fraction knapsack problem)

python的分數背包問題它在我運行代碼時出現錯誤,是拆分函數不適用於整數值。

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 腳本的頂部。 然后,如果您使文件可執行(例如,通過在 ubuntu 上運行chmod +x myscript.py ),則可以簡單地運行它

./my_script.py

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM