timeit

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

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

Решение на Социална мрежа от Ивелин Тодоров

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

Към профила на Ивелин Тодоров

Резултати

  • 9 точки от тестове
  • 0 бонус точки
  • 9 точки общо
  • 7 успешни тест(а)
  • 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
import uuid
import math
import datetime
import functools
from collections import deque, defaultdict


class User:

    def __init__(self, full_name):
        self.full_name = full_name
        self.__uuid = uuid.uuid4()
        self.posts = deque([], 50)

    @property
    def uuid(self):
        return self.__uuid

    def add_post(self, post_content):
        date_time = datetime.datetime.now()
        self.posts.append(Post(self.uuid, date_time, post_content))

    def get_post(self):
        ind = 0
        try:
            while True:
                yield self.posts[ind]
                ind += 1
        except IndexError:
            pass

class Post:

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


def user_checker_arg_modifier(arg_change=False):
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args):
            new_args = []
            new_args.append(args[0])
            for arg in args[1:]:
                if not isinstance(arg, int) \
                   and arg not in args[0].uuid_to_users:
                    raise UserDoesNotExistError
                elif not isinstance(arg, int):
                    new_args.append(args[0].uuid_to_users[arg])
                elif isinstance(arg, int):
                    new_args.append(arg)
            if arg_change:
                return func(*new_args)
            return func(*args)
        return wrapper
    return deco


class SocialGraph:

    def __init__(self):
        self.users = set()
        self.uuid_to_users = dict()
        self.follows = defaultdict(set)
        self.followed_by = defaultdict(set)

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

    @user_checker_arg_modifier()
    def get_user(self, user_uuid):
        return self.uuid_to_users[user_uuid]

    @user_checker_arg_modifier(True)
    def delete_user(self, user_uuid):
        self.users.remove(user_uuid)
        del self.uuid_to_users[user_uuid.uuid]

    @user_checker_arg_modifier()
    def follow(self, follower, followee):
        self.follows[follower].add(followee)
        self.followed_by[followee].add(follower)

    @user_checker_arg_modifier()
    def unfollow(self, follower, followee):
        try:
            self.follows[follower].remove(followee)
            self.followed_by[followee].remove(follower)
        except KeyError:
            pass

    @user_checker_arg_modifier()
    def is_following(self, follower, followee):
        return followee in self.follows[follower]

    @user_checker_arg_modifier()
    def followers(self, user_uuid):
        return self.followed_by[user_uuid]

    @user_checker_arg_modifier()
    def following(self, user_uuid):
        return self.follows[user_uuid]

    @user_checker_arg_modifier()
    def friends(self, user_uuid):
        return self.follows[user_uuid] & self.followed_by[user_uuid]

    def get_distances(self, user_uuid):
        visited = set()
        distances = defaultdict(set)
        queue = []
        queue.append((user_uuid, 0))

        while queue:
            current = queue[0][0]
            level = queue[0][1] + 1
            for followed in self.follows[current]:
                if followed not in distances:
                    distances[level].add(followed)
                if followed not in visited:
                    queue.append((followed, level))
                    visited.add(followed)
            queue.pop(0)

        return distances

    @user_checker_arg_modifier()
    def max_distance(self, user_uuid):
        if not self.follows[user_uuid]:
            return math.inf

        distances = self.get_distances(user_uuid)
        return max(distances.keys())

    @user_checker_arg_modifier()
    def min_distance(self, from_user_uuid, to_user_uuid):
        if not self.follows[from_user_uuid]:
            raise UsersNotConnectedError

        visited = set()
        queue = []
        queue.append((from_user_uuid, 0))

        while queue:
            current = queue[0][0]
            level = queue[0][1] + 1
            for followed in self.follows[current]:
                if followed == to_user_uuid:
                    return level
                if followed not in visited:
                    queue.append((followed, level))
                    visited.add(followed)
            queue.pop(0)
        else:
            raise UsersNotConnectedError

    @user_checker_arg_modifier()
    def nth_layer_followings(self, user_uuid, n):
        if not self.follows[user_uuid]:
            return set()

        distances = self.get_distances(user_uuid)
        try:
            return distances[n]
        except KeyError:
            return set()

    @user_checker_arg_modifier()
    def generate_feed(self, user_uuid, offset=0, limit=10):
        latest_posts = []
        for followed in self.follows[user_uuid]:
            latest_posts.extend(self.uuid_to_users[followed].posts)
        latest_posts.sort(key=lambda x: x.published_at)
        latest_posts.reverse()
        return latest_posts[offset: offset + limit]


class UserAlreadyExistsError(Exception):
    pass


class UserDoesNotExistError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass

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

.F......
======================================================================
FAIL: test_distnaces (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: 3 != 2

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

FAILED (failures=1)

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

Ивелин обнови решението на 18.04.2016 14:21 (преди над 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 math
import datetime
import functools
from collections import deque, defaultdict


class User:

    def __init__(self, full_name):
        self.full_name = full_name
        self.__uuid = uuid.uuid4()
        self.posts = deque([], 50)

    @property
    def uuid(self):
        return self.__uuid

    def add_post(self, post_content):
        date_time = datetime.datetime.now()
        self.posts.append(Post(self.uuid, date_time, post_content))

    def get_post(self):
        for i in range(self.posts.maxlen):
            yield self.posts[i]


class Post:

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


def user_checker_arg_modifier(arg_change=False):
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args):
            new_args = []
            new_args.append(args[0])
            for arg in args[1:]:
                if not isinstance(arg, int) \
                   and arg not in args[0].uuid_to_users:
                    raise UserDoesNotExistError
                elif not isinstance(arg, int):
                    new_args.append(args[0].uuid_to_users[arg])
                elif isinstance(arg, int):
                    new_args.append(arg)
            if arg_change:
                return func(*new_args)
            return func(*args)
        return wrapper
    return deco


class SocialGraph:

    def __init__(self):
        self.users = set()
        self.uuid_to_users = dict()
        self.follows = defaultdict(set)
        self.followed_by = defaultdict(set)

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

    @user_checker_arg_modifier()
    def get_user(self, user_uuid):
        return self.uuid_to_users[user_uuid]

    @user_checker_arg_modifier(True)
    def delete_user(self, user_uuid):
        self.users.remove(user_uuid)
        del self.uuid_to_users[user_uuid.uuid]

    @user_checker_arg_modifier()
    def follow(self, follower, followee):
        self.follows[follower].add(followee)
        self.followed_by[followee].add(follower)

    @user_checker_arg_modifier()
    def unfollow(self, follower, followee):
        try:
            self.follows[follower].remove(followee)
            self.followed_by[followee].remove(follower)
        except KeyError:
            pass

    @user_checker_arg_modifier()
    def is_following(self, follower, followee):
        return followee in self.follows[follower]

    @user_checker_arg_modifier()
    def followers(self, user_uuid):
        return self.followed_by[user_uuid]

    @user_checker_arg_modifier()
    def following(self, user_uuid):
        return self.follows[user_uuid]

    @user_checker_arg_modifier()
    def friends(self, user_uuid):
        return self.follows[user_uuid] & self.followed_by[user_uuid]

    def get_distances(self, user_uuid):
        visited = set()
        distances = defaultdict(set)
        queue = []
        queue.append((user_uuid, 0))

        while queue:
            current = queue[0][0]
            level = queue[0][1] + 1
            for followed in self.follows[current]:
                if followed not in distances:
                    distances[level].add(followed)
                if followed not in visited:
                    queue.append((followed, level))
                    visited.add(followed)
            queue.pop(0)

        return distances

    @user_checker_arg_modifier()
    def max_distance(self, user_uuid):
        if not self.follows[user_uuid]:
            return math.inf

        distances = self.get_distances(user_uuid)
        return max(distances.keys())

    @user_checker_arg_modifier()
    def min_distance(self, from_user_uuid, to_user_uuid):
        if not self.follows[from_user_uuid]:
            raise UsersNotConnectedError

        visited = set()
        queue = []
        queue.append((from_user_uuid, 0))

        while queue:
            current = queue[0][0]
            level = queue[0][1] + 1
            for followed in self.follows[current]:
                if followed == to_user_uuid:
                    return level
                if followed not in visited:
                    queue.append((followed, level))
                    visited.add(followed)
            queue.pop(0)
        else:
            raise UsersNotConnectedError

    @user_checker_arg_modifier()
    def nth_layer_followings(self, user_uuid, n):
        if not self.follows[user_uuid]:
            return set()

        distances = self.get_distances(user_uuid)
        try:
            return distances[n]
        except KeyError:
            return set()

    @user_checker_arg_modifier()
    def generate_feed(self, user_uuid, offset=0, limit=10):
        latest_posts = []
        for followed in self.follows[user_uuid]:
            latest_posts.extend(self.uuid_to_users[followed].posts)
        latest_posts.sort(key=lambda x: x.published_at)
        return latest_posts[offset + 1: offset + limit]


class UserAlreadyExistsError(Exception):
    pass


class UserDoesNotExistError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass

Ивелин обнови решението на 18.04.2016 15:01 (преди над 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
import uuid
import math
import datetime
import functools
from collections import deque, defaultdict


class User:

    def __init__(self, full_name):
        self.full_name = full_name
        self.__uuid = uuid.uuid4()
        self.posts = deque([], 50)

    @property
    def uuid(self):
        return self.__uuid

    def add_post(self, post_content):
        date_time = datetime.datetime.now()
        self.posts.append(Post(self.uuid, date_time, post_content))

    def get_post(self):
        ind = 0
        try:
            while True:
                yield self.posts[ind]
                ind += 1
        except IndexError:
            pass

class Post:

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


def user_checker_arg_modifier(arg_change=False):
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args):
            new_args = []
            new_args.append(args[0])
            for arg in args[1:]:
                if not isinstance(arg, int) \
                   and arg not in args[0].uuid_to_users:
                    raise UserDoesNotExistError
                elif not isinstance(arg, int):
                    new_args.append(args[0].uuid_to_users[arg])
                elif isinstance(arg, int):
                    new_args.append(arg)
            if arg_change:
                return func(*new_args)
            return func(*args)
        return wrapper
    return deco


class SocialGraph:

    def __init__(self):
        self.users = set()
        self.uuid_to_users = dict()
        self.follows = defaultdict(set)
        self.followed_by = defaultdict(set)

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

    @user_checker_arg_modifier()
    def get_user(self, user_uuid):
        return self.uuid_to_users[user_uuid]

    @user_checker_arg_modifier(True)
    def delete_user(self, user_uuid):
        self.users.remove(user_uuid)
        del self.uuid_to_users[user_uuid.uuid]

    @user_checker_arg_modifier()
    def follow(self, follower, followee):
        self.follows[follower].add(followee)
        self.followed_by[followee].add(follower)

    @user_checker_arg_modifier()
    def unfollow(self, follower, followee):
        try:
            self.follows[follower].remove(followee)
            self.followed_by[followee].remove(follower)
        except KeyError:
            pass

    @user_checker_arg_modifier()
    def is_following(self, follower, followee):
        return followee in self.follows[follower]

    @user_checker_arg_modifier()
    def followers(self, user_uuid):
        return self.followed_by[user_uuid]

    @user_checker_arg_modifier()
    def following(self, user_uuid):
        return self.follows[user_uuid]

    @user_checker_arg_modifier()
    def friends(self, user_uuid):
        return self.follows[user_uuid] & self.followed_by[user_uuid]

    def get_distances(self, user_uuid):
        visited = set()
        distances = defaultdict(set)
        queue = []
        queue.append((user_uuid, 0))

        while queue:
            current = queue[0][0]
            level = queue[0][1] + 1
            for followed in self.follows[current]:
                if followed not in distances:
                    distances[level].add(followed)
                if followed not in visited:
                    queue.append((followed, level))
                    visited.add(followed)
            queue.pop(0)

        return distances

    @user_checker_arg_modifier()
    def max_distance(self, user_uuid):
        if not self.follows[user_uuid]:
            return math.inf

        distances = self.get_distances(user_uuid)
        return max(distances.keys())

    @user_checker_arg_modifier()
    def min_distance(self, from_user_uuid, to_user_uuid):
        if not self.follows[from_user_uuid]:
            raise UsersNotConnectedError

        visited = set()
        queue = []
        queue.append((from_user_uuid, 0))

        while queue:
            current = queue[0][0]
            level = queue[0][1] + 1
            for followed in self.follows[current]:
                if followed == to_user_uuid:
                    return level
                if followed not in visited:
                    queue.append((followed, level))
                    visited.add(followed)
            queue.pop(0)
        else:
            raise UsersNotConnectedError

    @user_checker_arg_modifier()
    def nth_layer_followings(self, user_uuid, n):
        if not self.follows[user_uuid]:
            return set()

        distances = self.get_distances(user_uuid)
        try:
            return distances[n]
        except KeyError:
            return set()

    @user_checker_arg_modifier()
    def generate_feed(self, user_uuid, offset=0, limit=10):
        latest_posts = []
        for followed in self.follows[user_uuid]:
            latest_posts.extend(self.uuid_to_users[followed].posts)
        latest_posts.sort(key=lambda x: x.published_at)
        latest_posts.reverse()
        return latest_posts[offset: offset + limit]


class UserAlreadyExistsError(Exception):
    pass


class UserDoesNotExistError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass