"""Random variable generators.
bytes
-----
uniform bytes (values between 0 and 255)
integers
--------
uniform within range
sequences
---------
pick random element
pick random sample
pick weighted random sample
generate random permutation
distributions on the real line:
------------------------------
uniform
triangular
normal (Gaussian)
lognormal
negative exponential
gamma
beta
pareto
Weibull
distributions on the circle (angles 0 to 2pi)
---------------------------------------------
circular uniform
von Mises
General notes on the underlying Mersenne Twister core generator:
* The period is 2**19937-1.
* It is one of the most extensively tested generators in existence.
* The random() method is implemented in C, executes in a single Python step,
and is, therefore, threadsafe.
"""
이것은 python random.py 모듈의 주석 내용이다. 만들 수 있는 수에 대해서 요약되어 있으며, 오늘 이것들 중 몇 개의 random 함수를 다뤄본다.
< 실수 관련 >
import random
num1 = random.random()
print(f"random() = {num1}") #0.8737351792314224
num2 = random.uniform(1,10)
print(f"uniform(1,10) = {num2}") #5.387622011327463
num3 = random.randint(1, 10)
print(f"randint(1, 10) = {num3}") # 1~10 random int
num4_1 = random.randrange(0, 1000, 5)
print(f"randrange(0, 1000, 5) = {num4_1}") # 0-999까지 간격(step) 5에 해당하는 수 중 rand 추출
num4_2 = random.randrange(0, 10)
print(f"randrange(0, 1000, 5) = {num4_2}") # 0 ~ 9 중 수 1개 뽑기, 이렇게 사용하면 randint와 같다.
num5 = random.randbytes(1)
print(f"randbytes = {num5}") # 8byte (0~255) random byte value 반환
num6 = random.triangular(0, 1)
print(f"triangular = {num6}") # 0~1미만의 삼각함수 값을 반환
(1회차)
random() = 0.625753259433996
uniform(1,10) = 4.993728111936218
randint(1, 10) = 6
randrange(0, 1000, 5) = 365
randrange(0, 1000, 5) = 3
randbytes = b'J'
triangular = 0.8263672948031475
(2회차)
random() = 0.12223894921737943
uniform(1,10) = 3.014724048076995
randint(1, 10) = 6
randrange(0, 1000, 5) = 545
randrange(0, 1000, 5) = 6
randbytes = b'\xaf'
triangular = 0.5225005183685572
참고로, rand 함수는 C언어 random 함수처럼 seed를 통해 추출을 결정하므로, 완벽한 함수는 아니라는 걸 명심하자.
# Create one instance, seeded from current time, and export its methods from by random.py
random.seed(1)
num1 = random.random()
print(f"num1 = {num1}") #시드 1로 고정 시킨 상태
random.seed(1)
num2 = random.random()
print(f"num2 = {num2}") # 동일한 값이 나온다..
num1 = 0.13436424411240122
num2 = 0.13436424411240122
< 경우의 수 관련 >
import random
mylist = list("ABCDEFGH")
string1 = random.choice(mylist)
print(f"choice() = {string1}") # 제공한 list 중에 1글자 추출
string2 = random.choices(mylist,k=3)
print(f"choices() = {string2}") #제공한 list 중에 k만큼 추출(중복 포함)
string3 = random.sample(mylist, k=3)
print(f"sample() = {string3}") #제공한 list 중에 k만큼 뽑기(순열, 중복 없음)
string4 = random.shuffle(mylist)
print(f"shuffle() = {string4}") # return 없음
print(f"mylist = {mylist}") # myList의 변화를 잘 봐보자.
choice() = H
choices() = ['B', 'H', 'B']
sample() = ['D', 'H', 'E']
shuffle() = None
mylist = ['F', 'H', 'B', 'G', 'D', 'A', 'C', 'E']
조합과 순열이 편하게 함수로 제공된다는 점에서 알고리즘 문제, 블랙박스 테스트 때 사용할 값 등 여로모로 이용할 수 있을 것 같다. visit 매번 작성해줘야하는 자바보다 편하다!