timeit

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

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

Решение на Социална мрежа от Галин Ангелов

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

Към профила на Галин Ангелов

Резултати

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

Код

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
import uuid
import datetime


class UserDoesNotExistError(Exception):
    def __init__(self):
        self.msg = "User doesn't exist."


class UserAlreadyExistError(Exception):
    def __init__(self):
        self.msg = "User already exist."


class UsersNotConnectedError(Exception):
    def __init__(self):
        self.msg = "Users are not connected."
 

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


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

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

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


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

    def add_user(self, user):
        if user in self.users.keys():
            raise UserAlreadyExistError()
        self.users[user] = []

    def get_user(self, user_uuid):
        for user in self.users.keys():
            if user_uuid == user.uuid:
                return user
        raise UserDoesNotExistError();    

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

    def follow(self, follower, followee):   #follower = uuid, followee = uuid  
        self.users.get(self.get_user(follower)).append(followee)

    def unfollow(self, follower, followee):
        self.users.get(self.get_user(follower)).remove(followee)

    def is_following(self, follower, followee):
        for user in self.users.get(self.get_user(follower)):
            if user == followee:
                return True

    def followers(self, user_uuid):
        users = []
        for user in self.users.keys():
            for followee in self.users.get(user):
                if followee == user_uuid:
                    users.append(user.uuid)
        return set(users)

    def following(self, user_uuid):
        return set(self.users.get(self.get_user(user_uuid)))

    def friends(self, user_uuid):
        friends = []
        for user in self.following(user_uuid):
            for followee in self.following(user):
                if followee == user_uuid:
                    friends.append(user)
        return set(friends)

    def max_distance_helper(self, user_uuid, visited):
        if user_uuid in visited:
            return visited[user_uuid]
        max_dist = 0
        for user in self.following(user_uuid):
            max_dist = max(max_dist, self.max_distance_helper(user, visited) + 1)
        visited[user_uuid] = max_dist
        return max_dist

    def max_distance(self, user_uuid):
        visited = {}
        return self.max_distance_helper(user_uuid, visited)

    def min_distance_helper(self, from_user_uuid, to_user_uuid, path, short_paths):
        if from_user_uuid == to_user_uuid:
            short_paths.append(path)
            return
        for user in self.following(from_user_uuid):
            self.min_distance_helper(user, to_user_uuid, path + 1, short_paths)
        return short_paths

    def min_distance(self, from_user_uuid, to_user_uuid):
        short_paths = []
        path = 0
        if len(self.min_distance_helper(from_user_uuid, to_user_uuid, path, short_paths)) is 0:
            raise UsersNotConnectedError()
        return min(self.min_distance_helper(from_user_uuid, to_user_uuid, path, short_paths))

    def nth_layer_helper(self, user_uuid, n, index, following_nth, visited):
        if index + 1 == n:
            following_nth.extend(self.users.get(self.get_user(user_uuid)))
            return
        for user in self.following(user_uuid):
            if user not in visited:
                visited.append(user)
                self.nth_layer_helper(user, n, index + 1, following_nth, visited)

    def nth_layer_followings(self, user_uuid, n):
        index = 0
        visited = []
        following_nth = []
        self.nth_layer_helper(user_uuid, n, index, following_nth, visited)
        return set(following_nth)

    def cmpByDate(self, post):
        return post.published_at
        
    def generate_feed(self, user_uuid, offset=0, limit=10):
        friends_posts = []
        for user in self.following(user_uuid):
            print("User: " + self.get_user(user).full_name)
            for post in self.get_user(user).posts:
                friends_posts.append(post)
        friends = sorted(friends_posts, key=self.cmpByDate, reverse = True)
        if offset == 0 and limit == 0:
            return []
        elif len(friends) < limit:
            return friends
        else:
            return friends[offset+1::limit+1]

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

EFF.....
======================================================================
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: module 'solution' has no attribute 'UserAlreadyExistsError'

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

======================================================================
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: ['29', '36', '4', '11'] != ['39', '29', '19', '9', '38', '28', '18', '8', '37', '27']

First differing element 0:
29
39

Second list contains 6 additional elements.
First extra element 4:
38

- ['29', '36', '4', '11']
+ ['39', '29', '19', '9', '38', '28', '18', '8', '37', '27']

----------------------------------------------------------------------
Ran 8 tests in 0.066s

FAILED (failures=2, errors=1)

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

Галин обнови решението на 18.04.2016 16:15 (преди над 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
import uuid
import datetime


class UserDoesNotExistError(Exception):
    def __init__(self):
        self.msg = "User doesn't exist."


class UserAlreadyExistError(Exception):
    def __init__(self):
        self.msg = "User already exist."


class UsersNotConnectedError(Exception):
    def __init__(self):
        self.msg = "Users are not connected."
 

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


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

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

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


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

    def add_user(self, user):
        if user in self.users.keys():
            raise UserAlreadyExistError()
        self.users[user] = []

    def get_user(self, user_uuid):
        for user in self.users.keys():
            if user_uuid == user.uuid:
                return user
        raise UserDoesNotExistError();    

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

    def follow(self, follower, followee):   #follower = uuid, followee = uuid  
        self.users.get(self.get_user(follower)).append(followee)

    def unfollow(self, follower, followee):
        self.users.get(self.get_user(follower)).remove(followee)

    def is_following(self, follower, followee):
        for user in self.users.get(self.get_user(follower)):
            if user == followee:
                return True

    def followers(self, user_uuid):
        users = []
        for user in self.users.keys():
            for followee in self.users.get(user):
                if followee == user_uuid:
                    users.append(user.uuid)
        return set(users)

    def following(self, user_uuid):
        return set(self.users.get(self.get_user(user_uuid)))

    def friends(self, user_uuid):
        friends = []
        for user in self.following(user_uuid):
            for followee in self.following(user):
                if followee == user_uuid:
                    friends.append(user)
        return set(friends)

    def max_distance_helper(self, user_uuid, visited):
        if user_uuid in visited:
            return visited[user_uuid]
        max_dist = 0
        for user in self.following(user_uuid):
            max_dist = max(max_dist, self.max_distance_helper(user, visited) + 1)
        visited[user_uuid] = max_dist
        return max_dist

    def max_distance(self, user_uuid):
        visited = {}
        return self.max_distance_helper(user_uuid, visited)

    def min_distance_helper(self, from_user_uuid, to_user_uuid, path, short_paths):
        if from_user_uuid == to_user_uuid:
            short_paths.append(path)
            return
        for user in self.following(from_user_uuid):
            self.min_distance_helper(user, to_user_uuid, path + 1, short_paths)
        return short_paths

    def min_distance(self, from_user_uuid, to_user_uuid):
        short_paths = []
        path = 0
        if len(self.min_distance_helper(from_user_uuid, to_user_uuid, path, short_paths)) is 0:
            raise UsersNotConnectedError()
        return min(self.min_distance_helper(from_user_uuid, to_user_uuid, path, short_paths))

    def nth_layer_helper(self, user_uuid, n, index, following_nth, visited):
        if index + 1 == n:
            following_nth.extend(self.users.get(self.get_user(user_uuid)))
            return
        for user in self.following(user_uuid):
            if user not in visited:
                visited.append(user)
                self.nth_layer_helper(user, n, index + 1, following_nth, visited)

    def nth_layer_followings(self, user_uuid, n):
        index = 0
        visited = []
        following_nth = []
        self.nth_layer_helper(user_uuid, n, index, following_nth, visited)
        return set(following_nth)

    def cmpByDate(self, post):
        return post.published_at
        
    def generate_feed(self, user_uuid, offset=0, limit=10):
        friends_posts = []
        for user in self.following(user_uuid):
            print("User: " + self.get_user(user).full_name)
            for post in self.get_user(user).posts:
                friends_posts.append(post)
        friends = sorted(friends_posts, key=self.cmpByDate, reverse = True)
        if offset == 0 and limit == 0:
            return []
        elif len(friends) < limit:
            return friends
        else:
            return friends[offset+1::limit+1]