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)
    
  • 相关阅读:
    可汗学院公开课:统计学
    libsvm 之 easy.py(流程化脚本)注释
    机器学习概览
    学习资源
    libsvm-3.21使用文档
    Machine Learning
    Machine Learning
    MySQL 5.7半同步复制after sync和after commit详解【转】
    网站架构设计【转】
    httpd功能配置之虚拟主机【转】
  • 原文地址:https://www.cnblogs.com/luozx207/p/12689994.html
Copyright © 2011-2022 走看看