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
193
194
195
196
197
198
199
200
201
202
203
204
import math
from collections import deque
from uuid import uuid4
from datetime import datetime


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass


class FollowerAndFolloweeAreTheSame(Exception):
    pass


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


class User:

    __GENERATED_UUIDS = set()

    def __init__(self, name):
        self.name = name
        self.uuid = uuid4()
        self.posts = deque(maxlen=50)

    def add_post(self, post_content):
        self.posts.append(Post(self.uuid, post_content))

    def get_post(self):
        return iter(self.posts)


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

    def add_follower(self, user_uuid):
        self.followers.add(user_uuid)

    def add_followee(self, user_uuid):
        self.followees.add(user_uuid)

    def remove_follower(self, user_uuid):
        self.followers.discard(user_uuid)

    def remove_followee(self, user_uuid):
        self.followees.discard(user_uuid)

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


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

    def get_nodes(self, first_uuid, second_uuid):
        first = self.nodes.get(first_uuid)
        second = self.nodes.get(second_uuid)
        if first and second:
            return first, second
        raise UserDoesNotExistError()

    def get_single_node(self, user_uuid):
        if user_uuid in self.nodes:
            return self.nodes[user_uuid]
        raise UserDoesNotExistError()

    def add_user(self, user):
        if self.nodes.get(user.uuid):
            raise UserAlreadyExistsError()
        self.nodes[user.uuid] = Node(user)

    def get_user(self, user_uuid):
        node = self.get_single_node(user_uuid)
        return node.user

    def delete_user(self, user_uuid):
        if self.nodes.get(user_uuid):
            del self.nodes[user_uuid]
        else:
            raise UserDoesNotExistError()

    def follow(self, follower_uuid, followee_uuid):
        if follower_uuid == followee_uuid:
            raise FollowerAndFolloweeAreTheSame()

        follower, followee = self.get_nodes(follower_uuid, followee_uuid)
        follower.add_followee(followee_uuid)
        followee.add_follower(follower_uuid)

    def unfollow(self, follower_uuid, followee_uuid):
        follower, followee = self.get_nodes(follower_uuid, followee_uuid)
        follower.remove_followee(followee_uuid)
        followee.remove_follower(follower_uuid)

    def is_following(self, follower_uuid, followee_uuid):
        if follower_uuid == followee_uuid:
            raise FollowerAndFolloweeAreTheSame()

        follower, followee = self.get_nodes(follower_uuid, followee_uuid)
        return followee_uuid in follower.followees

    def followers(self, user_uuid):
        node = self.get_single_node(user_uuid)
        return node.followers

    def following(self, user_uuid):
        node = self.get_single_node(user_uuid)
        return node.followees

    def friends(self, user_uuid):
        node = self.get_single_node(user_uuid)
        return node.followers.intersection(node.followees)

    def max_distance(self, user_uuid):
        self.get_single_node(user_uuid)
        layered_followers = self.bfs(user_uuid)

        if len(layered_followers) == 1:
            return math.inf
        return len(layered_followers) - 1

    def min_distance(self, from_user_uuid, to_user_uuid):
        first, second = self.get_nodes(from_user_uuid, to_user_uuid)
        layered_followers = self.bfs(from_user_uuid, to_user_uuid)

        if to_user_uuid in layered_followers[-1]:
            return len(layered_followers) - 1
        raise UsersNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        self.get_single_node(user_uuid)
        layered_followers = self.bfs(user_uuid, n)

        if n > 0 and n < len(layered_followers):
            return layered_followers[n]
        return []

    def bfs(self, from_user_uuid, end_condition=None):
        queue = [(0, from_user_uuid)]
        visited = set()
        result = []
        while queue:
            level, current = queue.pop(0)

            if end_condition == level-1:
                break

            if level > len(result)-1:
                result.append([current])
            else:
                result[level].append(current)

            if end_condition == current:
                break

            visited.add(current)
            user = self.nodes[current]
            level += 1
            next_lvl = [(level, v) for v in user.followees if v not in visited]
            queue.extend(next_lvl)

        return result

    def generate_feed(self, user_uuid, offset=0, limit=10):
        node = self.get_single_node(user_uuid)
        all_posts = self.get_all_posts(node)
        return all_posts[offset:(offset+limit)]

    def get_all_posts(self, node):
        fposts = [list(self.nodes[u].get_post())[::-1] for u in node.followees]
        posts = [(x.pop(0), x) for x in fposts]
        result = []
        while posts:
            most_recent = posts[0][0]
            index = 0
            for i, (post, rest) in enumerate(posts):
                if most_recent.published_at < post.published_at:
                    most_recent = post
                    index = i

            result.append(most_recent)
            rest_posts = posts[index][1]
            if rest_posts:
                posts[index] = (rest_posts.pop(0), rest_posts)
            else:
                del posts[index]
        return result

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

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

OK

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

Александър обнови решението на 13.04.2016 19:18 (преди над 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import math
from uuid import uuid4
from datetime import datetime


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass


class FollowerAndFolloweeAreTheSame(Exception):
    pass


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


class PostHistory:
    def __init__(self, author):
        self.posts = []
        self.author = author

    def add(self, post_content):
        if len(self.posts) >= 50:
            self.posts.pop(0)
        self.posts.append(Post(self.author, post_content))

    def get_post(self):
        return iter(self.posts)


class User:

    __GENERATED_UUIDS = set()

    def __init__(self, name):
        self.name = name
        self.uuid = User.__generate_uuid()
        self.posts = PostHistory(self.uuid)

    @staticmethod
    def __generate_uuid():
        while True:
            uuid = uuid4()
            if uuid not in User.__GENERATED_UUIDS:
                return uuid

    def add_post(self, post_content):
        self.posts.add(post_content)

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


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

    def add_follower(self, user_uuid):
        self.followers.add(user_uuid)

    def add_followee(self, user_uuid):
        self.followees.add(user_uuid)

    def remove_follower(self, user_uuid):
        self.followers.discard(user_uuid)

    def remove_followee(self, user_uuid):
        self.followees.discard(user_uuid)

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


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

    def add_user(self, user):
        if self.nodes.get(user.uuid):
            raise UserAlreadyExistsError()
        self.nodes[user.uuid] = Node(user)

    def get_user(self, user_uuid):
        node = self.nodes.get(user_uuid)
        if node:
            return node.user
        raise UserDoesNotExistError()

    def delete_user(self, user_uuid):
        if self.nodes.get(user_uuid):
            del self.nodes[user_uuid]
        else:
            raise UserDoesNotExistError()

    def follow(self, follower_uuid, followee_uuid):
        if follower_uuid == followee_uuid:
            raise FollowerAndFolloweeAreTheSame()

        follower = self.nodes.get(follower_uuid)
        followee = self.nodes.get(followee_uuid)
        if follower and followee:
            follower.add_followee(followee_uuid)
            followee.add_follower(follower_uuid)
        else:
            raise UserDoesNotExistError()

    def unfollow(self, follower_uuid, followee_uuid):
        follower = self.nodes.get(follower_uuid)
        followee = self.nodes.get(followee_uuid)
        if follower and followee:
            follower.remove_followee(followee_uuid)
            followee.remove_follower(follower_uuid)
        else:
            raise UserDoesNotExistError()

    def is_following(self, follower_uuid, followee_uuid):
        if follower_uuid == followee_uuid:
            raise FollowerAndFolloweeAreTheSame()

        follower = self.nodes.get(follower_uuid)
        followee = self.nodes.get(followee_uuid)
        if follower and followee:
            return followee_uuid in follower.followees
        raise UserDoesNotExistError()

    def followers(self, user_uuid):
        node = self.nodes.get(user_uuid)
        if node:
            return node.followers
        raise UserDoesNotExistError()

    def following(self, user_uuid):
        node = self.nodes.get(user_uuid)
        if node:
            return node.followees
        raise UserDoesNotExistError()

    def friends(self, user_uuid):
        node = self.nodes.get(user_uuid)
        if node:
            return node.followers.intersection(node.followees)
        raise UserDoesNotExistError()

    def max_distance(self, user_uuid):
        node = self.nodes.get(user_uuid)
        if not node:
            raise UserDoesNotExistError()

        layered_followers = self.bfs(user_uuid)
        if len(layered_followers) == 1:
            return math.inf
        return len(layered_followers) - 1

    def min_distance(self, from_user_uuid, to_user_uuid):
        first = self.nodes.get(from_user_uuid)
        second = self.nodes.get(to_user_uuid)
        if not first and not second:
            raise UserDoesNotExistError()
        layered_followers = self.bfs(from_user_uuid, to_user_uuid)
        if to_user_uuid in layered_followers[-1]:
            return len(layered_followers) - 1

        raise UsersNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        node = self.nodes.get(user_uuid)
        if not node:
            raise UserDoesNotExistError

        layered_followers = self.bfs(user_uuid, n)
        if n > 0 and n < len(layered_followers):
            return layered_followers[n]
        return []

    def bfs(self, from_user_uuid, end_condition=None):
        queue = [(0, from_user_uuid)]
        visited = set()
        result = []
        while queue:
            level, current = queue.pop(0)

            if end_condition == level-1:
                break

            if level > len(result)-1:
                result.append([current])
            else:
                result[level].append(current)

            if end_condition == current:
                break

            visited.add(current)
            user = self.nodes[current]
            level += 1
            next_lvl = [(level, v) for v in user.followees if v not in visited]
            queue.extend(next_lvl)

        return result

    def generate_feed(self, user_uuid, offset=0, limit=10):
        node = self.nodes.get(user_uuid)
        if not node:
            raise UserDoesNotExistError

        all_posts = self.get_all_posts(node)
        return all_posts[offset:(offset+limit)]

    def get_all_posts(self, node):
        fposts = [list(self.nodes[u].get_post())[::-1] for u in node.followees]
        posts = [(x.pop(0), x) for x in fposts]
        result = []
        while posts:
            most_recent = posts[0][0]
            index = 0
            for i, (post, rest) in enumerate(posts):
                if most_recent.published_at < post.published_at:
                    most_recent = post
                    index = i

            result.append(most_recent)
            rest_posts = posts[index][1]
            if rest_posts:
                posts[index] = (rest_posts.pop(0), rest_posts)
            else:
                del posts[index]
        return result

Александър обнови решението на 18.04.2016 16:46 (преди над 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
194
195
196
197
198
199
200
201
202
203
204
import math
from collections import deque
from uuid import uuid4
from datetime import datetime


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass


class FollowerAndFolloweeAreTheSame(Exception):
    pass


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


class User:

    __GENERATED_UUIDS = set()

    def __init__(self, name):
        self.name = name
        self.uuid = uuid4()
        self.posts = deque(maxlen=50)

    def add_post(self, post_content):
        self.posts.append(Post(self.uuid, post_content))

    def get_post(self):
        return iter(self.posts)


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

    def add_follower(self, user_uuid):
        self.followers.add(user_uuid)

    def add_followee(self, user_uuid):
        self.followees.add(user_uuid)

    def remove_follower(self, user_uuid):
        self.followers.discard(user_uuid)

    def remove_followee(self, user_uuid):
        self.followees.discard(user_uuid)

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


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

    def get_nodes(self, first_uuid, second_uuid):
        first = self.nodes.get(first_uuid)
        second = self.nodes.get(second_uuid)
        if first and second:
            return first, second
        raise UserDoesNotExistError()

    def get_single_node(self, user_uuid):
        if user_uuid in self.nodes:
            return self.nodes[user_uuid]
        raise UserDoesNotExistError()

    def add_user(self, user):
        if self.nodes.get(user.uuid):
            raise UserAlreadyExistsError()
        self.nodes[user.uuid] = Node(user)

    def get_user(self, user_uuid):
        node = self.get_single_node(user_uuid)
        return node.user

    def delete_user(self, user_uuid):
        if self.nodes.get(user_uuid):
            del self.nodes[user_uuid]
        else:
            raise UserDoesNotExistError()

    def follow(self, follower_uuid, followee_uuid):
        if follower_uuid == followee_uuid:
            raise FollowerAndFolloweeAreTheSame()

        follower, followee = self.get_nodes(follower_uuid, followee_uuid)
        follower.add_followee(followee_uuid)
        followee.add_follower(follower_uuid)

    def unfollow(self, follower_uuid, followee_uuid):
        follower, followee = self.get_nodes(follower_uuid, followee_uuid)
        follower.remove_followee(followee_uuid)
        followee.remove_follower(follower_uuid)

    def is_following(self, follower_uuid, followee_uuid):
        if follower_uuid == followee_uuid:
            raise FollowerAndFolloweeAreTheSame()

        follower, followee = self.get_nodes(follower_uuid, followee_uuid)
        return followee_uuid in follower.followees

    def followers(self, user_uuid):
        node = self.get_single_node(user_uuid)
        return node.followers

    def following(self, user_uuid):
        node = self.get_single_node(user_uuid)
        return node.followees

    def friends(self, user_uuid):
        node = self.get_single_node(user_uuid)
        return node.followers.intersection(node.followees)

    def max_distance(self, user_uuid):
        self.get_single_node(user_uuid)
        layered_followers = self.bfs(user_uuid)

        if len(layered_followers) == 1:
            return math.inf
        return len(layered_followers) - 1

    def min_distance(self, from_user_uuid, to_user_uuid):
        first, second = self.get_nodes(from_user_uuid, to_user_uuid)
        layered_followers = self.bfs(from_user_uuid, to_user_uuid)

        if to_user_uuid in layered_followers[-1]:
            return len(layered_followers) - 1
        raise UsersNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        self.get_single_node(user_uuid)
        layered_followers = self.bfs(user_uuid, n)

        if n > 0 and n < len(layered_followers):
            return layered_followers[n]
        return []

    def bfs(self, from_user_uuid, end_condition=None):
        queue = [(0, from_user_uuid)]
        visited = set()
        result = []
        while queue:
            level, current = queue.pop(0)

            if end_condition == level-1:
                break

            if level > len(result)-1:
                result.append([current])
            else:
                result[level].append(current)

            if end_condition == current:
                break

            visited.add(current)
            user = self.nodes[current]
            level += 1
            next_lvl = [(level, v) for v in user.followees if v not in visited]
            queue.extend(next_lvl)

        return result

    def generate_feed(self, user_uuid, offset=0, limit=10):
        node = self.get_single_node(user_uuid)
        all_posts = self.get_all_posts(node)
        return all_posts[offset:(offset+limit)]

    def get_all_posts(self, node):
        fposts = [list(self.nodes[u].get_post())[::-1] for u in node.followees]
        posts = [(x.pop(0), x) for x in fposts]
        result = []
        while posts:
            most_recent = posts[0][0]
            index = 0
            for i, (post, rest) in enumerate(posts):
                if most_recent.published_at < post.published_at:
                    most_recent = post
                    index = i

            result.append(most_recent)
            rest_posts = posts[index][1]
            if rest_posts:
                posts[index] = (rest_posts.pop(0), rest_posts)
            else:
                del posts[index]
        return result