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


MAX_FEED_SIZE = 50


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = 'User already exists!'


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


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


class UsersCannotFollowThemselvesError(Exception):
    def __init__(self):
        self.message = 'Users cannot follow themselves!'


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

    def add_post(self, post_content):
        date = datetime.datetime.now()
        post = Post(self.uuid, date, post_content)
        if len(self.feed) >= MAX_FEED_SIZE:
            self.feed.pop(0)
        self.feed.append(post)

    def get_post(self):
        yield from (post for post in self.feed)


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.__follow_data = defaultdict(set)

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

    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
        self.__users.pop(user_uuid)
        if user_uuid in self.__follow_data:
            self.__follow_data.pop(user_uuid)
        for f_data in self.__follow_data:
            if user_uuid in f_data:
                f_data.remove(user_uuid)

    def follow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        if follower is followee:
            raise UsersCannotFollowThemselvesError
        self.__follow_data[follower].add(followee)

    def unfollow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        self.__follow_data[follower].remove(followee)

    def is_following(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        return followee in self.__follow_data[follower]

    def followers(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        return {
            id for id in self.__users
            if user_uuid in self.__follow_data[id]}

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

    def __are_friends(self, uid1, uid2):
        return self.is_following(uid1, uid2) and self.is_following(uid2, uid1)

    def friends(self, uid):
        if uid not in self.__users:
            raise UserDoesNotExistError
        return {id for id in self.__users if self.__are_friends(uid, id)}

    def max_distance(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        current = user_uuid
        distance = 0
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0:
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
            distance += 1
        if distance == 1:
            return math.inf
        return distance - 1

    def min_distance(self, from_id, to_id):
        if from_id not in self.__users or to_id not in self.__users:
            raise UserDoesNotExistError
        if from_id is to_id:
            return 0
        current = from_id
        distance = 0
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0:
            distance += 1
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id == to_id:
                        return distance
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
        raise UsersNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        current = user_uuid
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0 and n > 0:
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
            n -= 1
        return next_users

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        feed = []
        for user_id in self.__follow_data[user_uuid]:
            feed.extend(list(self.__users[user_id].get_post()))
        feed.sort(key=lambda x: x.published_at, reverse=True)
        return feed[offset:offset + limit]

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

........
----------------------------------------------------------------------
Ran 8 tests in 0.078s

OK

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

Николай обнови решението на 09.04.2016 16:37 (преди над 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
import uuid
import datetime
from collections import defaultdict


MAX_FEED_SIZE = 50


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = 'User already exists!'


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


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


class IterableQueue(list):
    def __init__(self, max_size):
        super().__init__()
        self.__max_size = max_size

    def push(self, value):
        if len(self) >= self.__max_size:
            self.pop(0)
        self.append(value)


class User:
    def __init__(self, full_name):
        self.full_name = full_name
        self.uuid = uuid.uuid4()
        self.feed = IterableQueue(MAX_FEED_SIZE)

    def add_post(self, post_content):
        date = datetime.datetime.now()
        post = Post(self.uuid, date, post_content)
        self.feed.push(post)

    def get_post(self):
        for post in reversed(self.feed):
            yield post


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.__follow_data = defaultdict(set)

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

    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
        self.__users.pop(user_uuid)

    def follow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        self.__follow_data[follower].add(followee)

    def unfollow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        self.__follow_data[follower].remove(followee)

    def is_following(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        return followee in self.__follow_data[follower]

    def followers(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        return {
            id for id in self.__users
            if user_uuid in self.__follow_data[id]}

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

    def friends(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        return {
            id for id in self.__users
            if user_uuid in self.__follow_data[id] and
            id in self.__follow_data[user_uuid]}

    def max_distance(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        current = user_uuid
        distance = 0
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0:
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
            distance += 1
        return distance - 1

    def min_distance(self, from_id, to_id):
        if from_id not in self.__users or to_id not in self.__users:
            raise UserDoesNotExistError
        current = from_id
        distance = 0
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0:
            distance += 1
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id == to_id:
                        return distance
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
        raise UsersNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        current = user_uuid
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0 and n > 0:
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
            n -= 1
        return next_users

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        feed = []
        for user_id in self.__follow_data[user_uuid]:
            feed.extend(list(self.__users[user_id].get_post()))
        feed.sort(key=lambda x: x.published_at, reverse=True)
        return feed[offset:offset + limit]

Николай обнови решението на 10.04.2016 20:20 (преди над 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
import uuid
import datetime
from collections import defaultdict


MAX_FEED_SIZE = 50


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = 'User already exists!'


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


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


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

    def add_post(self, post_content):
        date = datetime.datetime.now()
        post = Post(self.uuid, date, post_content)
        if len(self.feed) >= MAX_FEED_SIZE:
            self.feed.pop(0)
        self.feed.append(post)

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


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.__follow_data = defaultdict(set)

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

    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
        self.__users.pop(user_uuid)

    def follow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        self.__follow_data[follower].add(followee)

    def unfollow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        self.__follow_data[follower].remove(followee)

    def is_following(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        return followee in self.__follow_data[follower]

    def followers(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        return {
            id for id in self.__users
            if user_uuid in self.__follow_data[id]}

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

    def friends(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        return {
            id for id in self.__users
            if user_uuid in self.__follow_data[id] and
            id in self.__follow_data[user_uuid]}

    def max_distance(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        current = user_uuid
        distance = 0
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0:
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
            distance += 1
        return distance - 1

    def min_distance(self, from_id, to_id):
        if from_id not in self.__users or to_id not in self.__users:
            raise UserDoesNotExistError
        current = from_id
        distance = 0
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0:
            distance += 1
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id == to_id:
                        return distance
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
        raise UsersNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        current = user_uuid
        next_users = [current]
        while len(next_users) > 0 and n > 0:
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                        next_users.append(user_id)
                next_users.pop(0)
                current_dist_users -= 1
            n -= 1
        return next_users

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        feed = []
        for user_id in self.__follow_data[user_uuid]:
            feed.extend(list(self.__users[user_id].get_post()))
        feed.sort(key=lambda x: x.published_at, reverse=True)
        return feed[offset:offset + limit]
  • Можеш да погледнеш yield from и да видиш дали няма да ти свърши работа

  • При изтриване на user трябва да се увериш, че си изтрил всичката информация, която имаш за него в графа

  • Изразът на 88-89 ред ще изглежда много по-добре, ако го събереш на един ред и оставиш само скобите на отделен ред :)

  • Във friends можеш да използваш методите, които вече си написал

  • Можеш да си спестиш малко цикли в обхожданията с list comprehensions

  • Защо липсва проверка за вече обходени user-и в nth_layer_followings?

Николай обнови решението на 14.04.2016 20:19 (преди над 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
import uuid
import datetime
from collections import defaultdict


MAX_FEED_SIZE = 50


class UserAlreadyExistsError(Exception):
    def __init__(self):
        self.message = 'User already exists!'


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


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


class UsersCannotFollowThemselvesError(Exception):
    def __init__(self):
        self.message = 'Users cannot follow themselves!'


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

    def add_post(self, post_content):
        date = datetime.datetime.now()
        post = Post(self.uuid, date, post_content)
        if len(self.feed) >= MAX_FEED_SIZE:
            self.feed.pop(0)
        self.feed.append(post)

    def get_post(self):
        yield from (post for post in self.feed)


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.__follow_data = defaultdict(set)

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

    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
        self.__users.pop(user_uuid)
        if user_uuid in self.__follow_data:
            self.__follow_data.pop(user_uuid)
        for f_data in self.__follow_data:
            if user_uuid in f_data:
                f_data.remove(user_uuid)

    def follow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        if follower is followee:
            raise UsersCannotFollowThemselvesError
        self.__follow_data[follower].add(followee)

    def unfollow(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        self.__follow_data[follower].remove(followee)

    def is_following(self, follower, followee):
        if follower not in self.__users or followee not in self.__users:
            raise UserDoesNotExistError
        return followee in self.__follow_data[follower]

    def followers(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        return {
            id for id in self.__users
            if user_uuid in self.__follow_data[id]}

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

    def __are_friends(self, uid1, uid2):
        return self.is_following(uid1, uid2) and self.is_following(uid2, uid1)

    def friends(self, uid):
        if uid not in self.__users:
            raise UserDoesNotExistError
        return {id for id in self.__users if self.__are_friends(uid, id)}

    def max_distance(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        current = user_uuid
        distance = 0
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0:
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
            distance += 1
        if distance == 1:
            return math.inf
        return distance - 1

    def min_distance(self, from_id, to_id):
        if from_id not in self.__users or to_id not in self.__users:
            raise UserDoesNotExistError
        if from_id is to_id:
            return 0
        current = from_id
        distance = 0
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0:
            distance += 1
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id == to_id:
                        return distance
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
        raise UsersNotConnectedError

    def nth_layer_followings(self, user_uuid, n):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        current = user_uuid
        passed = set()
        next_users = [current]
        passed.add(current)
        while len(next_users) > 0 and n > 0:
            current_dist_users = len(next_users)
            while current_dist_users > 0:
                for user_id in self.__follow_data[next_users[0]]:
                    if user_id not in passed:
                        next_users.append(user_id)
                        passed.add(user_id)
                next_users.pop(0)
                current_dist_users -= 1
            n -= 1
        return next_users

    def generate_feed(self, user_uuid, offset=0, limit=10):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError
        feed = []
        for user_id in self.__follow_data[user_uuid]:
            feed.extend(list(self.__users[user_id].get_post()))
        feed.sort(key=lambda x: x.published_at, reverse=True)
        return feed[offset:offset + limit]