Skip to content

Commit

Permalink
Switch to index based dictionary instead
Browse files Browse the repository at this point in the history
  • Loading branch information
dave-andersen committed Sep 24, 2023
1 parent fbcc082 commit 5b59531
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions python/related.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,26 +36,35 @@ def main():
posts = json.load(f)

tag_map = {}
for post in posts:
for idx, post in enumerate(posts):
for tag in post["tags"]:
if tag not in tag_map:
tag_map[tag] = []
tag_map[tag].append(Post(post["_id"], post["title"], post["tags"]))
tag_map[tag].append(idx)

all_related_posts = []
for post in posts:
for this_post_idx, post in enumerate(posts):
related_posts_dict: Dict[Post, int] = {}
for tag in post["tags"]:
for related_post in tag_map[tag]:
if related_post._id != post["_id"]:
if related_post != this_post_idx:
if related_post not in related_posts_dict:
related_posts_dict[related_post] = 0
related_posts_dict[related_post] += 1

top_posts = [
p.to_dict()
for p in heapq.nlargest(5, related_posts_dict, key=related_posts_dict.get)
]
top_posts_idx = heapq.nlargest(
5, related_posts_dict, key=related_posts_dict.get
)
top_posts = []
for idx in top_posts_idx:
tp = posts[idx]
top_posts.append(
{
"_id": tp["_id"],
"title": tp["title"],
"tags": tp["tags"],
}
)

all_related_posts.append(
{
Expand Down

0 comments on commit 5b59531

Please sign in to comment.