timeit

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

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

Решение на Социална мрежа от Петър Иванов

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

Към профила на Петър Иванов

Резултати

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

Код

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
import uuid
import datetime
from collections import deque


class User:
    MAX_POSTS = 50

    def __init__(self, full_name):
        self.full_name = full_name
        self.__uuid = uuid.uuid4()
        self.__posts = deque([], User.MAX_POSTS)
        self.__followers = set()
        self.__following = set()

    def add_post(self, post_content):
        new_post = Post(self.__uuid, post_content)
        self.__posts.append(new_post)

    def get_post(self):
        for post in range(0, self.__posts.maxlen):
            try:
                yield self.__posts[post]
            except IndexError:
                pass

    @property
    def uuid(self):
        return self.__uuid

    @property
    def posts(self):
        return self.__posts

    @property
    def followers(self):
        return self.__followers

    @property
    def following(self):
        return self.__following

    def __str__(self):
        return self.full_name

    def __repr__(self):
        return str(self)

    def __hash__(self):
        return self.__uuid.int


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

    @property
    def published_at(self):
        return self.__published_at

    def __str__(self):
        return "{} - {}".format(self.author, self.content)

    def __repr__(self):
        return str(self)


class SocialGraph:
    def __init__(self):
        self.__graph = dict()
        self.users = set()

    def add_user(self, user):
        if user in self.users:
            raise UserAlreadyExistsError
        else:
            self.__graph[user] = set()
            self.users.add(user)

    def get_user(self, user_uuid):
        current_user = None
        for user in self.users:
            if user.uuid == user_uuid:
                current_user = user
        if current_user is None:
            raise UserDoesNotExistError
        return current_user

    def delete_user(self, user_uuid):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        else:
            self.users.remove(user)

    def follow(self, follower, followee):
        user_follower = self.get_user(follower)
        user_followee = self.get_user(followee)
        if user_follower is None or user_followee is None:
            raise UserDoesNotExistError
        self.__graph[user_follower].add(user_followee)
        user_follower.following.add(user_followee)
        user_followee.followers.add(user_follower)

    def unfollow(self, follower, followee):
        user_follower = self.get_user(follower)
        user_followee = self.get_user(followee)
        if user_follower is None or user_followee is None:
            raise UserDoesNotExistError
        self.__graph[user_follower].remove(user_followee)
        user_follower.following.remove(user_followee)
        user_followee.followers.remove(user_follower)

    def is_following(self, follower, followee):
        user_follower = self.get_user(follower)
        user_followee = self.get_user(followee)
        if user_follower is None or user_followee is None:
            raise UserDoesNotExistError
        if user_followee in user_follower.following:
            return True
        return False

    def followers(self, user_uuid):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        return user.followers

    def following(self, user_uuid):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        return user.following

    def friends(self, user_uuid):
        user = self.get_user(user_uuid)
        friends = set()
        if user is None:
            raise UserDoesNotExistError
        for i in user.following:
            if user in i.following:
                friends.add(i.uuid)
        return friends

    def max_distance(self, user_uuid):
        to_user = self.get_user(user_uuid)
        if to_user is None:
            raise UserDoesNotExistError

    def min_distance(self, from_user_uuid, to_user_uuid):
        from_user = self.get_user(from_user_uuid)
        to_user = self.get_user(to_user_uuid)
        if from_user is None or to_user is None:
            raise UserDoesNotExistError

        current_level = 0
        visited = set()
        queue = []
        queue.append((current_level, from_user))
        visited.add(from_user)
        found = False

        while len(queue) != 0:
            current_level, current_user = queue.pop(0)

            if current_user.uuid == to_user.uuid:
                found = True
                return current_level

            for user in self.__graph[current_user]:
                if user not in visited:
                    queue.append((current_level + 1, user))
                    visited.add(user)

        if found is False:
            raise UserNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        from_user = self.get_user(user_uuid)
        if from_user is None:
            raise UserDoesNotExistError

        current_level = 1
        visited = set()
        queue = []
        queue.append((current_level, from_user))
        visited.add(from_user)

        while len(queue) != 0:
            current_level, current_user = queue.pop(0)

            if current_level == n:
                following = [user.uuid for user in current_user.following]
                return following

            for user in self.__graph[current_user]:
                if user not in visited:
                    queue.append((current_level + 1, user))
                    visited.add(user)

    def generate_feed(self, user_uuid, offset=0, limit=10):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        following = user.following
        all_posts = []
        for i in following:
            all_posts.extend(i.posts)
        all_posts.sort(key=lambda post: post.published_at, reverse=True)
        return all_posts[offset:offset + limit]


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass


class UserNotConnectedError(Exception):
    pass

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

.F.F....
======================================================================
FAIL: test_distnaces (test.TestSocialGraph)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: None != 2

======================================================================
FAIL: test_following (test.TestSocialGraph)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: False is not true

----------------------------------------------------------------------
Ran 8 tests in 0.064s

FAILED (failures=2)

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

Петър обнови решението на 18.04.2016 16:32 (преди над 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
import uuid
import datetime
from collections import deque


class User:
    MAX_POSTS = 50

    def __init__(self, full_name):
        self.full_name = full_name
        self.__uuid = uuid.uuid4()
        self.__posts = deque([], User.MAX_POSTS)
        self.__followers = set()
        self.__following = set()

    def add_post(self, post_content):
        new_post = Post(self.__uuid, post_content)
        self.__posts.append(new_post)

    def get_post(self):
        for post in range(0, self.__posts.maxlen):
            yield self.__posts[post]

    @property
    def uuid(self):
        return self.__uuid

    @property
    def posts(self):
        return self.__posts

    @property
    def followers(self):
        return self.__followers

    @property
    def following(self):
        return self.__following

    def __str__(self):
        return self.full_name

    def __repr__(self):
        return str(self)

    def __hash__(self):
        return self.__uuid.int


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

    @property
    def published_at(self):
        return self.__published_at

    def __str__(self):
        return "{} - {}".format(self.author, self.content)

    def __repr__(self):
        return str(self)


class SocialGraph:
    def __init__(self):
        self.__graph = dict()
        self.users = set()

    def add_user(self, user):
        if user in self.users:
            raise UserAlreadyExistsError
        else:
            self.__graph[user] = set()
            self.users.add(user)

    def get_user(self, user_uuid):
        current_user = None
        for user in self.users:
            if user.uuid == user_uuid:
                current_user = user
        if current_user is None:
            raise UserDoesNotExistError
        return current_user

    def delete_user(self, user_uuid):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        else:
            self.users.remove(user)

    def follow(self, follower, followee):
        user_follower = self.get_user(follower)
        user_followee = self.get_user(followee)
        if user_follower is None or user_followee is None:
            raise UserDoesNotExistError
        self.__graph[user_follower].add(user_followee)
        user_follower.following.add(user_followee)
        user_followee.followers.add(user_follower)

    def unfollow(self, follower, followee):
        user_follower = self.get_user(follower)
        user_followee = self.get_user(followee)
        if user_follower is None or user_followee is None:
            raise UserDoesNotExistError
        self.__graph[user_follower].remove(user_followee)
        user_follower.following.remove(user_followee)
        user_followee.followers.remove(user_follower)

    def is_following(self, follower, followee):
        user_follower = self.get_user(follower)
        user_followee = self.get_user(followee)
        if user_follower is None or user_followee is None:
            raise UserDoesNotExistError
        if user_followee in user_follower.following:
            return True
        return False

    def followers(self, user_uuid):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        return user.followers

    def following(self, user_uuid):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        return user.following

    def friends(self, user_uuid):
        user = self.get_user(user_uuid)
        friends = set()
        if user is None:
            raise UserDoesNotExistError
        for i in user.following:
            if user in i.following:
                friends.add(i.uuid)
        return friends

    def max_distance(self, user_uuid):
        to_user = self.get_user(user_uuid)
        if to_user is None:
            raise UserDoesNotExistError

    def min_distance(self, from_user_uuid, to_user_uuid):
        from_user = self.get_user(from_user_uuid)
        to_user = self.get_user(to_user_uuid)
        if from_user is None or to_user is None:
            raise UserDoesNotExistError

        current_level = 0
        visited = set()
        queue = []
        queue.append((current_level, from_user))
        visited.add(from_user)
        found = False

        while len(queue) != 0:
            current_level, current_user = queue.pop(0)

            if current_user.uuid == to_user.uuid:
                found = True
                return current_level

            for user in self.__graph[current_user]:
                if user not in visited:
                    queue.append((current_level + 1, user))
                    visited.add(user)

        if found is False:
            raise UserNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        from_user = self.get_user(user_uuid)
        if from_user is None:
            raise UserDoesNotExistError

        current_level = 1
        visited = set()
        queue = []
        queue.append((current_level, from_user))
        visited.add(from_user)

        while len(queue) != 0:
            current_level, current_user = queue.pop(0)

            if current_level == n:
                following = [user.uuid for user in current_user.following]
                return following

            for user in self.__graph[current_user]:
                if user not in visited:
                    queue.append((current_level + 1, user))
                    visited.add(user)

    def generate_feed(self, user_uuid, offset=0, limit=10):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        following = user.following
        all_posts = []
        for i in following:
            all_posts.extend(i.posts)
        all_posts.sort(key=lambda x: x.published_at)
        return all_posts[offset + 1:offset + limit]


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass


class UserNotConnectedError(Exception):
    pass

Петър обнови решението на 18.04.2016 16:45 (преди над 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
import uuid
import datetime
from collections import deque


class User:
    MAX_POSTS = 50

    def __init__(self, full_name):
        self.full_name = full_name
        self.__uuid = uuid.uuid4()
        self.__posts = deque([], User.MAX_POSTS)
        self.__followers = set()
        self.__following = set()

    def add_post(self, post_content):
        new_post = Post(self.__uuid, post_content)
        self.__posts.append(new_post)

    def get_post(self):
        for post in range(0, self.__posts.maxlen):
            try:
                yield self.__posts[post]
            except IndexError:
                pass

    @property
    def uuid(self):
        return self.__uuid

    @property
    def posts(self):
        return self.__posts

    @property
    def followers(self):
        return self.__followers

    @property
    def following(self):
        return self.__following

    def __str__(self):
        return self.full_name

    def __repr__(self):
        return str(self)

    def __hash__(self):
        return self.__uuid.int


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

    @property
    def published_at(self):
        return self.__published_at

    def __str__(self):
        return "{} - {}".format(self.author, self.content)

    def __repr__(self):
        return str(self)


class SocialGraph:
    def __init__(self):
        self.__graph = dict()
        self.users = set()

    def add_user(self, user):
        if user in self.users:
            raise UserAlreadyExistsError
        else:
            self.__graph[user] = set()
            self.users.add(user)

    def get_user(self, user_uuid):
        current_user = None
        for user in self.users:
            if user.uuid == user_uuid:
                current_user = user
        if current_user is None:
            raise UserDoesNotExistError
        return current_user

    def delete_user(self, user_uuid):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        else:
            self.users.remove(user)

    def follow(self, follower, followee):
        user_follower = self.get_user(follower)
        user_followee = self.get_user(followee)
        if user_follower is None or user_followee is None:
            raise UserDoesNotExistError
        self.__graph[user_follower].add(user_followee)
        user_follower.following.add(user_followee)
        user_followee.followers.add(user_follower)

    def unfollow(self, follower, followee):
        user_follower = self.get_user(follower)
        user_followee = self.get_user(followee)
        if user_follower is None or user_followee is None:
            raise UserDoesNotExistError
        self.__graph[user_follower].remove(user_followee)
        user_follower.following.remove(user_followee)
        user_followee.followers.remove(user_follower)

    def is_following(self, follower, followee):
        user_follower = self.get_user(follower)
        user_followee = self.get_user(followee)
        if user_follower is None or user_followee is None:
            raise UserDoesNotExistError
        if user_followee in user_follower.following:
            return True
        return False

    def followers(self, user_uuid):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        return user.followers

    def following(self, user_uuid):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        return user.following

    def friends(self, user_uuid):
        user = self.get_user(user_uuid)
        friends = set()
        if user is None:
            raise UserDoesNotExistError
        for i in user.following:
            if user in i.following:
                friends.add(i.uuid)
        return friends

    def max_distance(self, user_uuid):
        to_user = self.get_user(user_uuid)
        if to_user is None:
            raise UserDoesNotExistError

    def min_distance(self, from_user_uuid, to_user_uuid):
        from_user = self.get_user(from_user_uuid)
        to_user = self.get_user(to_user_uuid)
        if from_user is None or to_user is None:
            raise UserDoesNotExistError

        current_level = 0
        visited = set()
        queue = []
        queue.append((current_level, from_user))
        visited.add(from_user)
        found = False

        while len(queue) != 0:
            current_level, current_user = queue.pop(0)

            if current_user.uuid == to_user.uuid:
                found = True
                return current_level

            for user in self.__graph[current_user]:
                if user not in visited:
                    queue.append((current_level + 1, user))
                    visited.add(user)

        if found is False:
            raise UserNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        from_user = self.get_user(user_uuid)
        if from_user is None:
            raise UserDoesNotExistError

        current_level = 1
        visited = set()
        queue = []
        queue.append((current_level, from_user))
        visited.add(from_user)

        while len(queue) != 0:
            current_level, current_user = queue.pop(0)

            if current_level == n:
                following = [user.uuid for user in current_user.following]
                return following

            for user in self.__graph[current_user]:
                if user not in visited:
                    queue.append((current_level + 1, user))
                    visited.add(user)

    def generate_feed(self, user_uuid, offset=0, limit=10):
        user = self.get_user(user_uuid)
        if user is None:
            raise UserDoesNotExistError
        following = user.following
        all_posts = []
        for i in following:
            all_posts.extend(i.posts)
        all_posts.sort(key=lambda post: post.published_at, reverse=True)
        return all_posts[offset:offset + limit]


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass


class UserNotConnectedError(Exception):
    pass