-
Notifications
You must be signed in to change notification settings - Fork 43
/
design-twitter.py
551 lines (467 loc) · 19.5 KB
/
design-twitter.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
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
"""
355. Design Twitter
Medium
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed.
Implement the Twitter class:
Twitter() Initializes your twitter object.
void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId.
List<Integer> getNewsFeed(int userId) Retrieves 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 themself. Tweets must be ordered from most recent to least recent.
void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId.
void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.
Example 1:
Input
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
Output
[null, null, [5], null, null, [6, 5], null, [5]]
Explanation
Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]
twitter.follow(1, 2); // User 1 follows user 2.
twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.unfollow(1, 2); // User 1 unfollows user 2.
twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.
Constraints:
1 <= userId, followerId, followeeId <= 500
0 <= tweetId <= 104
All the tweets have unique IDs.
At most 3 * 104 calls will be made to postTweet, getNewsFeed, follow, and unfollow.
"""
# V0
# https://github.com/labuladong/fucking-algorithm/blob/master/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%B3%BB%E5%88%97/%E8%AE%BE%E8%AE%A1Twitter.md
from collections import defaultdict
from heapq import merge
class Twitter(object):
def __init__(self):
self.follower_followees_map = defaultdict(set)
self.user_tweets_map = defaultdict(list)
self.time_stamp = 0
def postTweet(self, userId, tweetId):
self.user_tweets_map[userId].append((self.time_stamp, tweetId))
self.time_stamp -= 1
def getNewsFeed(self, userId):
# get the followees list
followees = self.follower_followees_map[userId]
# add userId as well, since he/she can also see his/her post in the timeline
followees.add(userId)
# reversed(.) returns a listreverseiterator, so the complexity is O(1) not O(n)
candidate_tweets = [reversed(self.user_tweets_map[u]) for u in followees]
tweets = []
"""
python starred expression :
-> will extend Iterable Unpacking
example 1 : *candidate_tweets
exmaple 2 : a, *b, c = range(5)
ref :
https://www.python.org/dev/peps/pep-3132/
https://blog.csdn.net/weixin_41521681/article/details/103528136
http://swaywang.blogspot.com/2012/01/pythonstarred-expression.html
https://github.com/yennanliu/CS_basics/blob/master/doc/cheatsheet/python_trick.md
"""
# complexity is 10*log(n), n is twitter's user number in worst case
# both of below work
candidates = list(merge(*candidate_tweets))
#for t in merge(*candidate_tweets):
for t in candidates:
tweets.append(t[1])
if len(tweets) == 10:
break
return tweets
def follow(self, followerId, followeeId):
self.follower_followees_map[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
self.follower_followees_map[followerId].discard(followeeId)
# V0 : TODO : fix getNewsFeed returned format
from collections import defaultdict
class Twitter(object):
def __init__(self):
self.users = []
# {'id_1' : [foller_1, 2...], 'id_2' : [foller_3, 4...]..}
self.follower_followees = defaultdict(set)
# {'id_1' : [twitter_1, 2...], 'id_2' : [twitter_3, 4...]..}
self.user_tweets = defaultdict(list)
def postTweet(self, userId, tweetId):
self.user_tweets[userId].append(tweetId)
#TODO : fix this
def getNewsFeed(self, userId):
res = []
for user in list(self.follower_followees[userId]) + [userId]:
if user in self.user_tweets:
res.append(self.user_tweets[userId])
if len(res) >= 10:
break
else:
break
return res[::-1]
def follow(self, followerId, followeeId):
self.follower_followees[followeeId].add(followeeId)
def unfollow(self, followerId, followeeId):
if followeeId in self.follower_followees[followerId]:
idx = self.follower_followees[followeeId]
self.follower_followees[followeeId].pop(idx)
# V0''
import collections, itertools, heapq
class Twitter(object):
def __init__(self):
self.timer = itertools.count(step=-1)
self.tweets = collections.defaultdict(collections.deque)
self.followees = collections.defaultdict(set)
def postTweet(self, userId, tweetId):
self.tweets[userId].appendleft((next(self.timer), tweetId))
def getNewsFeed(self, userId):
tweets = heapq.merge(*(self.tweets[u] for u in self.followees[userId] | {userId}))
return [t for _, t in itertools.islice(tweets, 10)]
def follow(self, followerId, followeeId):
self.followees[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
self.followees[followerId].discard(followeeId)
# V1
# https://leetcode.com/problems/design-twitter/discuss/82943/Use-python-heapq.merge
# https://github.com/labuladong/fucking-algorithm/blob/master/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%B3%BB%E5%88%97/%E8%AE%BE%E8%AE%A1Twitter.md
# IDEA : heapq.merge
from collections import defaultdict
from heapq import merge
class Twitter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.follower_followees_map = defaultdict(set)
self.user_tweets_map = defaultdict(list)
self.time_stamp = 0
def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
self.user_tweets_map[userId].append((self.time_stamp, tweetId))
self.time_stamp -= 1
def getNewsFeed(self, userId):
"""
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.
:type userId: int
:rtype: List[int]
"""
followees = self.follower_followees_map[userId]
followees.add(userId)
# reversed(.) returns a listreverseiterator, so the complexity is O(1) not O(n)
candidate_tweets = [reversed(self.user_tweets_map[u]) for u in followees]
tweets = []
# complexity is 10lg(n), n is twitter's user number in worst case
for t in merge(*candidate_tweets):
tweets.append(t[1])
if len(tweets) == 10:
break
return tweets
def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
self.follower_followees_map[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
self.follower_followees_map[followerId].discard(followeeId)
# V1'
# https://leetcode.com/problems/design-twitter/discuss/82863/Python-solution
# IDEA : collections.defaultdict
# * DEMO : itertools.count
# EXAMPLE 1
# In [23]: import itertools
# ...: mytimer = itertools.count(step=-1)
# ...: print (mytimer)
# ...: for _ in range(5):
# ...: print (next(mytimer))
# ...:
# count(0, -1)
# 0
# -1
# -2
# -3
# -4
# EXAMPLE 2
# In [24]: import itertools
# ...: mytimer2 = itertools.count(step=1)
# ...: print (mytimer2)
# ...: for _ in range(5):
# ...: print (next(mytimer2))
# ...:
# count(0)
# 0
# 1
# 2
# 3
# 4
#
# * DEMO collections.defaultdict(collections.deque) :
# In [31]: mytweets = collections.defaultdict(collections.deque)
# ...: mytweets['001'].appendleft(('1', 'twitterid_1'))
# ...: mytweets['002'].appendleft(('2', 'twitterid_2'))
# ...: mytweets['003'].appendleft(('3', 'twitterid_3'))
# ...: mytweets['001'].appendleft(('10', 'twitterid_10'))
# ...: print (mytweets)
# ...:
# defaultdict(<class 'collections.deque'>, {'001': deque([('10', 'twitterid_10'), ('1', 'twitterid_1')]), '002': deque([('2', 'twitterid_2')]), '003': deque([('3', 'twitterid_3')])})
# * DEMO heapq.merge(*iterables) :
# https://www.geeksforgeeks.org/merge-two-sorted-arrays-python-using-heapq/
# heapq.merge(*iterables) -> Merge multiple sorted inputs into a single sorted output (for example, merge timestamped entries from multiple log files). Returns an iterator over the sorted values.
# In [46]: mytweets = collections.defaultdict(collections.deque)
# ...: mytweets['1'].appendleft(('1', 'twitterid_1'))
# ...: mytweets['2'].appendleft(('2', 'twitterid_2'))
# ...: mytweets['3'].appendleft(('3', 'twitterid_3'))
# ...: mytweets['1'].appendleft(('10', 'twitterid_10'))
# ...: #print (mytweets)
# ...: print (list(heapq.merge(*(mytweets[u] for u in ['1','2','3']))))
# ...: print ('='*30)
# ...: print (list(heapq.merge((mytweets[u] for u in ['1','2','3']))))
# ...:
# [('10', 'twitterid_10'), ('1', 'twitterid_1'), ('2', 'twitterid_2'), ('3', 'twitterid_3')]
# ==============================
# [deque([('10', 'twitterid_10'), ('1', 'twitterid_1')]), deque([('2', 'twitterid_2')]), deque([('3', 'twitterid_3')])]
# * DEMO : bitwise OR (a | b)
# -> a | b : bitwise OR Each bit position in the result is the logical OR of the bits in the corresponding position of the operands. (1 if either is 1, otherwise 0.)
# https://realpython.com/python-operators-expressions/
# In [67]: 1 | 1
# Out[67]: 1
# In [68]: 1 | 2
# Out[68]: 3
# In [69]: 1 | 0
# Out[69]: 1
import collections, itertools, heapq
class Twitter(object):
def __init__(self):
self.timer = itertools.count(step=-1)
self.tweets = collections.defaultdict(collections.deque)
self.followees = collections.defaultdict(set)
def postTweet(self, userId, tweetId):
self.tweets[userId].appendleft((next(self.timer), tweetId))
def getNewsFeed(self, userId):
tweets = heapq.merge(*(self.tweets[u] for u in self.followees[userId] | {userId}))
return [t for _, t in itertools.islice(tweets, 10)]
def follow(self, followerId, followeeId):
self.followees[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
self.followees[followerId].discard(followeeId)
# V1''
# https://blog.csdn.net/fuxuemingzhu/article/details/82155420
# IDEA : heapq
class User(object):
"""
User structure
"""
def __init__(self, userId):
self.userId = userId
self.tweets = set()
self.following = set()
class Tweet(object):
"""
Tweet structure
"""
def __init__(self, tweetId, userId, ts):
self.tweetId = tweetId
self.userId = userId
self.ts = ts
def __cmp__(self, other):
#call global(builtin) function cmp for int
return cmp(other.ts, self.ts)
class Twitter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.ts = 0
self.userMap = dict()
def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
if userId not in self.userMap:
self.userMap[userId] = User(userId)
tweet = Tweet(tweetId, userId, self.ts)
self.userMap[userId].tweets.add(tweet)
self.ts += 1
def getNewsFeed(self, userId):
"""
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.
:type userId: int
:rtype: List[int]
"""
res = list()
que = []
if userId not in self.userMap:
return res
mainUser = self.userMap[userId]
for t in mainUser.tweets:
heapq.heappush(que, t)
for u in mainUser.following:
for t in u.tweets:
heapq.heappush(que, t)
n = 0
while que and n < 10:
res.append(heapq.heappop(que).tweetId)
n += 1
return res
def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
if followeeId not in self.userMap:
self.userMap[followeeId] = User(followeeId)
if followerId not in self.userMap:
self.userMap[followerId] = User(followerId)
if followerId == followeeId:
return
followee = self.userMap[followeeId]
self.userMap[followerId].following.add(followee)
def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
if (followerId == followeeId) or (followerId not in self.userMap) or (followeeId not in self.userMap):
return
followee = self.userMap[followeeId]
if followee in self.userMap.get(followerId).following:
self.userMap.get(followerId).following.remove(followee)
# V1'''
# https://www.hrwhisper.me/leetcode-design-twitter/
class Twitter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.tweets_cnt = 0
self.tweets = collections.defaultdict(list)
self.follower_ship = collections.defaultdict(set)
def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
self.tweets[userId].append([tweetId, self.tweets_cnt])
self.tweets_cnt += 1
def getNewsFeed(self, userId):
"""
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.
:type userId: int
:rtype: List[int]
"""
recent_tweets = []
user_list = list(self.follower_ship[userId]) + [userId]
userId_tweet_index = [[userId, len(self.tweets[userId]) - 1] for userId in user_list if userId in self.tweets]
for _ in range(10):
max_index = max_tweet_id = max_user_id = -1
for i, (user_id, tweet_index) in enumerate(userId_tweet_index):
if tweet_index >= 0:
tweet_info = self.tweets[user_id][tweet_index]
if tweet_info[1] > max_tweet_id:
max_index, max_tweet_id, max_user_id = i, tweet_info[1], user_id
if max_index < 0: break
recent_tweets.append(self.tweets[max_user_id][userId_tweet_index[max_index][1]][0])
userId_tweet_index[max_index][1] -= 1
return recent_tweets
def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
if followerId != followeeId:
self.follower_ship[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
if followerId in self.follower_ship and followeeId in self.follower_ship[followerId]:
self.follower_ship[followerId].remove(followeeId)
# V1''''
# http://bookshadow.com/weblog/2016/06/11/leetcode-design-twitter/
# IDEA : JAVA
# V2
# https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/design-twitter.py
# Time: O(klogu), k is most recently number of tweets,
# u is the number of the user's following.
# Space: O(t + f), t is the total number of tweets,
# f is the total number of followings.
import collections
import heapq
class Twitter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.__number_of_most_recent_tweets = 10
self.__followings = collections.defaultdict(set)
self.__messages = collections.defaultdict(list)
self.__time = 0
def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
self.__time += 1
self.__messages[userId].append((self.__time, tweetId))
def getNewsFeed(self, userId):
"""
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.
:type userId: int
:rtype: List[int]
"""
max_heap = []
if self.__messages[userId]:
heapq.heappush(max_heap, (-self.__messages[userId][-1][0], userId, 0))
for uid in self.__followings[userId]:
if self.__messages[uid]:
heapq.heappush(max_heap, (-self.__messages[uid][-1][0], uid, 0))
result = []
while max_heap and len(result) < self.__number_of_most_recent_tweets:
t, uid, curr = heapq.heappop(max_heap)
nxt = curr + 1
if nxt != len(self.__messages[uid]):
heapq.heappush(max_heap, (-self.__messages[uid][-(nxt+1)][0], uid, nxt))
result.append(self.__messages[uid][-(curr+1)][1])
return result
def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
if followerId != followeeId:
self.__followings[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
self.__followings[followerId].discard(followeeId)