[파이썬] 난수 발생 random()함수 사용법 및 shuffle(), choice(), choices(), simple(),randint(), randrange(), uniform() 함수 사용법 등 정리자료

[파이썬] 난수 발생 random()함수 사용법 및 shuffle(), choice(), choices(), simple(),randint(), randrange(), uniform() 함수 사용법 등 정리자료

파이썬 언어에서 난수를 발생시켜 랜덤 숫자를 얻으려면 random() 모듈을 사용해야 합니다.

난수는 여러 모로 사용할 일이 많이 생깁니다. 주사위 놀이 게임을 만든다던가, 랜덤 숫자값을 받아서 임의 처리가 필요한 경우, 임시 비밀번호를 숫자로만 생성하는 경우 등 많이 있어요.

random()함수를 호출하게 되면 호출할 때 마다 다른 결과를 리턴 받게 됩니다. 그리고 난수 발생 범위 지정이 필요한 경우 randrange()메소드를 사용합니다. 정수형인경우 randint()메소드를 사용하는 것을 추천합니다. 

메소드(함수)설명
random()0 부터 1 사이의 부동소수점(float) 숫자를 리턴
randint(최소, 최대)최소부터 최대까지 중 임의의 정수를 리턴
uniform(최소, 최대) 최소부터 최대까지 중 임의의 부동소수점(float) 숫자를 리턴
randrange(시작,끝, 간격)시작부터 끝까지 숫자중에  지정된 간격의 숫자 중 리턴
간격 값은 선택사항
shuffle(컬렉션)컬렉션의 값을 뒤섞어서 리턴
choice(컬렉션)컬렉션의 값 중 하나의 값을 리턴
choices(컬렉션, 가중치, 샘플 수)컬렉션 값에 가중치를 지정하고 임의의 값을 추출
sample(컬렉션, 샘플 수)컬렉션타입의 값 중에 지정한 샘플 수 만큼 랜덤으로 추출

컬렉션이란 리스트(list), set, 튜플과 같은 데이터 타입을 의미합니다 

예제를 통해 알아보는 random 기본 사용방법

1. 0부터 1사이의 임의의 float를 리턴합니다.

>>> import random
>>>
>>> random.random()
0.983361278849976
>>>
>>> random.random()
0.7546796153627895
>>>
>>> random.random()
0.6371495644741066
>>>
>>> random.random()
0.14307228307572706
>>>
import random

print(random.random.__doc__)

for i in range(10):
    a = random.random()
    print(f'{a}')


#실행결과
C:\Users\ilike\AppData\Local\Programs\Python\Python39\python.exe C:/python/Workspace/main.py
random() -> x in the interval [0, 1).
0.05897188732159453
0.1060339035169654
0.034019252933518596
0.24913708736424067
0.47777998628975527
0.24211907360122376
0.7674417624764993
0.8853278248454853
0.3341873652933879
0.4877786963933164

2. random.randint(a, b)

randint()는 a와 b 사이의 정수를 리턴합니다.

import random

print(random.randint.__doc__)

for i in range(3):
    a = random.randint(0, 5)
    print(f'{a}')
    

#실행결과    
Return random integer in range [a, b], including both end points.
        
0
1
5

3. 랜덤함수를 사용하여 주사위 만들기(1에서 6까지)

>>> import random
>>>
>>> random.randint(1,6)
6
>>> random.randint(1,6)
2
>>> random.randint(1,6)
4
>>>
>>> random.randint(1,6)
6

4. random.randrange(start, stop, step)

randrange()는 start와 stop 사이의 수를 반환합니다.  stop, step는 생략가능합니다.

import random

print(random.randrange.__doc__)

for i in range(3):
    a = random.randrange(20)
    print(f'{a}')
    
    
#실행결과
7
1
5
import random

for i in range(3):
    a = random.randrange(5, 20)
    print(f'{a}')

       
#실행결과
14
19
14
import random

print(random.randrange.__doc__)

for i in range(5):
    a = random.randrange(0, 20, 3)
    print(f'{a}')


#실행결과
18
12
9
18
15

5. uniform(최소, 최대) 

1.14부터 36.5 사이의 float 값을 리턴합니다.

>>> random.uniform(1.14, 36.5)
2.8734970157351425
>>> random.uniform(1.14, 36.5)
27.86339913180026
>>> random.uniform(1.14, 36.5)
3.223311464564321
>>>

6. random.shuffle(list)

리스트(list) 자료형의 데이터를 섞어줍니다.

>>> import random
>>>
>>> a = ['a', 'b', 'c', 'd', 'e']
>>> random.shuffle(a)
>>> a
['d', 'b', 'c', 'a', 'e']
>>>
>>> random.shuffle(a)
>>> a
['d', 'e', 'c', 'b', 'a']
>>>
>>> random.shuffle(a)
>>> a
['d', 'b', 'a', 'c', 'e']
>>>
import random

print(random.shuffle.__doc__)

#실행결과
Shuffle list x in place, and return None.

        Optional argument random is a 0-argument function returning a
        random float in [0.0, 1.0); if it is the default None, the
        standard random.random will be used.


b = random.shuffle(a)
print(f'{b}') 

#실행결과 
None

 
 
for i in range(5):
    random.shuffle(a)
    print(f'{a}')
    
    
#실행결과
['apple', 'pitch', 'banana', 'orange']
['apple', 'orange', 'banana', 'pitch']
['banana', 'pitch', 'orange', 'apple']
['orange', 'apple', 'banana', 'pitch']
['pitch', 'banana', 'orange', 'apple']

7. random.choice(seq)

비어 있지 않은 시퀀스에서 임의의 요소를 선택합니다.

>>> import random
>>>
>>> a = ['a', 'b', 'c', 'd', 'e']
>>>
>>> random.choice(a)
'c'
>>>
>>> random.choice(a)
'e'
>>>
>>>
>>> random.choice(a)
'c'
>>>
import random

a = ("apple", "orange", "pitch", "banana")
for i in range(5):
    b = random.choice(a)
    print(f'{b}')

샘플링(sample) 하는 방법

sample()메소드를 사용하면 리스트, set, 튜플 등과 같은 컬렉션 타입의 자료형으로 부터 지정한 갯수 만큼의 샘플링을 랜덤하게 추출할 수 있습니다.

>>> a = [1,2,3,4,5,6,7,8,9,10]
>>> b = random.sample(a, 3)
>>> print(b)
[9, 7, 5]
>>> print(b)
[9, 7, 5]
>>>
>>> b = random.sample(a, 3)
>>> print(b)
[7, 6, 1]
>>>
import random

print(random.shuffle.__doc__)

a = ["apple", "orange", "pitch", "banana"]
for i in range(5):
    b = random.sample(a, 3)
    print(f'{b}')
    
#실행결과
Shuffle list x in place, and return None.

        Optional argument random is a 0-argument function returning a
        random float in [0.0, 1.0); if it is the default None, the
        standard random.random will be used.

        
['pitch', 'orange', 'banana']
['pitch', 'apple', 'orange']
['apple', 'orange', 'banana']
['apple', 'orange', 'pitch']
['banana', 'orange', 'pitch']
import random 
a = ["apple", "orange", "pitch", "banana"]
 
for i in range(5):
    b = random.sample(a, random.randint(1, 3))
    print(f'{b}')


#실행결과
['orange', 'pitch']
['pitch', 'banana']
['apple', 'pitch']
['pitch']
['pitch', 'apple', 'banana']

컬렉션 값에 가중치를 주어서 샘플링 하는 방법

아래 샘플코드에서 처럼 1,2,3,4,5의 값 가각에 대한 가중치로 10,10,20,20,5를 주었습니다. 그럼으로 가중치에 따라 랜덤으로 값을 추출할 수 있습니다. 아무래도 가중치가 높은 경우값이 추출이될 확률이 높습니다.

>>> random.choices([1,2,3,4,5], [10,10,20,20,5])
[4]
>>> random.choices([1,2,3,4,5], [10,10,20,20,5])
[3]
>>> random.choices([1,2,3,4,5], [10,10,20,20,5])
[2]
>>>
>>> random.choices([1,2,3,4,5], [10,10,20,20,5],k=2)
[1, 4]
>>> random.choices([1,2,3,4,5], [10,10,20,20,5],k=2)
[5, 3]
>>>


카테고리의 다른 글
error: Content is protected !!