0

With this code I'm able to select one comment from comments.txt and comment it without repeating itself. How do I select multiple comments at the same time from the comments.txt without the comments repeating themselves?

def random_comment():
    num = randint(1, COMMAND_AMOUNT)
    while num in USED:
        num = randint(1, COMMAND_AMOUNT)
    USED.append(num)
    return COMMENTS[num]    

USED = []
file = open("comments.txt", "r")
COMMENTS = {num: comment.strip() for num, comment in enumerate(file.readlines(), start=1)}
file.close()

COMMAND_AMOUNT = len(COMMENTS)
2
  • Perhaps you could call random_comment() multiple times. Commented Jul 11, 2021 at 15:53
  • Using random will possibly give you repeats. Instead do a random shuffle of the list and pick comments in order from the shuffled list. Commented Jul 11, 2021 at 20:25

2 Answers 2

1

You can use random.sample():

SAMPLE_SIZE = 4 # for example (your question does not indicate how many element should be selected)

def random_comments():
    return random.sample(COMMENTS, SAMPLE_SIZE) 
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to ensure there are no repeats:

import random

with open("comments", "r") as f:
    COMMENTS = [comment.strip() for comment in f]
random.shuffle(COMMENTS)

def random_comment():
    return COMMENTS.pop() if COMMENTS else None

# print all the comments until no more:
for comment in iter(random_comment, None):
    print(comment)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.