程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to generate 100million mobile phone numbers? Python has 22 methods to generate random numbers, and the random function is too strong

編輯:Python

Hello everyone , Here is Python Programmer Wanfeng .

Case analysis

Recently I saw a on the Internet python The interview topic of : How to use Python Generate 1 Million cell phone numbers ?

When I first saw it, I thought , This is not easy ? direct random.randint(1,999999999999) Just a matter of .

But I found the mistake immediately : This is the generation 1-99999999 Random number between , May be 1, It could be 666.

But the phone number is 11 Bit , And before 3 Bit has only the specified number segment , such as 135、136. direct random.randint(1,999999999999) This is not qualified .

So how to generate ? So here's the code :

import random
def create_phone_num(num):
all_phone_nums = set() # Store the generated phone number
while True: # because set It will automatically go heavy , So the loop generates phone numbers , Until it's equal to num Number stop
start = random.choice(['135', '136', '137']) # Before storage 3 Number segment of bit , Choose one at random
end = ''.join(random.sample(string.digits, 8)) # After random generation 8 Digit number
all_phone_nums.add(f'{start}{end}') # Before splicing 3 Position and back 8 position
if len(all_phone_nums) >= num: # If the number of numbers equals num, Then stop
break
phone_num(10000 * 10000)

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

After writing the code this time, I found , original Python Of random There are so many easy-to-use methods of generating random numbers .

I sorted them all out , Today we will learn together ~

If there are omissions or errors , Welcome to give more advice ~

Which file generates random numbers ?

In the first line of the code above :import random, We imported random This standard library .

This library has only one file :random.py, The structure of this document is mainly divided into 3 individual part ( As shown in the figure below ), Their functions are :

  • 2 Major classes :Random(_random.Random) and SystemRandom(Random)
    • Among them, we use the most Random()
  • Yes 2 Four test methods :_test_generator(n, func, args) and _test(N=2000)
    • We can't use this part
  • The function we call : The use method is as the code above random.choicerandom.sample, Specific usage , We will explain in detail next .

random What random number methods are provided ?

Next, we will focus on as python Users of , What will we use random The random number method of , As mentioned above random.py Page 2 of the document 3 part .

As shown in the code below ,random The methods provided are as follows 22 individual , It is mainly divided into 2 class :

  • Ordinary users Common methods , Altogether 12 individual ;
  • Scientific Computing Common methods , Altogether 10 individual .

For ordinary users 12 How to use a random number method ?

For the above 22 A random number method , Here I will focus on the one commonly used by ordinary users 12 A way .

As for the latter 10 A method for scientific calculation , Because it's really profound , I won't waste my time here , Interested students , You can go directly to the math book :《 probability theory 》.

1. random.seed & random.getstate & random.setstate

Put this 3 Put them together and say , Because random In essence, it generates pseudo-random numbers , And this 3 A function , It well reflects the characteristics of pseudo-random numbers

Code example :seed

# Appoint seed after , The generated random numbers are the same 
random.seed(1)
print(' random number 1:', random.random())
random.seed(1)
print(' random number 2:', random.random())
# output:
# random number 1: 0.13436424411240122
# random number 2: 0.13436424411240122

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

Code example : random.getstate & random.setstate


import random
random.seed(42)
print(random.sample(range(20), k=10))
st = random.getstate() # Take out and generate the last line of code ,random The state of 
print(random.sample(range(20), k=20)) # print 20
random.setstate(st) # Restore the last random state 
print(random.sample(range(20), k=10)) # print same first 10
# output:
# [12, 0, 4, 3, 11, 10, 19, 1, 5, 18]
# [4, 9, 0, 3, 10, 8, 16, 7, 18, 17, 14, 6, 2, 1, 5, 11, 15, 13, 19, 12]
# [4, 9, 0, 3, 10, 8, 16, 7, 18, 17]

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

2. random.random

Randomly generate one [0,1) The floating point number between

Code example

float = random.random()
""" float = 0.123565654548978 """

  • 1.
  • 2.
  • 3.
  • 4.

3. random.uniform

produce [a,b] A random floating-point number in the range

Code example

float = random.uniform(11,15)
""" float = 13.882923467738049 """

  • 1.
  • 2.
  • 3.
  • 4.

4. random.randint

Random generation [a,b] An integer in the range .

Code example

int = random.randint(1, 9)
""" int = 2 """

  • 1.
  • 2.
  • 3.
  • 4.

5. random.choice

Randomly select a data from a non empty sequence and bring it back , The sequence can be list、tuple、str、set.

Code example

str = random.choice(" Programmer Wanfeng original series ")
""" str = primary """

  • 1.
  • 2.
  • 3.
  • 4.

6. random.choices

Python3.6 Version added . Select randomly from the cluster k Time data , Return a list , You can set weights . Altogether 4 Parameters

  • population: colony , Required .
  • weights: Relative weights .
  • cum_weights: Add weight , Not commonly used . Unable to join weights share .
  • k: Selection times .

Code example

str = [" cheng ", " order ", " member ", " On the evening of ", " Maple "]
res = random.choices(str, weights=[0, 0, 1, 0, 0], k=5)
""" Because to 【 member 】 This word , adopt weights The parameter adds a special weight :1, Other weights are 0, So no matter how many times you choose randomly , The result is 【 member 】 res = [' member ', ' member ', ' member ', ' member ', ' member '] """

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

7. random.randrange(a,b,step)

Reference resources range Usage of :

  • Don't specify step, Random generation [a,b) An integer in the range .
  • Appoint step,step As a step size, it will further limit [a,b) The scope of the , such as randrange(0,11,2) It means to generate [0,11) Random even numbers in the range .
  • Don't specify a, Default from 0 Start .

Code example

int = random.randrange(3, 9)
""" int = 5 """

  • 1.
  • 2.
  • 3.
  • 4.

8. random.sample

Select from the set k Elements , Return a list , Clusters can be list、tuple、str、set.

  • No repetition : It can be understood as a deck of playing cards , It's really random , But it won't repeat .
  • Random number , Cannot exceed the length of the set . When dealing cards , A deck of cards has 54 Zhang , It is impossible to draw randomly 100 Time .

Code example

str = [" cheng ", " order ", " member ", " On the evening of ", " Maple "]
res = random.sample(str, 5)
""" res = [' member ', ' order ', ' cheng ', ' Maple ', ' On the evening of '] """

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

9. random.shuffle

Disrupt the original ordered set , Be careful : This method does not return a value , It directly changes the order of the original set . So if you want to change tuple This immutable set , Will report a mistake .

Code example

str = [" cheng ", " order ", " member ", " On the evening of ", " Maple ", " Yes ", " along ", " order "]
random.shuffle(str)
""" str = [' Maple ', ' along ', ' member ', ' order ', ' Yes ', ' On the evening of ', ' order ', ' cheng '] """

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

10. random.getrandbits

Generate an integer with a specified bit size .

Code example

int = random.getrandbits(8)
""" int = 136 """

  • 1.
  • 2.
  • 3.
  • 4.

At the end

Although I am Python The programmer , But in the recent development, I found that I didn't master many basic knowledge .

So I decided to start with this one , I decided to take that time to join Python when , The romantic feelings of feeding horses and chopping firewood and facing the sea , Go to the serious in-depth sorting and sharing Python Common knowledge points .

I hope it works for you .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved