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
import uuid
import datetime
import math


class User:
    def __init__(self, name):
        self.full_name = name
        self.uuid = uuid.uuid4()
        self.posts = list()
        self.patrons = set()
        self.followers = set()

    def add_post(self, post_content):
        to_add = Post(self.uuid, datetime.datetime.now(), post_content)
        if len(self.posts) < 50:
            self.posts.append(to_add)
        else:
            self.posts = self.posts[1:50]
            self.posts.append(to_add)

    def get_post(self):
        yield from (x for x in self.posts)

    def __repr__(self):
        return str(self.full_name)

    def __str__(self):
        return str(self.full_name)


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

    def __lt__(self, other):
        return self.published_at > other.published_at

    def __repr__(self):
        return str(self.content)

    def __str__(self):
        return str(self.content)


class UserDoesNotExistError(Exception):
    def __init__(self):
        self.message = "No such user in the SocialGraph!"

    def __repr__(self):
        return str(self.message)

    def __str__(self):
        return str(self.message)


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = "User has already been added to the SocialGraph!"

    def __repr__(self):
        return str(self.message)

    def __str__(self):
        return str(self.message)


class UsersNotConnectedError(Exception):
    def __init__(self):
        self.message = "Users not connected in the SocialGraph!"

    def __repr__(self):
        return str(self.message)

    def __str__(self):
        return str(self.message)


class SelfFollowingError(Exception):
    def __init__(self):
        self.message = "A User cannot follow themselves!"

    def __repr__(self):
        return str(self.message)

    def __str__(self):
        return str(self.message)


def merge(first, second):
    result = list()
    index_one = 0
    index_two = 0
    limit_one = len(first)
    limit_two = len(second)
    first1 = list(first)
    second2 = list(reversed(second))
    while index_one < limit_one and index_two < limit_two:
        if first1[index_one] < second2[index_two]:
            result.append(first1[index_one])
            index_one += 1
        else:
            result.append(second2[index_two])
            index_two += 1
    while index_one < limit_one:
            result.append(first1[index_one])
            index_one += 1
    while index_two < limit_two:
            result.append(second2[index_two])
            index_two += 1
    return result


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

    def add_user(self, user):
        if user.uuid in self.users:
            raise UserAlreadyExistsError
        self.users[user.uuid] = user
        for i in user.patrons:
            self.users[i].followers.add(user.uuid)
        for i in user.followers:
            self.users[i].patrons.add(user.uuid)

    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 i in self.users[user_uuid].patrons:
            self.unfollow(user_uuid, i)
        for i in self.users[user_uuid].followers:
            self.unfollow(i, 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 SelfFollowingError
        self.users[follower].patrons.add(followee)
        self.users[followee].followers.add(follower)

    def unfollow(self, follower, followee):
        if follower not in self.users or followee not in self.users:
            raise UserDoesNotExistError
        if followee in self.users[follower].patrons:
            self.users[follower].patrons.remove(followee)
        if follower in self.users[followee].followers:
            self.users[followee].followers.remove(follower)

    def is_following(self, follower, followee):
        if follower not in self.users or followee not in self.users:
            raise UserDoesNotExistError
        if followee in self.users[follower].patrons and \
                follower in self.users[followee].followers:
            return True
        return False

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

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

    def friends(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        user_friends = set()
        for i in self.users[user_uuid].patrons:
            if user_uuid in self.users[i].patrons:
                user_friends.add(i)
        return user_friends

    def get_next_layer(self, current_level, already_traversed):
        next_layer = (
                        [[j for j in self.users[current_level[i]].patrons
                         if j not in already_traversed]
                            for i in range(len(current_level))]
                      )
        result = [item for sublist in next_layer for item in sublist]
        already_traversed.extend(result)
        return result

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        if n <= 0:
            return set()
        current_level = [user_uuid]
        traversed = [user_uuid]
        counter = 0
        while counter < n:
            current_level = self.get_next_layer(current_level, traversed)
            counter += 1
        return set(current_level)

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.users or\
                to_user_uuid not in self.users:
            raise UserDoesNotExistError
        if from_user_uuid == to_user_uuid:
            return 0
        current_level = [from_user_uuid]
        traversed = [from_user_uuid]
        min_distance = 0
        while to_user_uuid not in current_level and len(current_level) > 0:
            current_level = self.get_next_layer(current_level, traversed)
            min_distance += 1
        if len(current_level) > 0:
            return min_distance
        raise UsersNotConnectedError

    def max_distance(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        if bool(self.users[user_uuid].patrons) == False:
            return math.inf
        depth = -1
        current_level = [user_uuid]
        traversed = [user_uuid]
        while bool(current_level) == True:
            current_level = self.get_next_layer(current_level, traversed)
            depth += 1
        return depth

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        needed = offset + limit
        buffer = []
        for i in self.users[user_uuid].patrons:
            length = len(self.users[i].posts)
            if length < needed:
                buffer = merge(buffer, self.users[i].posts)
            else:
                buffer = merge(buffer, self.users[i].posts[0:needed])
            if len(buffer) > needed:
                buffer = buffer[0:needed]
        if len(buffer) < offset:
            return buffer
        return buffer[offset::]

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

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

OK

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

Даниел обнови решението на 16.04.2016 10:41 (преди над 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
import uuid
import datetime
import math


class User:
    def __init__(self, name):
        self.full_name = name
        self.uuid = uuid.uuid4()
        self.posts = list()
        self.patrons = set()
        self.followers = set()

    def add_post(self, post_content):
        to_add = Post(self.uuid, datetime.datetime.now(), post_content)
        if len(self.posts) < 50:
            self.posts.append(to_add)
        else:
            self.posts = self.posts[1:50]
            self.posts.append(to_add)

    def get_post(self):
        yield from (x for x in self.posts)

    def __repr__(self):
        return str(self.full_name)

    def __str__(self):
        return str(self.full_name)


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

    def __lt__(self, other):
        return self.published_at > other.published_at

    def __repr__(self):
        return str(self.content)

    def __str__(self):
        return str(self.content)


class UserDoesNotExistError(Exception):
    def __init__(self):
        self.message = "No such user in the SocialGraph!"

    def __repr__(self):
        return str(self.message)

    def __str__(self):
        return str(self.message)


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = "User has already been added to the SocialGraph!"

    def __repr__(self):
        return str(self.message)

    def __str__(self):
        return str(self.message)


class UsersNotConnectedError(Exception):
    def __init__(self):
        self.message = "Users not connected in the SocialGraph!"

    def __repr__(self):
        return str(self.message)

    def __str__(self):
        return str(self.message)


class SelfFollowingError(Exception):
    def __init__(self):
        self.message = "A User cannot follow themselves!"

    def __repr__(self):
        return str(self.message)

    def __str__(self):
        return str(self.message)


def merge(first, second):
    result = list()
    index_one = 0
    index_two = 0
    limit_one = len(first)
    limit_two = len(second)
    first1 = list(first)
    second2 = list(reversed(second))
    while index_one < limit_one and index_two < limit_two:
        if first1[index_one] < second2[index_two]:
            result.append(first1[index_one])
            index_one += 1
        else:
            result.append(second2[index_two])
            index_two += 1
    while index_one < limit_one:
            result.append(first1[index_one])
            index_one += 1
    while index_two < limit_two:
            result.append(second2[index_two])
            index_two += 1
    return result


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

    def add_user(self, user):
        if user.uuid in self.users:
            raise UserAlreadyExistsError
        self.users[user.uuid] = user
        for i in user.patrons:
            self.users[i].followers.add(user.uuid)
        for i in user.followers:
            self.users[i].patrons.add(user.uuid)

    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 i in self.users[user_uuid].patrons:
            self.unfollow(user_uuid, i)
        for i in self.users[user_uuid].followers:
            self.unfollow(i, 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 SelfFollowingError
        self.users[follower].patrons.add(followee)
        self.users[followee].followers.add(follower)

    def unfollow(self, follower, followee):
        if follower not in self.users or followee not in self.users:
            raise UserDoesNotExistError
        if followee in self.users[follower].patrons:
            self.users[follower].patrons.remove(followee)
        if follower in self.users[followee].followers:
            self.users[followee].followers.remove(follower)

    def is_following(self, follower, followee):
        if follower not in self.users or followee not in self.users:
            raise UserDoesNotExistError
        if followee in self.users[follower].patrons and \
                follower in self.users[followee].followers:
            return True
        return False

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

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

    def friends(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        user_friends = set()
        for i in self.users[user_uuid].patrons:
            if user_uuid in self.users[i].patrons:
                user_friends.add(i)
        return user_friends

    def get_next_layer(self, current_level, already_traversed):
        next_layer = (
                        [[j for j in self.users[current_level[i]].patrons
                         if j not in already_traversed]
                            for i in range(len(current_level))]
                      )
        result = [item for sublist in next_layer for item in sublist]
        already_traversed.extend(result)
        return result

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        if n <= 0:
            return set()
        current_level = [user_uuid]
        traversed = [user_uuid]
        counter = 0
        while counter < n:
            current_level = self.get_next_layer(current_level, traversed)
            counter += 1
        return set(current_level)

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.users or\
                to_user_uuid not in self.users:
            raise UserDoesNotExistError
        if from_user_uuid == to_user_uuid:
            return 0
        current_level = [from_user_uuid]
        traversed = [from_user_uuid]
        min_distance = 0
        while to_user_uuid not in current_level and len(current_level) > 0:
            current_level = self.get_next_layer(current_level, traversed)
            min_distance += 1
        if len(current_level) > 0:
            return min_distance
        raise UsersNotConnectedError

    def max_distance(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        if bool(self.users[user_uuid].patrons) == False:
            return math.inf
        depth = -1
        current_level = [user_uuid]
        traversed = [user_uuid]
        while bool(current_level) == True:
            current_level = self.get_next_layer(current_level, traversed)
            depth += 1
        return depth

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        needed = offset + limit
        buffer = []
        for i in self.users[user_uuid].patrons:
            length = len(self.users[i].posts)
            if length < needed:
                buffer = merge(buffer, self.users[i].posts)
            else:
                buffer = merge(buffer, self.users[i].posts[0:needed])
            if len(buffer) > needed:
                buffer = buffer[0:needed]
        if len(buffer) < offset:
            return buffer
        return buffer[offset::]