0

I am wondering how the following code works:

def gen_game():
    rst = set()
    while len(rst) < 4:
        rst.add(random.randint(0, 9))
    print(rst)
    return "".join(str(i) for i in rst)

I understand that the above function will generate random numbers and add that together beside each other. What I am concern is that how do I know if the number do not generate distinct numbers?

For example, using random.randint(0,9). How come I do not get double 9s? or triple 9s? or quadruple 9s?

4
  • this basically implements random.sample. why not use that directly then? Commented Feb 20, 2020 at 18:01
  • 1
    This is because rst is a set. A set will only contain distinct objects (even when you try to add another 9) Commented Feb 20, 2020 at 18:01
  • 1
    You're using a set? Commented Feb 20, 2020 at 18:02
  • Thank you it answered my question. one more question. why do we use set instead or list? is there a particular reason? Commented Feb 21, 2020 at 5:57

1 Answer 1

4

rst = set()

Sets cannot contain duplicates. If you attempt to add a duplicate, it will reject it.

Sign up to request clarification or add additional context in comments.

2 Comments

out of curiousity why do we use 'set' instead of 'list'? Is there a particular reason?
In case you want a data structure that doesn't contain duplicates. It can be used as more of a contract. You're saying "if you use this, you know there won't be duplicates". For example, if you're passing a list of US States, there shouldn't be any duplicates, so you use a Set.

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.