Mini Twitter
这道题因为tweet类的问题,push模型比较难以实现,因为需要自己手动对tweet加时间戳排序,操作比较复杂,而pull模型基本上只需要一个时间戳同时对getNewsFeed函数进行for循环排序就行了,其他函数的实现则非常简单
'''
Definition of Tweet:
class Tweet:
@classmethod
def create(cls, user_id, tweet_text):
# This will create a new tweet object,
# and auto fill id
'''
class MiniTwitter:
def __init__(self):
# initialize your data structure here.
self.friendship = collections.defaultdict(set)
self.timeLineTable = collections.defaultdict(list)
self.time = 0
# @param {int} user_id
# @param {str} tweet
# @return {Tweet} a tweet
def postTweet(self, user_id, tweet_text):
# Write your code here
tweet = Tweet.create(user_id, tweet_text)
self.timeLineTable[user_id].append((self.time, tweet,))
self.time += 1
return tweet
# @param {int} user_id
# return {Tweet[]} 10 new feeds recently
# and sort by timeline
def getNewsFeed(self, user_id):
# Write your code here
result = []
for friend in self.friendship[user_id]:
if len(self.timeLineTable[friend]) < 10:
result += self.timeLineTable[friend]
else:
result += self.timeLineTable[friend][-10:]
result += self.timeLineTable[user_id][-10:]
finalResult = map(lambda x: x[1], sorted(result, reverse=True))
return finalResult if len(finalResult) < 10 else finalResult[:10]
# @param {int} user_id
# return {Tweet[]} 10 new posts recently
# and sort by timeline
def getTimeline(self, user_id):
# Write your code here
result = map(lambda x: x[1], sorted(self.timeLineTable[user_id], reverse=True))
return result if len(result) < 10 else result[:10]
# @param {int} from user_id
# @param {int} to_user_id
# from user_id follows to_user_id
def follow(self, from_user_id, to_user_id):
# Write your code here
if from_user_id != to_user_id:
self.friendship[from_user_id].add(to_user_id)
# @param {int} from user_id
# @param {int} to_user_id
# from user_id unfollows to_user_id
def unfollow(self, from_user_id, to_user_id):
# Write your code here
self.friendship[from_user_id].discard(to_user_id)