알고리즘 문제풀이_2

YJ·2023년 3월 25일

▷ 오늘 학습 계획: 알고리즘 강의(문풀 4~5)

재귀 알고리즘

  • 사용자가 정수 두 개를 입력하면 작은 정수와 큰 정수 사이의 모든 정수의 합을 구하는 프로그램
    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):
            if n <= 1:
                return n

            return n+ self.addNum(n-1)

        def getTotalResult(self):
            return self.addNum(self.bigNum-1) - self.addNum(self.smallNum)

평균 알고리즘

  • 최댓값, 최솟값, 평균, 근삿값 알고리즘 모두 적용되는 문제
    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 getFinalScores(self):
            return self.currentScores

📝 최댓값, 최솟값, 평균 알고리즘은 이해가 잘 됐다. 한 문제에서 여러 개의 알고리즘을 적용해야 될 때 모듈도 많아져서 복잡해 보였지만 차근차근 이해할 수 있었다. 강의 들으면서 함수, 클래스 생성을 자주 하다보니까 더 익숙해졌는데 그래도 알고리즘은 어렵다.

▷ 내일 학습 계획: 파이썬 프로그래밍 테스트

[이 글은 제로베이스 데이터 취업 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다.]

0개의 댓글