timeit

Програмиране с Python

Курс във Факултета по Математика и Информатика към СУ

Решение на Социална мрежа от Николай Мантаров

Обратно към всички решения

Към профила на Николай Мантаров

Резултати

  • 10 точки от тестове
  • 0 бонус точки
  • 10 точки общо
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)

Код

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import uuid
import datetime
import math


class User:
    def __init__(self, full_name):
        self.full_name = full_name
        self.uuid = uuid.uuid4()
        self.posts = []

    def add_post(self, post_content):
        post = Post(self.uuid, datetime.datetime.now(), post_content)
        if len(self.posts) == 50:
            del self.posts[0]
        self.posts.append(post)

    def get_post(self):
        for post in self.posts:
            yield post


class Post:
    def __init__(self, author, published_at, content):
        self.author = author
        self.published_at = published_at
        self.content = content


class SocialGraph:
    def __init__(self):
        self.graph = {}
        self.__users = {}

    def add_user(self, user):
        if user.uuid not in self.__users:
            self.graph[user.uuid] = []
            self.__users[user.uuid] = user
        else:
            raise UserAlreadyExistsError

    def get_user(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        return self.__users[user_uuid]

    def delete_user(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        for user in self.graph:
            self.unfollow(user_uuid, user)
        del self.graph[user_uuid]
        del self.__users[user_uuid]

    def follow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        if follower == followee:
            raise CantFollowYourselfError
        if not self.is_following(follower, followee):
            self.graph[followee].append(self.__users[follower])

    def unfollow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        for element in self.graph[followee]:
            if element.uuid == follower:
                index = self.graph[followee].index(element)
                del self.graph[followee][index]

    def is_following(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        for user in self.graph[followee]:
            if follower is user.uuid:
                return True
        return False

    def followers(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        result = set()
        for user in self.graph[user_uuid]:
            result.add(user.uuid)
        return result

    def following(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        return {user for user in self.graph
                if self.is_following(user_uuid, user)}

    def friends(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        followers = self.followers(user_uuid)
        following = self.following(user_uuid)
        return following.intersection(followers)

    def max_distance(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        distance = []
        for user in self.graph:
            try:
                distance.append(self.min_distance(user_uuid, user))
            except UsersNotConnectedError:
                pass
        if len(distance) == 1:
            return math.inf
        return max(distance)

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.graph or to_user_uuid not in self.graph:
            raise UserDoesNotExistError
        if from_user_uuid == to_user_uuid:
            return 0
        que = [from_user_uuid]
        visited = []
        level = 0
        item_count = 1
        while len(que) > 0:
            if item_count == 0:
                level += 1
                item_count = len(que)
            item_count -= 1
            user = que[0]
            del que[0]
            visited.append(user)
            if user == to_user_uuid:
                return level
            for element in self.following(user):
                if element not in visited:
                    que.append(element)
        raise UsersNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.graph:
            raise UserDoesNotExistError
        if n == 0:
            return set()
        result = set()
        for user in self.graph:
            try:
                if self.min_distance(user_uuid, user) == n:
                    result.add(user)
            except UsersNotConnectedError:
                pass
        return result

    def generate_feed(self, user_uuid, offset=0, limit=10):
        following = self.following(user_uuid)
        posts = []
        for user in following:
            posts.extend(self.get_user(user).posts)
        posts.sort(key=lambda x: x.published_at, reverse=True)
        return posts[offset:offset+limit]


class UserAlreadyExistsError(Exception):
    pass


class UserDoesNotExistError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass


class CantFollowYourselfError(Exception):
    pass

Лог от изпълнението

........
----------------------------------------------------------------------
Ran 8 tests in 0.074s

OK

История (2 версии и 1 коментар)

Николай обнови решението на 17.04.2016 12:42 (преди над 1 година)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import uuid
import datetime
import math


class User:
    def __init__(self, full_name):
        self.full_name = full_name
        self.uuid = uuid.uuid4()
        self.posts = []

    def add_post(self, post_content):
        post = Post(self.uuid, datetime.datetime.now(), post_content)
        if len(self.posts) == 50:
            del self.posts[0]
        self.posts.append(post)

    def get_post(self):
        for post in self.posts:
            yield post


class Post:
    def __init__(self, author, published_at, content):
        self.author = author
        self.published_at = published_at
        self.content = content


class SocialGraph:
    def __init__(self):
        self.graph = {}

    def add_user(self, user):
        if user.uuid not in self.graph:
            self.graph[user.uuid] = [user]
        else:
            raise UserAlreadyExistsError

    def get_user(self, user_uuid):
        if user_uuid not in self.graph:
            raise UserDoesNotExistError
        return self.graph[user_uuid][0]

    def delete_user(self, user_uuid):
        if user_uuid not in self.graph:
            raise UserDoesNotExistError
        for user in self.graph:
            self.unfollow(user_uuid, user)
        del self.graph[user_uuid]

    def follow(self, follower, followee):
        if follower not in self.graph or followee not in self.graph:
            raise UserDoesNotExistError
        if follower == followee:
            raise CantFollowYourselfError
        if not self.is_following(follower, followee):
            self.graph[followee].append(self.get_user(follower))

    def unfollow(self, follower, followee):
        if follower not in self.graph or followee not in self.graph:
            raise UserDoesNotExistError
        for element in range(1, len(self.graph[followee])):
            if self.graph[followee][element].uuid == follower:
                del self.graph[followee][element]

    def is_following(self, follower, followee):
        if follower not in self.graph or followee not in self.graph:
            raise UserDoesNotExistError
        length = len(self.graph[followee])
        for index in range(1, length):
            if follower is self.graph[followee][index].uuid:
                return True
        return False

    def followers(self, user_uuid):
        if user_uuid not in self.graph:
            raise UserDoesNotExistError
        result = set()
        length = len(self.graph[user_uuid])
        for index in range(1, length):
            result.add(self.graph[user_uuid][index].uuid)
        return result

    def following(self, user_uuid):
        if user_uuid not in self.graph:
            raise UserDoesNotExistError
        return {user for user in self.graph
                if self.is_following(user_uuid, user)}

    def friends(self, user_uuid):
        if user_uuid not in self.graph:
            raise UserDoesNotExistError
        followers = self.followers(user_uuid)
        following = self.following(user_uuid)
        result = {user for user in followers if user in following}
        return result

    def max_distance(self, user_uuid):
        if user_uuid not in self.graph:
            raise UserDoesNotExistError
        distance = []
        for user in self.graph:
            try:
                distance.append(self.min_distance(user_uuid, user))
            except UsersNotConnectedError:
                pass
        if len(distance) == 1:
            return math.inf
        return max(distance)

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.graph or to_user_uuid not in self.graph:
            raise UserDoesNotExistError
        if from_user_uuid == to_user_uuid:
            return 0
        que = [from_user_uuid]
        que.append('level up')
        visited = [from_user_uuid]
        level = 0
        while True:
            if que[0] == 'level up':
                level = level + 1
                del que[0]
                que.append('level up')
            user = que[0]
            if user == 'level up':
                raise UsersNotConnectedError
            visited.append(user)
            if user == to_user_uuid:
                    return level
            del que[0]
            for element in self.following(user):
                if element not in visited:
                    que.append(element)

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.graph:
            raise UserDoesNotExistError
        if n == 0:
            return []
        level = 0
        followers = [user_uuid]
        followers.append('level up')
        parents = {user_uuid: []}
        while True:
            if followers[0] == 'level up':
                level = level + 1
                del followers[0]
                followers.append('level up')
            if level == n:
                break
            user = followers[0]
            if user == 'level up':
                return []
            del followers[0]
            for element in self.following(user):
                if element not in parents:
                    parents[element] = []
                    for parent in parents[user]:
                        parents[element].append(parent)
                    parents[element].append(user)
                    followers.append(element)

                elif element not in parents[user]:
                    parents[user].extend(parents[user])
                    followers.append(element)
        followers.pop()
        return followers

    def generate_feed(self, user_uuid, offset=0, limit=10):
        following = self.following(user_uuid)
        posts = []
        for user in following:
            posts.extend(self.get_user(user).posts)
        posts.sort(key=lambda x: x.published_at, reverse=True)
        return posts[offset:offset+limit]


class UserAlreadyExistsError(Exception):
    pass


class UserDoesNotExistError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass


class CantFollowYourselfError(Exception):
    pass
  • Факта, че на нулев апозиция в graph списъка има нещо „магическо“ е много объркващо. Това прави кода ти доста сложен за разбиране. Като цяло там седи релацията на следене, но го има и самия потребител, който обаче не може да следи сам себе си. Не е яко.
  • За friends разгледай по-добре методите на set, там има нещо, което е много подходящо.
  • Виж queue модула от вградената библиотека.
  • Неща като 'level up' стринга е по-добре да са в глобални константи. Отделно е най-добре да ги няма, а да решиш проблема по по-различен начин. Това е сходен дизайн проблем на този с нулевия индекс в graph.

Николай обнови решението на 18.04.2016 16:38 (преди над 1 година)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import uuid
import datetime
import math


class User:
    def __init__(self, full_name):
        self.full_name = full_name
        self.uuid = uuid.uuid4()
        self.posts = []

    def add_post(self, post_content):
        post = Post(self.uuid, datetime.datetime.now(), post_content)
        if len(self.posts) == 50:
            del self.posts[0]
        self.posts.append(post)

    def get_post(self):
        for post in self.posts:
            yield post


class Post:
    def __init__(self, author, published_at, content):
        self.author = author
        self.published_at = published_at
        self.content = content


class SocialGraph:
    def __init__(self):
        self.graph = {}
        self.__users = {}

    def add_user(self, user):
        if user.uuid not in self.__users:
            self.graph[user.uuid] = []
            self.__users[user.uuid] = user
        else:
            raise UserAlreadyExistsError

    def get_user(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        return self.__users[user_uuid]

    def delete_user(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        for user in self.graph:
            self.unfollow(user_uuid, user)
        del self.graph[user_uuid]
        del self.__users[user_uuid]

    def follow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        if follower == followee:
            raise CantFollowYourselfError
        if not self.is_following(follower, followee):
            self.graph[followee].append(self.__users[follower])

    def unfollow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        for element in self.graph[followee]:
            if element.uuid == follower:
                index = self.graph[followee].index(element)
                del self.graph[followee][index]

    def is_following(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        for user in self.graph[followee]:
            if follower is user.uuid:
                return True
        return False

    def followers(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        result = set()
        for user in self.graph[user_uuid]:
            result.add(user.uuid)
        return result

    def following(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        return {user for user in self.graph
                if self.is_following(user_uuid, user)}

    def friends(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        followers = self.followers(user_uuid)
        following = self.following(user_uuid)
        return following.intersection(followers)

    def max_distance(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        distance = []
        for user in self.graph:
            try:
                distance.append(self.min_distance(user_uuid, user))
            except UsersNotConnectedError:
                pass
        if len(distance) == 1:
            return math.inf
        return max(distance)

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.graph or to_user_uuid not in self.graph:
            raise UserDoesNotExistError
        if from_user_uuid == to_user_uuid:
            return 0
        que = [from_user_uuid]
        visited = []
        level = 0
        item_count = 1
        while len(que) > 0:
            if item_count == 0:
                level += 1
                item_count = len(que)
            item_count -= 1
            user = que[0]
            del que[0]
            visited.append(user)
            if user == to_user_uuid:
                return level
            for element in self.following(user):
                if element not in visited:
                    que.append(element)
        raise UsersNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.graph:
            raise UserDoesNotExistError
        if n == 0:
            return set()
        result = set()
        for user in self.graph:
            try:
                if self.min_distance(user_uuid, user) == n:
                    result.add(user)
            except UsersNotConnectedError:
                pass
        return result

    def generate_feed(self, user_uuid, offset=0, limit=10):
        following = self.following(user_uuid)
        posts = []
        for user in following:
            posts.extend(self.get_user(user).posts)
        posts.sort(key=lambda x: x.published_at, reverse=True)
        return posts[offset:offset+limit]


class UserAlreadyExistsError(Exception):
    pass


class UserDoesNotExistError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass


class CantFollowYourselfError(Exception):
    pass