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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import uuid
from datetime import datetime


FEED_LIM = 50


class UserDoesNotExistError(KeyError):
    def __init__(self, message=''):
        super(KeyError, self).__init__(message)


class UserAlreadyExistsError(RuntimeError):
    def __init__(self, message=''):
        super(RuntimeError, self).__init__(message)


class UsersNotConnectedError(RuntimeError):
    def __init__(self, message=''):
        super(RuntimeError, self).__init__(message)


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


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

    def add_post(self, post_content):
        if (self.post_pos < FEED_LIM):
            self.posts.append(Post(self.uuid, post_content))
        else:
            post = Post(self.uuid, post_content)
            self.posts[self.post_pos % FEED_LIM] = post
        self.post_pos += 1

    def get_post(self):
        if len(self.posts) is 0:
            return iter([])
        self.posts.sort(key=lambda post: post.published_at)
        return (post for post in self.posts)


class Node:
    def __init__(self, user):
        self.user = user
        self.following = set()

    def get_post(self):
        return self.user.get_post()

    def add_post(self, post_content):
        self.user.add_post(post_content)


class SocialGraph:
    def __init__(self):
        self.users = {}
        self.uuids = set()

    def add_user(self, user):
        if user.uuid in self.uuids:
            raise UserAlreadyExistsError()
        self.users[user.uuid] = Node(user)
        self.uuids.add(user.uuid)

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

    def delete_user(self, user_uuid):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()
        for user in self.users.values():
            user.following.discard(user_uuid)
        del self.users[user_uuid]
        self.uuids.remove(user_uuid)

    def follow(self, follower, followee):
        if follower not in self.uuids:
            raise UserDoesNotExistError("Follower doesn't exist")
        if followee not in self.uuids:
            raise UserDoesNotExistError("Followee doesn't exist")
        self.users[follower].following.add(followee)

    def unfollow(self, follower, followee):
        if follower not in self.uuids:
            raise UserDoesNotExistError("Follower doesn't exist")
        if followee not in self.uuids:
            raise UserDoesNotExistError("Followee doesn't exist")
        self.users[follower].following.discard(followee)

    def is_following(self, follower, followee):
        if follower not in self.uuids:
            raise UserDoesNotExistError("Follower doesn't exist")
        if followee not in self.uuids:
            raise UserDoesNotExistError("Followee doesn't exist")
        return followee in self.users[follower].following

    def followers(self, user_uuid):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()
        return {
                uuid for uuid, user in self.users.items()
                if user_uuid in user.following
                }

    def following(self, user_uuid):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()
        return self.users[user_uuid].following

    def friends(self, user_uuid):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()
        following = self.users[user_uuid].following
        return {uid for uid in following if user_uuid in self.following(uid)}

    def max_distance(self, user_uuid):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()

        dist, visited, bfs_queue = {user_uuid: 0}, set(), [user_uuid]
        while bfs_queue:
            curr_vertex = bfs_queue.pop(0)
            level = dist[curr_vertex]
            if curr_vertex not in visited:
                next_vertecies = self.users[curr_vertex].following
                update = {
                          v: level + 1 for v in next_vertecies
                          if v not in dist.keys()
                         }
                dist.update(update)
                visited.add(curr_vertex)
                bfs_queue.extend(self.users[curr_vertex].following - visited)
        return max(dist.values())

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.uuids:
            raise UserDoesNotExistError()
        if to_user_uuid not in self.uuids:
            raise UserDoesNotExistError()

        dist, visited, bfs_queue = {from_user_uuid: 0}, set(), [from_user_uuid]
        while bfs_queue:
            curr_vertex = bfs_queue.pop(0)
            level = dist[curr_vertex]
            if self.users[curr_vertex].user.uuid is to_user_uuid:
                return level
            if curr_vertex not in visited:
                next_vertecies = self.users[curr_vertex].following
                dist.update({v: level + 1 for v in next_vertecies})
                visited.add(curr_vertex)
                bfs_queue.extend(self.users[curr_vertex].following - visited)
        raise UsersNotConnectedError()

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()

        dist, visited, bfs_queue = {user_uuid: 0}, set(), [user_uuid]
        while bfs_queue:
            curr_vertex = bfs_queue.pop(0)
            level = dist[curr_vertex]
            if level is n + 1:
                break
            if curr_vertex not in visited:
                next_vertecies = self.users[curr_vertex].following
                dist.update({v: level + 1 for v in next_vertecies})
                visited.add(curr_vertex)
                bfs_queue.extend(self.users[curr_vertex].following - visited)
        return [uuid for uuid, level in dist.items() if level is n]

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()

        feed, followees = [], self.users[user_uuid].following
        for followee in followees:
                feed.extend(self.users[followee].user.posts)

        feed.sort(key=lambda p: p.published_at, reverse=True)
        return feed[offset: offset + limit]

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

........
----------------------------------------------------------------------
Ran 8 tests in 0.063s

OK

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

Николай обнови решението на 18.04.2016 13:47 (преди над 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
import uuid
from datetime import datetime


FEED_LIM = 50


class UserDoesNotExistError(KeyError):
    def __init__(self, message=''):
        super(KeyError, self).__init__(message)


class UserAlreadyExistsError(RuntimeError):
    def __init__(self, message=''):
        super(RuntimeError, self).__init__(message)


class UsersNotConnectedError(RuntimeError):
    def __init__(self, message=''):
        super(RuntimeError, self).__init__(message)


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


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

    def add_post(self, post_content):
        if (self.post_pos < FEED_LIM):
            self.posts.append(Post(self.uuid, post_content))
        else:
            post = Post(self.uuid, post_content)
            self.posts[self.post_pos % FEED_LIM] = post
        self.post_pos += 1

    def get_post(self):
        if len(self.posts) is 0:
            return iter([])
        self.posts.sort(key=lambda post: post.published_at)
        return (post for post in self.posts)


class Node:
    def __init__(self, user):
        self.user = user
        self.following = set()

    def get_post(self):
        return self.user.get_post()

    def add_post(self, post_content):
        self.user.add_post(post_content)


class SocialGraph:
    def __init__(self):
        self.users = {}
        self.uuids = set()

    def add_user(self, user):
        if user.uuid in self.uuids:
            raise UserAlreadyExistsError()
        self.users[user.uuid] = Node(user)
        self.uuids.add(user.uuid)

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

    def delete_user(self, user_uuid):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()
        for user in self.users.values():
            user.following.discard(user_uuid)
        del self.users[user_uuid]
        self.uuids.remove(user_uuid)

    def follow(self, follower, followee):
        if follower not in self.uuids:
            raise UserDoesNotExistError("Follower doesn't exist")
        if followee not in self.uuids:
            raise UserDoesNotExistError("Followee doesn't exist")
        self.users[follower].following.add(followee)

    def unfollow(self, follower, followee):
        if follower not in self.uuids:
            raise UserDoesNotExistError("Follower doesn't exist")
        if followee not in self.uuids:
            raise UserDoesNotExistError("Followee doesn't exist")
        self.users[follower].following.discard(followee)

    def is_following(self, follower, followee):
        if follower not in self.uuids:
            raise UserDoesNotExistError("Follower doesn't exist")
        if followee not in self.uuids:
            raise UserDoesNotExistError("Followee doesn't exist")
        return followee in self.users[follower].following

    def followers(self, user_uuid):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()
        return {
                uuid for uuid, user in self.users.items()
                if user_uuid in user.following
                }

    def following(self, user_uuid):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()
        return self.users[user_uuid].following

    def friends(self, user_uuid):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()
        following = self.users[user_uuid].following
        return {uid for uid in following if user_uuid in self.following(uid)}

    def max_distance(self, user_uuid):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()

        dist, visited, bfs_queue = {user_uuid: 0}, set(), [user_uuid]
        while bfs_queue:
            curr_vertex = bfs_queue.pop(0)
            level = dist[curr_vertex]
            if curr_vertex not in visited:
                next_vertecies = self.users[curr_vertex].following
                update = {
                          v: level + 1 for v in next_vertecies
                          if v not in dist.keys()
                         }
                dist.update(update)
                visited.add(curr_vertex)
                bfs_queue.extend(self.users[curr_vertex].following - visited)
        return max(dist.values())

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.uuids:
            raise UserDoesNotExistError()
        if to_user_uuid not in self.uuids:
            raise UserDoesNotExistError()

        dist, visited, bfs_queue = {from_user_uuid: 0}, set(), [from_user_uuid]
        while bfs_queue:
            curr_vertex = bfs_queue.pop(0)
            level = dist[curr_vertex]
            if self.users[curr_vertex].user.uuid is to_user_uuid:
                return level
            if curr_vertex not in visited:
                next_vertecies = self.users[curr_vertex].following
                dist.update({v: level + 1 for v in next_vertecies})
                visited.add(curr_vertex)
                bfs_queue.extend(self.users[curr_vertex].following - visited)
        raise UsersNotConnectedError()

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()

        dist, visited, bfs_queue = {user_uuid: 0}, set(), [user_uuid]
        while bfs_queue:
            curr_vertex = bfs_queue.pop(0)
            level = dist[curr_vertex]
            if level is n + 1:
                break
            if curr_vertex not in visited:
                next_vertecies = self.users[curr_vertex].following
                dist.update({v: level + 1 for v in next_vertecies})
                visited.add(curr_vertex)
                bfs_queue.extend(self.users[curr_vertex].following - visited)
        return [uuid for uuid, level in dist.items() if level is n]

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.uuids:
            raise UserDoesNotExistError()

        feed, followees = [], self.users[user_uuid].following
        for followee in followees:
                feed.extend(self.users[followee].user.posts)

        feed.sort(key=lambda p: p.published_at, reverse=True)
        return feed[offset: offset + limit]