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

前端 未结 7 1344
悲哀的现实
悲哀的现实 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:12

    Generate one random number and map it onto your desired ranges of numbers.

    If you wanted to generate an integer between 1-4 or 7-10, excluding 5 and 6, you might:

    1. Generate a random integer in the range 1-8
    2. If the random number is greater than 4, add 2 to the result.

    The mapping becomes:

    Random number:    1  2  3  4  5  6  7  8
    Result:           1  2  3  4  7  8  9 10
    

    Doing it this way, you never need to "re-roll". The above example is for integers, but it can also be applied to floats.

    0 讨论(0)
提交回复
热议问题