My problem is very simple. I'm trying to pick between 2 random numbers in python but not from consecutive numbers like here .
For example: between 1 and 3, 2 not included.
get two random numbers, check if their difference is not 1 and print them out
import random
def get_two_random_numbers():
num1, num2 = random.sample(range(1, 100), 2)
return num1, num2
rand_num1, rand_num2 = get_two_random_numbers()
while (abs(rand_num1-rand_num2 == 1)):
rand_num1, rand_num2 = get_two_random_numbers()
print(rand_num1)
print(rand_num2)
The easiest solution to this is probably random.choice.
import random
number = random.choice((1, 3))
A different approach: instead of getting numbers and rejecting them we could let Python do the job for us. This may be useful if we need to exclude many numbers (or if we want to get more than one value at a time, of course)
from random import choices
def rand_except(start, stop, exclude, k):
weights = [1 for _ in range(start,stop)]
for excl in exclude:
weights[excl-start] = 0
return choices(range(start,stop), weights=weights, k=k)
Here is an approach:
import random
pool = list(range(1, 3+1))
pool.remove(2)
out = random.choice(pool)
def randint_except(start, stop, exclude=None):
pool = list(range(start, stop+1))
if exclude is not None:
if isinstance(exclude, int):
pool.remove(exclude)
else:
S = set(exclude)
pool = [x for x in pool if x not in S]
return random.choice(pool)
randint_except(1, 20, exclude=[5,10,15])
# 4
frequencies on 100k runs:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.