<Ch. 4> 파이썬 중급 문제 풀이

이희준·2023년 4월 27일
0
post-thumbnail

중급문제풀이 [1-2]

함수 (01)

연습 문제 1.

다음과 같이 출력 될 수 있도록 산술연산 계산기를 함수를 이용해서 만들어 보자.

#### A.
def add(n1, n2):
    return n1 + n2

def sub(n1, n2):
    return n1 - n2

def mul(n1, n2):
    return n1 * n2

def div(n1, n2):
    return n1 / n2

def flo(n1, n2):
    return n1 // n2

def mod(n1, n2):
    return n1 % n2

def exp(n1, n2):
    return n1 ** n2

while True:
    print('-' * 60)
    selectNum = int(input('1. 덧셈, 2. 뺄셈, 3. 곱셈, 4. 나눗셈 , 5. 몫, 6. 나머지, 7. 제곱승, 8. 종료\t'))
    if selectNum == 8:
        print('Bye~')
        break

    elif selectNum == 1:
        num1 = float(input('첫 번째 숫자 입력: '))
        num2 = float(input('두 번째 숫자 입력: '))
        print(f'{num1} + {num2} = {add(num1, num2)}')

    elif selectNum == 2:
        num1 = float(input('첫 번째 숫자 입력: '))
        num2 = float(input('두 번째 숫자 입력: '))
        print(f'{num1} - {num2} = {sub(num1, num2)}')

    elif selectNum == 3:
        num1 = float(input('첫 번째 숫자 입력: '))
        num2 = float(input('두 번째 숫자 입력: '))
        print(f'{num1} * {num2} = {mul(num1, num2)}')

    elif selectNum == 4:
        num1 = float(input('첫 번째 숫자 입력: '))
        num2 = float(input('두 번째 숫자 입력: '))
        print(f'{num1} / {num2} = {div(num1, num2)}')

    elif selectNum == 5:
        num1 = float(input('첫 번째 숫자 입력: '))
        num2 = float(input('두 번째 숫자 입력: '))
        print(f'{num1} // {num2} = {flo(num1, num2)}')

    elif selectNum == 6:
        num1 = float(input('첫 번째 숫자 입력: '))
        num2 = float(input('두 번째 숫자 입력: '))
        print(f'{num1} % {num2} = {mod(num1, num2)}')

    elif selectNum == 7:
        num1 = float(input('첫 번째 숫자 입력: '))
        num2 = float(input('두 번째 숫자 입력: '))
        print(f'{num1} ** {num2} = {exp(num1, num2)}')

    else:
        print('잘 못 입력하셨습니다. 다시 입력해주세요.')

    print('-' * 60)

함수 (02)

연습 문제 1.

다음과 같이 출력 될 수 있도록 이동거리와 이동시간을 반환하는 함수를 만들어 보자.

A.

def getDistance(speed, hour, minute):
    distance = speed * (hour + minute / 60)
    return distance

print('-' * 60)
s = float(input('속도(km/h) 입력: '))
h = float(input('시간(h) 입력: '))
m = float(input('시간(m) 입력: '))
d = getDistance(s, h, m)

print(f'{s}(km/h)속도로 {h}(h)시간 {m}(m)분 동안 이동한 거리: {d}(km)')
print('-' * 60)

연습 문제 2.

다음과 같이 출력 될 수 있도록 이동거리와 이동시간을 반환하는 함수를 만들어 보자.

A.

  • 직접 짠 코드:
def getTime(speed, distance):
    time = distance / speed * 60
    hr = int(time // 60)
    min = int(time - hr * 60)
    return [hr, min]


print('-' * 60)
s = float(input('속도(km/h) 입력: '))
d = float(input('거리(km) 입력: '))
t = getTime(s, d)
print(f'{s}(km/h)속도로 {d}(km) 이동한 시간: {t[0]}(h)시간 {t[1]}(m)분')
print('-' * 60)
  • 예시 답안:
def getTime(speed, distance):
    time = distance / speed
    h = int(time)
    m = int((time - h) * 100 * 60 / 100)
    return [h, m]


print('-' * 60)
s = float(input('속도(km/h) 입력: '))
d = float(input('거리(km) 입력: '))
t = getTime(s, d)
print(f'{s}(km/h)속도로 {d}(km) 이동한 시간: {t[0]}(h)시간 {t[1]}(m)분')
print('-' * 60)

함수 (03)

연습 문제 1.

다음과 같이 출력 될 수 있도록 비행기 티켓 영수증 출력 함수를 만들어 보자.

A.

childPrice = 18000
infantPrice = 25000
adultPrice = 50000
specialDC = 50

def formattedNum(n):
    return format(n, ',')

def printAirplaneReceipt(c1, c2, i1, i2, a1, a2):

    print('=' * 60)

    cp = c1 * childPrice
    cp_dc = int(c2 * childPrice * 0.5)
    print(f'유아 {c1}명 요금: {formattedNum(cp)}원')
    print(f'유아 할인 대상 {c2}명 요금: {formattedNum(cp_dc)}원')

    ip = i1 * infantPrice
    ip_dc = int(i2 * infantPrice * 0.5)
    print(f'소아 {i1}명 요금: {formattedNum(ip)}원')
    print(f'소아 할인 대상 {i2}명 요금: {formattedNum(ip_dc)}원')

    ap = a1 * adultPrice
    ap_dc = int(a2 * adultPrice * 0.5)
    print(f'성인 {a1}명 요금: {formattedNum(ap)}원')
    print(f'성인 할인 대상 {a2}명 요금: {formattedNum(ap_dc)}원')

    print('=' * 60)

    print(f'Total: {c1 + c2 + i1 + i2 + a1 + a2}명')
    print(f'TotalPrice: {formattedNum(cp + cp_dc + ip + ip_dc + ap + ap_dc)}원')

    print('=' * 60)


childCnt = int(input('유아 입력: '))
specialDCChildCtn = int(input('할인 대상 유아 입력: '))

infantCnt = int(input('소아 입력: '))
specialDCInfantCnt = int(input('할인 대상 소아 입력: '))

adultCnt = int(input('성인 입력: '))
specialDCAdultCnt = int(input('할인 대상 성인 입력: '))

printAirplaneReceipt(childCnt, specialDCChildCtn,
                     infantCnt, specialDCInfantCnt,
                     adultCnt, specialDCAdultCnt)

함수 (04)

연습 문제 1.

다음과 같이 출력 될 수 있도록 재귀함수를 이용해서 팩토리얼 함수를 만들어보자.

A.

def formattedNum(n):
    return format(n, ',')


# 단리
def singleRateCal(m, t, r):

    totalMoney = 0
    totalRateMoney = 0

    for i in range(t):
        totalRateMoney += m * (r * 0.01)

    totalMoney = m + totalRateMoney
    return int(totalMoney)


# 복리
def mulRateCal(m, t, r):

    t = t * 12
    rpm = (r / 12) * 0.01

    totalMoney = m

    for i in range(t):
        totalMoney += totalMoney * rpm

    return int(totalMoney)


money = int(input('예치금: '))
term = int(input('기간(년): '))
rate = int(input('연 이율(%): '))
print('\n')
print('[단리 계산기]')
print('=' * 60)
print(f'예치금\t: {formattedNum(money)}원')
print(f'예치기간\t: {term}년')
print(f'예치금\t: {rate}%')
print('-' * 60)
print(f'{term}년 후 총 수령액: {formattedNum(singleRateCal(money, term, rate))}원')
print('=' * 60)
print('\n')
print('[복리 계산기]')
print('=' * 60)
print(f'예치금\t: {formattedNum(money)}원')
print(f'예치기간\t: {term}년')
print(f'예치금\t: {rate}%')
print('-' * 60)
print(f'{term}년 후 총 수령액: {formattedNum(mulRateCal(money, term, rate))}원')
print('=' * 60)

함수 (05)

연습 문제 1.

다음과 같이 출력 될 수 있도록 등차 수열의 n번째 값과 합을 출력하는 함수를 만들어보자.

A.

# 등차 수열 공식 : an = a1 + (n-1) * d
# 등차 수열 합 공식 : sn = n * (a1 + an) / 2
def sequenceCal(n1, d, n):

    valueN = 0; sumN = 0;

    i = 1
    while i <= n:

        if i == 1:
            valueN = n1
            sumN += valueN
            print(f'{i}번째 항의 값: {valueN}')
            print(f'{i}번째 항까지의 합: {sumN}')

            i += 1
            continue

        valueN += d
        sumN += valueN
        print(f'{i}번째 항의 값: {valueN}')
        print(f'{i}번째 항까지의 합: {sumN}')

        i += 1

inputN1 = int(input('a1 입력: '))
inputD = int(input('공차 입력: '))
inputN = int(input('n 입력: '))

sequenceCal(inputN1, inputD, inputN)

함수 (06)

연습 문제 1.

다음과 같이 출력 될 수 있도록 등차 수열의 n번째 값과 합을 출력하는 함수를 만들어보자.

A.

def sequenceCal(n1, r, n):

    valueN = 0; sumN = 0;

    i = 1
    while i <= n:

        if i == 1:
            valueN = n1
            sumN = valueN
            print(f'{i}번째 항의 값: {valueN}')
            print(f'{i}번째 항까지의 합: {sumN}')

            i += 1
            continue

        valueN *= r
        sumN += valueN
        print(f'{i}번째 항의 값: {valueN}')
        print(f'{i}번째 항까지의 합: {sumN}')
        i += 1


inputN1 = int(input('a1 입력: '))
inputR = int(input('공비 입력: '))
inputN = int(input('n 입력: '))

sequenceCal(inputN1, inputR, inputN)

모듈 (01)

연습 문제 1.

과목별 점수를 입력하면 합격 여부를 출력하는 모듈을 만들어보자. (평균 60이상 합격, 과락 40으로 한다.)

A.

# passOrFail 모듈
def exampleResult(s1, s2, s3, s4, s5):

    passAvgScore = 60; limitScore = 40

    def getTotal():
        totalScore = s1 + s2 + s3 + s4 + s5
        print(f'평점: {totalScore}')
        return totalScore

    def getAverage():
        avg = getTotal() / 5
        print(f'평균: {avg}')
        return avg

    def printPassOrFail():
        print(f'{s1}: Pass') if s1 >= limitScore else print(f'{s1}: Fail')
        print(f'{s2}: Pass') if s2 >= limitScore else print(f'{s2}: Fail')
        print(f'{s3}: Pass') if s3 >= limitScore else print(f'{s3}: Fail')
        print(f'{s4}: Pass') if s4 >= limitScore else print(f'{s4}: Fail')
        print(f'{s5}: Pass') if s5 >= limitScore else print(f'{s5}: Fail')

    def printFinalPassOrFail():

        if getAverage() >= passAvgScore:
            if s1 >= limitScore and s2 >= limitScore and s3 >= limitScore and s4 >= limitScore and s5 >= limitScore:
                print('Final Pass!!')
            else:
                print('Final Fail!!')

        else:
            print('Final Fail!!')


    getAverage()
    printPassOrFail()
    printFinalPassOrFail()
    
# main 파일
import passOrFail as pf

if __name__ == '__main__':
    sub1 = int(input('과목1 점수 입력: '))
    sub2 = int(input('과목2 점수 입력: '))
    sub3 = int(input('과목3 점수 입력: '))
    sub4 = int(input('과목4 점수 입력: '))
    sub5 = int(input('과목5 점수 입력: '))

    pf.exampleResult(sub1, sub2, sub3, sub4, sub5)

모듈 (02)

연습 문제 1.

상품 구매 개수에 따라 할인율이 결정되는 모듈을 만들고, 다음과 같이 계산 결과가 출력되는 프로그램을 만들어보자.

A.

# 할인 모듈
def calTotalPrice(gs):

    if len(gs) <= 0:
        print('구매 상품이 존재하지 않습니다.')
        return

    rate = 25
    totalPrice = 0

    rates = {1:5, 2:10, 3:15, 4:20}

    if len(gs) in rates:
        rate = rates[len(gs)]

    for g in gs:
        totalPrice += g * (1 - rate * 0.01)

    return [rate, int(totalPrice)]
    
# main 모듈
import discount as dc

if __name__ == '__main__':

    flag = True
    gs = []

    while flag:

        selectNum = int(input('1.구매, 2.종료: '))

        if selectNum == 1:
            goods_price = int(input('상품 가격 입력: '))
            gs.append(goods_price)

        elif selectNum == 2:
            result = dc.calTotalPrice(gs)
            flag = False

    print(f'할인율: {result[0]}%')
    print(f'합계: {result[1]}원')

모듈 (03)

연습 문제 1.

로또 모듈을 만들고 다음과 같이 로또 결과가 출력될 수 있도록 프로그램을 만들어보자.

A.

# 로또 모듈
import random

userNums = []; randNums = []; collNums = []
randBonusNum = 0


def setUserNum(ns):
    global userNums
    userNums = ns


def getUserNums():
    return userNums


def setRandNums():
    global randNums
    randNums = random.sample(range(1, 46), 6)


def getRandNums():
    return randNums


def setBonusNum():
    global randBonusNum

    while True:
        randBonusNum = random.randint(1, 45)
        if randBonusNum not in randNums:
            break


def getBonusNum():
    return randBonusNum


def lotteryResult():
    global userNums
    global randNums
    global collNums

    collNums = []
    for un in userNums:
        if un in randNums:
            collNums.append(un)

    if len(collNums) == 6:
        print('1등 당첨!!')
        print(f'번호: {collNums}')

    elif (len(collNums)) == 5 and (randBonusNum in userNums):
        print('2등 당첨!!')
        print(f'번호: {collNums}, 보너스 번호: {randBonusNum}')

    elif len(collNums) == 5:
        print('3등 당첨!!')
        print(f'번호: {collNums}')

    elif len(collNums) == 4:
        print('4등 당첨!!')
        print(f'번호: {collNums}')

    else:
        print('아쉽습니다. 다음 기회에!')
        print(f'기계 번호: {randNums}')
        print(f'보너스 번호: {randBonusNum}')
        print(f'선택 번호: {userNums}')
        print(f'일치 번호: {collNums}')


def startLottery():
    n1 = int(input('번호(1~45) 입력: '))
    n2 = int(input('번호(1~45) 입력: '))
    n3 = int(input('번호(1~45) 입력: '))
    n4 = int(input('번호(1~45) 입력: '))
    n5 = int(input('번호(1~45) 입력: '))
    n6 = int(input('번호(1~45) 입력: '))
    selectNums = [n1, n2, n3, n4, n5, n6]

    setUserNum(selectNums)
    setRandNums()
    setBonusNum()

    lotteryResult()
    
# main 모듈
import lottery as lt

lt.startLottery()

중급문제풀이 [3]

모듈 (04)

연습 문제 1.

순열 계산 모듈을 만들고 다음 순열 계산 결과를 출력해 보자.

A.

  • 모듈 제작 ver.
# permutation 모듈
def getPermutationCnt(n, r, logPrint = True):

    result = 1
    for n in range(n, (n-r), -1):
        if logPrint: print('n:{}'.format(n))
        result = result * n

    return result

# main 모듈
import permutation as pt

numN = int(input('numN 입력: '))
numR = int(input('numR 입력: '))

# print(f'{numN}P{numR}: {pt.getPermutationCnt(numN, numR, logPrint=True)}')
  • itertools ver.
# permutation 모듈
from itertools import permutations

def getPermutations(ns, r):

    pList = list(permutations(ns, r))
    print(f'{len(ns)}P{r} 개수: {len(pList)}')

    for n in permutations(ns, r):
        print(n, end='')
        
# main 모듈
listVar = [1, 2, 3, 4, 5, 6, 7, 8]
rVar = 3
pt.getPermutations(listVar, rVar)

모듈 (05)

연습 문제 1.

조합 계산 모듈을 만들고 다음 조합 계산 결과를 출력해 보자.

A.

  • 모듈 제작 ver.
# combination 모듈
def getCombinationCnt(n, r, logPrint = True):

    resultP = 1
    resultR = 1
    resultC = 1

    for n in range(n, (n-r), -1):
        resultP = resultP * n
    if logPrint: print(f'resultP: {resultP}')

    for n in range(r, 0, -1):
        resultR = resultR * n
    if logPrint: print(f'resultR: {resultR}')

    resultC = int(resultP / resultR)
    if logPrint: print(f'result: {resultC}')

    return resultC

# main 모듈
import combinations as cb

numN = int(input('numN 입력: '))
numR = int(input('numR 입력: '))

print(f'{numN}C{numR}: {cb.getCombinationCnt(numN, numR, logPrint=True)}')
  • itertools ver.
# combination 모듈
from itertools import combinations

def getCombination(ns, r):
    cList = list(combinations(ns, r))
    print(f'{len(ns)}C{r}: {len(cList)}')
        
# main 모듈
listVar = [1, 2, 3, 4, 5, 6, 7, 8]
rVar = 3
cb.getCombination(listVar, rVar)

모듈 (06)

연습 문제 1.

수입과 공과금을 입력하면 공과금 총액과 수입 대비 공과금 비율을 계산하는 모듈을 만들어보자.

A.

# 공과금 모듈
income = 0
waterPrice = 0; elecPrice = 0; gasPrice = 0

def setIncome(ic):
    global income
    income = ic

def getIncome():
    return income

def setWaterPrice(wp):
    global waterPrice
    waterPrice = wp

def getWaterPrice():
    return waterPrice

def setElecPrice(ep):
    global elecPrice
    elecPrice = ep

def getElecPrice():
    return elecPrice

def setGasPrice(gp):
    global gasPrice
    gasPrice = gp

def getGasPrice():
    return gasPrice


def getUtilityBill():
    result = waterPrice + elecPrice + gasPrice
    return result


def getUtilityBillRate():
    result = getUtilityBill() / getIncome() * 100
    return result

def formattedNum(n):
    return format(n, ',')

# main 모듈
import utilityBill as ub

inputIncome = int(input('수입 입력: '))
ub.setIncome(inputIncome)

inputWaterPrice = int(input('수도요금 입력: '))
ub.setWaterPrice(inputWaterPrice)

inputElecPrice = int(input('전기요금 입력: '))
ub.setElecPrice(inputElecPrice)

inputGasPrice = int(input('갸스요금 입력: '))
ub.setGasPrice(inputGasPrice)

print(f'공과금: {ub.formattedNum(ub.getUtilityBill())}원')
print(f'수입 대비 공과금 비율: {ub.getUtilityBillRate()}%')

모듈 (07)

연습 문제 1.

다음과 같이 패키지와 모듈을 만들고 연산 결과를 출력해 보자.

A.

# basic_operator 모듈
def add(n1, n2):
    return round(n1 + n2, 2)

def sub(n1, n2):
    return round(n1 - n2, 2)

def mul(n1, n2):
    return round(n1 * n2, 2)

def div(n1, n2):
    return round(n1 / n2, 2)

# developer_operator 모듈
def mod(n1, n2):
    return round(n1 % n2, 2)

def flo(n1, n2):
    return round(n1 // n2, 2)

def exp(n1, n2):
    return round(n1 ** n2, 2)

# circle_area 모듈
def calCircleArea(r):
    return round(r ** 2 * 3.14, 2)

# triangle_square_area 모듈
def calTriArea(w, h):
    return round(w * h / 2, 2)

def calSquareArea(w, h):
    return round(w * h, 2)

# main 모듈
from arithmetic import basic_operator as bo
from arithmetic import developer_operator as do

from shape import circle_area as ca
from shape import triangle_square_area as tsa

inputNum1 = float(input('숫자1 입력: '))
inputNum2 = float(input('숫자2 입력: '))

print(f'{inputNum1} + {inputNum2} = {bo.add(inputNum1, inputNum2)}')
print(f'{inputNum1} - {inputNum2} = {bo.sub(inputNum1, inputNum2)}')
print(f'{inputNum1} * {inputNum2} = {bo.mul(inputNum1, inputNum2)}')
print(f'{inputNum1} / {inputNum2} = {bo.div(inputNum1, inputNum2)}')

print(f'{inputNum1} % {inputNum2} = {do.mod(inputNum1, inputNum2)}')
print(f'{inputNum1} // {inputNum2} = {do.flo(inputNum1, inputNum2)}')
print(f'{inputNum1} ** {inputNum2} = {do.exp(inputNum1, inputNum2)}')

inputWidth = float(input('가로 길이 입력: '))
inputHeight = float(input('세로 길이 입력: '))

print(f'삼각형 넓이: {tsa.calTriArea(inputWidth, inputHeight)}')
print(f'사각형 넓이: {tsa.calSquareArea(inputWidth, inputHeight)}')

inputRadius = float(input('반지름 길이 입력: '))

print(f'원 넓이: {ca.calCircleArea(inputRadius)}')

중급문제풀이 [4]

클래스 (01)

연습 문제 1.

회원가입 클래스와 회원정보를 관리하는 클래스를 만들고 회원가입 로그인 기능을 구현해 보자.

A.

# 회원가입 클래스
class Member:
    def __init__(self, i, p):
        self.id = i
        self.pw = p


class MemberRepository:

    def __init__(self):
        self.members = {}

    def addMember(self, m):
        self.members[m.id] = m.pw

    def loginMember(self, i, p):
        isMember = i in self.members

        if isMember and self.members[i] == p:
            print(f'{i}: log-in success!!')
        else:
            print(f'{i}: log-in fail!!')


    def removeMember(self, i, p):
        del self.members[i]


    def printMembers(self):
        for mk in self.members.keys():
            print(f'ID: {mk}')
            print(f'PW: {self.members[mk]}')

# main 모듈
import member as mb

mems = mb.MemberRepository()

for i in range(3):
    mId = input('아이디 입력: ')
    mPw = input('비밀번호 입력: ')
    mem = mb.Member(mId, mPw)
    mems.addMember(mem)

mems.printMembers()

mems.loginMember('abc@gmail.com', '1234')
mems.loginMember('def@gmail.com', '5678')
mems.loginMember('ghi@gmail.com', '9012')

mems.removeMember('abc@gmail.com', '1234')

mems.printMembers()

클래스 (02)

연습 문제 1.

TV클래스를 다음과 같은 상속 구조로 만들고 객체를 생성해 보자.

A.

# 스마트 티비 클래스
class NormalTv:

    def __init__(self, i=32, c='black', r='full-HD'):
        self.inch = i
        self.color = c
        self.resolution = r
        self.smartTv = 'off'
        self.aiTv = 'off'


    def turnOn(self):
        print('TV power on!!')


    def turnOff(self):
        print('TV power off!!')

    def printTvInfo(self):
        print(f'inch: {self.inch}inch')
        print(f'color: {self.color}')
        print(f'resolution: {self.resolution}')
        print(f'smartTv: {self.smartTv}')
        print(f'aiTv: {self.aiTv}')


class Tv4k(NormalTv):

    def __init__(self, i, c, r='4k'):
        super().__init__(i, c, r)

    def setSmartTv(self, s):
        self.smartTv = s


class Tv8k(NormalTv):

    def __init__(self, i, c, r='8k'):
        super().__init__(i, c, r)

    def setSmartTv(self, s):
        self.smartTv = s

    def setAiTv(self, a):
        self.aiTv = a
        
# main 모듈
import smartTV as st

my4kTv = st.Tv4k('65', 'silver', '4k')
my4kTv.setSmartTv('on')
my4kTv.turnOn()
my4kTv.printTvInfo()
my4kTv.turnOff()

print('=' * 60)

friend4kTv = st.Tv4k('55', 'white', '4k')
friend4kTv.setSmartTv('off')
friend4kTv.turnOn()
friend4kTv.printTvInfo()
friend4kTv.turnOff()


print('=' * 60)

my8kTV = st.Tv8k('75', 'black', '8k')
my8kTV.setSmartTv('on')
my8kTV.setAiTv('on')
my8kTV.turnOn()
my8kTV.printTvInfo()
my8kTV.turnOff()

print('=' * 60)

friend8kTV = st.Tv8k('86', 'red', '8k')
friend8kTV.setSmartTv('on')
friend8kTV.setAiTv('off')
friend8kTV.turnOn()
friend8kTV.printTvInfo()
friend8kTV.turnOff()

클래스 (03)

연습 문제 1.

다음 명세서를 참고해서 도서 관리 프로그램을 만들어보자.

A.

# 도서 관리 클래스
class Book:

    def __init__(self, name, price, isbn):
        self.bName = name
        self.bPrice = price
        self.bIsbn = isbn


class BookRepository:

    def __init__(self):
        self.bDic = {}

    def registBook(self, b):
        self.bDic[b.bIsbn] = b

    def removeBook(self, isbn):
        del self.bDic[isbn]

    def printBooksInfo(self):
        for isbn in self.bDic.keys():
            b = self.bDic[isbn]
            print(f'{b.bName}, {b.bPrice}, {b.bIsbn}')

    def printBookInfo(self, isbn):
        if isbn in self.bDic:
            b = self.bDic[isbn]
            print(f'{b.bName}, {b.bPrice}, {b.bIsbn}')
        else:
            print('Lookup result does not exist.')

# main 모듈
import book as bk

myBRepository = bk.BookRepository()

myBRepository.registBook(bk.Book('python', 20000, '1234567890'))
myBRepository.registBook(bk.Book('java', 25000, '3434232588'))
myBRepository.registBook(bk.Book('c/c++', 27000, '8658735421'))

myBRepository.printBooksInfo()

print()

myBRepository.printBookInfo('1234567890')
myBRepository.printBookInfo('3434232588')
myBRepository.printBookInfo('8658735421')
myBRepository.removeBook('1234567890')

print()

myBRepository.printBooksInfo()

print()
friendBRepository = bk.BookRepository()

friendBRepository.registBook(bk.Book('ruby', 20000, '1234567890'))
friendBRepository.registBook(bk.Book('c#', 25000, '3434232588'))
friendBRepository.registBook(bk.Book('linux', 27000, '8658735421'))

friendBRepository.printBooksInfo()

print()

friendBRepository.printBookInfo('1234567890')
friendBRepository.printBookInfo('3434232588')
friendBRepository.printBookInfo('8658735421')
friendBRepository.removeBook('1234567890')

friendBRepository.printBooksInfo()

클래스 (04)

연습 문제 1.

다음 추상 클래스를 이용해서 한/영, 한/일 사전 클래스를 만들어보자.

A.

# 한영 & 한일 사전 클래스
from abc import ABCMeta
from abc import abstractmethod

class AbsDictionary(metaclass=ABCMeta):

    def __init__(self):
        self.wordDic = {}

    @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'[KorToEng] registWord() : {w1} to {w2}')
        self.wordDic[w1] = w2

    def removeWord(self, w1):
        print(f'[KorToEng] removeWord() : {w1}')
        del self.wordDic[w1]

    def updateWord(self, w1, w2):
        print(f'[KorToEng] updateWord() : {w1} to {w2}')
        self.wordDic[w1] = w2

    def searchWord(self, w1):
        print(f'[KorToEng] searchWord() : {w1}')
        return self.wordDic[w1]

    def printWords(self):
        for k in self.wordDic.keys():
            print(f'{k} = {self.wordDic[k]}')


class KorToJpn(AbsDictionary):

    def __init__(self):
        super().__init__()

    def registWord(self, w1, w2):
        print(f'[KorToJpn] registWord() : {w1} to {w2}')
        self.wordDic[w1] = w2

    def removeWord(self, w1):
        print(f'[KorToJpn] removeWord() : {w1}')
        del self.wordDic[w1]

    def updateWord(self, w1, w2):
        print(f'[KorToJpn] updateWord() : {w1} to {w2}')
        self.wordDic[w1] = w2

    def searchWord(self, w1):
        print(f'[KorToJpn] searchWord() : {w1}')
        return self.wordDic[w1]

    def printWords(self):
        for k in self.wordDic.keys():
            print(f'{k} = {self.wordDic[k]}')
            
# main 모듈
import ADictionary as dic

k2e = dic.KorToEng()

k2e.registWord('책', 'bok')
k2e.registWord('나비', 'butterfly')
k2e.registWord('연필', 'pencil')
k2e.registWord('학생', 'student')
k2e.registWord('선생님', 'teacher')

k2e.printWords()

k2e.updateWord('책', 'book')
k2e.printWords()

print(f'{k2e.searchWord("책")}')
print(f'{k2e.searchWord("나비")}')
print(f'{k2e.searchWord("연필")}')

k2e.removeWord('책')
k2e.printWords()

중급문제풀이 [5]

클래스 (05)

연습 문제 1.

주사위 게임 클래스를 만들고 컴퓨터와 사용자의 게임 결과를 출력해 보자.

A.

# 주사위 게임 클래스
import random as rd


class Dice:

    def __init__(self):
        self.cNum = 0
        self.uNum = 0

    def setCNum(self):
        print('[Dice] setCNum()')
        self.cNum = rd.randint(1, 6)

    def setUNum(self):
        print('[Dice] setUNum()')
        self.uNum = rd.randint(1, 6)

    def startGame(self):
        print('[Dice] startGame()')

        self.setCNum()
        self.setUNum()

    def printResult(self):
        print('[Dice] printResult()')

        if self.cNum == 0 or self.uNum == 0:
            print('주사위 숫자 선정 전 입니다.')

        else:
            if self.cNum > self.uNum:
                print(f'컴퓨터 vs 유저 : {self.cNum} vs {self.uNum} --> 컴퓨터 승!!')
            elif self.cNum < self.uNum:
                print(f'컴퓨터 vs 유저 : {self.cNum} vs {self.uNum} --> 유저 승!!')
            elif self.cNum == self.uNum:
                print(f'컴퓨터 vs 유저 : {self.cNum} vs {self.uNum} -->  무승부!!')
                
# main 모듈
import dice as d

dc = d.Dice()
dc.startGame()
dc.printResult()

클래스 (06)

연습 문제 1.

자동차 경주 게임 클래스를 만들어 보자. 자동차는 랜덤하게 이동하며, 편의상 10초 동안 주행한다고 할 때 가장 멀리 이동한 자동차가 우승하는 게임이다.

A.

# car 클래스
import random

class Car:

    def __init__(self, n='fire car', c='red', s=200):
        self.name = n
        self.color = c
        self.max_speed = s
        self.distance = 0

    def printCarInfo(self):
        print(f'name: {self.name}, color: {self.color}, max_speed: {self.max_speed}')

    def controlSpeed(self):
        return random.randint(0, self.max_speed)

    def getDistanceForHour(self):
        return self.controlSpeed() * 1

# racing 클래스
from time import sleep

class CarRacing:

    def __init__(self):
        self.cars = []
        self.rankings = []

    def startRacing(self):
        for i in range(10):
            print(f'Racing: {i+1}바퀴')
            for car in self.cars:
                car.distance += car.getDistanceForHour()

            sleep(1)
            self.printCurrentCarDistance()

    def printCurrentCarDistance(self):
        for car in self.cars:
            print(f'{car.name}: {car.distance}\t\t', end='')
        print()

    def addCar(self, c):
        self.cars.append(c)

# main 모듈
from car_game import racing as rc
from car_game import car

myCarGame = rc.CarRacing()
car01 = car.Car('Car01', 'White', 250)
car02 = car.Car('Car02', 'Black', 220)
car03 = car.Car('Car03', 'Yellow', 180)
car04 = car.Car('Car04', 'Red', 200)
car05 = car.Car('Car05', 'Blue', 230)

myCarGame.addCar(car01)
myCarGame.addCar(car02)
myCarGame.addCar(car03)
myCarGame.addCar(car04)
myCarGame.addCar(car05)

myCarGame.startRacing()

클래스 (07)

연습 문제 1.

다음과 같이 mp3 플레이어 클래스를 만들고 노래 등록 후 재생해보자.

A.

# mp3 플레이어 클래스
from time import sleep
import random

class Song:

    def __init__(self, t, s, pt):
        self.title = t
        self.singer = s
        self.play_time = pt

    def printSongInfo(self):
        print(f'Tile: {self.title}, Singer: {self.singer}, Play Time: {self.play_time}')


class Player:

    def __init__(self):
        self.songList = []
        self.isLoop = False

    def addSong(self, s):
        self.songList.append(s)

    def play(self):
        if self.isLoop:
            while self.isLoop:
                for s in self.songList:
                    print(f'Tile: {s.title}, Singer: {s.singer}, Play Time: {s.play_time}sec')
                    sleep(s.play_time)

        else:
            for s in self.songList:
                print(f'Tile: {s.title}, Singer: {s.singer}, Play Time: {s.play_time}sec')
                sleep(s.play_time)

    def shuffle(self):
        random.shuffle(self.songList)

    def setIsLoop(self, flag):
        self.isLoop = flag

# main 모듈
import mp3Player as mp3

s1 = mp3.Song('That\'s Love', 'Marc E. Bassy', 3.30)
s2 = mp3.Song('Paranoid', 'Ty Dolla $ign', 3.25)
s3 = mp3.Song('Take it there', 'Tone Stith (feat.Ty Dolla $ign', 3.48)
s4 = mp3.Song('Beep', 'Ant Clemons', 3.18)
s5 = mp3.Song('Demons', 'Imagine Dragons', 3.20)

player = mp3.Player()
player.addSong(s1)
player.addSong(s2)
player.addSong(s3)
player.addSong(s4)
player.addSong(s5)

player.setIsLoop(False)
player.shuffle()
player.play()

예외처리 (01)

연습 문제 1.

사용자가 입력한 숫자를 이용해서 산술연산 결과를 출력하는 모듈을 만들되, 예상하는 예외에 대한 예외처리 코드를 작성해 보자.

A.

# 계산기 모듈
def add(n1, n2):
    print('덧셈 연산')

    try:
        n1 = float(n1)
    except:
        print('첫 번째 피연산자는 숫자가 아닙니다.')
        return

    try:
            n2 = float(n2)
    except:
        print('두 번째 피연산자는 숫자가 아닙니다.')
        return

    print(f'{n1} + {n2} = {n1 + n2}')

def sub(n1, n2):
    print('뺄셈 연산')

    try:
        n1 = float(n1)
    except:
        print('첫 번째 피연산자는 숫자가 아닙니다.')
        return

    try:
            n2 = float(n2)
    except:
        print('두 번째 피연산자는 숫자가 아닙니다.')
        return

    print(f'{n1} - {n2} = {n1 - n2}')

def mul(n1, n2):
    print('곱셈 연산')

    try:
        n1 = float(n1)
    except:
        print('첫 번째 피연산자는 숫자가 아닙니다.')
        return

    try:
            n2 = float(n2)
    except:
        print('두 번째 피연산자는 숫자가 아닙니다.')
        return

    print(f'{n1} * {n2} = {n1 * n2}')

def div(n1, n2):
    print('나눗셈 연산')

    try:
        n1 = float(n1)
    except:
        print('첫 번째 피연산자는 숫자가 아닙니다.')
        return

    try:
            n2 = float(n2)
    except:
        print('두 번째 피연산자는 숫자가 아닙니다.')
        return

    # if n2 == 0:
    #     print('0으로 나눌 수 없습니다.')
    #     return

    try:
        print(f'{n1} / {n2} = {n1 / n2}')
    except ZeroDivisionError as e:
        print(e)
        print('0으로 나눌 수 없습니다.')


def mod(n1, n2):
    print('나머지 연산')

    try:
        n1 = float(n1)
    except:
        print('첫 번째 피연산자는 숫자가 아닙니다.')
        return

    try:
            n2 = float(n2)
    except:
        print('두 번째 피연산자는 숫자가 아닙니다.')
        return

    # if n2 == 0:
    #     print('0으로 나눌 수 없습니다.')
    #     return

    try:
        print(f'{n1} % {n2} = {n1 % n2}')
    except ZeroDivisionError as e:
        print(e)
        print('0으로 나눌 수 없습니다.')


def flo(n1, n2):
    print('몫 연산')

    try:
        n1 = float(n1)
    except:
        print('첫 번째 피연산자는 숫자가 아닙니다.')
        return

    try:
            n2 = float(n2)
    except:
        print('두 번째 피연산자는 숫자가 아닙니다.')
        return

    try:
        print(f'{n1} // {n2} = {n1 // n2}')
    except ZeroDivisionError as e:
        print(e)
        print('0으로 나눌 수 없습니다.')


def exp(n1, n2):
    print('거듭제곱 연산')

    try:
        n1 = float(n1)
    except:
        print('첫 번째 피연산자는 숫자가 아닙니다.')
        return

    try:
            n2 = float(n2)
    except:
        print('두 번째 피연산자는 숫자가 아닙니다.')
        return

    print(f'{n1} ** {n2} = {n1 ** n2}')

# main 모듈
import calculator as cc

num1 = input('첫 번째 피연산자: ')
num2 = input('두 번째 피연산자: ')

cc.add(num1, num2)
cc.sub(num1, num2)
cc.mul(num1, num2)
cc.div(num1, num2)
cc.mod(num1, num2)
cc.flo(num1, num2)
cc.exp(num1, num2)

중급문제풀이 [6-7]

예외처리 (02)

연습 문제 1.

1부터 1000까지의 소수인 난수 10개를 생성하되, 소수가 아니면 사용자 예외가 발생하도록 프로그램을 만들어보자.

A.

# 소수 프로그램
class NotPrimeException(Exception):

    def __init__(self, n):
        super().__init__(f'{n} is not a prime number.')

class IsPrimeException(Exception):

    def __init__(self, n):
        super().__init__(f'{n} is a prime number.')


def isPrime(number):
    flag = True
    for n in range(2, number):
        if number % n == 0:
            flag = False
            break

    if flag == False:
        raise NotPrimeException(number)
    else:
        raise IsPrimeException(number)

# main 모듈
import random
import prime_module as pm

primeNumbers = []

n = 0
while n < 10:

    rn = random.randint(2, 1000)
    if rn not in primeNumbers:

        try:
            pm.isPrime(rn)
        except pm.NotPrimeException as e:
            print(e)
            continue

        except pm.IsPrimeException as e:
            print(e)
            primeNumbers.append(rn)

    else:
        print(f'{rn} is an overlapped number.')
        continue

    n += 1

print(f'prime numbers: {primeNumbers}')

예외처리 (03)

연습 문제 1.

상품 구매에 따른 ‘총 구매 금액’을 출력하되, 다음과 같이 개수가 잘 못 입력된 경우 별도로 출력하도록 프로그램을 만들어보자.

A.

# 구매 프로그램
g1Price = 1200;
g2Price = 1000;
g3Price = 800
g4Price = 2000;
g5Price = 900


def formattedNumber(n):
    return format(n, ',')


def calculator(*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.keys():
        totalPrice += globals()[f'{g}Price'] * gcsDic[g]

    print('-' * 70)
    print(f'총 구매 금액: {formattedNumber(totalPrice)}원')
    print('-' * 30, '미결제 항목', '-' * 30)
    for g in againCntInput.keys():
        print(f'상품: {g}, \t 구매 개수: {againCntInput[g]}')
    print('-' * 70)

# main 모듈
import calculatorPurchase as cp

g1Cnt = input('goods1 구매 개수: ')
g2Cnt = input('goods2 구매 개수: ')
g3Cnt = input('goods3 구매 개수: ')
g4Cnt = input('goods4 구매 개수: ')
g5Cnt = input('goods5 구매 개수: ')

cp.calculator(g1Cnt, g2Cnt, g3Cnt, g4Cnt, g5Cnt)

예외처리 (04)

연습 문제 1.

회원가입 프로그램을 만들되 입력하지 않은 항목이 있는 경우 에러 메시지를 출력하는 프로그램을 만들어보자.

A.

# 회원가입 프로그램
class EmptyDataException(Exception):

    def __init__(self, i):
        super().__init__(f'{i} is empty!')

def checkInputData(n, m, p, a, ph):

    if n == '':
        raise EmptyDataException('name')

    elif m == '':
        raise EmptyDataException('mail')

    elif p == '':
        raise EmptyDataException('password')

    elif a == '':
        raise EmptyDataException('address')

    elif ph == '':
        raise EmptyDataException('phone')


class RegistMember():

    def __init__(self, n, m, p, a, ph):
        self.m_name = n
        self.m_mail = m
        self.m_pw = p
        self.m_addr = a
        self.m_phone = ph
        print('Membership Register Complete!')

    def printMemberInfo(self):
        print(f'm_name: {self.m_name}')
        print(f'm_mail: {self.m_mail}')
        print(f'm_pw: {self.m_pw}')
        print(f'm_addr: {self.m_addr}')
        print(f'm_phone: {self.m_phone}')
        
# main 모듈
import mem

m_name = input('이름 입력: ')
m_mail = input('메일 주소 입력: ')
m_pw = input('비밀번호 입력: ')
m_addr = input('주소 입력: ')
m_phone = input('연락처 입력: ')

try:
    mem.checkInputData(m_name, m_mail, m_pw, m_addr, m_phone)
    newMember = mem.RegistMember(m_name, m_mail, m_pw, m_addr, m_phone)
    newMember.printMemberInfo()
except mem.EmptyDataException as e:
    print(e)

예외처리 (05)

연습 문제 1.

다음과 같은 은행 계좌 계설 및 입/출금 프로그램을 만들어 보자.

A.

# 은행 입/출금 프로그램
import random

class PrivateBank:

    def __init__(self, bank, account_name):
        self.bank = bank
        self.account_name = account_name

        while True:
            newAccountNo = random.randint(10000, 99999)
            if bank.isAccount(newAccountNo):
                continue
            else:
                self.account_no = newAccountNo
                break

        self.totalMoney = 0
        bank.addAccount(self)

    def printBankInfo(self):
        print('-' * 60)
        print(f'account_name" {self.account_name}')
        print(f'account_no" {self.account_no}')
        print(f'totalMoney" {self.totalMoney}')
        print('-' * 60)

class Bank:

    def __init__(self):
        self.accounts = {}

    def addAccount(self, privateBank):
        self.accounts[privateBank.account_no] = privateBank

    def isAccount(self, ano):
        return ano in self.accounts

    def doDeposit(self, ano, m):
        pb = self.accounts[ano]
        pb.totalMoney = pb.totalMoney + m

    def dopWithdraw(self, ano, m):
        pb = self.accounts[ano]
        if pb.totalMoney - m < 0:
            raise LackException(pb.totalMoney, m)
        pb.totalMoney = pb. totalMoney - m


class LackException(Exception):

    def __init__(self, m1, m2):
        super().__init__(f'잔고 부족!! 잔액: {m1}, 총금액: {m2}')
        
# main 모듈
import bank

koreaBank = bank.Bank()

new_account_name = input('통장 개설을 위한 예금주 입력: ')
myAccount = bank.PrivateBank(koreaBank, new_account_name)
myAccount.printBankInfo()

while True:

    selectNumber = int(input('1. 현금 \t 2.출금 \t 3.종료 : '))
    if selectNumber == 1:
        m = int(input('입금액 입력: '))
        koreaBank.doDeposit(myAccount.account_no, m)
        myAccount.printBankInfo()

    elif selectNumber == 2:
        m = int(input('출금액 입력: '))
        try:
            koreaBank.dopWithdraw(myAccount.account_no, m)

        except bank.LackException as e:
            print(e)

        finally:
            myAccount.printBankInfo()

    elif selectNumber == 3:
        print('Bye')
        break

    else:
        print('잘 못 입력하셨습니다. 다시 선택해주세요.')

텍스트 파일 (01)

연습 문제 1.

회원 계정별 텍스트 파일을 생성한 후 회원 본인 파일에 ‘한 줄 일기’를 쓰고 읽는 프로그램을 만들어보자.

A.

# 일기 프로그램
import time
def writeDiary(u, f, d):
    lt = time.localtime()
    timeStr = time.strftime('%Y-%m-%d %I:%M:%S %p', lt)

    filePath = u + f
    with open(filePath, 'a') as f:
        f.write(f'[{timeStr}] {d}\n')


def readDiary(u, f):
    filePath = u + f
    datas = []
    with open(filePath, 'r') as f:
        datas = f.readlines()

    return datas

# main 모듈
import diary

members = {}
uri = '/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/'

def printMembers():
    for m in members.keys():
        print(f'ID: {m} \t PW: {members[m]}')

while True:
    selectNum = int(input('1.회원가입, 2.한줄읽기쓰기, 3.일기보기, 4.종료 : '))

    if selectNum == 1:
        mId = input('Input ID: ')
        mPw = input('Input PW: ')
        members[mId] = mPw

    elif selectNum == 2:
        mId = input('Input ID: ')
        mPw = input('Input PW: ')

        if mId in members and members[mId] == mPw:
            print('Login Success!')
            fileName = 'myDiary_' + mId + '.txt'
            data = input('오늘 하루 인상 깊은 일을 기록하세요. ')
            diary.writeDiary(uri, fileName, data)

        else:
            print('Login Fail!')
            printMembers()

    elif selectNum == 3:
        mId = input('Input ID: ')
        mPw = input('Input PW: ')

        if mId in members and members[mId] == mPw:
            print('Login Success!')
            fileName = 'myDiary_' + mId + '.txt'
            datas = diary.readDiary(uri, fileName)
            for d in datas:
                print(d, end='')

        else:
            print('Login Fail!')

    elif selectNum == 4:
        print('Bye!')
        break

중급문제풀이 [8]

텍스트 파일 (02)

연습 문제 1.

텍스트 파일에 수입과 지출을 기록하는 가계부를 만들어보자.

A.

import time

def getTime():
    lt = time.localtime()
    st = time.strftime('%Y-%m-%d %H:%M:%S')
    return st


while True:

    selectNum = int(input('1.입금, \t2.출금, \t3.종료\t'))

    if selectNum == 1:
        money = int(input('입금액 입력: '))
        with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/money.txt', 'r') as f:
            m = f.read()

        with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/money.txt', 'w') as f:
            f.write(str(int(m) + money))

        memo = input('입금 내역 입력: ')
        with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/pocketMoneyRegister.txt', 'a') as f:
            f.write('----------------------------------------------\n')
            f.write(f'{getTime()}\n')
            f.write(f'[입금] {memo} : {str(money)}원\n')
            f.write(f'[잔액] : {str(int(m) + money)}원\n')

        print('입금 완료!!')
        print(f'기존 잔액: {m}')
        print(f'입금 후 잔액 : {int(m) + money}')



    elif selectNum == 2:
        money = int(input('출금액 입력: '))
        with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/money.txt', 'r') as f:
            m = f.read()

        with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/money.txt', 'w') as f:
            f.write(str(int(m) - money))

        memo = input('출금 내역 입력: ')
        with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/pocketMoneyRegister.txt', 'a') as f:
            f.write('----------------------------------------------\n')
            f.write(f'{getTime()}\n')
            f.write(f'[출금] {memo} : {str(money)}원\n')
            f.write(f'[잔액] : {str(int(m) - money)}원\n')

        print('출금 완료!!')
        print(f'기존 잔액: {m}')
        print(f'출금 후 잔액 : {int(m) - money}')


    elif selectNum == 3:
        print('Bye~')
        break

    else:
        print('잘 못 입력하셨습니다. 다시 입력해주세요.')

텍스트 파일 (03)

연습 문제 1.

사용자가 입력한 숫자의 약수를 텍스트 파일에 기록해 보자

A.

inputNum = int(input('0보다 큰 정수 입력: '))

divisor = []
for number in range(1, (inputNum +1)):
    if inputNum % number == 0:
        divisor.append(number)

if len(divisor) > 0:
    try:
        with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/divisor.txt', 'a') as f:
            f.write(f'{inputNum}의 약수: ')
            f.write(f'{divisor}\n')

    except Exception as e:
        print(e)

    else:
        print('divisor write complete!')
### 연습 문제 2.

사용자가 입력한 숫자까지의 소수를 텍스트 파일에 기록해 보자.

A.

inputNum = int(input('0보다 큰 정수 입력: '))

prime = []
for number in range(2, (inputNum +1)):
    flag = True
    for n in range(2, number):
        if number % n == 0:
            flag = False
            break

    if flag:
        prime.append(number)

if len(prime) > 0:
    try:
        with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/prime.txt', 'a') as f:
            f.write(f'{inputNum}까지의 소수: ')
            f.write(f'{prime}\n')

    except Exception as e:
        print(e)

    else:
        print('prime number write complete!')

텍스트 파일 (04)

연습 문제 1.

두 개의 수를 입력하면 공약수를 텍스트 파일에 작성해보자.

A.

num1 = int(input('1보다 큰 정수 입력: '))
num2 = int(input('1보다 큰 정수 입력: '))

common = []

for i in range(1, (num1 +1)):
    if num1 % i == 0 and num2 % i == 0:
        common.append(i)

if len(common) > 0:
    try:
        with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/common.txt', 'a') as f:
            f.write(f'{num1}{num2}의 공약수 :')
            f.write(f'{common}\n')

    except Exception as e:
        print(e)

    else:
        print('common factor write complete!!')

연습 문제 2.

두 개의 수를 입력하면 최대공약수를 텍스트 파일에 작성해보자.

A.

num1 = int(input('1보다 큰 정수 입력: '))
num2 = int(input('1보다 큰 정수 입력: '))

maxCoNum = []

for i in range(1, (num1 +1)):
    if num1 % i == 0 and num2 % i == 0:
        maxCoNum = i

try:
    with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/maxCoNum.txt', 'a') as f:
        f.write(f'{num1}{num2}의 공약수 : {maxCoNum}\n')
except Exception as e:
    print(e)

else:
    print('max common factor write complete!!')

텍스트 파일 (05)

연습 문제 1.

섬마을에 과일, 생선, 야채를 판매하는 배가 다음 주기로 입항한다고 할 때, 모든 배가 입항하는 날짜를 텍스트 파일에 기록해보자. (첫 입항일은 2021년 1월 1일 오전 10시로 한다.)

A.

ship1 = 3
ship2 = 4
ship3 = 5
maxDay = 0

for i in range(1, (ship1 + 1)):
    if ship1 % i == 0 and ship2 % i == 0:
        maxDay = i

minDay = (ship1 * ship2) // maxDay

newDay = minDay
for i in range(1, (newDay + 1)):
    if newDay % i == 0 and ship3 % i == 0:
        maxDay = i

minDay = (newDay * ship3) // maxDay

print(f'minDay: {minDay}')
print(f'maxDay: {maxDay}')

from datetime import datetime
from datetime import timedelta

n = 1
baseTime = datetime(2021, 1, 1, 10, 0, 0)

with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/arrival.txt', 'a') as f:
    f.write(f'2023년 모든 선박 입항일\n')
    f.write(f'{baseTime}\n')

nextTime = baseTime + timedelta(days=minDay)
while True:

    with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/arrival.txt', 'a') as f:
        f.write(f'{nextTime}\n')

    nextTime = nextTime + timedelta(days=minDay)
    if nextTime.year > 2021:
        break

이상 데이터 취업 스쿨 Day 7의 스터디노트이다.





이미지 출처: @waterglasstoon, 제로베이스 강의 일부

profile
On My Way

0개의 댓글