0

我正在学习集体智能的工作原理,并且正在练习第 2 章中的示例 Recommendations.py 问题。这是链接:

http://cdn.jampad.net/Library/collectiveintelligence/#calibre_link-201

当我复制并粘贴此代码时:

# Gets recommendations for a person by using a weighted average
# of every other user's rankings
def getRecommendations(prefs,person,similarity=sim_pearson):
  totals={}
  simSums={}
  for other in prefs:
# don't compare me to myself
if other==person: continue
sim=similarity(prefs,person,other)

# ignore scores of zero or lower
if sim<=0: continue
for item in prefs[other]:

  # only score movies I haven't seen yet
  if item not in prefs[person] or prefs[person][item]==0:
    # Similarity * Score
    totals.setdefault(item,0)totals[item]+=prefs[other][item]*sim
    # Sum of similarities
    simSums.setdefault(item,0)
    simSums[item]+=sim

# Create the normalized list
rankings=[(total/simSums[item],item) for item,total in totals.items(  )]

# Return the sorted list
rankings.sort(  )
rankings.reverse(  )
return rankings

进入我的 Recommendations.py 文件,当我重新加载文件时,我收到一个语法错误。

>>> reload(recommendations)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "recommendations.py", line 100
  totals.setdefault(item,0)totals[item]+=prefs[other][item]*sim
                              ^

SyntaxError: invalid syntax

这就是我收到的信息。我不确定我是否正确复制并粘贴了代码,或者给定的代码行是否错误。

4

1 回答 1

2

这个...

totals.setdefault(item,0)totals[item]+=prefs[other][item]*sim

意味着是两行:

totals.setdefault(item,0)
totals[item]+=prefs[other][item]*sim
于 2012-03-14T07:31:04.963 回答