I"m using combinations to show all total subsets of items possible within a knapsack, So if I had like 10 items, with varying value and weight It'd show all combinations of the items, the total weights which is in the second spot in the tuple (Id,Weight,Val) and the total values, my issue is I'm getting a tuple index out of range error.
#Knapsack
from random import *
from itertools import *
#Creates List of Items, using N for Num of Items
#Weightmax for the max range of weights
#Valmax of max value range
#Each Item has a Id, Weight and Value.
#Represented as a tuple. [(Id,Weight,Value)]
def item_list(n,weightmax,valmax):
items = []
for i in range(1,n+1):
items.append((i,randrange(1,weightmax),randrange(1,valmax)))
return items
#----------------------------------------------------
#Is the Sack, Takes Items as a parameter, and Capacity
#Purpose is to find and print all possible combinations that
#Will fit in the sack,then print which subset has the best
#weight for value mix.
def knapsack(items,capacity):
sack = items
subs = []
print("------------------------------")
print("Subset,"," | ", "Total Weight", " | ", "Total Value")
for i in range(len(sack)+1):
print(i)
for j in combinations(items, i):
subs.append(j)
print(j," | ",j[i][1]," | ",j[i][2])
#------------------------------------
#Main, Asks for UserInput and allows you
#to re-enter mistypes.
def main():
choices = False
print("Welcome to the Knapsack Filler!")
print("Please Input the Following Parameters; ")
while choices is False:
knapcap = int(input("Enter Knapsack Max Capacity: "))
maxweight = int(input("Enter Max Range for Weights: "))
maxval = int(input("Enter Max Value Range for Weights: "))
numitems = int(input("Number of Items you wish to generate: "))
prompt= input("\n Y or N; Are you Sure about your Choices?: ")
if prompt.lower() =="yes" or "y":
choices = True
else:
pass
knapsack(item_list(numitems,maxweight,maxval),knapcap)
main()
Error:
Traceback (most recent call last):
File "C:\CS230\CS320_P2_Knapsack.py", line 54, in <module>
main()
File "C:\CS230\CS320_P2_Knapsack.py", line 53, in main
knapsack(item_list(numitems,maxweight,maxval),knapcap)
File "C:\CS230\CS320_P2_Knapsack.py", line 31, in knapsack
print(j," | ",j[i][1]," | ",j[i][2])
IndexError: tuple index out of range
Sample Input:
Welcome to the Knapsack Filler!
Please Input the Following Parameters;
Enter Knapsack Max Capacity: **30**
Enter Max Range for Weights: **10**
Enter Max Value Range for Weights: **10**
Number of Items you wish to generate: **3**
Y or N; Are you Sure about your Choices?: Y
------------------------------
Subset, | Total Weight | Total Value
0