I am writing a Python script that opens a file and for each test case, it should write the total number of items gathered in that case and display the total amount $ that it costs.
When running my code:
f = open("shopping.txt", "r")
outFile = open("results.txt", "w")
t = int(f.readline().strip())
for z in range(t):
# Assuming prices are unique
myList = {}
items = int(f.readline().strip())
ind = 1
# Read each line for each item
for i in range(items):
p, w = map(int, f.readline().strip().split())
myList[p] = [w, ind]
ind+=1
weights = []
F = int(f.readline().strip())
for i in range(F):
weights.append(int(f.readline().strip()))
RES = []
values = []
for weight in weights:
sortedPrice = sorted(myList.keys())[::-1]
m = 0
p = 0
tmp = []
# Grabbing all possible results using greedy method
# Max price stored into values array and item # in RES array.
for i in range(len(myList)):
R = []
s = 0
p = 0
if myList[sortedPrice[i]][0]<=weight:
s=myList[sortedPrice[i]][0]
p=sortedPrice[i]
R+=myList[sortedPrice[i]][1],
for j in range(i+1, len(myList)):
if myList[sortedPrice[j]][0]+s<=weight:
s+=myList[sortedPrice[j]][0]
p+=sortedPrice[j]
R+=myList[sortedPrice[j]][1],
if m<p:
m = p
tmp = R
tmp.sort()
RES.append(tmp)
values.append(m)
outFile.write("Test Case %d\n" %(z+1))
outFile.write("Total Price: %d\n" %(sum(values)))
outFile.write("Member Items:\n")
for i in range(len(RES)):
outFile.write("%d: %s" %(i+1, " ".join(map(str, RES[i]))))
f.close()
outFile.close()
I get the result:
Test Case 1
Total Price: 0
Member Items:
Test Case 2
Total Price: 0
Member Items:
When I expected something like this:
Test Case1
Total Price 72
Member Items
1: 1
Test Case2
Total Price 568
Member Items
1: 3 4
2: 3 6
3: 3 6
4: 3 4 6
I am relatively new to programming in general so if there is any insight anyone could give for my code, I would appreciate it. Adding to this, my guess is that the sum()
and/or the map
commands may be breaking and not working as intended, as I'm writing to the file to get the total value and items of the case.