Skip to content

Instantly share code, notes, and snippets.

@docapotamus
Last active November 25, 2015 13:04
Show Gist options
  • Save docapotamus/fe0a62e96e55d8e30b2d to your computer and use it in GitHub Desktop.
Save docapotamus/fe0a62e96e55d8e30b2d to your computer and use it in GitHub Desktop.
Finding suggestions example
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)
@docapotamus
Copy link
Author

AGPLv3 code for github.com/pjuu/pjuu

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment