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


class Queue:
    def __init__(self):
        self.data = []

    def pop(self):
        return self.data.pop(0)

    def push(self, x):
        if self.empty():
            self.data.append(x)
        else:
            self.data.insert(0, x)

    def empty(self):
        return len(self.data) == 0


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

    def add_post(self, post_content):
        if len(self.posts) >= 50:
            self.posts.pop(0)

        self.posts.append(Post(self.uuid, datetime.now(), post_content))

    def get_post(self):
        return (post for post in self.posts)


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.__adjacency_list = {}

    def __exists(self, user_uuid):
        return user_uuid in self.__adjacency_list

    def add_user(self, user):
        if self.__exists(user.uuid):
            raise UserAlreadyExistsError
        else:
            self.__adjacency_list[user.uuid] = (user, [])

    def get_user(self, user_uuid):
        if self.__exists(user_uuid):
            return self.__adjacency_list[user_uuid][0]
        else:
            raise UserDoesNotExistError

    def delete_user(self, user_uuid):
        if self.__exists(user_uuid):
            del self.__adjacency_list[user_uuid]
            for id, data in self.__adjacency_list.items():
                if user_uuid in data[1]:
                    data[1].remove(user_uuid)
        else:
            raise UserDoesNotExistError

    def follow(self, follower, followee):
        if not self.__exists(follower) or not self.__exists(followee):
            raise UserDoesNotExistError

        if not self.is_following(follower, followee):
            self.__adjacency_list[follower][1].append(followee)

    def unfollow(self, follower, followee):
        if not self.__exists(follower) or not self.__exists(followee):
            raise UserDoesNotExistError

        if followee in self.__adjacency_list[follower][1]:
            self.__adjacency_list[follower][1].remove(followee)

    def is_following(self, follower, followee):
        if not self.__exists(follower) or not self.__exists(followee):
            raise UserDoesNotExistError

        if followee in self.__adjacency_list[follower][1]:
            return True
        else:
            return False

    def followers(self, user_uuid):
        if not self.__exists(user_uuid):
            raise UserDoesNotExistError

        return {id for id, user in self.__adjacency_list.items()
                if user_uuid in user[1]}

    def following(self, user_uuid):
        if not self.__exists(user_uuid):
            raise UserDoesNotExistError

        return set(self.__adjacency_list[user_uuid][1])

    def friends(self, user_uuid):
        if not self.__exists(user_uuid):
            raise UserDoesNotExistError

        return {id for id, user in self.__adjacency_list.items()
                if id in self.__adjacency_list[user_uuid][1] and
                user_uuid in self.__adjacency_list[id][1]}

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

        if n == 0:
            return []

        visited = []
        bfs_queue = Queue()

        bfs_queue.push(user_uuid)
        visited.append(user_uuid)
        distances = {user_uuid: 0}

        while not bfs_queue.empty():
            current = bfs_queue.pop()
            for node in self.__adjacency_list[current][1]:
                if node not in visited:
                    visited.append(node)
                    distances[node] = distances[current] + 1
                    bfs_queue.push(node)

        return [node for node, distance in distances.items() if distance == n]

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

        result = 0
        while self.nth_layer_followings(user_uuid, result + 1) != []:
            result += 1

        if result != 0:
            return result
        else:
            return inf

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

        if from_user_uuid == to_user_uuid:
            return 0

        level = 1
        layer = self.nth_layer_followings(from_user_uuid, level)
        while layer != []:
            if to_user_uuid in layer:
                return level
            level += 1
            layer = self.nth_layer_followings(from_user_uuid, level)

        return inf

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

        feed = [post for id in self.__adjacency_list[user_uuid][1]
                for post in self.get_user(id).get_post()]

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


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass

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

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

OK

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

Кристофър обнови решението на 18.04.2016 01:04 (преди над 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
from uuid import uuid4
from datetime import datetime
from math import inf


class Queue:
    def __init__(self):
        self.data = []

    def pop(self):
        return self.data.pop(0)

    def push(self, x):
        if self.empty():
            self.data.append(x)
        else:
            self.data.insert(0, x)

    def empty(self):
        return len(self.data) == 0


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

    def add_post(self, post_content):
        if len(self.posts) >= 50:
            self.posts.pop(0)

        self.posts.append(Post(self.uuid, datetime.now(), post_content))

    def get_post(self):
        return (post for post in self.posts)


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


class SocialGraph:
    __adjacency_list = {}

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

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

    def delete_user(self, user_uuid):
        if user_uuid in self.__adjacency_list:
            del self.__adjacency_list[user_uuid]
            for id, data in self.__adjacency_list.items():
                if user_uuid in data[1]:
                    data[1].remove(user_uuid)
        else:
            raise UserDoesNotExistError

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

        if followee not in self.__adjacency_list[follower][1]:
            self.__adjacency_list[follower][1].append(followee)

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

        if followee in self.__adjacency_list[follower][1]:
            self.__adjacency_list[follower][1].remove(followee)

    def is_following(self, follower, followee):
        if follower not in self.__adjacency_list or \
           followee not in self.__adjacency_list:
            raise UserDoesNotExistError

        if followee in self.__adjacency_list[follower][1]:
            return True
        else:
            return False

    def followers(self, user_uuid):
        if user_uuid not in self.__adjacency_list:
            raise UserDoesNotExistError

        return {id for id, user in self.__adjacency_list.items()
                if user_uuid in user[1]}

    def following(self, user_uuid):
        if user_uuid not in self.__adjacency_list:
            raise UserDoesNotExistError

        return set(self.__adjacency_list[user_uuid][1])

    def friends(self, user_uuid):
        if user_uuid not in self.__adjacency_list:
            raise UserDoesNotExistError

        return {id for id, user in self.__adjacency_list.items()
                if id in self.__adjacency_list[user_uuid][1] and
                user_uuid in self.__adjacency_list[id][1]}

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

        if n == 0:
            return []

        visited = []
        bfs_queue = Queue()

        bfs_queue.push(user_uuid)
        visited.append(user_uuid)
        distances = {user_uuid: 0}

        while not bfs_queue.empty():
            current = bfs_queue.pop()
            for node in self.__adjacency_list[current][1]:
                if node not in visited:
                    visited.append(node)
                    distances[node] = distances[current] + 1
                    bfs_queue.push(node)

        return [node for node, distance in distances.items() if distance == n]

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

        result = 0
        while self.nth_layer_followings(user_uuid, result + 1) != []:
            result += 1

        if result != 0:
            return result
        else:
            return inf

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

        if from_user_uuid == to_user_uuid:
            return 0

        level = 1
        layer = self.nth_layer_followings(from_user_uuid, level)
        while layer != []:
            if to_user_uuid in layer:
                return level
            level += 1
            layer = self.nth_layer_followings(from_user_uuid, level)

        return inf

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

        feed = [post for id in self.__adjacency_list[user_uuid][1]
                for post in self.get_user(id).get_post()]

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


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass

Кристофър обнови решението на 18.04.2016 01:28 (преди над 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
from uuid import uuid4
from datetime import datetime
from math import inf


class Queue:
    def __init__(self):
        self.data = []

    def pop(self):
        return self.data.pop(0)

    def push(self, x):
        if self.empty():
            self.data.append(x)
        else:
            self.data.insert(0, x)

    def empty(self):
        return len(self.data) == 0


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

    def add_post(self, post_content):
        if len(self.posts) >= 50:
            self.posts.pop(0)

        self.posts.append(Post(self.uuid, datetime.now(), post_content))

    def get_post(self):
        return (post for post in self.posts)


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.__adjacency_list = {}

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

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

    def delete_user(self, user_uuid):
        if user_uuid in self.__adjacency_list:
            del self.__adjacency_list[user_uuid]
            for id, data in self.__adjacency_list.items():
                if user_uuid in data[1]:
                    data[1].remove(user_uuid)
        else:
            raise UserDoesNotExistError

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

        if followee not in self.__adjacency_list[follower][1]:
            self.__adjacency_list[follower][1].append(followee)

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

        if followee in self.__adjacency_list[follower][1]:
            self.__adjacency_list[follower][1].remove(followee)

    def is_following(self, follower, followee):
        if follower not in self.__adjacency_list or \
           followee not in self.__adjacency_list:
            raise UserDoesNotExistError

        if followee in self.__adjacency_list[follower][1]:
            return True
        else:
            return False

    def followers(self, user_uuid):
        if user_uuid not in self.__adjacency_list:
            raise UserDoesNotExistError

        return {id for id, user in self.__adjacency_list.items()
                if user_uuid in user[1]}

    def following(self, user_uuid):
        if user_uuid not in self.__adjacency_list:
            raise UserDoesNotExistError

        return set(self.__adjacency_list[user_uuid][1])

    def friends(self, user_uuid):
        if user_uuid not in self.__adjacency_list:
            raise UserDoesNotExistError

        return {id for id, user in self.__adjacency_list.items()
                if id in self.__adjacency_list[user_uuid][1] and
                user_uuid in self.__adjacency_list[id][1]}

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

        if n == 0:
            return []

        visited = []
        bfs_queue = Queue()

        bfs_queue.push(user_uuid)
        visited.append(user_uuid)
        distances = {user_uuid: 0}

        while not bfs_queue.empty():
            current = bfs_queue.pop()
            for node in self.__adjacency_list[current][1]:
                if node not in visited:
                    visited.append(node)
                    distances[node] = distances[current] + 1
                    bfs_queue.push(node)

        return [node for node, distance in distances.items() if distance == n]

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

        result = 0
        while self.nth_layer_followings(user_uuid, result + 1) != []:
            result += 1

        if result != 0:
            return result
        else:
            return inf

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

        if from_user_uuid == to_user_uuid:
            return 0

        level = 1
        layer = self.nth_layer_followings(from_user_uuid, level)
        while layer != []:
            if to_user_uuid in layer:
                return level
            level += 1
            layer = self.nth_layer_followings(from_user_uuid, level)

        return inf

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

        feed = [post for id in self.__adjacency_list[user_uuid][1]
                for post in self.get_user(id).get_post()]

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


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass

Кристофър обнови решението на 18.04.2016 14:09 (преди над 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
from uuid import uuid4
from datetime import datetime
from math import inf


class Queue:
    def __init__(self):
        self.data = []

    def pop(self):
        return self.data.pop(0)

    def push(self, x):
        if self.empty():
            self.data.append(x)
        else:
            self.data.insert(0, x)

    def empty(self):
        return len(self.data) == 0


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

    def add_post(self, post_content):
        if len(self.posts) >= 50:
            self.posts.pop(0)

        self.posts.append(Post(self.uuid, datetime.now(), post_content))

    def get_post(self):
        return (post for post in self.posts)


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.__adjacency_list = {}

    def __exists(self, user_uuid):
        return user_uuid in self.__adjacency_list

    def add_user(self, user):
        if self.__exists(user.uuid):
            raise UserAlreadyExistsError
        else:
            self.__adjacency_list[user.uuid] = (user, [])

    def get_user(self, user_uuid):
        if self.__exists(user_uuid):
            return self.__adjacency_list[user_uuid][0]
        else:
            raise UserDoesNotExistError

    def delete_user(self, user_uuid):
        if self.__exists(user_uuid):
            del self.__adjacency_list[user_uuid]
            for id, data in self.__adjacency_list.items():
                if user_uuid in data[1]:
                    data[1].remove(user_uuid)
        else:
            raise UserDoesNotExistError

    def follow(self, follower, followee):
        if not self.__exists(follower) or not self.__exists(followee):
            raise UserDoesNotExistError

        if not self.is_following(follower, followee):
            self.__adjacency_list[follower][1].append(followee)

    def unfollow(self, follower, followee):
        if not self.__exists(follower) or not self.__exists(followee):
            raise UserDoesNotExistError

        if followee in self.__adjacency_list[follower][1]:
            self.__adjacency_list[follower][1].remove(followee)

    def is_following(self, follower, followee):
        if not self.__exists(follower) or not self.__exists(followee):
            raise UserDoesNotExistError

        if followee in self.__adjacency_list[follower][1]:
            return True
        else:
            return False

    def followers(self, user_uuid):
        if not self.__exists(user_uuid):
            raise UserDoesNotExistError

        return {id for id, user in self.__adjacency_list.items()
                if user_uuid in user[1]}

    def following(self, user_uuid):
        if not self.__exists(user_uuid):
            raise UserDoesNotExistError

        return set(self.__adjacency_list[user_uuid][1])

    def friends(self, user_uuid):
        if not self.__exists(user_uuid):
            raise UserDoesNotExistError

        return {id for id, user in self.__adjacency_list.items()
                if id in self.__adjacency_list[user_uuid][1] and
                user_uuid in self.__adjacency_list[id][1]}

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

        if n == 0:
            return []

        visited = []
        bfs_queue = Queue()

        bfs_queue.push(user_uuid)
        visited.append(user_uuid)
        distances = {user_uuid: 0}

        while not bfs_queue.empty():
            current = bfs_queue.pop()
            for node in self.__adjacency_list[current][1]:
                if node not in visited:
                    visited.append(node)
                    distances[node] = distances[current] + 1
                    bfs_queue.push(node)

        return [node for node, distance in distances.items() if distance == n]

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

        result = 0
        while self.nth_layer_followings(user_uuid, result + 1) != []:
            result += 1

        if result != 0:
            return result
        else:
            return inf

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

        if from_user_uuid == to_user_uuid:
            return 0

        level = 1
        layer = self.nth_layer_followings(from_user_uuid, level)
        while layer != []:
            if to_user_uuid in layer:
                return level
            level += 1
            layer = self.nth_layer_followings(from_user_uuid, level)

        return inf

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

        feed = [post for id in self.__adjacency_list[user_uuid][1]
                for post in self.get_user(id).get_post()]

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


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass