分数背包算法 Python 输入问题

Fractional Knapsack Algorithm Python Input Issues

我对 python 的了解还很浅,正在尝试解决这个背包算法问题。

一个例子input/output是:

输入:

3 50

60 20

100 50

120 30

输出:

180.000

下面是我看不懂的代码,在算法题的起始代码文件中提供。对于之前的问题集,我一直用 input() 替换 sys.stdin.read() 因为我更了解它。我认为它试图映射输入,所以它最终是:n = 3,capacity = 50,values = [60, 100, 120],weights = [20, 50, 30]。

if __name__ == "__main__":
    data = list(map(int, sys.stdin.read().split()))
    n, capacity = data[0:2]
    values = data[2:(2 * n + 2):2]
    weights = data[3:(2 * n + 2):2]
    opt_value = get_optimal_value(capacity, weights, values)
    print("{:.10f}".format(opt_value))

我在堆栈的某处读到我可能需要将最后一行更改为:

print("{!s:10f}".format(opt_value))

但这产生了不同的错误

ValueError:'str'.

类型对象的未知格式代码 'f'

如果您能帮助我理解或指出正确的方向,我将不胜感激。谢谢你。

  1. 我会回到 input(),因为它更容易阅读,也少了一件需要担心的事情。

  2. 关于最后一行生成 "unknown format code'f' for object of type 'str'" 的最后一点可能意味着它正在尝试格式化一个数字,但你给它一个字符串。检查 get_optimal_value() returns.

  3. 的值的类型
  4. 这是您的代码的极其粗略的注释版本:

    if __name__ == "__main__": #if it's the main program
    data = list(map(int, sys.stdin.read().split())) #make a list of the input, split up and turned into integers.
    n, capacity = data[0:2] #set n and capacity to the first two values in data
    values = data[2:(2 * n + 2):2] set values equal to a subsection of data. Specifically, every second character from index 2 to index (2 * n + 2).
    weights = data[3:(2 * n + 2):2] #the same as the line above, but starting at 3.
    opt_value = get_optimal_value(capacity, weights, values) #set opt_value to whatever the function returns.
    print("{:.10f}".format(opt_value)) #print the value of opt_value in a fancy way. Specifically, as a floating point number. If you're currently feeding it a string, then Python will squawk at you.
    
  5. 以下是一些可能有用的有用链接: https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3 https://pyformat.info

希望上面的一些内容对你有用。

您也可以使用下面的代码。

if __name__ == "__main__":
data = list(map(int, input().split()))
n, capacity = data
values = [0]*n
weights = [0]*n
for i in range(n):
    values[i], weights[i] = map(int, input().split())
opt_value = get_optimal_value(capacity, weights, values)
print("{:.10f}".format(opt_value))