Skip to content

Commit a4c5e25

Browse files
authored
Create mini_twitter.py
1 parent d0b7010 commit a4c5e25

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

mini_twitter.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# coding: utf-8
2+
3+
class MiniTwitter:
4+
5+
def __init__(self):
6+
# initialize your data structure here.
7+
self.tweets = []
8+
self.follows = {}
9+
10+
# @param {int} user_id
11+
# @param {str} tweet
12+
# @return {Tweet} a tweet
13+
def postTweet(self, user_id, tweet_text):
14+
# Write your code here
15+
t = Tweet.create(user_id, tweet_text)
16+
self.tweets.append(t)
17+
return t
18+
19+
# @param {int} user_id
20+
# return {Tweet[]} 10 new feeds recently
21+
# and sort by timeline
22+
def getNewsFeed(self, user_id):
23+
# Write your code here
24+
cnt = 0
25+
ret = []
26+
for i in range(len(self.tweets) - 1, -1, -1):
27+
# 这里复杂一点,要确定是不是自己或者是follow的用户
28+
if self.tweets[i].user_id == user_id:
29+
ret.append(self.tweets[i])
30+
cnt += 1
31+
elif user_id in self.follows:
32+
if self.tweets[i].user_id in self.follows[user_id]:
33+
ret.append(self.tweets[i])
34+
cnt += 1
35+
if cnt == 10:
36+
break
37+
return ret
38+
39+
# medium: http://lintcode.com/zh-cn/problem/mini-twitter/#
40+
# @param {int} user_id
41+
# return {Tweet[]} 10 new posts recently
42+
# and sort by timeline
43+
def getTimeline(self, user_id):
44+
# Write your code here
45+
cnt = 0
46+
ret = []
47+
for i in range(len(self.tweets) - 1, -1, -1):
48+
if self.tweets[i].user_id == user_id:
49+
ret.append(self.tweets[i])
50+
cnt += 1
51+
if cnt == 10:
52+
break
53+
return ret
54+
55+
# @param {int} from user_id
56+
# @param {int} to_user_id
57+
# from user_id follows to_user_id
58+
def follow(self, from_user_id, to_user_id):
59+
# Write your code here
60+
if from_user_id in self.follows:
61+
if to_user_id not in self.follows[from_user_id]:
62+
self.follows[from_user_id].append(to_user_id)
63+
else:
64+
self.follows[from_user_id] = [to_user_id]
65+
66+
# @param {int} from user_id
67+
# @param {int} to_user_id
68+
# from user_id unfollows to_user_id
69+
def unfollow(self, from_user_id, to_user_id):
70+
# Write your code here
71+
if from_user_id in self.follows:
72+
if to_user_id in self.follows[from_user_id]:
73+
self.follows[from_user_id].remove(to_user_id)

0 commit comments

Comments
 (0)