Ch4 알고리즘 문제풀이 39-50 (알고문풀3-5)

김민지·2023년 3월 26일
0
  1. 최댓값 알고리즘
  • 클래스 모듈 만들어 사용
class MaxAlgorithm:

    def __init__(self, ns):
        self.nums = ns
        self.maxNum = 0
        self.maxNumCnt = 0

    def setMaxNum(self):
        self.maxNum = 0

        for n in self.nums:
            if self.maxNum < n:
                self.maxNum = n

    def getMaxNum(self):
        self.setMaxNum()
        return self.maxNum

    def setMaxNumCnt(self):
        self.setMaxNum()

        for n in self.nums:
            if self.maxNum == n:
                self.maxNumCnt += 1

    def getMaxNumCnt(self):
        self.setMaxNumCnt()
        return self.maxNumCnt
  • 실행파일
import random
import maxMod

if __name__ == '__main__':
    nums = []
    for n in range(30):
        nums.append(random.randint(1, 50))

    print(f'nums: {nums}')

    ma = maxMod.MaxAlgorithm(nums)

    print(f'max num: {ma.getMaxNum()}')
    print(f'max num count: {ma.getMaxNumCnt()}')
  • 평균,최댓값,편차 구하는 함수
def getAvg(ns):

    total = 0
    for n in ns:
        total += n

    return total / len(ns)

def getMax(ns):

    maxNum = ns[0]
    for n in ns:
        if maxNum < n:
            maxNum = n

    return maxNum

def getDeviation(n1, n2):
    return round(abs(n1 - n2), 2)
  • 실행파일
import mod

scores = [100, 64, 94, 66, 75, 58, 99, 76, 96, 74,
          54, 73, 88, 70, 68, 50, 95, 89, 69, 98]

scores_avg = mod.getAvg(scores)
scores_max = mod.getMax(scores)

deviation = mod.getDeviation(scores_avg, scores_max)

print(f'scores_avg: {scores_avg}')
print(f'scores_max: {scores_max}')
print(f'deviation: {deviation}')
  1. 최솟값 알고리즘
  • 클래스모듈 만들어 사용
class MinAlgorithm:

    def __init__(self, ns):
        self.nums = ns
        self.minNum = 0
        self.minNumCnt = 0

    def setMinNum(self):
        self.minNum = 51

        for n in self.nums:
            if self.minNum > n:
                self.minNum = n

    def getMinNum(self):
        self.setMinNum()
        return self.minNum


    def setMinNumCnt(self):
        self.setMinNum()

        for n in self.nums:
            if self.minNum == n:
                self.minNumCnt += 1

    def getMinNumCnt(self):
        self.setMinNumCnt()
        return self.minNumCnt
import random
import minMod

if __name__ == '__main__':

    nums = []
    for n in range(30):
        nums.append(random.randint(1, 50))

    print(f'nums: {nums}')

    ma = minMod.MinAlgorithm(nums)
    minNum = ma.getMinNum()
    minNumCnt = ma.getMinNumCnt()

    print(f'minNum: {minNum}')
    print(f'minNumCnt: {minNumCnt}')
  • 평균,최솟값,편차 구하기
def getAvg(ns):

    total = 0
    for n in ns:
        total += n

    return total / len(ns)

def getMin(ns):      # 최솟값 구하기

    minN = ns[0]
    for n in ns:
        if minN > n:
            minN = n

    return minN

def getDeviation(n1, n2):
    return round(abs(n1 - n2), 2)

def getMaxOrMin(ns, maxFlag=True):   # 최솟값,최댓값 선택해서 구할 수 있는 함수

    resultN = ns[0]

    for n in ns:
        if maxFlag:
            if resultN < n:
                resultN = n
        else:
            if resultN > n:
                resultN = n

    return resultN
  • 실행파일
import mod

scores = [100, 64, 94, 66, 75, 58, 99, 76, 96, 74,
          54, 73, 88, 70, 68, 50, 95, 89, 69, 98]

scores_avg = mod.getAvg(scores)
scores_min = mod.getMaxOrMin(scores, maxFlag=False)
scores_max = mod.getMaxOrMin(scores, maxFlag=True)

deviation = mod.getDeviation(scores_avg, scores_min)


print(f'scores_avg: {scores_avg}')
print(f'scores_min: {scores_min}')
print(f'scores_max: {scores_max}')

print(f'min deviation: {deviation}')
  • 클래스 만들기
class ScoreManagement:

    def __init__(self, ss):
        self.scores = ss
        self.score_min = 0
        self.score_max = 0
        self.score_total = 0
        self.score_avg = 0


    def getMinScore(self):
        if self.scores == None or len(self.scores) == 0:
            return None

        self.score_min = self.scores[0]
        for score in self.scores:
            if self.score_min > score:
                self.score_min = score

        return self.score_min


    def getMaxScore(self):
        if self.scores == None or len(self.scores) == 0:
            return None

        self.score_max = self.scores[0]
        for score in self.scores:
            if self.score_max < score:
                self.score_max = score

        return self.score_max


    def getTotalScore(self):
        if self.scores == None or len(self.scores) == 0:
            return None

        self.score_total = 0
        for score in self.scores:
            self.score_total += score

        return self.score_total

    def getAvgScore(self):
        if self.scores == None or len(self.scores) == 0:
            return None

        self.score_avg = round(self.getTotalScore() / len(self.scores), 2)

        return self.score_avg


    def getMaxDeviation(self):
        result = abs(self.getAvgScore() - self.getMaxScore())
        return round(result, 2)

    def getMinDeviation(self):
        result = abs(self.getAvgScore() - self.getMinScore())
        return round(result, 2)
  • 실행파일
scores = [100, 64, 94, 66, 75, 58, 99, 76, 96, 74,
          54, 73, 88, 70, 68, 50, 95, 89, 69, 98]

import mod2

sm = mod2.ScoreManagement(scores)
print(f'score_avg: {sm.getAvgScore()}')
print(f'score_min: {sm.getMinScore()}')
print(f'score_max: {sm.getMaxScore()}')
print(f'score_min_deviation: {sm.getMinDeviation()}')
print(f'score_max_deviation: {sm.getMaxDeviation()}')
  1. 최빈값 알고리즘
  • 최댓값 구하는 모듈
class MaxAlgorithm:

    def __init__(self, ns):
        self.nums = ns
        self.maxNum = 0
        self.maxNumIdx = 0

    def setMaxIdxAndNum(self):
        self.maxNum = 0
        self.maxNumIdx = 0

        for i, n in enumerate(self.nums):
            if self.maxNum < n:
                self.maxNum = n
                self.maxNumIdx = i

    def getMaxNum(self):
        return self.maxNum

    def getMaxNumIdx(self):
        return self.maxNumIdx
  • 최빈값 구하고 이쁘게 출력하는 모듈
import maxMod
class ModeAlgorithm:

    def __init__(self, ns, mn):
        self.nums = ns
        self.maxNum = mn
        self.indexes = []

    def setIndexList(self):
        self.indexes = [0 for i in range(self.maxNum + 1)]

        for n in self.nums:
            self.indexes[n] += 1

    def getIndexList(self):
        if sum(self.indexes) == 0:
            return None
        else:
            return self.indexes

    def printAges(self):

        n = 1
        while True:

            maxAlgo = maxMod.MaxAlgorithm(self.indexes)
            maxAlgo.setMaxIdxAndNum()
            maxNum = maxAlgo.getMaxNum()
            maxNumIdx = maxAlgo.getMaxNumIdx()

            if maxNum == 0:
                break

            print(f'[{n:0>3}] {maxNumIdx}세 빈도수: {maxNum} \t', end='')
                     #3자리로 맞추고 오른쪽정렬(>), 빈자리는 0으로 채움
            print('+' * maxNum)
            self.indexes[maxNumIdx] = 0

            n += 1    
  • 실행파일
import modeMod
import maxMod

ages = [25, 27, 27, 24, 31, 34, 33, 31, 29, 25,
        45, 37, 38, 46, 47, 22, 24, 29, 33, 35,
        27, 34, 37, 40, 42, 29, 27, 25, 26, 27,
        31, 31, 32, 38, 25, 27, 28, 40, 41, 34]

print(f'employee cnt: {len(ages)}명')

maxAlgo = maxMod.MaxAlgorithm(ages)
maxAlgo.setMaxIdxAndNum()
maxAge = maxAlgo.getMaxNum()
print(f'maxAge: {maxAge}')

modAlgo = modeMod.ModeAlgorithm(ages, maxAge)
modAlgo.setIndexList()
print(f'IndexList: {modAlgo.getIndexList()}')

modAlgo.printAges()
  • 출력결과
employee cnt: 40명
maxAge: 47
IndexList: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 4, 1, 6, 1, 3, 0, 4, 1, 2, 3, 1, 0, 2, 2, 0, 2, 1, 1, 0, 0, 1, 1, 1]
[001] 27세 빈도수: 6 	++++++
[002] 25세 빈도수: 4 	++++
[003] 31세 빈도수: 4 	++++
[004] 29세 빈도수: 3 	+++
[005] 34세 빈도수: 3 	+++
[006] 24세 빈도수: 2 	++
[007] 33세 빈도수: 2 	++
[008] 37세 빈도수: 2 	++
[009] 38세 빈도수: 2 	++
[010] 40세 빈도수: 2 	++
[011] 22세 빈도수: 1 	+
[012] 26세 빈도수: 1 	+
[013] 28세 빈도수: 1 	+
[014] 32세 빈도수: 1 	+
[015] 35세 빈도수: 1 	+
[016] 41세 빈도수: 1 	+
[017] 42세 빈도수: 1 	+
[018] 45세 빈도수: 1 	+
[019] 46세 빈도수: 1 	+
[020] 47세 빈도수: 1 	+
  • 로또 30회차분의 번호 빈도수 구하기
class LottoMode:

    def __init__(self, ln):
        self.lottoNums = ln
        self.modeList = [0 for n in range(1, 47)]

    def getLottoNumMode(self):

        for roundNums in self.lottoNums:
            for num in roundNums:
                self.modeList[num] += 1

        return self.modeList


    def printModeList(self):
        if sum(self.modeList) == 0:    # 빈도수를 구한후에만 실행되도록 함
            return None

        for i, m in enumerate(self.modeList):
            if i != 0:   # 0번은 로또번호에 없기때문에 의미없음
                print(f'번호: {i:>2}, 빈도수: {m}, {"*" * m}')
import mod

lottoNums = [[13, 23, 15, 5, 6, 39], [36, 13, 5, 3, 30, 16], [43, 1, 15, 9, 3, 38],
             [32, 42, 24, 45, 8, 31], [18, 39, 41, 11, 4, 9], [12, 39, 11, 38, 32, 5],
             [29, 25, 13, 6, 14, 8], [21, 33, 19, 20, 42, 7], [6, 28, 3, 45, 41, 24],
             [42, 15, 8, 5, 35, 4], [14, 4, 35, 24, 29, 3], [15, 20, 6, 37, 34, 39],
             [27, 5, 32, 15, 25, 19], [45, 25, 2, 8, 30, 43], [4, 19, 33, 10, 6, 24],
             [25, 26, 45, 23, 24, 16], [33, 28, 45, 21, 38, 24], [4, 30, 29, 28, 32, 38],
             [11, 28, 12, 2, 42, 3], [40, 29, 16, 8, 9, 28], [6, 9, 37, 30, 3, 35],
             [29, 18, 41, 28, 38, 15], [9, 31, 13, 44, 1, 36], [36, 1, 37, 32, 15, 12],
             [41, 32, 16, 6, 26, 33], [12, 43, 10, 29, 39, 9], [41, 9, 23, 35, 18, 17],
             [35, 38, 3, 28, 36, 31], [21, 44, 4, 29, 18, 7], [20, 23, 6, 2, 34, 44]]


lm = mod.LottoMode(lottoNums)
mList = lm.getLottoNumMode()
print(f'mList: {mList}')

lm.printModeList()
  1. 근삿값 알고리즘
  • 수심에 따른 온도(근삿값) 구하기
class NearAlgorithm:

    def __init__(self, d):
        self.temps = {0: 24, 5: 22, 10: 20, 15: 16, 20: 13, 25: 10, 30: 6}
        self.depth = d
        self.nearNum = 0
        self.minNum = 24     # 최댓값으로 일단 설정해 놓음

    def getNearNumbers(self):

        for n in self.temps.keys():
            absNum = abs(n - self.depth)
            if absNum < self.minNum:
                self.minNum = absNum
                self.nearNum = n

        return self.temps[self.nearNum]
import nearMod

depth = int(float(input('input depth: ')))  # float형태도 받을 수 있도록 설정
print(f'depth: {depth}')

na = nearMod.NearAlgorithm(depth)
temp = na.getNearNumbers()
print(f'water temperature: {temp}도')
  • BMI 수치 구하고 근삿값으로 상태 구하기
class BmiAlgorithm:

    def __init__(self, w, h):
        self.BMISection = {18.5: ['저체중', '정상'],
                           23: ['정상', '과체중'],
                           25: ['과체중', '비만']}
        self.userWeight = w
        self.userHeight = h
        self.userBMI = 0
        self.userCondition = ''
        self.nearNum = 0
        self.minNum = 25


    def calculatorBMI(self):
        self.userBMI = round(self.userWeight / (self.userHeight ** 2), 2)
        print(f'self.userBMI: {self.userBMI}')

    def printUserCondition(self):

        for n in self.BMISection.keys():
            absNum = abs(n - self.userBMI)
            if absNum < self.minNum:
                self.minNum = absNum
                self.nearNum = n

        print(f'self.nearNum: {self.nearNum}')

        if self.userBMI <= self.nearNum:
            self.userCondition = self.BMISection[self.nearNum][0]
        else:
            self.userCondition = self.BMISection[self.nearNum][1]

        print(f'self.userCondition: {self.userCondition}')
import nearMod

uWeight = float(input('input weight(kg): '))
uHeight = float(input('input height(m): '))

na = nearMod.BmiAlgorithm(uWeight, uHeight)
na.calculatorBMI()
na.printUserCondition()
  1. 재귀 알고리즘
  • 전월 대비 매출 증감액 구하기
sales = [12000, 13000, 12500, 11000, 10500, 98000, 91000, 91500, 10500, 11500, 12000, 12500]

def salesUpAndDown(ss):
    if len(ss) == 1:
        return ss

    print(f'sales: {ss}')

    currentSales = ss.pop(0)
    nextSales = ss[0]

    increase = nextSales - currentSales
    if increase > 0:
        increase = '+' + str(increase)
    print(f'매출 증감액: {increase}')

    return salesUpAndDown(ss)


if __name__ == '__main__':
    salesUpAndDown(sales)
  • 입력한 두 정수 사이에 있는 모든 정수들의 합 구하기
class NumsSum:

    def __init__(self, n1, n2):
        self.bigNum = 0
        self.smallNum = 0
        self.setN1N2(n1, n2)

    def setN1N2(self, n1, n2):
        self.bigNum = n1
        self.smallNum = n2

        if n1 < n2:
            self.bigNum = n2
            self.smallNum = n1

    def addNum(self, n):  # 1부터 n까지의 합 구하기
        if n <= 1:
            return n

        return n + self.addNum(n - 1)


    def sumBetweenNums(self):
        return self.addNum(self.bigNum - 1) - self.addNum(self.smallNum)
    # 두 수 사이의 정수들의 합은 1부터 큰 수-1까지의 합에서 1부터 작은수까지의 합을 뺀것과 같다.
    # (1+2+...+(n2-1)) - (1+2+...+n1) = (n1+1) + (n1+2) + ... +(n2-1)
import mod

num1 = int(input('input number1: '))
num2 = int(input('input number2: '))

ns = mod.NumsSum(num1, num2)
result = ns.sumBetweenNums()
print(f'result: {result}')
  1. 평균 알고리즘
  • 점수들 중 최댓값, 최솟값을 제외한 나머지 점수 평균 구하고 기준순위와 비교하여(근삿값) 순위 정하기
  • 최솟값, 최댓값 구하고 제외하는 알고리즘
class MinAlgorithm:

    def __init__(self, ss):
        self.scores = ss
        self.minScore = 0
        self.minIdx = 0

    def removeMinScore(self):
        self.minScore = self.scores[0]

        for i, s in enumerate(self.scores):
            if self.minScore > s:
                self.minScore = s
                self.minIdx = i

        print(f'self.minScore: {self.minScore}')
        print(f'self.minIdx: {self.minIdx}')

        self.scores.pop(self.minIdx)
        print(f'scores: {self.scores}')
class MaxAlgorithm:

    def __init__(self, ss):
        self.scores = ss
        self.maxScore = 0
        self.maxIdx = 0

    def removeMaxScore(self):
        self.maxScore = self.scores[0]

        for i, s in enumerate(self.scores):
            if self.maxScore < s:
                self.maxScore = s
                self.maxIdx = i

        print(f'self.maxScore: {self.maxScore}')
        print(f'self.maxIdx: {self.maxIdx}')

        self.scores.pop(self.maxIdx)
        print(f'scores: {self.scores}')
  • 근삿값 구하고 Top5 갱신하는 알고리즘
class Top5Players:

    def __init__(self, cts, ns):
        self.currentScores = cts
        self.newScore = ns

    def setAlignScore(self):
        nearIdx = 0
        minNum = 10.0

        for i, s in enumerate(self.currentScores):
            absNum = abs(self.newScore - s)
            if absNum < minNum:
                minNum = absNum
                nearIdx = i

        if self.newScore >= self.currentScores[nearIdx]:
            for i in range(len(self.currentScores)-1, nearIdx, -1):
                self.currentScores[i] = self.currentScores[i-1]
            self.currentScores[nearIdx] = self.newScore
        else:
            for i in range(len(self.currentScores)-1, nearIdx+1, -1):
                self.currentScores[i] = self.currentScores[i-1]
            self.currentScores[nearIdx+1] = self.newScore

    def getFinalTop5Scores(self):
        return self.currentScores
  • 실행파일
import maxAlgorithm
import minAlgorithm
import nearAlgorithm

top5Scores = [9.12, 8.95, 8.12, 6.90, 6.18]
scores = [6.7, 5.9, 8.1, 7.9, 6.7, 7.3, 7.2, 8.2, 6.2, 5.8]
print(f'scores: {scores}')

maxA = maxAlgorithm.MaxAlgorithm(scores)
maxA.removeMaxScore()

minA = minAlgorithm.MinAlgorithm(scores)
minA.removeMinScore()

total = 0
average = 0
for n in scores:
    total += n
average = round(total / len(scores), 2)

print(f'total: {round(total, 2)}')
print(f'average: {average}')

tp = nearAlgorithm.Top5Players(top5Scores, average)
tp.setAlignScore()
top5PlayerScores = tp.getFinalTop5Scores()
print(f'top5PlayerScores: {top5PlayerScores}')

-> 복잡!!!!!

  • 전체 학생 평균점수에서 홍길동 학생을 제외한 나머지의 평균 구하고 홍길동 점수와의 차이 출력하기
kor_avg = 88; eng_avg = 82; mat_avg = 90
sci_avg = 78; his_avg = 92

hong_kor_score = 85; hong_eng_score = 90; hong_mat_score = 82
hong_sci_score = 88; hong_his_score = 100

stu19Cnt_kor_total = kor_avg * 20 - hong_kor_score
stu19Cnt_eng_total = eng_avg * 20 - hong_eng_score
stu19Cnt_mat_total = mat_avg * 20 - hong_mat_score
stu19Cnt_sci_total = sci_avg * 20 - hong_sci_score
stu19Cnt_his_total = his_avg * 20 - hong_his_score

stu19Cnt_kor_avg = stu19Cnt_kor_total / 19
stu19Cnt_eng_avg = stu19Cnt_eng_total / 19
stu19Cnt_mat_avg = stu19Cnt_mat_total / 19
stu19Cnt_sci_avg = stu19Cnt_sci_total / 19
stu19Cnt_his_avg = stu19Cnt_his_total / 19

kor_gap = hong_kor_score - stu19Cnt_kor_avg
eng_gap = hong_eng_score - stu19Cnt_eng_avg
mat_gap = hong_mat_score - stu19Cnt_mat_avg
sci_gap = hong_sci_score - stu19Cnt_sci_avg
his_gap = hong_his_score - stu19Cnt_his_avg

print(f'국어 점수 차이: {"+" + str(round(kor_gap, 2)) if kor_gap > 0 else round(kor_gap, 2)}')
print(f'영어 점수 차이: {"+" + str(round(eng_gap, 2)) if eng_gap > 0 else round(eng_gap, 2)}')
print(f'수학 점수 차이: {"+" + str(round(mat_gap, 2)) if mat_gap > 0 else round(mat_gap, 2)}')
print(f'과학 점수 차이: {"+" + str(round(sci_gap, 2)) if sci_gap > 0 else round(sci_gap, 2)}')
print(f'국사 점수 차이: {"+" + str(round(his_gap, 2)) if his_gap > 0 else round(his_gap, 2)}')

stu19Cnt_total = stu19Cnt_kor_avg + stu19Cnt_eng_avg + stu19Cnt_mat_avg + stu19Cnt_sci_avg + stu19Cnt_his_avg
stu19Cnt_avg = stu19Cnt_total / 5

hong_total = hong_kor_score + hong_eng_score + hong_mat_score + hong_sci_score + hong_his_score
hong_avg = hong_total / 5

avg_gap = round(hong_avg - stu19Cnt_avg, 2)
print(f'평균 차이: {"+" + str(round(avg_gap, 2)) if avg_gap > 0 else round(avg_gap, 2)}')

<제로베이스 데이터 취업 스쿨>

0개의 댓글