Skip to content

Instantly share code, notes, and snippets.

@cyyeh
Created May 23, 2020 11:00
Show Gist options
  • Save cyyeh/ccce4daa34dc5c354f71d8e8912164d8 to your computer and use it in GitHub Desktop.
Save cyyeh/ccce4daa34dc5c354f71d8e8912164d8 to your computer and use it in GitHub Desktop.
Design Twitter
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.tweets = []
self.following_dict = {}
self.followed_dict = {}
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
self.tweets.append((userId, tweetId))
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.
"""
def should_show(tweet):
return (userId in self.following_dict and tweet[0] in self.following_dict[userId]) or \
tweet[0] == userId
def get_tweet(tweet):
return tweet[1]
return [*map(get_tweet,filter(should_show, self.tweets))][:-11:-1]
def follow(self, followerId: int, followeeId: int) -> None:
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
if followerId == followeeId:
return
if followerId not in self.following_dict:
self.following_dict[followerId] = {followeeId}
else:
self.following_dict[followerId].add(followeeId)
if followeeId not in self.followed_dict:
self.followed_dict[followeeId] = {followerId}
else:
self.followed_dict[followeeId].add(followerId)
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
if followerId == followeeId:
return
if followerId not in self.following_dict or \
followeeId not in self.followed_dict:
return
else:
if followeeId in self.following_dict[followerId]:
self.following_dict[followerId].remove(followeeId)
if followerId in self.followed_dict[followeeId]:
self.followed_dict[followeeId].remove(followerId)
# 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment