I have a TXT in following form, which is the data for Knapsack problem:
100in first row represents the total capacity10in first row represent the number of items- Then each row contains the value and weight for each item. For example, the second row
9 46represents an item with 9 in value and 46 in weight.
100 10\n 9 46\n 28 31\n 15 42\n 13 19\n 31 48\n 36 11\n 13 27\n 42 17\n 28 19\n 1 31
I use the code below to read the information and put it into separate list.
with open(path) as f:
capacity,total_number = f.readline().split(' ')
capacity = int(capacity)
total_number = int(total_number)
value_list = [int(x.split(' ')[0]) for x in f.readlines()]
f.seek(0)
next(f)
weight_list = [int(x.split(' ')[1]) for x in f.readlines()]
assert total_number==len(weight_list)==len(value_list)
But it kinds feel redundant in a way.
Ccould anyone help me with improvements on that?