제로베이스 데이터 취업 스쿨 과정 학습 내용을 정리한 포스팅입니다.
📍 한/영 사전 프로그래밍
from abc import ABCMeta
from abc import abstractmethod
class AbsDictionary(metaclass=ABCMeta):
def __init__(self):
self.wordDict = {}
@abstractmethod
def registWord(self, w1, w2):
pass
@abstractmethod
def removeWord(self, w1):
pass
@abstractmethod
def updateWord(self, w1, w2):
pass
@abstractmethod
def searchWord(self, w1):
pass
먼저 한/영, 영/한 등 사전을 만드는 상위 클래스를 만들어주고, 추상클래스로 구현하여 구체적인 하위 클래스 사전에서 메소드를 만들도록 강제한다.
class KorToEng(AbsDictionary): # 상위 클래스 상속받기
def __init__(self):
super().__init__()
def registWord(self, w1, w2):
print(f'단어 등록 / {w1} : {w2} ')
self.wordDict[w1] = w2
def removeWord(self, w1):
print(f'단어 제거 / {w1}')
del self.wordDict[w1]
def updateWord(self, w1, w2):
print(f'단어 변경 / {w1} : {w2} ')
self.wordDict[w1] = w2
def searchWord(self, w1):
print(f'단어 검색 / {w1} : {self.wordDict[w1]}')
def printWord(self):
for i in self.wordDict:
print(f'{i} -> {self.wordDict[i]}')
상위 추상클래스를 상속 받아 구체적으로 메소드를 구현한다.
import ADictionary as ad # 다른 실행 파일에서 위의 클래스가 저장된 Adictionary.py를 불러온다
kte = ad.KorToEng()
kte.registWord('책', 'bok')
kte.registWord('나비', 'butterfly')
kte.registWord('연필', 'pencil')
kte.registWord('학생', 'studen')
kte.registWord('선생님', 'teacher')
kte.printWord()
kte.updateWord('책', 'book')
kte.searchWord('책')
kte.removeWord('책')
kte.printWord()
이와 같은 방식으로 한영 사전 KorToEng() 클래스를 불러와 kte 인스턴스를 선언한다.
KorToEng 클래스에 구현해 놓은 메소드들을 이용할 수 있게 된다.
📍 소수 판별기 프로그래밍
class NotPrimeException(Exception):
def __init__(self, n):
super().__init__(f'{n} is not a prime number')
class PrimeException(Exception):
def __init__(self, n):
super().__init__(f'{n} is a prime number')
NotPrimeException : 소수가 아니라고 표현하는 (exception 발생시키는 X) 클래스 정의
PrimeException : 소수라고 표현하는 (exception 발생시키는 X) 클래스 정의
def isPrime(number):
flag = True
for i in range(2, number):
if number % i == 0:
flag = False
break
if flag == True:
raise PrimeException(number)
else:
raise NotPrimeException(number)
isPrime 함수 : 숫자가 소수인지 판별하고, 맞다면 PrimeException을, 아니라면 NotPrimeException을 발생(raise)시키는 기능
import Primecheck as pc
import random
prime_nums = []
n = 0
while n < 10:
rn = random.randint(2, 1000)
if rn not in prime_nums:
try:
pc.isPrime(rn)
except pc.PrimeException as e:
print(e)
prime_nums.append(rn)
except pc.NotPrimeException as e:
print(e)
continue
else:
print(f'{rn} is already in')
continue
n += 1
print(prime_nums)
소수를 확인하는 primecheck.py를 불러오기
2 ~ 1000 의 난수가 소수면 PrimeException이 발생하고 리스트에 추가, 소수가 아니면 NotPrimeException이 발생하고 다시 iter를 실행하는 반복문 작성
📍 상품 총 구매금액 계산하기 프로그래밍
g1price = 1200; g2price = 1000; g3price = 800
g4price = 2000; g5price = 900
def calculate(*gcs):
gcsDic = {}
againCntInput = {}
for idx, gc in enumerate(gcs):
try:
gcsDic[f'g{idx+1}'] = int(gc)
except Exception as e:
againCntInput[f'g{idx+1}'] = gc
print(e)
totalPrice = 0
for g in gcsDic:
totalPrice += globals()[f'{g}price'] * gcsDic[g]
totalPrice = format(totalPrice, ',')
print(f'총 구매금액 : {totalPrice}원')
print(f'미결제 항목')
for g in againCntInput:
print(f'상품: {g}, 구매 개수: {againCntInput[g]}')
상품금액 x 구매 개수로 총 구매금액을 구하는데, 개수로 숫자가 아닌 값이 입력되면 예외처리
* globals() : 변수 = 값으로 선언된 모든 것을 딕셔너리로 반환해주는 함수
import goods as gd
g1Cnt = input('goods1 구매 개수: ')
g2Cnt = input('goods2 구매 개수: ')
g3Cnt = input('goods3 구매 개수: ')
g4Cnt = input('goods4 구매 개수: ')
g5Cnt = input('goods5 구매 개수: ')
gd.calculate(g1Cnt, g2Cnt, g3Cnt, g4Cnt, g5Cnt)