In A recent experiment, the data needs to be randomly divided into two parts at a certain percentage. At the heart of this problem is the problem of generating non-repetitive random numbers. The first thought of the recursive method, then found in Python actually has provided this method of the function, can be used directly. The specific code is as follows:
#生成某区间内不重复的N个随机数的方法import random; #1, using recursion to generate resultlist=[]; #用于存放结果的ListA = 1; #最小随机数B =10 #最大随机数COUNT =10# generates a recursive math of random numbers, and the parameter counter represents the number of valid random numbers currently ready to be generated Def generaterand (counter): tempint= Random.randint (A, b); # Generate a range of temporary random numbers, if (Counter<=count): # First Look at the total number of random numbers is not enough if not enough if (Tempint not in resultlist): # Then check that the temporary random number that is currently generated is not already present if Resultlist.append (tempint) is present, and the #则将其追加到结果List中 counter+=1;# then adds 1 to the number of valid results. Note here that if the temporary random number already exists, then this if does not hold, then will execute 16 lines directly, counter does not need to add 1 generaterand (counter); # Regardless of whether or not the above is true, recursion. If the above temporary random number is valid, then the conter here will add 1, if the above provisional random number already exists, you need to regenerate the random number again, counter can not change generaterand (1); #调用递归函数, and set the sequence number of the valid random number currently being generated to 1, since the first one is the print (resultlist) # # of prints, using the randomw.sample () function in Python resultlist=random.sample (Range (a,b+1), COUNT); # The role of the sample (x, Y) function is to randomly select Y non-repeating elements from sequence x. The above method is written so much, in fact Python is finished in a word. Print (resultlist) # Printing results
Results:
"Recommended"
1. A detailed description of the mathematical and random numbers in the Python standard library (math package, random package)
2. Example tutorial for Python random () function
3. Share an example tutorial on random (randomly generated numbers) in Python
4. Share a tutorial on how to generate random numbers in Python module
5. Python Random Module (get random number) common methods and use examples
6. Python Random Module Common methods
7. Python Module Learning: Random number generation