[Python] 알고리즘 문제 풀이 - 최빈값, 재귀, 근삿값, 평균

박미영·2023년 3월 24일
0

📌최빈값

Q. 다음은 어떤 회사의 전직원 나이를 나타내는 리스트이다. 최빈값 알고리즘을 이용해서 나이 분포를 간단한 그래프로 출력하는 모듈을 만들어보자.

  • maxMod.py (최댓값 알고리즘)
class MaxAlgorithm:

    def __init__(self, ns):
        self.nums = ns
        self.max_num = 0
        self.max_num_idx = 0

    def set_max_idx_and_num(self):
        self.max_num = 0
        self.max_num_idx = 0

        for i, n in enumerate(self.nums):
            if self.max_num < n:
                self.max_num = n
                self.max_num_idx = i

    def get_max_num(self):
        return self.max_num

    def get_max_idx(self):
        return self.max_num_idx
  • modeMod.py (최빈값 알고리즘)
import maxMod

class ModeAlgorithm:

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

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

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

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

    def print_ages(self):

        n = 1
        while True:

            max_alo = maxMod.MaxAlgorithm(self.indexes)
            max_alo.set_max_idx_and_num()
            max_num = max_alo.get_max_num()
            max_num_idx = max_alo.get_max_idx()

            if max_num == 0:
                break
            else:
                # n:0>3 - n을 세 자리 맞추는데 오른쪽 정렬(나머지0)
                print(f'[{n:0>3}] {max_num_idx}세 빈도수: {max_num} \t', end='')
                print('+' * max_num)
                self.indexes[max_num_idx] = 0
            n += 1
  • modeEx.py
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)}명')

max_alo = maxMod.MaxAlgorithm(ages)
max_alo.set_max_idx_and_num()
max_age = max_alo.get_max_num()
print(f'max age: {max_age}')

mode_alo = modeMod.ModeAlgorithm(ages, max_age)
mode_alo.set_index_list()
print(f'Index list: {mode_alo.get_index_list()}')
mode_alo.print_ages()
  • 출력결과



📌재귀함수

📍Q1

다음은 ‘A상사’의 2021년 월별 매출을 나타내는 표이다. 재귀 알고리즘을 이용해서 1월부터 12월까지 전월대비 매출 증감액을 나타내는 프로그램을 만들어보자.

sales = [1200, 1300, 12500, 11000, 10500, 98000, 91000, 91500, 10500, 11500, 12000, 12500]

def sales_up_and_down(ss):

    if len(ss) == 1:
        return ss
    print(f'sales: {sales}')
    current_sales = ss.pop(0)
    next_sales = ss[0]

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

    return sales_up_and_down(ss)


if __name__ == '__main__':
    sales_up_and_down(sales)
  • 출력결과



📍Q2

사용자가 정수 두개를 입력하면 작은 정수와 큰 정수 사이의 모든 정수의 합을 구하는 프로그램을 재귀 알고리즘을 이용해서 만들어보자.

-recusionMod.py

class NumsSum:

    def __init__(self, n1, n2):
        self.big_num = 0
        self.small_num = 0
        self.set_n1_n2(n1, n2)

    def set_n1_n2(self, n1, n2):
        self.big_num = n1
        self.small_num = n2

        if n1 < n2:
            self.big_num = n2
            self.small_num = n1

    def add_num(self, n):
        if n <= 1:
            return n

        return n + self.add_num(n-1)

    def sum_between_nums(self):
        return self.add_num(self.big_num - 1) - self.add_num(self.small_num)
  • recusionEx.py
import recusionMod

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

ns = recusionMod.NumsSum(num1, num2)
result = ns.sum_between_nums()
print(f'result: {result}')
  • 출력결과



📌근삿값

📍Q1

다음 표는 수심에 따른 수온을 나타내고 있다. 근사값 알고리즘을 이용해서 수심을 입력하면 수온을 출력하는 모듈을 만들어보자.

  • nearMod.py
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.near_num = 0
        self.min_num = 24


    def get_near_numbers(self):

        for n in self.temps.keys():
            abs_num = abs(n - self.depth)
            if abs_num < self.min_num:
                self.min_num = abs_num
                self.near_num = n
        return self.temps[self.near_num]
  • nearEx.py
import nearMod

depth = int(float(input('input depth: ')))
print(f'depth: {depth}m')

na = nearMod.NearAlgorithm(depth)
temp = na.get_near_numbers()
print(f'water temperature: {temp}도')
  • 출력결과




📍Q2

사용자의 몸무게(kg)와 키(m)를 입력하면 체질량지수(BMI)를 계산하고, 근삿값 알고리즘과 BMI표를 이용해서 신체 상태를 출력하는 프로그램을 만들어보자.

  • nearMod.py
class BmiAlgorithm:

    def __init__(self, w, h):

        self.BMI_section = {18.5: ['저체중', '정상'],
                            23: ['정상', '과체중'],
                            25: ['과체중', '비만']}
        self.user_weight = w
        self.user_height = h
        self.user_BMI = 0
        self.user_condition = ''
        self.near_num = 0
        self.min_num = 25

    def calculator_BMI(self):
        self.user_BMI = round(self.user_weight / (self.user_height ** 2), 2)
        print(f'self.user_BMI: {self.user_BMI}')

    def print_user_condition(self):

        for n in self.BMI_section.keys():
            abs_num = abs(n - self.user_BMI)
            if abs_num < self.min_num:
                self.min_num = abs_num
                self.near_num = n
        print(f'self.near_num: {self.near_num}')
        
        if self.user_BMI <= self.near_num:
            self.user_condition = self.BMI_section[self.near_num][0]
        else:
            self.user_condition = self.BMI_section[self.near_num][1]
        print(f'self.user_condition: {self.user_condition}')
  • nearEx.py
import nearMod

user_weight = float(input('input weight(kg): '))
user_height = float(input('input height(m): '))

na = nearMod.BmiAlgorithm(user_weight, user_height)
na.calculator_BMI()
na.print_user_condition()
  • 출력결과



📌평균

📍Q1

다음은 어떤 체조선수의 경기 점수이다. 최댓값과 최솟값을 제외한 나머지 점수에 대한 평균을 구하고 순위를 정하는 알고리즘을 만들어보자.

  • 출력결과



📍Q2

다음은 홍길동 학생을 포함한 학급 전체 학생의 시험 점수 평균을 나타낸 표이다.
표를 보고, 홍길동 학생을 제외한 나머지 학생의 평균과 홍길동 학생의 점수의 차이를 출력하는 프로그램을 만들어보자.(출력은 과목별 점수와 평균 점수를 모두 출력한다.)

  • 출력결과




"이 글은 제로베이스 데이터 취업 스쿨 강의 자료 일부를 발췌한 내용이 포함되어 있습니다."

0개의 댓글