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

前端 未结 7 1347
悲哀的现实
悲哀的现实 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 20:46

    You still need some range, i.e., a min-max possible value excluding your middle values.

    Why don't you first randomly pick which "half" of the range you want, then pick a random number in that range? E.g.:

    def rand_not_in_range(a,b):
        rangechoices = ((0,a-b-1),(a+b+1, 10000000))
        # Pick a half
        fromrange = random.choice(rangechoices)
        # return int from that range
        return random.randint(*fromrange)
    

提交回复
热议问题