Last active
November 25, 2015 13:04
-
-
Save docapotamus/fe0a62e96e55d8e30b2d to your computer and use it in GitHub Desktop.
Finding suggestions example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from collections import Counter | |
def get_follow_suggestions(user_id, count=5): | |
# Get all users a user is following | |
following = r.zrange(k.USER_FOLLOWING.format(user_id), 0, -1) | |
# Ensure the user is getting suggestions based on at least 5 people | |
# | |
following_count = len(following) | |
if len(following_count) < 5: | |
cursor = m.db.users.find( | |
{'_id': {'$nin': following}}, | |
{'_id': True} | |
).sort({ | |
'score': -1 | |
}).limit(5 - following_count) | |
for user in cursor: | |
following.append(user.get('_id')) | |
suggestions = [] | |
for user in following: | |
suggestions += r.zrange(k.USER_FOLLOWING.format(user), 0, -1) | |
# Count and group the elements | |
suggestions = Counter(suggestions) | |
# Doesn't matter if the followee isn't in the Counter | |
for followee in following: | |
del suggestions[followee] | |
return suggestions.most_common(count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AGPLv3 code for github.com/pjuu/pjuu