zoukankan      html  css  js  c++  java
  • 【Leetcode刷题】设计推特

    题目:https://leetcode-cn.com/problems/design-twitter/

    filter切片解法:

    import itertools
    
    class Twitter:
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.followers = {}
            self.tweets = []
    
        def postTweet(self, userId: int, tweetId: int) -> None:
            """
            Compose a new tweet.
            """
            self.tweets.insert(0, (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.
            """
            my_follow = self.followers.get(userId, [])
            my_follow.append(userId)
            iter = filter(lambda x: x[0] in my_follow, self.tweets)
            return [x[1] for x in itertools.islice(iter, 0, 10)]
    
        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 in self.followers:
                follower = self.followers[followerId]
                if followeeId not in follower:
                    follower.append(followeeId)
            else:
                follower = [followeeId]
                self.followers[followerId] = follower
    
        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 in self.followers:
                follower = self.followers[followerId]
                if followeeId in follower:
                    follower.remove(followeeId)
            
    
    
    # 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)
    
  • 相关阅读:
    Python爬虫-05:Ajax加载的动态页面内容
    Python爬虫-04:贴吧爬虫以及GET和POST的区别
    Python-爬虫03:urllib.request模块的使用
    Python Numpy-基础教程
    8皇后算法
    迷宫算法
    归并排序
    查找算法
    排序算法
    设计模式
  • 原文地址:https://www.cnblogs.com/luozx207/p/12689994.html
Copyright © 2011-2022 走看看