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


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass


class FollowUserError(Exception):
    pass


class User:
    def __init__(self, full_name):
        self.uuid = uuid.uuid4()
        self.full_name = full_name
        self.__posts = deque(maxlen=50)

    def add_post(self, post_content):
        self.__posts.append(Post(post_content, self.uuid))

    def get_post(self):
        return (post for post in self.__posts)


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


def check_for_not_existing_user(function):
    def checked_for_not_existing_user(self, *args, **kwargs):
        for arg in args:
            if isinstance(arg, uuid.UUID):
                if arg not in self._SocialGraph__users:
                    raise UserDoesNotExistError
        return function(self, *args, **kwargs)
    return checked_for_not_existing_user


class SocialGraph:
    def __init__(self):
        self.__graph = defaultdict(set)
        self.__users = {}

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

    @check_for_not_existing_user
    def get_user(self, user_uuid):
        return self.__users[user_uuid]

    @check_for_not_existing_user
    def delete_user(self, user_uuid):
        del self.__users[user_uuid]
        if self.__graph[user_uuid]:
            del self.__graph[user_uuid]
        for followees in self.__graph.values():
            if user_uuid in followees:
                followees.remove(user_uuid)

    @check_for_not_existing_user
    def follow(self, follower, followee):
        if follower == followee:
            raise FollowUserError
        self.__graph[follower].add(followee)

    @check_for_not_existing_user
    def unfollow(self, follower, followee):
        self.__graph[follower].discard(followee)

    @check_for_not_existing_user
    def is_following(self, follower, followee):
        return followee in self.__graph[follower]

    @check_for_not_existing_user
    def followers(self, user_uuid):
        return {follower for follower in self.__graph
                if self.is_following(follower, user_uuid)}

    @check_for_not_existing_user
    def following(self, user_uuid):
        return self.__graph[user_uuid]

    @check_for_not_existing_user
    def friends(self, user_uuid):
        return {followee for followee in self.following(user_uuid)
                if self.is_following(followee, user_uuid)}

    @check_for_not_existing_user
    def max_distance(self, user_uuid):
        min_distances = []
        for to_uuid in self.__users:
            try:
                min_distances.append(self.min_distance(user_uuid, to_uuid))
            except UsersNotConnectedError:
                pass
        return max(min_distances) if max(min_distances) else math.inf

    @check_for_not_existing_user
    def min_distance(self, from_user_uuid, to_user_uuid):
        min_path = self.__min_path(from_user_uuid, to_user_uuid, [])
        if not min_path:
            raise UsersNotConnectedError
        return len(min_path) - 1

    @check_for_not_existing_user
    def nth_layer_followings(self, user_uuid, n):
        return self.__nth_layer(user_uuid, n)

    @check_for_not_existing_user
    def generate_feed(self, user_uuid, offset=0, limit=10):
        all_posts = [post for followee in self.following(user_uuid)
                     for post in self.get_user(followee).get_post()]
        all_posts.sort(key=lambda post: post.published_at, reverse=True)
        return all_posts[offset:offset + limit]

    def __min_path(self, from_user_uuid, to_user_uuid, path):
        path = path + [from_user_uuid]
        if from_user_uuid == to_user_uuid:
            return path
        if not self.__graph[from_user_uuid]:
            return None
        min_path = None
        for user_uuid in self.__graph[from_user_uuid]:
            if user_uuid not in path:
                new_path = self.__min_path(user_uuid, to_user_uuid, path)
                if new_path:
                    if not min_path or len(new_path) < len(min_path):
                        min_path = new_path
        return min_path

    def __nth_layer(self, user_uuid, n, index=1, layers=defaultdict(set)):
        visited = {followee for followees in layers.values()
                   for followee in followees}
        layers[index] |= {followee for followee in self.following(user_uuid)
                          if followee not in visited}
        if index == n:
            return layers[n]
        for followee in self.__graph[user_uuid]:
            layers[index] |= self.__nth_layer(followee, n, index + 1, layers)
        return layers[n]

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

........
----------------------------------------------------------------------
Ran 8 tests in 0.074s

OK

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

Марина обнови решението на 15.04.2016 21:44 (преди над 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
import uuid
import datetime
import math
from collections import defaultdict


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass


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

    def add_post(self, post_content):
        post = Post(post_content)
        post.author = self.uuid
        self.__posts.append(post)
        if len(self.__posts) > 50:
            self.__posts = self.__posts[1:]

    def get_post(self):
        return (post for post in self.__posts)


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


class SocialGraph:
    def __init__(self):
        self.__graph = defaultdict(set)
        self.__users = {}

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

    def get_user(self, user_uuid):
        self.__contains_user(user_uuid)
        return self.__users[user_uuid]

    def delete_user(self, user_uuid):
        self.__contains_user(user_uuid)
        del self.__users[user_uuid]
        if self.__graph[user_uuid]:
            del self.__graph[user_uuid]
        for followees in self.__graph.values():
            if user_uuid in followees:
                followees.remove(user_uuid)

    def follow(self, follower, followee):
        self.__contains_user(follower)
        self.__contains_user(followee)
        self.__graph[follower].add(followee)

    def unfollow(self, follower, followee):
        self.__contains_user(follower)
        self.__contains_user(followee)
        self.__graph[follower].discard(followee)

    def is_following(self, follower, followee):
        self.__contains_user(follower)
        self.__contains_user(followee)
        return followee in self.__graph[follower]

    def followers(self, user_uuid):
        self.__contains_user(user_uuid)
        return {follower for follower in self.__graph
                if self.is_following(follower, user_uuid)}

    def following(self, user_uuid):
        self.__contains_user(user_uuid)
        return self.__graph[user_uuid]

    def friends(self, user_uuid):
        self.__contains_user(user_uuid)
        return {followee for followee in self.following(user_uuid)
                if self.is_following(followee, user_uuid)}

    def max_distance(self, user_uuid):
        self.__contains_user(user_uuid)
        max_path = self.__max_path(user_uuid, [])
        return len(max_path) - 1 if len(max_path) > 1 else math.inf

    def min_distance(self, from_user_uuid, to_user_uuid):
        self.__contains_user(from_user_uuid)
        self.__contains_user(to_user_uuid)
        min_path = self.__min_path(from_user_uuid, to_user_uuid, [])
        if not min_path:
            raise UsersNotConnectedError
        return len(min_path) - 1

    def nth_layer_followings(self, user_uuid, n):
        self.__contains_user(user_uuid)
        return self.__nth_layer(user_uuid, n)

    def generate_feed(self, user_uuid, offset=0, limit=10):
        self.__contains_user(user_uuid)
        all_posts = [post for followee in self.following(user_uuid)
                     for post in self.get_user(followee).get_post()]
        all_posts.sort(key=lambda post: post.published_at, reverse=True)
        return all_posts[offset:offset + limit]

    def __contains_user(self, user_uuid):
        if user_uuid not in self.__users:
            raise UserDoesNotExistError

    def __max_path(self, from_user_uuid, path):
        path = path + [from_user_uuid]
        if not self.__graph[from_user_uuid]:
            return path
        max_path = None
        for user_uuid in self.__graph[from_user_uuid]:
            if user_uuid not in path:
                new_path = self.__max_path(user_uuid, path)
                if new_path:
                    if not max_path or len(new_path) >= len(max_path):
                        max_path = new_path
        return max_path

    def __min_path(self, from_user_uuid, to_user_uuid, path):
        path = path + [from_user_uuid]
        if from_user_uuid == to_user_uuid:
            return path
        if not self.__graph[from_user_uuid]:
            return None
        min_path = None
        for user_uuid in self.__graph[from_user_uuid]:
            if user_uuid not in path:
                new_path = self.__min_path(user_uuid, to_user_uuid, path)
                if new_path:
                    if not min_path or len(new_path) < len(min_path):
                        min_path = new_path
        return min_path

    def __nth_layer(self, user_uuid, n, index=1, layers=defaultdict(set)):
        visited = {followee for followees in layers.values()
                   for followee in followees}
        layers[index] |= {followee for followee in self.following(user_uuid)
                          if followee not in visited}
        if index == n:
            return layers[n]
        for followee in self.__graph[user_uuid]:
            layers[index] |= self.__nth_layer(followee, n, index + 1, layers)
        return layers[n]

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


class UserDoesNotExistError(Exception):
    pass


class UserAlreadyExistsError(Exception):
    pass


class UsersNotConnectedError(Exception):
    pass


class FollowUserError(Exception):
    pass


class User:
    def __init__(self, full_name):
        self.uuid = uuid.uuid4()
        self.full_name = full_name
        self.__posts = deque(maxlen=50)

    def add_post(self, post_content):
        self.__posts.append(Post(post_content, self.uuid))

    def get_post(self):
        return (post for post in self.__posts)


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


def check_for_not_existing_user(function):
    def checked_for_not_existing_user(self, *args, **kwargs):
        for arg in args:
            if isinstance(arg, uuid.UUID):
                if arg not in self._SocialGraph__users:
                    raise UserDoesNotExistError
        return function(self, *args, **kwargs)
    return checked_for_not_existing_user


class SocialGraph:
    def __init__(self):
        self.__graph = defaultdict(set)
        self.__users = {}

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

    @check_for_not_existing_user
    def get_user(self, user_uuid):
        return self.__users[user_uuid]

    @check_for_not_existing_user
    def delete_user(self, user_uuid):
        del self.__users[user_uuid]
        if self.__graph[user_uuid]:
            del self.__graph[user_uuid]
        for followees in self.__graph.values():
            if user_uuid in followees:
                followees.remove(user_uuid)

    @check_for_not_existing_user
    def follow(self, follower, followee):
        if follower == followee:
            raise FollowUserError
        self.__graph[follower].add(followee)

    @check_for_not_existing_user
    def unfollow(self, follower, followee):
        self.__graph[follower].discard(followee)

    @check_for_not_existing_user
    def is_following(self, follower, followee):
        return followee in self.__graph[follower]

    @check_for_not_existing_user
    def followers(self, user_uuid):
        return {follower for follower in self.__graph
                if self.is_following(follower, user_uuid)}

    @check_for_not_existing_user
    def following(self, user_uuid):
        return self.__graph[user_uuid]

    @check_for_not_existing_user
    def friends(self, user_uuid):
        return {followee for followee in self.following(user_uuid)
                if self.is_following(followee, user_uuid)}

    @check_for_not_existing_user
    def max_distance(self, user_uuid):
        min_distances = []
        for to_uuid in self.__users:
            try:
                min_distances.append(self.min_distance(user_uuid, to_uuid))
            except UsersNotConnectedError:
                pass
        return max(min_distances) if max(min_distances) else math.inf

    @check_for_not_existing_user
    def min_distance(self, from_user_uuid, to_user_uuid):
        min_path = self.__min_path(from_user_uuid, to_user_uuid, [])
        if not min_path:
            raise UsersNotConnectedError
        return len(min_path) - 1

    @check_for_not_existing_user
    def nth_layer_followings(self, user_uuid, n):
        return self.__nth_layer(user_uuid, n)

    @check_for_not_existing_user
    def generate_feed(self, user_uuid, offset=0, limit=10):
        all_posts = [post for followee in self.following(user_uuid)
                     for post in self.get_user(followee).get_post()]
        all_posts.sort(key=lambda post: post.published_at, reverse=True)
        return all_posts[offset:offset + limit]

    def __min_path(self, from_user_uuid, to_user_uuid, path):
        path = path + [from_user_uuid]
        if from_user_uuid == to_user_uuid:
            return path
        if not self.__graph[from_user_uuid]:
            return None
        min_path = None
        for user_uuid in self.__graph[from_user_uuid]:
            if user_uuid not in path:
                new_path = self.__min_path(user_uuid, to_user_uuid, path)
                if new_path:
                    if not min_path or len(new_path) < len(min_path):
                        min_path = new_path
        return min_path

    def __nth_layer(self, user_uuid, n, index=1, layers=defaultdict(set)):
        visited = {followee for followees in layers.values()
                   for followee in followees}
        layers[index] |= {followee for followee in self.following(user_uuid)
                          if followee not in visited}
        if index == n:
            return layers[n]
        for followee in self.__graph[user_uuid]:
            layers[index] |= self.__nth_layer(followee, n, index + 1, layers)
        return layers[n]