Skip to content

Commit 4be189b

Browse files
Question 355
1 parent edc8328 commit 4be189b

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

355. Design Twitter.py

+52-1
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,55 @@
3131
// User 1's news feed should return a list with 1 tweet id -> [5],
3232
// since user 1 is no longer following user 2.
3333
twitter.getNewsFeed(1);
34-
'''
34+
'''
35+
36+
class Twitter:
37+
38+
def __init__(self):
39+
self.users = {}
40+
self.tweets = []
41+
42+
43+
def postTweet(self, userId: int, tweetId: int) -> None:
44+
if userId not in self.users:
45+
self.users[userId] = set()
46+
self.tweets.append([tweetId, userId])
47+
48+
49+
def getNewsFeed(self, userId: int) -> List[int]:
50+
feed = []
51+
for i in range(len(self.tweets)-1, -1, -1):
52+
if userId in self.users and (self.tweets[i][1] in self.users[userId] or self.tweets[i][1]==userId):
53+
feed.append(self.tweets[i][0])
54+
55+
if len(feed)==10:
56+
break
57+
return feed
58+
59+
60+
def follow(self, followerId: int, followeeId: int) -> None:
61+
"""
62+
Follower follows a followee. If the operation is invalid, it should be a no-op.
63+
"""
64+
if followerId!=followeeId:
65+
if followerId not in self.users:
66+
self.users[followerId] = set()
67+
self.users[followerId].add(followeeId)
68+
69+
70+
71+
def unfollow(self, followerId: int, followeeId: int) -> None:
72+
"""
73+
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
74+
"""
75+
if followerId!=followeeId and followerId in self.users and followeeId in self.users[followerId]:
76+
self.users[followerId].remove(followeeId)
77+
78+
79+
80+
# Your Twitter object will be instantiated and called as such:
81+
# obj = Twitter()
82+
# obj.postTweet(userId,tweetId)
83+
# param_2 = obj.getNewsFeed(userId)
84+
# obj.follow(followerId,followeeId)
85+
# obj.unfollow(followerId,followeeId)

0 commit comments

Comments
 (0)