timeit

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

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

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

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

Към профила на Илиан Стаменов

Резултати

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

Код

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


class UserDoesNotExistError(BaseException):
    pass


class UsersNotConnectedError(BaseException):
    pass


class UserAlreadyExistsError(BaseException):
    pass


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

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

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


class Post:
    def __init__(self, uuid, time, post_content):
        self.author = uuid
        self.published_at = time
        self.content = post_content


class SocialGraph:
    def __init__(self):
        self.followers = {}
        self.followed_by = {}
        self.users = {}

    def add_user(self, user):
        if user.uuid in self.users.keys():
            raise UserAlreadyExistsError
        self.users[user.uuid] = user
        self.followers[user.uuid] = set()
        self.followed_by[user.uuid] = set()

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

    def delete_user(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        self.users.remove(user_uuid)
        for follower in self.followers[user_uuid]:
            del self.following[follower][user_uuid]
        del self.followers[user_uuid]
        del self.following[user_uuid]

    def follow(self, follower, followee):
        self.followers[followee].add(follower)
        self.followed_by[follower].add(followee)

    def unfollow(self, follower, followee):
        self.followers[followee].remove(follower)
        self.followed_by[follower].remove(followee)

    def is_following(self, follower, followee):
        if followee not in self.users:
            raise UserDoesNotExistError
        for f in self.followers[followee]:
            if follower == f:
                return True
        return False

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

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

    def friends(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        res = []
        for follower in self.followers[user_uuid]:
            for followee in self.followers[follower]:
                if followee == user_uuid:
                    res.append(follower)
        return res

    def max_distance(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        len = {}
        current = []
        current.append(followers(user_uuid))
        len[user_uuid] = 0
        while(len(current)):
            for user in current:
                if user not in colored:
                    colored.append(user)
                    current.append(followers(user))
                    current.remove(user)
        return math.inf

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.users or to_user_uuid not in self.users:
            raise UserDoesNotExistError
        distance = 0
        if from_user_uuid == to_user_uuid:
            return distance
        colored = set([from_user_uuid])
        current = set()
        current = current.union(set(followers(from_user_uuid)))
        while(len(current)):
            distance += 1
            for user in current:
                if user == to_user_uuid:
                    return distance
                if user not in colored:
                    current = current.union(set([user]))
                    for x in followers(user):
                        current.add(x)
                current.remove(user)
        raise UsersNotConnectedError

    def nth_layer_following(self, user_uuid, n):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        colored = set()
        res = set()
        if 0 == n:
            return res
        res = set(followers(user_uuid))
        colored = colored.union(set(followers(user_uuid)))
        for i in range(n):
            res2 = set()
            for x in res:
                if x not in colored:
                    res2 = res2.union(set(followers(x)))
                    colored = colored.union(set(followers(x)))
            res = res2
        return res

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

        def custom_sorter(elem):
            return elem.time
        res = []
        for followee in self.followed_by[user_uuid]:
            for post in followee.get_post():
                res.append(post)
        res.sort(key=custom_sorter)
        return res[offset:][:10]

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

EEEE.E..
======================================================================
ERROR: test_add_get_and_delete_user (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: 'dict' object has no attribute 'remove'

======================================================================
ERROR: 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
NameError: name 'followers' is not defined

======================================================================
ERROR: 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
AttributeError: 'UUID' object has no attribute 'get_post'

======================================================================
ERROR: 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
TypeError: 'dict' object is not callable

======================================================================
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'

----------------------------------------------------------------------
Ran 8 tests in 0.076s

FAILED (errors=5)

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

Илиан обнови решението на 18.04.2016 16:54 (преди над 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
from uuid import uuid4
from datetime import datetime
from collections import deque


class UserDoesNotExistError(BaseException):
    pass


class UsersNotConnectedError(BaseException):
    pass


class UserAlreadyExistsError(BaseException):
    pass


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

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

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


class Post:
    def __init__(self, uuid, time, post_content):
        self.author = uuid
        self.published_at = time
        self.content = post_content


class SocialGraph:
    def __init__(self):
        self.followers = {}
        self.followed_by = {}
        self.users = {}

    def add_user(self, user):
        if user.uuid in self.users.keys():
            raise UserAlreadyExistsError
        self.users[user.uuid] = user
        self.followers[user.uuid] = set()
        self.followed_by[user.uuid] = set()

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

    def delete_user(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        self.users.remove(user_uuid)
        for follower in self.followers[user_uuid]:
            del self.following[follower][user_uuid]
        del self.followers[user_uuid]
        del self.following[user_uuid]

    def follow(self, follower, followee):
        self.followers[followee].add(follower)
        self.followed_by[follower].add(followee)

    def unfollow(self, follower, followee):
        self.followers[followee].remove(follower)
        self.followed_by[follower].remove(followee)

    def is_following(self, follower, followee):
        if followee not in self.users:
            raise UserDoesNotExistError
        for f in self.followers[followee]:
            if follower == f:
                return True
        return False

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

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

    def friends(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        res = []
        for follower in self.followers[user_uuid]:
            for followee in self.followers[follower]:
                if followee == user_uuid:
                    res.append(follower)
        return res

    def max_distance(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        len = {}
        current = []
        current.append(followers(user_uuid))
        len[user_uuid] = 0
        while(len(current)):
            for user in current:
                if user not in colored:
                    colored.append(user)
                    current.append(followers(user))
                    current.remove(user)
        return 0

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.users or to_user_uuid not in self.users:
            raise UserDoesNotExistError
        distance = 0
        if from_user_uuid == to_user_uuid:
            return distance
        colored = set([from_user_uuid])
        current = set()
        current = current.union(set(followers(from_user_uuid)))
        while(len(current)):
            distance += 1
            for user in current:
                if user == to_user_uuid:
                    return distance
                if user not in colored:
                    current = current.union(set([user]))
                    for x in followers(user):
                        current.add(x)
                current.remove(user)
        raise UsersNotConnectedError

    def nth_layer_following(self, user_uuid, n):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        colored = set()
        res = set()
        if 0 == n:
            return res
        res = set(followers(user_uuid))
        colored = colored.union(set(followers(user_uuid)))
        for i in range(n):
            res2 = set()
            for x in res:
                if x not in colored:
                    res2 = res2.union(set(followers(x)))
                    colored = colored.union(set(followers(x)))
            res = res2
        return res

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

        def custom_sorter(elem):
            return elem.time
        res = []
        for followee in self.followed_by[user_uuid]:
            for post in followee.get_post():
                res.append(post)
        res.sort(key=custom_sorter)
        return res[offset:][:10]

Илиан обнови решението на 18.04.2016 16:55 (преди над 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
from uuid import uuid4
from datetime import datetime
from collections import deque


class UserDoesNotExistError(BaseException):
    pass


class UsersNotConnectedError(BaseException):
    pass


class UserAlreadyExistsError(BaseException):
    pass


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

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

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


class Post:
    def __init__(self, uuid, time, post_content):
        self.author = uuid
        self.published_at = time
        self.content = post_content


class SocialGraph:
    def __init__(self):
        self.followers = {}
        self.followed_by = {}
        self.users = {}

    def add_user(self, user):
        if user.uuid in self.users.keys():
            raise UserAlreadyExistsError
        self.users[user.uuid] = user
        self.followers[user.uuid] = set()
        self.followed_by[user.uuid] = set()

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

    def delete_user(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        self.users.remove(user_uuid)
        for follower in self.followers[user_uuid]:
            del self.following[follower][user_uuid]
        del self.followers[user_uuid]
        del self.following[user_uuid]

    def follow(self, follower, followee):
        self.followers[followee].add(follower)
        self.followed_by[follower].add(followee)

    def unfollow(self, follower, followee):
        self.followers[followee].remove(follower)
        self.followed_by[follower].remove(followee)

    def is_following(self, follower, followee):
        if followee not in self.users:
            raise UserDoesNotExistError
        for f in self.followers[followee]:
            if follower == f:
                return True
        return False

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

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

    def friends(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        res = []
        for follower in self.followers[user_uuid]:
            for followee in self.followers[follower]:
                if followee == user_uuid:
                    res.append(follower)
        return res

    def max_distance(self, user_uuid):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        len = {}
        current = []
        current.append(followers(user_uuid))
        len[user_uuid] = 0
        while(len(current)):
            for user in current:
                if user not in colored:
                    colored.append(user)
                    current.append(followers(user))
                    current.remove(user)
        return math.inf

    def min_distance(self, from_user_uuid, to_user_uuid):
        if from_user_uuid not in self.users or to_user_uuid not in self.users:
            raise UserDoesNotExistError
        distance = 0
        if from_user_uuid == to_user_uuid:
            return distance
        colored = set([from_user_uuid])
        current = set()
        current = current.union(set(followers(from_user_uuid)))
        while(len(current)):
            distance += 1
            for user in current:
                if user == to_user_uuid:
                    return distance
                if user not in colored:
                    current = current.union(set([user]))
                    for x in followers(user):
                        current.add(x)
                current.remove(user)
        raise UsersNotConnectedError

    def nth_layer_following(self, user_uuid, n):
        if user_uuid not in self.users:
            raise UserDoesNotExistError
        colored = set()
        res = set()
        if 0 == n:
            return res
        res = set(followers(user_uuid))
        colored = colored.union(set(followers(user_uuid)))
        for i in range(n):
            res2 = set()
            for x in res:
                if x not in colored:
                    res2 = res2.union(set(followers(x)))
                    colored = colored.union(set(followers(x)))
            res = res2
        return res

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

        def custom_sorter(elem):
            return elem.time
        res = []
        for followee in self.followed_by[user_uuid]:
            for post in followee.get_post():
                res.append(post)
        res.sort(key=custom_sorter)
        return res[offset:][:10]