继续在python中获取语法错误

时间:2014-01-23 01:53:53

标签: python syntax

我正在进行麻省理工学院开放课件课程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

2 个答案:

答案 0 :(得分:2)

通常情况下,错误行高于报告的错误行:

      d2={candidate:subjects[candidate]
      NA.append(candidate)

在这种情况下,您没有关闭d2声明

中的大括号
      d2={candidate:subjects[candidate]} #<--- here
      NA.append(candidate)

答案 1 :(得分:1)

          d2={candidate:subjects[candidate]
          NA.append(candidate)

你掉了一根支撑。

下次,请查看错误消息:

    NA.append(candidate)
     ^
SyntaxError: invalid syntax
然后看看它指向的线和它上面的线。