Home > Enterprise >  A random integer between specific values excluding 0
A random integer between specific values excluding 0

Time:10-04

I have to generate a random integer i between a chosen minimum and chosen maximum value, which I have written as follows:

min = -10
max = 10
i = random.randint(min, max)

The problem is that I don't know how to exclude the number zero.

I need to exclude 0 because later on I'll be dividing min/max, so min can't be zero and max can't be as well (cause you'll get a zero modulo error).

CodePudding user response:

You could pick from -10 to 9 and then increase non-negative picks by 1:

min = -10
max = 10
i = random.randint(min, max - 1)
i  = i >= 0

Or an implementation of @luk2302's suggestion, again picking from -10 to 9 but then replacing 0 with 10:

min = -10
max = 10
i = random.randint(min, max - 1) or max

Could also use randrange:

min = -10
max = 10
i = random.randrange(min, max) or max

CodePudding user response:

As I cannot comment (yet): it can be very, very bad to name your variables min/max as you are overriding the build-in python function names:

max = 10
>>> max([1, 2, 3])
TypeError: 'int' object is not callable

CodePudding user response:

There are a few ways to do this.

First is very simple. If u get a 0, generate another number until you get one which is not zero.

import random
min = -10
max = 10
i = random.randint(min, max)
while i == 0:
    i = random.randint(min, max)

Another way is to generate a list of possible values and then use random.choice

import random
min = -10
max = 10
possible_values = [num for num in range(min, max 1) if num!=0]
i = random.choice(possible_values)

Yet another way is to do what @luk2302 suggested

import random
min = -10
max = 10
i = random.randint(min, max - 1) or max

There are also other ways if you would like to explore.

CodePudding user response:

For a small range, I would just enumerate the valid choices and choose among them:

x = list(range(min_value, max_value   1))
x.remove(0)
i = random.choice(x)

As the range increases, the chance of picking 0 decreases, and thus so does the amortized cost of simply rerolling if you do choose 0:

while True:
    i = randint(min_value, max_value)
    if i:
        break
  • Related