Question: Python. I need help with my program that involves greedy algorithm and bruite force algorithm. The code is already done, however, I am getting some
Python. I need help with my program that involves greedy algorithm and bruite force algorithm. The code is already done, however, I am getting some errors. Thanks
line 119, in subjects = loadSubjects(SHORT_SUBJECT_FILENAME) line 34, in loadSubjects subjects[elems[0]] = (int(elems[1]), int(elems[2])) #set the key to item 1 and 2 , convert string to int for items IndexError: list index out of range
Code: http://www.codesend.com/view/10b08bcc104ec2b4976b3c6d034984d5/
SUBJECT_FILENAME = "subjects.txt" SHORT_SUBJECT_FILENAME = "shortened_subjects.txt" VALUE, WORK = 0, 1
# # Problem 1: Building A Subject Dictionary # def loadSubjects(filename): """ Returns a dictionary mapping subject name to (value, work), where the name is a string and the value and work are integers. The subject information is read from the file named by the string filename. Each line of the file contains a string of the form "name,value,work".
returns: dictionary mapping subject name to (value, work) """
# The following sample code reads lines from the specified file and prints # each one. inputFile = open(filename) subjects = {} #empty dict initializing for line in inputFile: elems = line.strip().split('.') #split the lines by comma, 3 items subjects[elems[0]] = (int(elems[1]), int(elems[2])) #set the key to item 1 and 2 , convert string to int for items print(line)
return subjects
# Instead of printing each line, modify the above to parse the name, # value, and work of each subject and create a dictionary mapping the name # to the (value, work).
def printSubjects(subjects): """ Prints a string containing name, value, and work of each subject in the dictionary of subjects and total value and work of all subjects """ totalVal, totalWork = 0,0 if len(subjects) == 0: return 'Empty SubjectList' res = 'Course\t\tValue\tWork ======\t\t=====\t==== ' subNames = list(subjects.keys()) subNames.sort() for s in subNames: val = subjects[s][VALUE] work = subjects[s][WORK] res = res + s + '\t' + str(val) + '\t' + str(work) + ' ' totalVal += val totalWork += work res = res + ' Total Value:\t' + str(totalVal) +' ' res = res + 'Total Work:\t' + str(totalWork) + ' ' print(res)
# # Problem 2: Subject Selection By Greedy Optimization #
def cmpValue(subInfo1, subInfo2): """ Returns True if value in (value, work) tuple subInfo1 is GREATER than value in (value, work) tuple in subInfo2 """ return subInfo1[VALUE] > subInfo2[VALUE]
def cmpWork(subInfo1, subInfo2): """ Returns True if work in (value, work) tuple subInfo1 is LESS than than work in (value, work) tuple in subInfo2 """ return subInfo1[WORK] < subInfo2[WORK]
def cmpRatio(subInfo1, subInfo2): """ Returns True if value/work in (value, work) tuple subInfo1 is GREATER than value/work in (value, work) tuple in subInfo2 """ return subInfo1[VALUE]/subInfo1[WORK] > subInfo2[VALUE]/subInfo2[WORK]
def greedyAdvisor(subjects, maxWork, comparator): """ Returns a dictionary mapping subject name to (value, work) which includes subjects selected by the algorithm, such that the total work of subjects in the dictionary is not greater than maxWork. The subjects are chosen using a greedy algorithm. The subjects dictionary should not be mutated.
subjects: dictionary mapping subject name to (value, work) maxWork: int >= 0 comparator: function taking two tuples and returning a bool returns: dictionary mapping subject name to (value, work) """ subjectsCopy = subjects.copy() result = {} totalWork = 0 while totalWork < maxWork and len(subjectsCopy) > 0: bestSubName = None for subName in subjectsCopy.keys(): if bestSubName is None or comparator(subjects[subName], subjects[bestSubName]): bestSubName = subName bestSubject = subjectsCopy.pop(bestSubName) if totalWork + bestSubject[WORK] <= maxWork: result[bestSubName] = bestSubject totalWork += bestSubject[WORK] return result
subjects = loadSubjects(SHORT_SUBJECT_FILENAME) print(greedyAdvisor(subjects, 5, cmpRatio))
# # Problem 3: Subject Selection By Brute Force # def bruteForceAdvisor(subjects, maxWork): """ Returns a dictionary mapping subject name to (value, work), which represents the globally optimal selection of subjects using a brute force algorithm.
subjects: dictionary mapping subject name to (value, work) maxWork: int >= 0 returns: dictionary mapping subject name to (value, work) """ subjects = subjects.items() options = [] best = [] for i in range(1, len(subjects)+1): options.append(itertools.combinations(subjects, i)) for schedules in options: for courses in schedules: work = 0 val = 0 bestVal = 0 for i in courses: work += i[1][WORK] if work <= maxWork: for i in courses: val += i[1][VALUE] for i in best: bestVal += i[1][VALUE] if value > bestVal: best = courses return best
#subjects = loadSubjects(SHORT_SUBJECT_FILENAME) #print bruteForceAdvisor(subjects, 7)
************************************************************************************************************************************8
The text in subjects.txt : http://www.codesend.com/view/3524b59ed9eb74b3436a908e164dd2e8/ The text in shortened_subjects.txt: http://www.codesend.com/view/484666f65f0b698ee9522bdcea7f8929/
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
