timeit

Програмиране с Python

Курс във Факултета по Математика и Информатика към СУ

Решение на Социална мрежа от Бисер Кръстев

Обратно към всички решения

Към профила на Бисер Кръстев

Резултати

  • 5 точки от тестове
  • 0 бонус точки
  • 5 точки общо
  • 4 успешни тест(а)
  • 4 неуспешни тест(а)

Код

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

MAX_POSTS = 50


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

    def __str__(self):
        return self.full_name

    def add_post(self, post_content):
        if len(self._posts) > MAX_POSTS:
            del self._posts[0]

        self._posts.append(Post(self.uuid, post_content))

    def get_post(self):
        yield from self._posts


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

    def __str__(self):
        return "{0}[{1}]: {2}".format(self.author,
                                      self.published_at,
                                      str(self.content))


class SocialGraph:
    def __init__(self):
        self._users = {}
        self._edges = defaultdict(list)

    def _has_user(self, user_uuid):
        return user_uuid in self._users

    def _assert_user(self, user_uuid):
        if not self._has_user(user_uuid):
            raise UserDoesNotExistError()

    def _has_users(self, first_uuid, second_uuid):
        return self._has_user(first_uuid) and self._has_user(second_uuid)

    def _assert_users(self, first_uuid, second_uuid):
        if not self._has_users(first_uuid, second_uuid):
            raise UserDoesNotExistError()

    def add_user(self, user):
        if self._has_user(user.uuid):
            raise UserAlreadyExistsError()

        self._users[user.uuid] = user

    def get_user(self, user_uuid):
        self._assert_user(user_uuid)
        return self._users[user_uuid]

    def delete_user(self, user_uuid):
        self._assert_user(user_uuid)
        del self._users[user_uuid]

    def follow(self, follower, followee):
        self._assert_users(follower, followee)
        self._edges[follower].append(followee)

    def unfollow(self, follower, followee):
        self._assert_users(follower, followee)
        self._edges[follower].remove(followee)

    def is_following(self, follower, followee):
        self._assert_users(follower, followee)
        return followee in self._edges[follower]

    def followers(self, user_uuid):
        self._assert_user(user_uuid)
        return [user for user in self._edges
                if self.is_following(user, user_uuid)]

    def following(self, user_uuid):
        self._assert_user(user_uuid)
        return self._edges[user_uuid]

    def _are_friends(self, userA, userB):
        self._assert_users(userA, userB)
        return (self.is_following(userA, userB) and
                self.is_following(userB, userA))

    def friends(self, user_uuid):
        self._assert_user(user_uuid)
        return [user for user in self._users
                if (self._are_friends(user_uuid, user) and
                    user != user_uuid)]

    def _bfs(self, user_uuid):
        q = [user_uuid]
        distances = defaultdict(lambda: -1)
        distances[user_uuid] = 0
        levels = [[user_uuid]]

        while q:
            current = q.pop(0)

            for followee in self.following(current):
                if distances[followee] != -1:
                    continue

                q.append(followee)
                distances[followee] = distances[current] + 1

                if len(levels) <= distances[followee]:
                    levels.append([])
                levels[distances[followee]].append(followee)

        return levels

    def max_distance(self, user_uuid):
        self._assert_user(user_uuid)
        return len(self._bfs(user_uuid)) - 1

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

        n = 0
        levels = self._bfs(from_user_uuid)
        for level in levels:
            if to_user_uuid in level:
                return n
            n = n + 1

        return -1

    def nth_layer_following(self, user_uuid, n):
        self._assert_user(user_uuid)
        levels = self._bfs(user_uuid)
        if n < 0 or n > len(levels):
            return []

        return levels[n]

    def _full_feed(self, user_uuid):
        self._assert_user(user_uuid)
        raw = [post for followee in self.following(user_uuid)
               for post in self.get_user(followee).get_post()]

        return sorted(raw, key=lambda post: post.published_at)

    def generate_feed(self, user_uuid, offset=0, limit=10):
        self._assert_user(user_uuid)
        return self._full_feed(user_uuid)[offset:(offset + limit)]


class SocialGraphException(Exception):
    pass


class UserDoesNotExistError(SocialGraphException):
    pass


class UserAlreadyExistsError(SocialGraphException):
    pass

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

..FF.EF.
======================================================================
ERROR: test_layer_followings (test.TestSocialGraph)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: 'SocialGraph' object has no attribute 'nth_layer_followings'

======================================================================
FAIL: test_feed (test.TestSocialGraph)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: Lists differ: ['0', '10', '20', '30', '1', '11', '21', '31', '2', '12'] != ['39', '29', '19', '9', '38', '28', '18', '8', '37', '27']

First differing element 0:
0
39

- ['0', '10', '20', '30', '1', '11', '21', '31', '2', '12']
+ ['39', '29', '19', '9', '38', '28', '18', '8', '37', '27']

======================================================================
FAIL: test_following (test.TestSocialGraph)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: False is not true

======================================================================
FAIL: test_add_post (test.TestUser)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: 51 != 50

----------------------------------------------------------------------
Ran 8 tests in 0.077s

FAILED (failures=3, errors=1)

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

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

MAX_POSTS = 50


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

    def __str__(self):
        return self.full_name

    def add_post(self, post_content):
        if len(self._posts) > MAX_POSTS:
            del self._posts[0]

        self._posts.append(Post(self.uuid, post_content))

    def get_post(self):
        yield from self._posts


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

    def __str__(self):
        return "{0}[{1}]: {2}".format(self.author,
                                      self.published_at,
                                      str(self.content))


class SocialGraph:
    def __init__(self):
        self._users = {}
        self._edges = defaultdict(lambda: [])

    def _has_user(self, user_uuid):
        return user_uuid in self._users

    def _has_users(self, first_uuid, second_uuid):
        return self._has_user(first_uuid) and self._has_user(second_uuid)

    def add_user(self, user):
        if self._has_user(user.uuid):
            raise UserAlreadyExistsError()

        self._users[user.uuid] = user

    def get_user(self, user_uuid):
        if not self._has_user(user_uuid):
            raise UserDoesNotExistError()

        return self._users[user_uuid]

    def delete_user(self, user_uuid):
        if not self._has_user(user_uuid):
            raise UserDoesNotExistError()

        del self._users[user_uuid]

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

        self._edges[follower].append(followee)

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

        self._edges[follower].remove(followee)

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

        return followee in self._edges[follower]

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

        return [user for user in self._edges
                if self.is_following(user, user_uuid)]

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

        return self._edges[user_uuid]

    def _are_friends(self, userA, userB):
        if not self._has_users(userA, userB):
            raise UserDoesNotExistError()

        return (self.is_following(userA, userB) and
                self.is_following(userB, userA))

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

        return [user for user in self._users
                if (self._are_friends(user_uuid, user) and
                    user != user_uuid)]

    def _bfs(self, user_uuid):
        q = [user_uuid]
        distances = defaultdict(lambda: -1)
        distances[user_uuid] = 0
        levels = [[user_uuid]]

        while q:
            current = q.pop(0)

            for followee in self.following(current):
                if distances[followee] != -1:
                    continue

                q.append(followee)
                distances[followee] = distances[current] + 1

                if len(levels) <= distances[followee]:
                    levels.append([])
                levels[distances[followee]].append(followee)

        return levels

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

        return len(self._bfs(user_uuid)) - 1

    def min_distance(self, from_user_uuid, to_user_uuid):
        if not self._has_users(from_user_uuid, to_user_uuid):
            raise UserDoesNotExistError()

        n = 0
        levels = self._bfs(from_user_uuid)
        for level in levels:
            if to_user_uuid in level:
                return n
            n = n + 1

        return -1

    def nth_layer_following(self, user_uuid, n):
        if not self._has_user(user_uuid):
            raise UserDoesNotExistError()

        levels = self._bfs(user_uuid)
        if n < 0 or n > len(levels):
            return []

        return levels[n]

    def _full_feed(self, user_uuid):
        if not self._has_user(user_uuid):
            raise UserDoesNotExistError()

        raw = [post for followee in self.following(user_uuid)
               for post in self.get_user(followee).get_post()]

        return sorted(raw, key=lambda post: post.published_at)

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

        return self._full_feed(user_uuid)[offset:(offset + limit)]


class SocialGraphException(Exception):
    pass


class UserDoesNotExistError(SocialGraphException):
    pass


class UserAlreadyExistsError(SocialGraphException):
    pass

Имаш чупещи се примерни тестове, погледни какъв е проблема там.

  • Много по-добра идея е да подадеш на defaultdict просто list, което така и така е конструктора на списъци, от колкото въпросната lambda
  • На доста места се хвърля UserDoesNotExistError. Не е лоша идея това също да се случва във функцията, която прави проверката.

Бисер обнови решението на 17.04.2016 23:41 (преди над 1 година)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import uuid
from collections import defaultdict
import datetime

MAX_POSTS = 50


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

    def __str__(self):
        return self.full_name

    def add_post(self, post_content):
        if len(self._posts) > MAX_POSTS:
            del self._posts[0]

        self._posts.append(Post(self.uuid, post_content))

    def get_post(self):
        yield from self._posts


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

    def __str__(self):
        return "{0}[{1}]: {2}".format(self.author,
                                      self.published_at,
                                      str(self.content))


class SocialGraph:
    def __init__(self):
        self._users = {}
        self._edges = defaultdict(list)

    def _has_user(self, user_uuid):
        return user_uuid in self._users

    def _assert_user(self, user_uuid):
        if not self._has_user(user_uuid):
            raise UserDoesNotExistError()

    def _has_users(self, first_uuid, second_uuid):
        return self._has_user(first_uuid) and self._has_user(second_uuid)

    def _assert_users(self, first_uuid, second_uuid):
        if not self._has_users(first_uuid, second_uuid):
            raise UserDoesNotExistError()

    def add_user(self, user):
        if self._has_user(user.uuid):
            raise UserAlreadyExistsError()

        self._users[user.uuid] = user

    def get_user(self, user_uuid):
        self._assert_user(user_uuid)
        return self._users[user_uuid]

    def delete_user(self, user_uuid):
        self._assert_user(user_uuid)
        del self._users[user_uuid]

    def follow(self, follower, followee):
        self._assert_users(follower, followee)
        self._edges[follower].append(followee)

    def unfollow(self, follower, followee):
        self._assert_users(follower, followee)
        self._edges[follower].remove(followee)

    def is_following(self, follower, followee):
        self._assert_users(follower, followee)
        return followee in self._edges[follower]

    def followers(self, user_uuid):
        self._assert_user(user_uuid)
        return [user for user in self._edges
                if self.is_following(user, user_uuid)]

    def following(self, user_uuid):
        self._assert_user(user_uuid)
        return self._edges[user_uuid]

    def _are_friends(self, userA, userB):
        self._assert_users(userA, userB)
        return (self.is_following(userA, userB) and
                self.is_following(userB, userA))

    def friends(self, user_uuid):
        self._assert_user(user_uuid)
        return [user for user in self._users
                if (self._are_friends(user_uuid, user) and
                    user != user_uuid)]

    def _bfs(self, user_uuid):
        q = [user_uuid]
        distances = defaultdict(lambda: -1)
        distances[user_uuid] = 0
        levels = [[user_uuid]]

        while q:
            current = q.pop(0)

            for followee in self.following(current):
                if distances[followee] != -1:
                    continue

                q.append(followee)
                distances[followee] = distances[current] + 1

                if len(levels) <= distances[followee]:
                    levels.append([])
                levels[distances[followee]].append(followee)

        return levels

    def max_distance(self, user_uuid):
        self._assert_user(user_uuid)
        return len(self._bfs(user_uuid)) - 1

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

        n = 0
        levels = self._bfs(from_user_uuid)
        for level in levels:
            if to_user_uuid in level:
                return n
            n = n + 1

        return -1

    def nth_layer_following(self, user_uuid, n):
        self._assert_user(user_uuid)
        levels = self._bfs(user_uuid)
        if n < 0 or n > len(levels):
            return []

        return levels[n]

    def _full_feed(self, user_uuid):
        self._assert_user(user_uuid)
        raw = [post for followee in self.following(user_uuid)
               for post in self.get_user(followee).get_post()]

        return sorted(raw, key=lambda post: post.published_at)

    def generate_feed(self, user_uuid, offset=0, limit=10):
        self._assert_user(user_uuid)
        return self._full_feed(user_uuid)[offset:(offset + limit)]


class SocialGraphException(Exception):
    pass


class UserDoesNotExistError(SocialGraphException):
    pass


class UserAlreadyExistsError(SocialGraphException):
    pass