Python Numbers Baseball Game Question: How to pick three numbers so that they don't overlap.

Asked 2 years ago, Updated 2 years ago, 13 views

When I made the first three digits in number baseball, I originally made it random.randint (1,999), but then I got a duplicate number like 888. So I tried coding to make it without duplication.

import random

num = [1,2,3,4,5,6,7,8,9]

tmp1 = (random.randint(0,8))
num1 = str(num.pop(tmp1))

tmp2 = (random.randint(0,7))
num2 = str(num.pop(tmp2))

tmp3 = (random.randint(0,6))
num3 = str(num.pop(tmp3))

number = [num1, num2, num3]

It works well, but I think the cord is too long to make only three numbers. like for I think I can make it much shorter if I use it. Is there a way?

python

2022-09-21 10:53

1 Answers

Do it like below

import random
random.sample(range(1, 10), 3)


2022-09-21 10:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.