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


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

    def add_post(self, post_content):
        self.posts = self.posts[-49:]
        self.posts.append(Post(self, post_content))
        return self.posts

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


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


class SocialGraph:
    def __init__(self):
        self.graph_for_user_uuids = defaultdict(set)
        self.users = defaultdict(User)

    def check_user_exist(self, user_uuid):
        if user_uuid not in self.graph_for_user_uuids:
            raise UserDoesNotExistError

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

    def get_user(self, user_uuid):
        self.check_user_exist(user_uuid)
        return self.users[user_uuid]

    def delete_user(self, user_uuid):
        self.check_user_exist(user_uuid)
        del self.users[user_uuid]
        del self.graph_for_user_uuids[user_uuid]

    def follow(self, follower, followee):
        self.check_user_exist(follower)
        self.check_user_exist(followee)
        if follower == followee:
            raise ValueError("User cannot follow himsel")
        self.graph_for_user_uuids[follower].add(followee)

    def unfollow(self, follower, followee):
        self.check_user_exist(follower)
        self.check_user_exist(followee)
        if follower == followee:
            raise ValueError("User cannot unfollow himsel")
        if self.is_following(follower, followee):
            self.graph_for_user_uuids[follower].remove(followee)

    def is_following(self, follower, followee):
        self.check_user_exist(follower)
        self.check_user_exist(followee)
        if follower == followee:
            raise ValueError("User cannot follow himsel")
        if followee in self.graph_for_user_uuids[follower]:
            return True
        return False

    def followers(self, user_uuid):
        self.check_user_exist(user_uuid)
        followers = set()
        for user in self.graph_for_user_uuids:
            if user_uuid in self.graph_for_user_uuids[user]:
                followers.add(user)
        return followers

    def following(self, user_uuid):
        self.check_user_exist(user_uuid)
        return set(self.graph_for_user_uuids[user_uuid])

    def friends(self, user_uuid):
        self.check_user_exist(user_uuid)
        user_followers = self.followers(user_uuid)
        user_following = self.following(user_uuid)
        return user_followers & user_following

    def __find_min_path(self, from_user_uuid, to_user_uuid, path=[]):
        if from_user_uuid == to_user_uuid and path == []:
            return None
        path = path + [from_user_uuid]
        if from_user_uuid == to_user_uuid:
            return path
        if from_user_uuid not in self.graph_for_user_uuids:
            return None
        shortest = None
        for vertex in self.graph_for_user_uuids[from_user_uuid]:
            if vertex not in path:
                newpath = self.__find_min_path(vertex, to_user_uuid, path)
                if newpath:
                    if not shortest or len(newpath) < len(shortest):
                        shortest = newpath
        return shortest

    def max_distance(self, user_uuid):
        self.check_user_exist(user_uuid)
        distances = [0]
        for user in self.graph_for_user_uuids:
            distance = self.__find_min_path(user_uuid, user)
            if distance is not None:
                distances.append(len(distance))

        if distances == [0]:
            return math.inf
        return max(distances) - 1

    def min_distance(self, from_user_uuid, to_user_uuid):
        self.check_user_exist(from_user_uuid)
        self.check_user_exist(to_user_uuid)

        distance = self.__find_min_path(from_user_uuid, to_user_uuid)
        if distance is None:
            raise UsersNotConnectedError
        return len(distance) - 1

    def nth_layer_followings(self, user_uuid, n):
        self.check_user_exist(user_uuid)
        if n < 0:
            raise ValueError("Nth layer cannot be negative")
        if n == 0:
            return set()
        distances = []
        for user in self.graph_for_user_uuids:
            distance = self.__find_min_path(user_uuid, user)
            if distance is not None:
                distances.append(distance)

        return set([distance[n]
                    for distance in distances if len(distance) == n + 1])

    def generate_feed(self, user_uuid, offset=0, limit=10):
        self.check_user_exist(user_uuid)
        if offset < 0 or limit < 0:
            raise ValueError("Offset and limit cannot be negative")
        feed = []
        user_following = self.graph_for_user_uuids[user_uuid]
        for user in user_following:
            a = self.users[user].get_post()
            for post in a:
                feed.append(post)

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

        return feed[offset:(limit + offset)]


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


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = "User already exist"


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

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

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

OK

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

Борис обнови решението на 16.04.2016 00:12 (преди над 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
from uuid import uuid4
from datetime import datetime
from collections import defaultdict
import math


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

    def add_post(self, post_content):
        self.posts = self.posts[-49:]
        self.posts.append(Post(self, post_content))
        return self.posts

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


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


class SocialGraph:
    def __init__(self):
        self.graph_ids = defaultdict(list)
        self.users = defaultdict(User)

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

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

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

    def follow(self, follower, followee):
        if follower not in self.graph_ids or \
                followee not in self.graph_ids:
            raise UserDoesNotExistError
        if follower == followee:
            raise UserCannotFollowHimself
        else:
            self.graph_ids[follower].append(followee)

    def unfollow(self, follower, followee):
        if follower not in self.graph_ids or \
                followee not in self.graph_ids:
            raise UserDoesNotExistError
        else:
            self.graph_ids[follower].remove(followee)

    def is_following(self, follower, followee):
        if follower not in self.graph_ids or \
                followee not in self.graph_ids:
            raise UserDoesNotExistError
        if follower == followee:
            raise UserCannotFollowHimself
        else:
            if followee in self.graph_ids[follower]:
                return True
            else:
                return False

    def followers(self, user_uuid):
        if user_uuid not in self.graph_ids:
            raise UserDoesNotExistError
        else:
            buffer_set = set()
            for user_id in self.graph_ids:
                if user_uuid in self.graph_ids[user_id]:
                    buffer_set.add(user_id)
            return buffer_set

    def following(self, user_uuid):
        if user_uuid not in self.graph_ids:
            raise UserDoesNotExistError
        else:
            return set(self.graph_ids[user_uuid])

    def friends(self, user_uuid):
        if user_uuid not in self.graph_ids:
            raise UserDoesNotExistError
        else:
            user_followers = self.followers(user_uuid)
            user_following = self.following(user_uuid)
            return user_followers & user_following

    def find_all_paths(self, from_user_uuid, to_user_uuid, path=[]):
        path = path + [from_user_uuid]
        if from_user_uuid == to_user_uuid:
            return [path]
        if from_user_uuid not in self.graph_ids:
            return []
        paths = []
        for vertex in self.graph_ids[from_user_uuid]:
            if vertex not in path:
                newpaths = self.find_all_paths(vertex, to_user_uuid, path)
                for newpath in newpaths:
                    paths.append(newpath)
        return paths

    def max_distance(self, user_uuid):
        if user_uuid not in self.graph_ids:
            raise UserDoesNotExistError
        distances = []
        for user in self.graph_ids:
            try:
                distances.append(self.min_distance(user_uuid, user))
            except UsersNotConnectedError:
                pass

        if distances == [0] * len(distances):
            return math.inf
        else:
            return max(distances)

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

        distances = []
        distances.extend(self.find_all_paths(from_user_uuid, to_user_uuid))

        if distances == []:
            raise UsersNotConnectedError
        return min(len(distance) for distance in distances) - 1

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.graph_ids:
            raise UserDoesNotExistError
        if n == 0:
            return set()
        distances = []
        for user in self.graph_ids:
            distances.extend(self.find_all_paths(user_uuid, user))

        return set([distance[n]
                    for distance in distances if len(distance) == n + 1])

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.graph_ids:
            raise UserDoesNotExistError
        feed = []
        user_following = self.graph_ids[user_uuid]
        for user in user_following:
            a = self.users[user].get_post()
            for post in a:
                feed.append(post)

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

        return feed[offset:(limit + offset)]


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


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = "User already exist"


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


class UserCannotFollowHimself(Exception):
    def __init__(self):
        self.message = "User cannot follow himself"
  • Името graph_ids е доста объркващо. Изглежда го ползваш за представяне ан самата релация на слведване. От името обаче изобщо не става ясно.
  • В тоя ред на мисли искаш ли да е defaultdict точно от list-ове? По условие follow трябва да е идемпотентен, т.е. да може да се извиква много пъти с еднакви аргументи. В unfollow извикването на remove метода на list ще изтрие само първото срещане на елемента в списъка, а в твоя случай при неколкократно извикване на follow с еднакви аргументи може да има няколко еднакви uuid-та в списъка.
  • Помисли как можещ да направиш двуредовите условия на if-ове на едноредови. Допълнително функции също биха били супер решение.
  • Във followers user_uuid и user_id са объркващо близки. Най-добре е може би да преименуваш user_id на нещо по-описателно за случая.
  • if user_uuid not in self.graph_ids: raise UserDoesNotExistError се повтаря доста често. Това е добра индикация, че има смисъл от функция, която да го прави.

Борис обнови решението на 18.04.2016 13:39 (преди над 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
from uuid import uuid4
from datetime import datetime
from collections import defaultdict
import math


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

    def add_post(self, post_content):
        self.posts = self.posts[-49:]
        self.posts.append(Post(self, post_content))
        return self.posts

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


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


class SocialGraph:
    def __init__(self):
        self.graph_for_user_uuids = defaultdict(set)
        self.users = defaultdict(User)

    def check_user_exist(self, user_uuid):
        if user_uuid not in self.graph_for_user_uuids:
            raise UserDoesNotExistError

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

    def get_user(self, user_uuid):
        self.check_user_exist(user_uuid)
        return self.users[user_uuid]

    def delete_user(self, user_uuid):
        self.check_user_exist(user_uuid)
        del self.users[user_uuid]
        del self.graph_for_user_uuids[user_uuid]

    def follow(self, follower, followee):
        self.check_user_exist(follower)
        self.check_user_exist(followee)
        if follower == followee:
            raise UserCannotFollowHimself
        self.graph_for_user_uuids[follower].add(followee)

    def unfollow(self, follower, followee):
        self.check_user_exist(follower)
        self.check_user_exist(followee)
        self.graph_for_user_uuids[follower].remove(followee)

    def is_following(self, follower, followee):
        self.check_user_exist(follower)
        self.check_user_exist(followee)
        if follower == followee:
            raise UserCannotFollowHimself
        if followee in self.graph_for_user_uuids[follower]:
            return True
        return False

    def followers(self, user_uuid):
        self.check_user_exist(user_uuid)
        followers = set()
        for user in self.graph_for_user_uuids:
            if user_uuid in self.graph_for_user_uuids[user]:
                followers.add(user)
        return followers

    def following(self, user_uuid):
        self.check_user_exist(user_uuid)
        return set(self.graph_for_user_uuids[user_uuid])

    def friends(self, user_uuid):
        self.check_user_exist(user_uuid)
        user_followers = self.followers(user_uuid)
        user_following = self.following(user_uuid)
        return user_followers & user_following

    def __find_min_path(self, from_user_uuid, to_user_uuid, path=[]):
        if from_user_uuid == to_user_uuid and path == []:
            return None
        path = path + [from_user_uuid]
        if from_user_uuid == to_user_uuid:
            return path
        if from_user_uuid not in self.graph_for_user_uuids:
            return None
        shortest = None
        for vertex in self.graph_for_user_uuids[from_user_uuid]:
            if vertex not in path:
                newpath = self.__find_min_path(vertex, to_user_uuid, path)
                if newpath:
                    if not shortest or len(newpath) < len(shortest):
                        shortest = newpath
        return shortest

    def max_distance(self, user_uuid):
        self.check_user_exist(user_uuid)
        distances = [0]
        for user in self.graph_for_user_uuids:
            distance = self.__find_min_path(user_uuid, user)
            if distance is not None:
                distances.append(len(distance))

        if distances == [0]:
            return math.inf
        return max(distances) - 1

    def min_distance(self, from_user_uuid, to_user_uuid):
        self.check_user_exist(from_user_uuid)
        self.check_user_exist(to_user_uuid)

        distance = self.__find_min_path(from_user_uuid, to_user_uuid)
        if distance is None:
            raise UsersNotConnectedError
        return len(distance) - 1

    def nth_layer_followings(self, user_uuid, n):
        self.check_user_exist(user_uuid)
        if n == 0:
            return set()
        distances = []
        for user in self.graph_for_user_uuids:
            distance = self.__find_min_path(user_uuid, user)
            if distance is not None:
                distances.append(distance)

        return set([distance[n]
                    for distance in distances if len(distance) == n + 1])

    def generate_feed(self, user_uuid, offset=0, limit=10):
        self.check_user_exist(user_uuid)
        feed = []
        user_following = self.graph_for_user_uuids[user_uuid]
        for user in user_following:
            a = self.users[user].get_post()
            for post in a:
                feed.append(post)

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

        return feed[offset:(limit + offset)]


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


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = "User already exist"


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


class UserCannotFollowHimself(Exception):
    def __init__(self):
        self.message = "User cannot follow himself"

Борис обнови решението на 18.04.2016 16:50 (преди над 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
from uuid import uuid4
from datetime import datetime
from collections import defaultdict
import math


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

    def add_post(self, post_content):
        self.posts = self.posts[-49:]
        self.posts.append(Post(self, post_content))
        return self.posts

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


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


class SocialGraph:
    def __init__(self):
        self.graph_for_user_uuids = defaultdict(set)
        self.users = defaultdict(User)

    def check_user_exist(self, user_uuid):
        if user_uuid not in self.graph_for_user_uuids:
            raise UserDoesNotExistError

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

    def get_user(self, user_uuid):
        self.check_user_exist(user_uuid)
        return self.users[user_uuid]

    def delete_user(self, user_uuid):
        self.check_user_exist(user_uuid)
        del self.users[user_uuid]
        del self.graph_for_user_uuids[user_uuid]

    def follow(self, follower, followee):
        self.check_user_exist(follower)
        self.check_user_exist(followee)
        if follower == followee:
            raise ValueError("User cannot follow himsel")
        self.graph_for_user_uuids[follower].add(followee)

    def unfollow(self, follower, followee):
        self.check_user_exist(follower)
        self.check_user_exist(followee)
        if follower == followee:
            raise ValueError("User cannot unfollow himsel")
        if self.is_following(follower, followee):
            self.graph_for_user_uuids[follower].remove(followee)

    def is_following(self, follower, followee):
        self.check_user_exist(follower)
        self.check_user_exist(followee)
        if follower == followee:
            raise ValueError("User cannot follow himsel")
        if followee in self.graph_for_user_uuids[follower]:
            return True
        return False

    def followers(self, user_uuid):
        self.check_user_exist(user_uuid)
        followers = set()
        for user in self.graph_for_user_uuids:
            if user_uuid in self.graph_for_user_uuids[user]:
                followers.add(user)
        return followers

    def following(self, user_uuid):
        self.check_user_exist(user_uuid)
        return set(self.graph_for_user_uuids[user_uuid])

    def friends(self, user_uuid):
        self.check_user_exist(user_uuid)
        user_followers = self.followers(user_uuid)
        user_following = self.following(user_uuid)
        return user_followers & user_following

    def __find_min_path(self, from_user_uuid, to_user_uuid, path=[]):
        if from_user_uuid == to_user_uuid and path == []:
            return None
        path = path + [from_user_uuid]
        if from_user_uuid == to_user_uuid:
            return path
        if from_user_uuid not in self.graph_for_user_uuids:
            return None
        shortest = None
        for vertex in self.graph_for_user_uuids[from_user_uuid]:
            if vertex not in path:
                newpath = self.__find_min_path(vertex, to_user_uuid, path)
                if newpath:
                    if not shortest or len(newpath) < len(shortest):
                        shortest = newpath
        return shortest

    def max_distance(self, user_uuid):
        self.check_user_exist(user_uuid)
        distances = [0]
        for user in self.graph_for_user_uuids:
            distance = self.__find_min_path(user_uuid, user)
            if distance is not None:
                distances.append(len(distance))

        if distances == [0]:
            return math.inf
        return max(distances) - 1

    def min_distance(self, from_user_uuid, to_user_uuid):
        self.check_user_exist(from_user_uuid)
        self.check_user_exist(to_user_uuid)

        distance = self.__find_min_path(from_user_uuid, to_user_uuid)
        if distance is None:
            raise UsersNotConnectedError
        return len(distance) - 1

    def nth_layer_followings(self, user_uuid, n):
        self.check_user_exist(user_uuid)
        if n < 0:
            raise ValueError("Nth layer cannot be negative")
        if n == 0:
            return set()
        distances = []
        for user in self.graph_for_user_uuids:
            distance = self.__find_min_path(user_uuid, user)
            if distance is not None:
                distances.append(distance)

        return set([distance[n]
                    for distance in distances if len(distance) == n + 1])

    def generate_feed(self, user_uuid, offset=0, limit=10):
        self.check_user_exist(user_uuid)
        if offset < 0 or limit < 0:
            raise ValueError("Offset and limit cannot be negative")
        feed = []
        user_following = self.graph_for_user_uuids[user_uuid]
        for user in user_following:
            a = self.users[user].get_post()
            for post in a:
                feed.append(post)

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

        return feed[offset:(limit + offset)]


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


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = "User already exist"


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