1
def random_comment():
    with open('comments.txt', 'r') as f:
        comments = [line.strip() for line in f]
    comment = random.choice(comments)
    return comment
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Landry N.
  • 11
  • 2

1 Answers1

1

Read all the comments once (before calling random). Then in the random_comment(), chose a random comment from your list and remove it from the list.

all_comments = []
with open('comments.txt', 'r') as f:
    all_comments.append([line.strip() for line in f])

def random_comment(all_comments):
    index = random.randint(0,len(all_comments))
    result = all_comments.pop(index)
    return result, all_comments
Jules Civel
  • 449
  • 2
  • 13
  • `.remove` removes by value, not by index. – mkrieger1 Jul 07 '21 at 15:00
  • This has a major drawback, though: you need to regenerate the complete list if you want to take another sample. – Thierry Lathuille Jul 07 '21 at 15:00
  • ``` import random class Comments: def __init__(self, file_path): with open('comments.txt', 'r') as f: self.comments = random.shuffel([line.strip() for line in f]) self.position = 0 def random_comment(self): comment = self.comment[self.position] position += 1 return comment myComments = Comments("file_path") randomComment = myComments.random_comment() ``` – FloLie Jul 07 '21 at 15:04
  • @ThierryLathuille no you don't, you return the updated list. And you take the list as parameter so you just have to pass the last returned list. – Jules Civel Jul 07 '21 at 15:06
  • @mkrieger1 indeed, let me edit it – Jules Civel Jul 07 '21 at 15:06
  • Yes, you do. Try it with `all_comments = ["A", "B", "C"] ; res, comm = random_comment(all_comments) ; print(res, all_comments)`. It prints `B ['A', 'C']`. You only mutate the original list that your function got as argument, and never create a new one. – Thierry Lathuille Jul 07 '21 at 15:14
  • i'm getting this error: randint() missing 1 required positional argument: 'b' – Landry N. Jul 07 '21 at 15:22
  • Oh ok, i thought you meant that you have to read it all again every time. You are indeed right, we should use pop instead. I'll edit my answer. – Jules Civel Jul 07 '21 at 15:22
  • A 0 is missing in random.randint, it's edited. – Jules Civel Jul 07 '21 at 15:24