Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- from datetime import datetime, timedelta, timezone
- from random import choice, randint, seed
- NUM_COMMENTS = 600
- ORIG_POSTS = int(NUM_COMMENTS / 10)
- DAY_SECONDS = 24 * 60 * 60
- START = datetime.now(tz=timezone.utc) - timedelta(seconds=DAY_SECONDS)
- # random interval between a post and a reply to it - range from 0 to this
- DELAY_INTERVAL = DAY_SECONDS / 12
- # deterministic
- seed(0)
- class Comment:
- def __init__(self, num: int, replies: list["Comment"]):
- self.content: int = num
- self.replies: list["Comment"] = replies
- self.post_date: datetime | None = None
- self.level: int | None = None
- def __lt__(self, other: "Comment"):
- return self.post_date < other.post_date
- def total_children(self) -> int:
- return 1 + sum([c.total_children() for c in self.replies])
- def flatten_comments(comments: list[Comment]) -> list[Comment]:
- return sorted(
- {
- c for c in
- [
- r for c in comments
- for r in
- [
- c, *flatten_comments(c.replies)
- ]
- ]
- }
- )
- # all comments
- comments = [Comment(i, []) for i in range(NUM_COMMENTS)]
- # set the first one as root of the tree
- comments[0].post_date = START
- comments[0].level = 0
- # split into original posts and replies
- posts, replies = comments[:ORIG_POSTS], comments[ORIG_POSTS:]
- # for all but the first post, set the date later than the first, and note they're top-level
- for post in posts[1:]:
- post.post_date = START + timedelta(seconds=randint(0, DAY_SECONDS))
- post.level = 0
- # assign each reply a randomly-chosen parent. Set its level 1 higher than its parent, a post
- # date later than its parent, and add it to that parent's replies
- for reply in replies:
- parent = choice(posts)
- reply.post_date = parent.post_date + timedelta(seconds=randint(0, DELAY_INTERVAL))
- reply.level = parent.level + 1
- parent.replies.append(reply)
- # then move the reply into the posts list, so it can be assigned replies as well
- posts.append(reply)
- flattened = flatten_comments(comments)
- for comment in flattened:
- print(
- f"{comment.post_date.isoformat()} - "
- f"level {comment.level}: '{comment.content:-3d}' - "
- f"{len(comment.replies):-3d} replies - {comment.total_children():-3d} children"
- )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement