我正在做麻省理工学院开放课件课程6.00计算机科学和编程入门课程,我被塞进了第8期作业的第2题,我应该创建一个贪婪的算法,根据价值和工作关系,给学生尽可能最好的科目。
这是我的代码中的一部分,在代码中,我得到了语法错误,并且似乎找不出出了什么问题:
subjects={'6.00': (16, 8),'1.00': (7, 7),'6.01': (5, 3), '15.01': (9, 6)}
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)
"""
bestSubjects={}
currentWork=0
NA=['0']
while currentWork<maxWork:
candidate=find_best_sub(subjects,comparator)
candidate_work= find_work(candidate)
if candidate_work+currentWork<=15:
d2={candidate:subjects[candidate]
NA.append(candidate)
bestSubjects.update(d2)
currentWork+=candidate_work
elif candidate_work+currentWork>15:
continue
return bestSubjects
def find_best_sub(subjects,comparator, NA):
"""returns the best subject according to a comparator, the subject must be available so if it's in the NA list it wont be considered"""
subs= subjects.keys()
subs=list(subs)
best_subject='1.00'
for subject in subs:
if subject not in NA:
if comparator(subjects[subject],subjects[best_subject])== True:
best_subject= subject
elif comparator(subjects[subject],subjects[best_subject])== False:
continue
return best_subject
def find_work(subjects,sub):
work=sub[WORK]
return work发布于 2014-01-23 01:55:52
正如经常发生的那样,错误线高于所报告的一行:
d2={candidate:subjects[candidate]
NA.append(candidate)在本例中,您没有关闭d2声明中的大括号
d2={candidate:subjects[candidate]} #<--- here
NA.append(candidate)发布于 2014-01-23 01:55:46
d2={candidate:subjects[candidate]
NA.append(candidate)你掉了个支架。
下一次,查看错误消息:
NA.append(candidate)
^
SyntaxError: invalid syntax然后看看它指向的那条线和上面的那条线。
https://stackoverflow.com/questions/21297838
复制相似问题