1

Почему если в строке

if not_the_same(user, users[foaf])
#and not_friends(user, users[foaf])

(пред-предпоследняя) убрать #, программа перестает работать? Причем ошибка выскакивает касательно функции

not_the_same(user, users[foaf])

Ошибка:

return user['id']!=other_user['id']
TypeError: 'int' object has no attribute '__getitem__'

Функция сравнивает id 'юзера' с id друга его друга и дает true, если они отличаются Сам код, сократил как мог.

from collections import Counter

users = [
        {'id': 0, 'name': 'Hero'},
        {'id': 1, 'name': 'Dunn'},
        {'id': 2, 'name': 'Sue'},
        {'id': 3, 'name': 'Chi'},
        {'id': 4, 'name': 'Thor'},
        {'id': 5, 'name': 'Clive'},
        {'id': 6, 'name': 'Hicks'},
        {'id': 7, 'name': 'Devin'},
        {'id': 8, 'name': 'Kate'},
        {'id': 9, 'name': 'Klein'}
        ]

friendships = {(0, 1), (1, 2), (1, 3), (0, 2), (2, 3), (3, 4),
               (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)
               }
for user in users:
    user['friends'] = []
for i, j in friendships:
    users[i]['friends'].append(users[j]['id'])
    users[j]['friends'].append(users[i]['id'])


def not_the_same(user, other_user):
    """ 2 users are not the same if they have different id's"""
    return user['id']!=other_user['id']

def not_friends(user, other_user):
    """ other_user is not a friend if he's not in user['friends'];
    that is, if he's not_the_same as all the people is user['friends']"""
    return all(not_the_same(friend, other_user)
               for friend in user['friends'])

def friends_of_friend_ids(user):
    """foaf = friend of a friend"""
    return Counter(users[foaf]['id']
                  for friend in user['friends']         #for each friend of 
                  for foaf in users[friend]['friends']  #a user's friend
                  if not_the_same(user, users[foaf])
                  #and not_friends(user, users[foaf])
                  )
print friends_of_friend_ids(users[3])

1 ответ 1

1

В user['friends'] хранятся числа, а не словари. Поэтому когда здесь

(not_the_same(friend, other_user) for friend in user['friends'])

в функцию not_the_same передаётся число, а в этой функции выполняется user['id'], возникает ошибка.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.