Usage of Python random

Source: Internet
Author: User
Tags function prototype shuffle

Python's method of random inside is actually an object instantiated by random.

There are several commonly used in several Parties import random

Print(Random.Randint(1,10) ) # generates an integer random number from 1 to 10Print(Random.Random() ) # Generate random floating-point numbers from 0 to 1Print(Random.Uniform(1.1,5.4) ) # generates a random floating-point number between 1.1 and 5.4, and the interval may not be an integerPrint(Random.Choice(' Tomorrow ') ) # random selection of an element from a sequencePrint(Random.Randrange (1,100 2)     # Generate random integers from 1 to 100 with an interval of 2 a=[1 3,5,6 ,7] # to disrupt the order of elements in sequence a Span class= "PLN" >random. (a) print (a         

I'll see the source.
def randrange (self, start, Stop=none, Step=1, _int=int):
Self is the value you instantiate object start, stop is the key parameter, step interval 1 _int = Int (integer object)
"" "Choose a random item from range (Start, stop[, step]).
      

This fixes the problem with Randint () which includes the
Endpoint In Python, this is usually don't what want.

"""

# This code was a bit messy to make it fast for the
# Common case while still doing adequate error checking.
Istart = _int (start)
Force Istart is an integer
If Istart! = Start:
  Determine if start is not an integer
Raise ValueError ("Non-integer Arg 1 for Randrange ()")
Parameter error
)
If stop is None:
whether the keyword argument for the end value of the interpretation is none
If Istart > 0:
       determine if the start value is greater than 0
Return Self._randbelow (Istart)
         call _randbelow method to pass in and out, is probably the maximum range of judging the starting value
Raise ValueError ("Empty range for Randrange ()")
      triggering a value that cannot be null error
# Stop argument supplied.
Istop = _int (stop)

If istop! = Stop:
Raise ValueError ("Non-integer Stop for Randrange ()")
   range values for loops
width = Istop-istart

If step = = 1 and width > 0:
return Istart + self._randbelow (width)
If step = = 1:
Raise ValueError ("Empty range for Randrange () (%d,%d,%d)"% (Istart, istop, width))

# non-unit Step argument supplied.
Istep = _int (step)
If istep! = Step:
Raise ValueError ("Non-integer Step for Randrange ()")
If Istep > 0:
n = (width + istep-1)//Istep
      N (should be the number of random loops)For example (1,10) Wdith = 10-1 + istep =2//2 n =5
So the ordered set is 5 "1,3,5,7,9"

Elif Istep < 0:
n = (width + istep + 1)//Istep
Else
Raise ValueError ("Zero Step for Randrange ()")

If n <= 0:
Raise ValueError ("Empty range for Randrange ()")

return Istart + istep*self._randbelow (n)
Looked down the source code can not see

def choice (self, seq):
"" "Choose a random element from a non-empty sequence." ""
Select a random element from a set that has a virtual collection, what is the "string, list, and ancestor" of the ordered collection in Python
Both the dictionary and the collection are invalid

Try
i = Self._randbelow (len (seq))
Except ValueError:
Raise Indexerror (' cannot choose from an empty sequence ')
return Seq[i]

def randint (self, A, b):
"" "Return random integer in range [A, b], including both end points.
"""

Return Self.randrange (A, b+1) here's the point. I'm not going to say anything.


PYTHON Random Module (get random number) common methods and usage examples

Random.random
Random.random () is used to generate a random number of 0 to 1 points: 0 <= N < 1.0

Random.uniform
Random.uniform (A, b), used to generate a random number of characters in a specified range, two parameters one of which is the upper bound, and the other is the lower limit. If a > B, the generated random number n:a <= n <= B. If a <b, then B <= N <= a

The code is as follows:
Print Random.uniform (10, 20)
Print Random.uniform (20, 10)
# 18.7356606526
# 12.5798298022

Random.randint
Random.randint (A, b), used to generate an integer within a specified range. Where parameter A is the lower limit, parameter B is the upper limit, the generated random number n:a <= n <= B

The code is as follows:
Print Random.randint (12, 20) # generated random number N:12 <= n <= 20
Print Random.randint (20, 20) # The result is always 20
# Print Random.randint (20, 10) # The statement is wrong. Lower limit must be less than upper limit

Random.randrange
Random.randrange ([start], stop[, step]), from within the specified range, gets a random number in the collection incremented by the specified cardinality. such as: Random.randrange (10, 100, 2), the result is equivalent from [10, 12, 14, 16, ... 96, 98] gets a random number in the sequence. Random.randrange (10, 100, 2) equivalent to Random.choice (range (10, 100, 2) on the result

Random.choice
Random.choice gets a random element from the sequence. Its function prototype is: Random.choice (sequence). The parameter sequence represents an ordered type. Here's a note: sequence is not a specific type in Python, but a series of types. list, tuple, string all belong to sequence. For sequence, you can view the Python manual data Model chapter. Here are some examples of using choice:

The code is as follows:
Print Random.choice ("Learning python")
Print Random.choice (["Jgood", "is", "a", "handsome", "boy"])
Print Random.choice (("Tuple", "List", "Dict")

Random.shuffle
Random.shuffle (x[, Random]), which is used to disrupt elements in a list. Such as:

The code is as follows:
p = [' Python ', ' is ', ' powerful ', ' simple ', ' and so ' on ... ']
Random.shuffle (P)
Print P
# [' Powerful ', ' simple ', ' was ', ' Python ', ' and so on ... ']

Random.sample
Random.sample (sequence, k), randomly fetching fragments of the specified length from the specified sequence. The sample function does not modify the original sequence

The code is as follows:
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Slice = random.sample (list, 5) # randomly fetches 5 elements from the list, returning as a fragment
Print Slice
Print List # The original sequence has not changed


Random integers:

The code is as follows:>>> import random
>>> Random.randint (0,99)
# 21

Randomly select even numbers between 0 and 100:

The code is as follows:>>> import random
>>> random.randrange (0, 101, 2)
# 42

Random floating point number:

The code is as follows:>>> import random
>>> Random.random ()
0.85415370477785668
>>> random.uniform (1, 10)
# 5.4221167969800881

Random characters:

The code is as follows:>>> import random
>>> random.choice (' abcdefg&#%^*f ')
# ' d '

Select a specific number of characters in more than one character:

The code is as follows:>>> import random
Random.sample (' Abcdefghij ', 3)
# [' A ', ' d ', ' B ']

Select a specific number of characters to form a new string in multiple characters:

The code is as follows:>>> import random
>>> Import String
>>> String.Join (Random.sample ([' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J '], 3)). Replace ("", "" ")
# ' FIH '

Randomly pick a string:

The code is as follows:>>> import random
>>> random.choice ([' Apple ', ' pear ', ' peach ', ' orange ', ' Lemon '])
# ' Lemon '

Shuffle:

The code is as follows:>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle (items)
>>> Items
# [3, 2, 5, 6, 4, 1]




Usage of Python random

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.