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

USER = 0
FOLLOWEES = 1
DISTANCE = 2


class UsersNotConnectedError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class UserDoesNotExistError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class UserAlreadyExistsError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class Post:

    def __init__(self, content, author_uuid):
        self.author = author_uuid
        self.published_at = datetime.datetime.now()
        self.content = content


class User:

    def __init__(self, name):
        self.full_name = name
        self.uuid = uuid.uuid4()
        self.posts = deque()

    def add_post(self, post_content):
        if len(self.posts) is 50:
            self.posts.popleft()
        self.posts.append(Post(post_content, self.uuid))

    def get_post(self):
        count = 0
        while count < len(self.posts):
            yield self.posts[count]
            count += 1


class SocialGraph:

    def __init__(self):
        self.users = {}

    def add_user(self, user):
        if user.uuid in self.users:
            raise UserAlreadyExistsError("User already exists.")
        else:
            self.users[user.uuid] = (user, set())

    def get_user(self, user_uuid):
        if user_uuid in self.users:
            return self.users[user_uuid][USER]
        raise UserDoesNotExistError("User does not exist.")

    def delete_user(self, user_uuid):
        if user_uuid in self.users:
            del self.users[user_uuid]
        else:
            raise UserDoesNotExistError("User does not exist.")

    def follow(self, follower, followee):
        self.users[follower][FOLLOWEES].add(followee)

    def unfollow(self, follower, followee):
        self.users[follower][FOLLOWEES].remove(followee)

    def is_following(self, follower, followee):
        if followee in self.users[follower][FOLLOWEES]:
            return True
        return False

    def followers(self, user_uuid):
        result = set()
        for key, value in self.users.items():
            if user_uuid in value[FOLLOWEES]:
                result.add(key)
        return result

    def following(self, user_uuid):
        return self.users[user_uuid][FOLLOWEES]

    def friends(self, user_uuid):
        result = set()
        for each in self.users[user_uuid][FOLLOWEES]:
            if user_uuid in self.users[each][FOLLOWEES]:
                result.add(each)
        return result

    def bfs(self, user_uuid):
        graph = self.users
        queue = deque()
        distances = {user_uuid: 0}

        queue.append(user_uuid)

        while len(queue) > 0:
            current = queue.popleft()

            for next in graph[current][FOLLOWEES]:
                if next not in distances:
                    distances[next] = distances[current] + 1
                    queue.append(next)

        return distances

    def min_distance(self, from_user_uuid, to_user_uuid):
        distances = self.bfs(from_user_uuid)

        if to_user_uuid not in distances:
            raise UsersNotConnectedError("Users not connected")

        return distances[to_user_uuid]

    def max_distance(self, user_uuid):
        graph = self.users
        max_distance = -1
        distances = self.bfs(user_uuid)

        for current_distance in distances.values():
            if max_distance < current_distance:
                max_distance = current_distance

        if max_distance is -1:
            return math.inf

        return max_distance

    def nth_layer_followings(self, user_uuid, n):
        graph = self.users
        result = set()
        distances = self.bfs(user_uuid)

        for key, value in distances.items():
            if value is n:
                result.add(key)

        return result

    def generate_feed(self, user_uuid, offset=0, limit=10):
        feed = list()
        followees = set()

        for each in self.users[user_uuid][FOLLOWEES]:
            followees.add(self.users[each][USER])

        for each in followees:
            for post in each.posts:
                feed.append(post)

        sorted_feed = sorted(feed, key=lambda x: x.published_at, reverse=True)

        start = offset
        end = offset + limit

        return sorted_feed[start:end]

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

........
----------------------------------------------------------------------
Ran 8 tests in 0.081s

OK

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

Атанас обнови решението на 18.04.2016 01: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
import uuid
from collections import deque
import datetime
import math

USER = 0
FOLLOWEES = 1
DISTANCE = 2


class UsersNotConnectedError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class UserDoesNotExistError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class UserAlreadyExistsError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class Post:

    def __init__(self, content, author_uuid):
        self.author = author_uuid
        self.published_at = datetime.datetime.now()
        self.content = content


class User:

    def __init__(self, name):
        self.full_name = name
        self.uuid = uuid.uuid4()
        self.posts = deque()

    def add_post(self, post_content):
        if len(self.posts) is 50:
            self.posts.popleft()
        self.posts.append(Post(post_content, self.uuid))

    def get_post(self):
        count = 0
        while count < len(self.posts):
            yield self.posts[count]
            count += 1

    def add_follower(self, user):
        self.followers.add(user)

    def follow(self, user):
        self.following.add(user)


class SocialGraph:

    def __init__(self):
        self.users = {}

    def add_user(self, user):
        if user.uuid in self.users:
            raise UserAlreadyExistsError("User already exists.")
        else:
            self.users[user.uuid] = (user, set())

    def get_user(self, user_uuid):
        if user_uuid in self.users:
            return self.users[user_uuid][USER]
        raise UserDoesNotExistError("User does not exist.")

    def delete_user(self, user_uuid):
        if user_uuid in self.users:
            del self.users[user_uuid]
        else:
            raise UserDoesNotExistError("User does not exist.")

    def follow(self, follower, followee):
        self.users[follower][FOLLOWEES].add(followee)

    def unfollow(self, follower, followee):
        self.users[follower][FOLLOWEES].remove(followee)

    def is_following(self, follower, followee):
        if followee in self.users[follower][FOLLOWEES]:
            return True
        return False

    def followers(self, user_uuid):
        result = set()
        for key, value in self.users.items():
            if user_uuid in value[FOLLOWEES]:
                result.add(key)
        return result

    def following(self, user_uuid):
        return self.users[user_uuid][FOLLOWEES]

    def friends(self, user_uuid):
        result = set()
        for each in self.users[user_uuid][FOLLOWEES]:
            if user_uuid in self.users[each][FOLLOWEES]:
                result.add(each)
        return result

    def min_distance(self, from_user_uuid, to_user_uuid):
        graph = self.users
        queue = deque()
        distances = {from_user_uuid: 0}

        queue.append(from_user_uuid)

        while len(queue) > 0:
            current = queue.popleft()

            for next in graph[current][FOLLOWEES]:
                if next not in distances:
                    distances[next] = distances[current] + 1
                    queue.append(next)

        if to_user_uuid not in distances:
            raise UsersNotConnectedError("Users not connected")

        return distances[to_user_uuid]

    def max_distance(self, user_uuid):
        graph = self.users
        max_distance = -1

        for each in graph:
            try:
                current_distance = self.min_distance(user_uuid, each)
            except UsersNotConnectedError:
                current_distance = -1

            if max_distance < current_distance:
                max_distance = current_distance

        if max_distance is -1:
            return math.inf

        return max_distance

    def nth_layer_followings(self, user_uuid, n):
        graph = self.users
        result = set()

        for each in graph:
            try:
                distance = self.min_distance(user_uuid, each)
            except UsersNotConnectedError:
                distance = -1

            if distance is n:
                result.add(each)

        return result

    def generate_feed(self, user_uuid, offset=0, limit=10):
        feed = list()
        followees = set()

        for each in self.users[user_uuid][FOLLOWEES]:
            followees.add(self.users[each][USER])

        for each in followees:
            for post in each.posts:
                feed.append(post)

        sorted_feed = sorted(feed, key=lambda x: x.published_at, reverse=True)

        start = offset
        end = offset + limit

        return sorted_feed[start:end]

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

USER = 0
FOLLOWEES = 1
DISTANCE = 2


class UsersNotConnectedError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class UserDoesNotExistError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class UserAlreadyExistsError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class Post:

    def __init__(self, content, author_uuid):
        self.author = author_uuid
        self.published_at = datetime.datetime.now()
        self.content = content


class User:

    def __init__(self, name):
        self.full_name = name
        self.uuid = uuid.uuid4()
        self.posts = deque()

    def add_post(self, post_content):
        if len(self.posts) is 50:
            self.posts.popleft()
        self.posts.append(Post(post_content, self.uuid))

    def get_post(self):
        count = 0
        while count < len(self.posts):
            yield self.posts[count]
            count += 1

    def add_follower(self, user):
        self.followers.add(user)

    def follow(self, user):
        self.following.add(user)


class SocialGraph:

    def __init__(self):
        self.users = {}

    def add_user(self, user):
        if user.uuid in self.users:
            raise UserAlreadyExistsError("User already exists.")
        else:
            self.users[user.uuid] = (user, set())

    def get_user(self, user_uuid):
        if user_uuid in self.users:
            return self.users[user_uuid][USER]
        raise UserDoesNotExistError("User does not exist.")

    def delete_user(self, user_uuid):
        if user_uuid in self.users:
            del self.users[user_uuid]
        else:
            raise UserDoesNotExistError("User does not exist.")

    def follow(self, follower, followee):
        self.users[follower][FOLLOWEES].add(followee)

    def unfollow(self, follower, followee):
        self.users[follower][FOLLOWEES].remove(followee)

    def is_following(self, follower, followee):
        if followee in self.users[follower][FOLLOWEES]:
            return True
        return False

    def followers(self, user_uuid):
        result = set()
        for key, value in self.users.items():
            if user_uuid in value[FOLLOWEES]:
                result.add(key)
        return result

    def following(self, user_uuid):
        return self.users[user_uuid][FOLLOWEES]

    def friends(self, user_uuid):
        result = set()
        for each in self.users[user_uuid][FOLLOWEES]:
            if user_uuid in self.users[each][FOLLOWEES]:
                result.add(each)
        return result

    def bfs(self, user_uuid):
        graph = self.users
        queue = deque()
        distances = {user_uuid: 0}

        queue.append(user_uuid)

        while len(queue) > 0:
            current = queue.popleft()

            for next in graph[current][FOLLOWEES]:
                if next not in distances:
                    distances[next] = distances[current] + 1
                    queue.append(next)

        return distances

    def min_distance(self, from_user_uuid, to_user_uuid):
        distances = self.bfs(from_user_uuid)

        if to_user_uuid not in distances:
            raise UsersNotConnectedError("Users not connected")

        return distances[to_user_uuid]

    def max_distance(self, user_uuid):
        graph = self.users
        max_distance = -1
        distances = self.bfs(user_uuid)

        for current_distance in distances.values():
            if max_distance < current_distance:
                max_distance = current_distance

        if max_distance is -1:
            return math.inf

        return max_distance

    def nth_layer_followings(self, user_uuid, n):
        graph = self.users
        result = set()
        distances = self.bfs(user_uuid)

        for key, value in distances.items():
            if value is n:
                result.add(key)

        return result

    def generate_feed(self, user_uuid, offset=0, limit=10):
        feed = list()
        followees = set()

        for each in self.users[user_uuid][FOLLOWEES]:
            followees.add(self.users[each][USER])

        for each in followees:
            for post in each.posts:
                feed.append(post)

        sorted_feed = sorted(feed, key=lambda x: x.published_at, reverse=True)

        start = offset
        end = offset + limit

        return sorted_feed[start:end]

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

USER = 0
FOLLOWEES = 1
DISTANCE = 2


class UsersNotConnectedError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class UserDoesNotExistError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class UserAlreadyExistsError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class Post:

    def __init__(self, content, author_uuid):
        self.author = author_uuid
        self.published_at = datetime.datetime.now()
        self.content = content


class User:

    def __init__(self, name):
        self.full_name = name
        self.uuid = uuid.uuid4()
        self.posts = deque()

    def add_post(self, post_content):
        if len(self.posts) is 50:
            self.posts.popleft()
        self.posts.append(Post(post_content, self.uuid))

    def get_post(self):
        count = 0
        while count < len(self.posts):
            yield self.posts[count]
            count += 1


class SocialGraph:

    def __init__(self):
        self.users = {}

    def add_user(self, user):
        if user.uuid in self.users:
            raise UserAlreadyExistsError("User already exists.")
        else:
            self.users[user.uuid] = (user, set())

    def get_user(self, user_uuid):
        if user_uuid in self.users:
            return self.users[user_uuid][USER]
        raise UserDoesNotExistError("User does not exist.")

    def delete_user(self, user_uuid):
        if user_uuid in self.users:
            del self.users[user_uuid]
        else:
            raise UserDoesNotExistError("User does not exist.")

    def follow(self, follower, followee):
        self.users[follower][FOLLOWEES].add(followee)

    def unfollow(self, follower, followee):
        self.users[follower][FOLLOWEES].remove(followee)

    def is_following(self, follower, followee):
        if followee in self.users[follower][FOLLOWEES]:
            return True
        return False

    def followers(self, user_uuid):
        result = set()
        for key, value in self.users.items():
            if user_uuid in value[FOLLOWEES]:
                result.add(key)
        return result

    def following(self, user_uuid):
        return self.users[user_uuid][FOLLOWEES]

    def friends(self, user_uuid):
        result = set()
        for each in self.users[user_uuid][FOLLOWEES]:
            if user_uuid in self.users[each][FOLLOWEES]:
                result.add(each)
        return result

    def bfs(self, user_uuid):
        graph = self.users
        queue = deque()
        distances = {user_uuid: 0}

        queue.append(user_uuid)

        while len(queue) > 0:
            current = queue.popleft()

            for next in graph[current][FOLLOWEES]:
                if next not in distances:
                    distances[next] = distances[current] + 1
                    queue.append(next)

        return distances

    def min_distance(self, from_user_uuid, to_user_uuid):
        distances = self.bfs(from_user_uuid)

        if to_user_uuid not in distances:
            raise UsersNotConnectedError("Users not connected")

        return distances[to_user_uuid]

    def max_distance(self, user_uuid):
        graph = self.users
        max_distance = -1
        distances = self.bfs(user_uuid)

        for current_distance in distances.values():
            if max_distance < current_distance:
                max_distance = current_distance

        if max_distance is -1:
            return math.inf

        return max_distance

    def nth_layer_followings(self, user_uuid, n):
        graph = self.users
        result = set()
        distances = self.bfs(user_uuid)

        for key, value in distances.items():
            if value is n:
                result.add(key)

        return result

    def generate_feed(self, user_uuid, offset=0, limit=10):
        feed = list()
        followees = set()

        for each in self.users[user_uuid][FOLLOWEES]:
            followees.add(self.users[each][USER])

        for each in followees:
            for post in each.posts:
                feed.append(post)

        sorted_feed = sorted(feed, key=lambda x: x.published_at, reverse=True)

        start = offset
        end = offset + limit

        return sorted_feed[start:end]