numpy 실습

강정우·2022년 7월 21일
0

data, ai

목록 보기
2/18
post-thumbnail

numpy random함수를 이용한 lotto 번호 만들기

1. set 집합을 이용하여 만들기

import random
nums = set()
while len(nums) != 6:
    nums.add(random.randint(4,46))
arr = np.array(sorted(list(nums)))
arr

#result
## array([16, 19, 32, 36, 42, 45])
  • 하지만 조건에 충족하진 않음. numpy 결여

2.

lottoNum = []

# 첫번째 번호 생성
num = np.random.randint(1,7)

for i in range(6):
    # 로또 번호 리스트에 현재 뽑은 번호가 있다면
    while num in lottoNum:
        # 다시 번호를 뽑는다
        num = np.random.randint(1,7)
        
    lottoNum.append(num)

# 크기순으로 정렬
lottoNum.sort()

# 배열로 변환해서 출력
arrLotto=np.array(lottoNum)

arrLotto

#result
## array([1, 2, 3, 4, 5, 6])
  • for문 6번 돌려 6개의 번호만 추출하되 그 안에 조건을 만족할 때까지 while문을 돌려 번호표 6개를 출력한다.

3.

ran_ch = np.array(sorted(np.random.choice(range(1,46),6,replace=False)))
ran_ch
  • 숏 코딩 choice 함수를 이용하고 choice 안에 있는 조건의 replace를 false로 만들어 비복원 추출을 하여 중복을 막을 수 있다.
profile
智(지)! 德(덕)! 體(체)!

0개의 댓글