forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
50 lines (44 loc) · 1.79 KB
/
Solution.py
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
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.user_tweets = defaultdict(list)
self.user_following = defaultdict(set)
self.tweets = defaultdict()
self.time = 0
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
self.time += 1
self.user_tweets[userId].append(tweetId)
self.tweets[tweetId] = self.time
def getNewsFeed(self, userId: int) -> List[int]:
"""
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
"""
following = self.user_following[userId]
users = set(following)
users.add(userId)
tweets = [self.user_tweets[u][::-1][:10] for u in users]
tweets = sum(tweets, [])
return nlargest(10, tweets, key=lambda tweet: self.tweets[tweet])
def follow(self, followerId: int, followeeId: int) -> None:
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
self.user_following[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
following = self.user_following[followerId]
if followeeId in following:
following.remove(followeeId)
# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)