friends_of_friend_ids(用户)函数错误(尝试确定2度连接)

时间:2015-05-29 13:05:28

标签: python

函数friends_of_friend_ids(用户)应该找到朋友的朋友。该功能应根据某些规则计算用户的朋友(见下文)。我正在按照“从零开始的数据科学:使用Python的第一原则”和“#34;以前的一个功能中有一个勘误表。现在我必须调整friends_of_friend_ids(用户)以使其再次起作用。

foaf =朋友的朋友

正确的代码(我认为)

users = [
    {"id": 0, "name": "Ashley"},
    {"id": 1, "name": "Ben"},
    {"id": 2, "name": "Conrad"},
    {"id": 3, "name": "Doug"},
    {"id": 4, "name": "Evin"},
    {"id": 5, "name": "Florian"},
    {"id": 6, "name": "Gerald"}
]

#create list of tuples where each tuple represents a friendships between ids
friendships = [(0,1), (0,2), (0,5), (1,2), (1,5), (2,3), (2,5), (3,4), (4,5), (4,6)]

#add friends key to each user 
for user in users:
    user["friends"] = []

#go through friendships and add each one to the friends key in users
for i, j in friendships:
    users[i]["friends"].append(j)
    users[j]["friends"].append(i)    

#friends of friend projects
def friends_of_friend_ids_bad(user): 
    return [users[foaf]["id"]
        for friend in user["friends"]
        for foaf in users[friend]["friends"]]

def not_the_same(user, other_user):
    return user["id"] != other_user["id"]

def not_friends(user, other_user):
    return all(not_the_same(friend, other_user) 
        for friend in user["friends"])

功能我无法理解

def friends_of_friend_ids(user):
    return Counter(users[foaf]["id"]
        for friend in user["friends"]
        for foaf in users[friend]["friends"]
        if not_the_same(user, foaf) and not_friends(user, foaf)]

1 个答案:

答案 0 :(得分:2)

]中的最后friends_of_friend_ids()替换为),并且循环中的foaf是整数,而不是字典,因此您需要将其解析为用户词典:

def friends_of_friend_ids(user):
    return Counter(users[foaf]["id"]
        for friend in user["friends"]
        for foaf in users[friend]["friends"]
        if not_the_same(user, users[foaf]) and 
           not_friends(user, users[foaf]))

not_friends()中有类似的错误;您需要将ID解析为完整的用户词典:

def not_friends(user, other_user):
    return all(not_the_same(users[friend], other_user) 
        for friend in user["friends"])

生成器表达式基本上是这样做的:

counter = Counter()
for friend in user["friends"]:
    for foaf in users[friend]["friends"]:
        if not_the_same(user, users[foaf]) and not_friends(user, users[foaf]):
            counter[users[foaf]['id']] += 1

注意循环如何以它们在生成器表达式中列出的顺序嵌套。

通过上述两个修复,代码可以正常工作:

>>> for user in users:
...     print('User: {}'.format(user['name']))
...     print(friends_of_friend_ids(user))
... 
User: Ashley
Counter({3: 1, 4: 1})
User: Ben
Counter({3: 1, 4: 1})
User: Conrad
Counter({4: 2})
User: Doug
Counter({5: 2, 0: 1, 1: 1, 6: 1})
User: Evin
Counter({2: 2, 0: 1, 1: 1})
User: Florian
Counter({3: 2, 6: 1})
User: Gerald
Counter({3: 1, 5: 1})