from collections import defaultdict
classTwitter:def__init__(self):"""
Initialize your data structure here.
先說初始化函數,self.tweets是一個字典結構,鍵是userId,值是tweetId的列表,保存每個用戶發表的tweet信息。類似,following 保存每個用戶的關注列表。idd是保持所有tweet時間序的整數,無論哪位用戶發一條tweet前idd都會自增1。
"""
self.tweets = defaultdict(list)
self.following = defaultdict(set)
self.idd =0defpostTweet(self, userId:int, tweetId:int)->None:"""
Compose a new tweet.
"""
self.idd +=1
self.tweets[userId].append((tweetId, self.idd))deffollow(self, followerId:int, followeeId:int)->None:"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
self.following[followerId].add(followeeId)#這裏採用的集合,存在值則不add,不存在則adddefunfollow(self, followerId:int, followeeId:int)->None:"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""if followeeId in self.following[followerId]:
self.following[followerId].remove(followeeId)defgetNewsFeed(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.
"""
users = self.following[userId]
users.add(userId)
tmp_data =[self.tweets[item][-10:]for item in users]# 取出每個用戶(包括自己)的最後發佈的10條推文
tmp_data =[tmp for item in tmp_data for tmp in item]# 將每個用戶的前10條推文都整合一起
tmp_data.sort(key=lambda a: a[1], reverse=True)# 根據idd從大到小排序return[item[0]for item in tmp_data[:10]]# 取出推文# 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)