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

江枫思渺然 提交于 2019-12-02 00:26:52

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)  

"0" != 0.

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

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!