【发布时间】:2017-06-04 09:48:01
【问题描述】:
这是推荐代码.py 编程集体智能书第 2 章。
下面的代码是从偏好字典中返回最佳匹配的人,并通过使用每个其他用户排名的加权平均值来获得推荐人
from math import sqrt
critics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,'The Night Listener': 3.0},'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,'You, Me and Dupree': 3.5},'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,'Superman Returns': 3.5, 'The Night Listener': 4.0},'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,'The Night Listener': 4.5, 'Superman Returns': 4.0,'You, Me and Dupree': 2.5},'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,'You, Me and Dupree': 2.0},'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},'Toby': {'Snakes on a Plane':4.5,'You, Me and Dupree':1.0,'Superman Returns':4.0}}
def sim_distance(prefs,person1,person2): # Get the list of shared_items
si={}
for item in prefs[person1]:
if item in prefs[person2]:
si[item]=1
# if they have no ratings in common, return 0
if len(si)==0:
return 0
# Add up the squares of all the differences
sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)
for item in prefs[person1] if item in prefs[person2]])
return 1/(1+sum_of_squares)
我刚开始使用python,所以我很困惑这两个循环之间有什么区别:
一开始,
for item in prefs[person1]:
if item in prefs[person2]:
最后,
for item in prefs[person1] if item in prefs[person2]])
此外,他们在 implementation 中使用平方根,在这段代码中,他们没有使用过。那么,这只是一个例子还是我们不在代码中使用? 此外,如果这两个 for 循环相同,那么当我像这样应用第二个 for 循环时,它们会给出不同的答案。
for item in prefs[person1]:
if item in prefs[person2]:
sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)])
【问题讨论】:
-
第二个是列表理解的一部分。第一个是典型的循环结构。就根而言,这只是一个执行问题。当然我们在代码中使用它
-
谢谢,是的,我明白了,但是当我以第一个 for 循环方式实现第二个 for 循环时,我得到了不同的答案。我不明白为什么?如果只是执行问题。
-
答案必须相同。但请注意,字典不理解概念或顺序,因此遍历字典可能会产生排序不同的结果;例如,1、2、3 和 2、3、1。
-
以传统方式使用第二个循环,它给出〜0.3,作为列表理解,它给出0.148。我猜,它不应该改变结果值。即使顺序发生变化,for 和 if 循环也会发生变化,我们只关心差异。你对此有什么想法吗?
标签: python