+-------------+---------+
| Column Name | Type |
+-------------+---------+
| followee | varchar |
| follower | varchar |
+-------------+---------+
(followee, follower) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates that the user follower follows the user followee on a social network.
There will not be a user following themself.
A second-degree follower is a user who:
follows at least one user, and
is followed by at least one user.
Write a solution to report the second-degree users and the number of their followers.
Return the result table ordered by followerin alphabetical order.
Input:
Follow table:+----------+----------+| followee | follower |+----------+----------+| Alice | Bob || Bob | Cena || Bob | Donald || Donald | Edward |+----------+----------+Output:
+----------+-----+| follower | num |+----------+-----+| Bob |2|| Donald |1|+----------+-----+Explanation:
User Bob has 2 followers. Bob is a second-degree follower because he follows Alice, so we include him in the result table.User Donald has 1 follower. Donald is a second-degree follower because he follows Bob, so we include him in the result table.User Alice has 1 follower. Alice is not a second-degree follower because she does not follow anyone, so we don not include her in the result table.
A second-degree follower is someone who both follows someone and is followed by someone. We can find all users who are followers (appear in the follower column) and are also followees (appear in the followee column), then count their followers.
SELECT follower, COUNT(*) AS num
FROM Follow
WHERE follower IN (SELECTDISTINCT followee FROM Follow)
GROUPBY follower
ORDERBY follower ASC;
1
2
3
4
5
SELECT follower, COUNT(*) AS num
FROM Follow
WHERE follower IN (SELECTDISTINCT followee FROM Follow)
GROUPBY follower
ORDERBY follower ASC;
1
2
3
4
5
6
7
8
9
# Follow is a pandas DataFrameimport pandas as pd
defsecond_degree_follower(Follow):
followees = set(Follow['followee'])
mask = Follow['follower'].isin(followees)
res = Follow[mask].groupby('follower').size().reset_index(name='num')
res = res.sort_values('follower').reset_index(drop=True)
return res
# result = second_degree_follower(Follow)