Can Python generate a random number that excludes a set of numbers, without using recursion?

前端 未结 7 1348
悲哀的现实
悲哀的现实 2020-12-30 20:46

I looked over Python Docs (I may have misunderstood), but I didn\'t see that there was a way to do this (look below) without calling a recursive function.
What I\'d like

7条回答
  •  甜味超标
    2020-12-30 21:07

    A possible solution would be to just shift the random numbers out of that range. E.g.

    def NormalWORange(a, b, sigma):
        r = random.normalvariate(a,sigma)
        if r < a:
            return r-b
        else:
            return r+b
    

    That would generate a normal distribution with a hole in the range (a-b,a+b).

    Edit: If you want integers then you will need a little bit more work. If you want integers that are in the range [c,a-b] or [a+b,d] then the following should do the trick.

    def RangeWORange(a, b, c, d):
        r = random.randrange(c,d-2*b) # 2*b because two intervals of length b to exclude
        if r >= a-b:
            return r+2*b
        else:
            return r
    

提交回复
热议问题