Generating non-repeating random numbers in Python

前端 未结 17 1754
粉色の甜心
粉色の甜心 2020-11-30 19:56

Ok this is one of those trickier than it sounds questions so I\'m turning to stack overflow because I can\'t think of a good answer. Here is what I want: I need Python to ge

17条回答
  •  Happy的楠姐
    2020-11-30 20:34

    You can run 1) without running into the problem of too many wrong random numbers if you just decrease the random interval by one each time.

    For this method to work, you will need to save the numbers already given (which you want to do anyway) and also save the quantity of numbers taken.

    It is pretty obvious that, after having collected 10 numbers, your pool of possible random numbers will have been decreased by 10. Therefore, you must not choose a number between 1 and 1.000.000 but between 1 an 999.990. Of course this number is not the real number but only an index (unless the 10 numbers collected have been 999.991, 999.992, …); you’d have to count now from 1 omitting all the numbers already collected.

    Of course, your algorithm should be smarter than just counting from 1 to 1.000.000 but I hope you understand the method.

    I don’t like drawing random numbers until I get one which fits either. It just feels wrong.

提交回复
热议问题