1
+ # Definition for a binary tree node.
2
+ import collections
3
+ import heapq
4
+ import time
5
+ import unittest
6
+
7
+ # Read about enumerate in python
8
+ from collections import defaultdict
9
+ from typing import List
10
+
11
+ # please see https://leetcode.com/problems/design-twitter/discuss/714702/python-solution%3A-simplest-data-structure
12
+
13
+ class Twitter :
14
+
15
+ def __init__ (self ):
16
+ """
17
+ Initialize your data structure here.
18
+ """
19
+ self .twitter = collections .defaultdict (list )
20
+ self .following = collections .defaultdict (set )
21
+
22
+ def postTweet (self , userId : int , tweetId : int ) -> None :
23
+ """
24
+ Compose a new tweet.
25
+ """
26
+ self .twitter [userId ].append ((tweetId , time .time ()))
27
+
28
+ def getNewsFeed (self , userId : int ) -> List [int ]:
29
+ """
30
+ 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.
31
+ """
32
+ allNews = []
33
+ for tweets in self .twitter [userId ]:
34
+ allNews .append (tweets )
35
+
36
+ for followingId in self .following [userId ]:
37
+ if followingId == userId : continue
38
+ for tweets in self .twitter [followingId ]:
39
+ allNews .append (tweets )
40
+
41
+ allNews .sort (key = lambda x : x [1 ], reverse = True )
42
+
43
+ return list (map (lambda x : x [0 ], allNews ))[:10 ]
44
+
45
+ def follow (self , followerId : int , followeeId : int ) -> None :
46
+ """
47
+ Follower follows a followee. If the operation is invalid, it should be a no-op.
48
+ """
49
+ self .following [followerId ].add (followeeId )
50
+
51
+ def unfollow (self , followerId : int , followeeId : int ) -> None :
52
+ """
53
+ Follower unfollows a followee. If the operation is invalid, it should be a no-op.
54
+ """
55
+ if followeeId in self .following [followerId ]:
56
+ self .following [followerId ].remove (followeeId )
57
+
58
+ class DesignTwitter (unittest .TestCase ):
59
+
60
+ def test_Leetcode (self ):
61
+ twitter = Twitter ()
62
+ twitter .postTweet (1 , 5 )
63
+ twitter .getNewsFeed (1 )
64
+ twitter .follow (1 , 2 )
65
+ twitter .postTweet (2 , 6 )
66
+ twitter .getNewsFeed (1 )
67
+ twitter .unfollow (1 , 2 )
68
+ twitter .getNewsFeed (1 )
69
+
70
+ if __name__ == '__main__' :
71
+ unittest .main ()
0 commit comments