
오늘은 실전 연습용 코딩 한번 짜 봅니다. 로또번호 생성은 너무 쉽게 되더군요! 과거 당첨된 로또번호 자료(1회~961회)를 구글링으로 찾아 lotto_data.txt로 넣어주고 random 함수로 생성된 로또번호를 비교하여 당첨 여부, 당첨 횟수를 출력하는 프로그램을 만들었습니다. 간단해 보이지만 코딩 초보에겐 약간의 벽이 있었답니다. (벽은 부숴버리라고 있는 것 아니 긋습니까?!^^) 함수, random 함수, 다중(2차원) 리스트, 다중(3중) 반복문, 파일로부터 자료 입력받기 등 복합적으로 파이썬 문법을 살펴보는 계기가 되었습니다.
import random
def Lotto_Num():
count = 0
Lotto = []
while count < 6:
rnd = random.randint(1,45)
if Lotto.count(rnd) < 1 :
Lotto.append(rnd)
count += 1
return Lotto
def File2List():
file=open('lotto_data.txt','r')
raw_data =[]
for line in file: raw_data.append(line.split())
file.close()
return raw_data
mylt_num=Lotto_Num()
raw_data=File2List()
print ('My Lotto Num.',mylt_num)
count = 1
total = [0,0,0,0,0]
while raw_data:
main_match = 0
bonus_match = 0
for i in mylt_num:
for j in raw_data[count][4:10]:
if i == int(j) : main_match += 1
if i == int(raw_data[count][10]) : bonus_match = 1
if main_match == 3 :
print('5등! 나쁘지 않음',raw_data[count][0:3])
total[4] += 1
elif main_match == 4 :
print('4등! 가볍게 소주 한 잔',raw_data[count][0:3])
total[3] += 1
elif main_match == 5 and bonus_match == 0:
print('3등! 근사한 식사 한 끼',raw_data[count][0:3])
total[2] += 1
elif main_match == 5 and bonus_match == 1:
print('2등! 어디 여행이라도~',raw_data[count][0:3])
total[1] += 1
elif main_match == 6:
print('인생역전',raw_data[count][0:4])
total[0] += 1
else: pass
if count < 961 : count+=1 (index 오류 방지)
else : break
print (f'count:{count}\n 1등 {total[0]}명 2등{total[1]}명 3등{total[2]}명 4등{total[3]} 5등{total[4]}')
당첨된 번호는 회차, 추첨 일자, 1등 당첨자 수 등을 출력합니다.

단순한 작업이었지만 다중 리스트 사용법을 좀 더 알 수 있었습니다.
그리고 또 한 가지! 로또 당첨 확률을 알고 있었지만 3등 하나 나오기가 이렇게 어려울 줄은 몰랐네요… 몇 번을 돌려도 안 나옵니다. (3등 이상이 나오질 않아 뭔가 코딩에 문제 있나 확인차 당첨번호를 직접 변수에 넣어보니 나옵니다. 코딩 잘못이 아니었더군요!)
'코딩 이야기 > 파이썬(Python)' 카테고리의 다른 글
단도직입 파이썬(Python) – 정규식(Regular Expression) 2/2 (0) | 2021.12.17 |
---|---|
단도직입 파이썬(Python) – 정규식(Regular Expression) 1/2 (0) | 2021.12.17 |
단도직입 파이썬(Python) – 연습코딩(클래스, 모듈,~라이브러리) (0) | 2021.12.16 |
단도직입 파이썬(Python) – 라이브러리(Library) (0) | 2021.12.16 |
단도직입 파이썬(Python) – 내장 함수(Built in Function) (0) | 2021.12.16 |
댓글