[연습 문제] 모듈

JERRY·2025년 1월 2일
0

Python

목록 보기
14/35
post-thumbnail

01

passOrFail module

# 01
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()


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

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




# 02
def exampleResult(*s):

    passAvgScore = 60
    limitScore = 40

    def getTotal():
        totalScore = sum(s)
        print(f'총점: {totalScore}')
        return totalScore

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

    def printPassOrFail():
        for idx, score in enumerate(s):
            print(f'과목{idx+1}: Pass') if score >= limitScore else print(f'과목{idx+1}: Fail')

    def printFinalPassOrFail():

        result = 'Final Pass!!'

        if getAverage() >= passAvgScore:
            for idx, score in enumerate(s):
                if score < limitScore:
                    result = 'Final Fail!!'
                    break
        else:
            result = 'Final Fail!!'

        print(result)

    getAverage()
    printPassOrFail()
    printFinalPassOrFail()


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

실행파일

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

discount module

def calculatorTotalPrice(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)]


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

실행파일

import  discount as dc

if __name__ == '__main__':
    flag = True
    gs = []

    while flag:
        selectNumber = int(input('상품을 구매 하시겠어요? 1.구매 2.종료 '))

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

        elif selectNumber == 2:
            result = dc.calculatorTotalPrice(gs)
            flag = False


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

03

startLotto module

import random

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

def setUserNums(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 setBonuNum():
    global randBonuNum

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

def getBonuNum():
    return randBonuNum

def lottoResult():
    global userNums
    global randNums
    global collNums

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

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

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

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

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

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

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


def startLotto():
    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]

    setUserNums(selectNums)
    setRandNums()
    setBonuNum()

    lottoResult()

실행파일

import lotto as lt

lt.startLotto()

04

permutation module

# 01
def getPermutaionCnt(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


# 02
from itertools import permutations

def getPermutaions(ns, r):

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

    for n in permutations(ns, r):
        print(n, end=', ')



if __name__ == '__main__':
    numN = int(input('numN 입력: '))
    numR = int(input('numR 입력: '))


    print(f'{numN}P{numR}: {getPermutaionCnt(numN, numR, logPrint=False)}')

    ns = [1, 2, 3, 4, 5, 6, 7, 8]
    getPermutaions(ns, 3)

실행파일

import permutation as pt

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

# print(f'{numN}P{numR}: {pt.getPermutaionCnt(numN, numR)}')
print(f'{numN}P{numR}: {pt.getPermutaionCnt(numN, numR, logPrint=False)}')



listVar = [1, 2, 3, 4, 5, 6, 7, 8]
rVar = 3
pt.getPermutaions(listVar, rVar)

05

combination module

# 01
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('resultP : {}'.format(resultP))


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

    resultC = int(resultP / resultR)
    if logPrint: print('resultC: {}'.format(resultC))

    return resultC


# 02
from itertools import combinations

def getCombinations(ns, r):

    cList = list(combinations(ns, r))
    print(f'{len(ns)}C{r} 개수: {len(cList)}')

    for n in combinations(ns, r):
        print(n, end=', ')



if __name__ == '__main__':
    numN = int(input('numN 입력: '))
    numR = int(input('numR 입력: '))


    print(f'{numN}C{numR}: {getCombinationCnt(numN, numR, logPrint=False)}')

    ns = [1, 2, 3, 4, 5, 6, 7, 8]
    getCombinations(ns, 3)

실행파일

import combination as ct

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

# print(f'{numN}C{numR}: {ct.getCombinationCnt(numN, numR)}')
print(f'{numN}C{numR}: {ct.getCombinationCnt(numN, numR, logPrint=False)}')



listVar = [1, 2, 3, 4, 5, 6, 7, 8]
rVar = 3
ct.getCombinations(listVar, rVar)

06

utilityBill module

income = 0
waterPrice = 0; electricPrice = 0; gasPrice = 0

def setIncome(ic):
    global income
    income = ic

def getIncome():
    return income

def setWaterPrice(wp):
    global waterPrice
    waterPrice = wp

def setElectricPrice(ep):
    global electricPrice
    electricPrice = ep

def setGasPrice(gp):
    global gasPrice
    gasPrice = gp

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

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

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

실행파일

import utilityBill as ub

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

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

inputElectricPrice = int(input('전기요금 입력: '))
ub.setElectricPrice(inputElectricPrice)

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

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

07

arithmetic Package(basic_operator/developer_oerator module)

# arithmetic - 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)
# arithmetic - developer_oerator

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)

shape Package(triangle_square_area/circle_area module)

# shape - triangle_square_area

def calTriangleArea(w, h):
    return round(w * h / 2, 2)

def calSquareArea(w, h):
    return round(w * h, 2)
# shape - circle_area

def calCircleArea(r):
    return round(r ** 2 * 3.14, 2)

실행파일

from arithmetic import basic_operator as bo
from arithmetic import developer_oerator as do

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


inputNumber1 = float(input('숫자1 입력: '))
inputNumber2 = float(input('숫자2 입력: '))

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

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


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

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

inputRadius = float(input('반지름 입력: '))
print(f'사각형 넓이: {ca.calCircleArea(inputRadius)}')

0개의 댓글