Python random 모듈을 이용해서 간단한 로또 번호 생성기 만드는 방법을 소개합니다.
로또는 1 부터 45까지 중복되지 않는 숫자 6개의 조합입니다.
[필요 조건]
1. 1 부터 45까지 정수
2. 중복되지 않는 숫자 세트
3. 숫자 6개가 완성
로또 번호 생성하는 5가지 방법
1. random.randint
-
1234567891011121314151617import random# 중복 방지를 위해 set()lotto = set()# 로또 번호는 6개이므로 6개가 되면 중지while 6 > len(lotto):# a이상 b이하의 정수를 반환 (a <= N <= b)number = random.randint(1, 45)lotto.add(number)# 생성된 숫자 정렬lotto = sorted(lotto)print(lotto)# run# [5, 6, 7, 14, 27, 42]
cs
2. random.randrange
-
12345678910111213141516import random# 중복 방지를 위해 set()lotto = set()# 로또 번호는 6개이므로 6개가 되면 중지while 6 > len(lotto):# a이상 b이하의 정수를 반환 (0 <= N < stop)number = random.randrange(45) + 1# 생성된 숫자 정렬lotto = sorted(lotto)print(lotto)# run# [1, 8, 9, 22, 43, 45]
cs
3. random.choice
-
1234567891011121314151617181920import random# 1~45 정수 리스트nums = [x + 1 for x in range(45)]# 중복 방지를 위해 set()lotto = set()# 로또 번호는 6개이므로 6개가 되면 중지while 6 > len(lotto):# nums 리스트의 원소 하나를 선택number = random.choice(nums)lotto.add(number)# 생성된 숫자 정렬lotto = sorted(lotto)print(lotto)# run# [15, 21, 30, 34, 38, 39]
cs
4. random.shuffle
-
1234567891011121314151617181920212223import random# 1~45 정수 리스트nums = [x + 1 for x in range(45)]# nums 리스트를 썩는다random.shuffle(nums)# 썩인 nums의 0번째 ~ 6번째 인덱스를 가져온다# nums의 인덱스는 다른 곳으로 해도 상관 없다.lotto1 = nums[0:6]lotto2 = nums[10:16]# 생성된 숫자 정렬lotto1 = sorted(lotto1)lotto2 = sorted(lotto2)print(lotto1)print(lotto2)# run# [15, 17, 24, 25, 34, 35]# [3, 6, 9, 12, 33, 40]
cs
5. random.sample
-
1234567891011121314import random# 1~45 정수 리스트nums = [x + 1 for x in range(45)]# nums 리스트에서 6개 원소를 선택lotto = random.sample(nums, 6)# 생성된 숫자 정렬lotto = sorted(lotto)print(lotto)# run# [3, 14, 23, 34, 37, 39]
cs
'Python' 카테고리의 다른 글
[Python] 파이썬 랜덤(random) 함수 (0) | 2020.06.15 |
---|