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. Your design should support the following methods:
- postTweet(userId, tweetId): Compose a new tweet.
- getNewsFeed(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.
- follow(followerId, followeeId): Follower follows a followee.
- unfollow(followerId, followeeId): Follower unfollows a followee.
code:
class Twitter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.user_follow = {}
self.post_twieets = []
def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
item = [userId, tweetId]
self.post_twieets.append(item)
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]
"""
twitters_10 = []
temp_twitter = [i for i in self.post_twieets]
temp_twitter.reverse()
for item in temp_twitter:
if item[0] == userId:
twitters_10.append(item[1])
else:
if userId in self.user_follow:
if item[0] in self.user_follow[userId]:
twitters_10.append(item[1])
if len(twitters_10) == 10:
break
return twitters_10
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 not in self.user_follow:
self.user_follow[followerId] = []
self.user_follow[followerId].append(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
"""
try:
self.user_follow[followerId].remove(followeeId)
except: pass