How do you create a random range, but exclude a sp

2019-02-26 03:35发布

问题:

I have the following code:

while True:
    if var_p1 != "0":
        break
    else:
        import random
        var_p1 = random.randint(-5,5)

I want the loop to repeat until var_p1 equals anything but zero. However, I get zero all the time. What am I doing wrong?

回答1:

Answering the question in the title, not the real problem (which was answered by Daniel Roseman):

How do you create a random range, but exclude a specific number?

Using random.choice:

import random
allowed_values = list(range(-5, 5+1))
allowed_values.remove(0)

# can be anything in {-5, ..., 5} \ {0}:
random_value = random.choice(allowed_values)  


回答2:

"0" != 0.

You are comparing against a string, but randint gives you an integer.



回答3:

Well you check against a string to break the loop. So use:

if var_p1 != 0:

instead of:

if var_p1 != "0":

A memory efficient way to generate from a to b but not including a value c is:

r = random.randint(a, b - 1)
if r >= c:
    r += 1 

This way, in the first step we'll generate a random int between a and c - 1 or between c and b - 1. In the second case we increment by one and we get a random number between c + 1 and b. It's easy to see that each number between a..(c - 1) and (c + 1)..b has the same probability.



回答4:

Your code fails because you're comparing an integer to a string. There are other problems with your code:

  • You have an import statement inside a loop.
  • There's no telling how many times your loop will run.

Here is a loop-free way to randomly generate a non-zero integer from -5 to +5, inclusive.

import random
x = random.randint(1, 5)
if random.randrange(2) == 1:
  x = -x

This code is guaranteed to call random.randrange exactly twice.



回答5:

As an alternative method, just pick one random element from the array, [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5]. Guaranteed to work with just one call.