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
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import uuid
import datetime
import pdb
import math


class User:
    def __init__(self, full_name):
        self.full_name = full_name
        self.uuid = uuid.uuid4()
        self.posts = []
        self.__cnt_posts = 0
        self.__posts_last_at = -1
        self.__followings = set()
        self.__followers = set()
        self.__friends = set()
        self.__member_in = None

    def add_post(self, post_content):
        if len(self.posts) < 50:
            self.posts.append(
                Post(self.uuid, datetime.datetime.now(), post_content))
            self.__posts_last_at += 1
        elif self.__posts_last_at < 49:
            self.posts[self.__posts_last_at] = Post(
                self.uuid, datetime.datetime.now(), post_content)
            self.__posts_last_at += 1
        elif self.__posts_last_at == 49:
            self.__posts_last_at = 0
            self.posts[0] = Post(
                self.uuid, datetime.datetime.now(), post_content)

        if self.__cnt_posts < 50:
            self.__cnt_posts += 1

    def get_post(self):
        if self.__cnt_posts < 50 or self.__posts_last_at == 49:
            at = 0
        else:
            at = self.__posts_last_at + 1

        cnt = 0

        while cnt < self.__cnt_posts:
            if at == 49:
                at = 0
            yield self.posts[at]
            cnt += 1
            at += 1

        raise StopIteration

    def add_follow(self, followee):
        self.__followings.add(followee)
        self.__member_in.get_user(followee).add_follower(self.uuid)
        if self.uuid in self.__member_in.get_user(followee).get_follows():
            self.__friends.add(followee)

    def remove_follow(self, followee):
        self.__followings.discard(followee)
        self.__member_in.get_user(followee).remove_follower(self.uuid)
        if followee in self.__friends:
            self.__friends.discard(followee)

    def is_following(self, followee):
        return followee in self.__followings

    def add_follower(self, followee):
        self.__followers.add(followee)
        if self.uuid in self.__member_in.get_user(followee).get_follows() and\
                followee in self.__followings:
            self.__friends.add(followee)

    def remove_follower(self, followee):
        self.__followers.discard(followee)
        if followee in self.__friends:
            self.__friends.discard(followee)

    def get_follows(self):
        return self.__followings

    def get_followers(self):
        return self.__followers

    def set_membership(self, social_graph):
        self.__member_in = social_graph

    def remove_membership(self):
        self.__member_in = None

    def get_friends(self):
        return self.__friends


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.__users = {}
        self.__min_distance = math.inf
        self.__max_distance = 0

    def get_users(self):
        return self.__users

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

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

    def delete_user(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        else:
            self.__users[user_uuid].remove_membership()
            del self.__users[user_uuid]

    def follow(self, follower, followee):
        if follower not in self.__users.keys() or \
                followee not in self.__users.keys():
            raise UserDoesNotExistError

        self.__users[follower].add_follow(followee)
        self.__users[followee].add_follower(follower)

    def unfollow(self, follower, followee):
        if follower not in self.__users.keys() or \
                followee not in self.__users.keys():
            raise UserDoesNotExistError

        self.__users[follower].remove_follow(followee)
        self.__users[followee].remove_follower(follower)

    def is_following(self, follower, followee):
        return self.__users[follower].is_following(followee)

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

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

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

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

        visited = set()

        self.__calc_max_distance(user_uuid, user_uuid, 0, visited)

        distance = self.__max_distance

        self.__max_distance = 0

        return distance

    def __calc_max_distance(self, original, user, current, visited):
        if current > self.__max_distance and \
                user not in visited and \
                user not in self.__users[original].get_follows():
            self.__max_distance = current

        visited.add(user)

        for follow in self.__users[user].get_follows():
            self.__calc_max_distance(original, follow, current + 1, visited)

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.__users.keys() or \
                to_user_uuid not in self.__users.keys():
            raise UserDoesNotExistError

        self.__calc_min_distance(
            from_user_uuid, from_user_uuid, to_user_uuid, 1)

        distance = self.__min_distance

        self.__min_distance = math.inf

        return distance

    def __calc_min_distance(self, original, from_, to, current):
        if to in self.__users[from_].get_follows() and \
                original not in self.__users[from_].get_follows() and\
                current < self.__min_distance:
            self.__min_distance = current
        else:
            for follow in self.__users[from_].get_follows():
                self.__calc_min_distance(original, follow, to, current + 1)

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

        followings = set()
        self.__layer(user_uuid, followings, n, 1)
        return followings

    def __layer(self, user_uuid, followings, n, current):
        if current == n:
            for follow in self.__users[user_uuid].get_follows():
                followings.add(follow)
        else:
            for follow in self.__users[user_uuid].get_follows():
                self.__layer(follow, followings, n, current + 1)

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.__users.keys():
            raise UsersNotConnectedError
        all_posts = []
        for followee in self.__users[user_uuid].get_follows():
            all_posts.extend(self.__users[followee].posts)

        all_posts.sort(key=lambda post: post.published_at, reverse=True)

        if limit - offset <= len(all_posts):
            return all_posts[offset:offset + limit]

        return all_posts[offset:len(all_posts)]


class UserDoesNotExistError(Exception):
    def __init__(self):
        self.message = "User with that uuid does not exist"


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = "User with that uuid already existing"


class UsersNotConnectedError(Exception):
    def __init__(self):
        self.message = "Users are not connected"

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

........
----------------------------------------------------------------------
Ran 8 tests in 0.065s

OK

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

Георги обнови решението на 17.04.2016 20:17 (преди над 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import uuid
import datetime
import pdb
import math


class User:
    def __init__(self, full_name):
        self.full_name = full_name
        self.uuid = uuid.uuid4()
        self.posts = []
        self.__cnt_posts = 0
        self.__posts_last_at = -1
        self.__followings = set()
        self.__followers = set()
        self.__friends = set()
        self.__member_in = None

    def add_post(self, post_content):
        if len(self.posts) < 50:
            self.posts.append(
                Post(self.uuid, datetime.datetime.now(), post_content))
            self.__posts_last_at += 1
        elif self.__posts_last_at < 49:
            self.posts[self.__posts_last_at] = Post(
                self.uuid, datetime.datetime.now(), post_content)
            self.__posts_last_at += 1
        elif self.__posts_last_at == 49:
            self.__posts_last_at = 0
            self.posts[0] = Post(
                self.uuid, datetime.datetime.now(), post_content)

        if self.__cnt_posts < 50:
            self.__cnt_posts += 1

    def get_post(self):
        if self.__cnt_posts < 50 or self.__posts_last_at == 49:
            at = 0
        else:
            at = self.__posts_last_at + 1

        cnt = 0

        while cnt < self.__cnt_posts:
            if at == 49:
                at = 0
            yield self.posts[at]
            cnt += 1
            at += 1

        raise StopIteration

    def add_follow(self, followee):
        self.__followings.add(followee)
        self.__member_in.get_user(followee).add_follower(self.uuid)
        if self.uuid in self.__member_in.get_user(followee).get_follows():
            self.__friends.add(followee)

    def remove_follow(self, followee):
        self.__followings.discard(followee)
        self.__member_in.get_user(followee).remove_follower(self.uuid)
        if followee in self.__friends:
            self.__friends.discard(followee)

    def is_following(self, followee):
        return followee in self.__followings

    def add_follower(self, followee):
        self.__followers.add(followee)
        if self.uuid in self.__member_in.get_user(followee).get_follows() and\
                followee in self.__followings:
            self.__friends.add(followee)

    def remove_follower(self, followee):
        self.__followers.discard(followee)
        if followee in self.__friends:
            self.__friends.discard(followee)

    def get_follows(self):
        return self.__followings

    def get_followers(self):
        return self.__followers

    def set_membership(self, social_graph):
        self.__member_in = social_graph

    def remove_membership(self):
        self.__member_in = None

    def get_friends(self):
        return self.__friends


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.__users = {}
        self.__min_distance = math.inf
        self.__max_distance = 0

    def get_users(self):
        return self.__users

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

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

    def delete_user(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        else:
            self.__users[user_uuid].remove_membership()
            del self.__users[user_uuid]

    def follow(self, follower, followee):
        if follower not in self.__users.keys() or \
                followee not in self.__users.keys():
            raise UserDoesNotExistError

        self.__users[follower].add_follow(followee)
        self.__users[followee].add_follower(follower)

    def unfollow(self, follower, followee):
        if follower not in self.__users.keys() or \
                followee not in self.__users.keys():
            raise UserDoesNotExistError

        self.__users[follower].remove_follow(followee)
        self.__users[followee].remove_follower(follower)

    def is_following(self, follower, followee):
        return self.__users[follower].is_following(followee)

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

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

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

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

        visited = set()

        self.__calc_max_distance(user_uuid, user_uuid, 0, visited)

        distance = self.__max_distance

        self.__max_distance = 0

        return distance

    def __calc_max_distance(self, original, user, current, visited):
        if current > self.__max_distance and \
                user not in visited and \
                user not in self.__users[original].get_follows():
            self.__max_distance = current

        visited.add(user)

        for follow in self.__users[user].get_follows():
            self.__calc_max_distance(original, follow, current + 1, visited)

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.__users.keys() or \
                to_user_uuid not in self.__users.keys():
            raise UserDoesNotExistError

        self.__calc_min_distance(
            from_user_uuid, from_user_uuid, to_user_uuid, 1)

        distance = self.__min_distance

        self.__min_distance = math.inf

        return distance

    def __calc_min_distance(self, original, from_, to, current):
        if to in self.__users[from_].get_follows() and \
                original not in self.__users[from_].get_follows() and\
                current < self.__min_distance:
            self.__min_distance = current
        else:
            for follow in self.__users[from_].get_follows():
                self.__calc_min_distance(original, follow, to, current + 1)

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

        followings = set()
        self.__layer(user_uuid, followings, n, 1)
        return followings

    def __layer(self, user_uuid, followings, n, current):
        if current == n:
            for follow in self.__users[user_uuid].get_follows():
                followings.add(follow)
        else:
            for follow in self.__users[user_uuid].get_follows():
                self.__layer(follow, followings, n, current + 1)

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.__users.keys():
            raise UsersNotConnectedError
        all_posts = []
        for followee in self.__users[user_uuid].get_follows():
            all_posts.extend(self.__users[followee].posts)

        all_posts.sort(key=lambda post: post.published_at, reverse=True)

        if limit - offset <= len(all_posts):
            return all_posts[offset:offset + limit]

        return all_posts[offset:len(all_posts)]


class UserDoesNotExistError(Exception):
    def __init__(self):
        self.message = "User with that uuid does not exist"


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = "User with that uuid already existing"


class UsersNotConnectedError(Exception):
    def __init__(self):
        self.message = "Users are not connected"
  • __cnt_posts и __posts_last_at дублират информация, която можеш да вземеш като провериш дължината на posts. Това прави add_post и get_post ужасно сложи, при положение, че няма нужда от това.
  • Има много дублираща се функционалност пазене на една и съща информация на две места в User и SocialGraph.