파이썬_알고리즘_008 문제풀이2

이새롬·2023년 2월 21일
0

python

목록 보기
21/21
post-thumbnail

👀 다시보기

근사값 (딕셔너리에 들어있는 값을 비교)

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]

1 __init__메서드 속성값으로 수온을 깊이대비 수온을 딕셔너리로 넣고,
비교치가 될 최저값은 가장 높은 온도인 24도로 설정.

  1. for문에 키값을 돌려 깊이(키 값) - 입력깊이를 뺀 값을 절대값으로 구해줌

  2. 그 절대값이 minNum보다 적으면 가장 적은차이임으로 nearNum에 할당

  3. nearNum을 인덱스값으로 temps[nearNum]으로 value값인 온도를 뽑아줌!


BMI = 몸무게 / 키^2

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

__init__매서드에는
1. BMI section을 딕셔너리로 담음. 범위는 값으로서 리스트로 2개씩 문자열로 담음.
2. bmi section, 받는 값인 사용자 무게,키
그리고 구할 값인 bmi,사용자의 bmi섹션에 해당하는 값, 근사치, 비교대상인 최저값

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

bmi 구하기

    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}')

        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}')

★★ 요게 가장 핵심
1. bmi섹션의 키값인 기준치랑 근사값 비교해줄 miNum과의 차이에 절대값
2. 절대값이 적을 시 minNum 할당하여 nearNum 구하기
+ 더 나아가
사용자 bmi가 근사치보다 적을 시
-> 섹션 값 앞값을 내보냄. self.BMISection[self.nearNum][0]
근사치보다 클시
-> 섹션 값 뒷값을 내보냄 self.BMISection[self.nearNum][1]


근사값

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
  1. 구할 값인 nearIdx, 구할 때 기준이되고 도와줄 minNum 초기화
    (여기서 minNum은 차이가 가장 적은 값을 가져와야하기에, 최대값을 넣어야한다. 그래야 minNum보다 차이가 다들 작아진다.)

  2. 구할 데이터 for문에 enumerate로 돌리기.

  3. absNum에 근사치 찾을 값과 s(self.currentScores의 데이터,값)을 빼고 절대값처리.

  4. 그게 minNum보다 작으면 minNum 새로 담아주고, 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

재귀함수

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

def salesUpAndDown(ss):
    print(f'sales : {ss}')
    if len(sales) == 1:
        return ss

    currentSales = ss.pop(0)
    nextSales = ss[0]
    increase = nextSales - currentSales
    if increase > 0:
        increase = '+' + str(increase)

    print(f'매출 증감액 : {increase}')

    return salesUpAndDown(ss)
  1. 가격을 받아서 길이가 1이면 비교할게 없기때문에 retrun
  2. 그 외에는 현재 가격에 가격에 첫번째 값을 pop으로 자르고 currentSales의 담음
    → next sales의 잘린 전체가격의 첫번째 인덱스 호출
    → increase에 nextSales에 currentSale를 뺀 값을 넣기
    → 만약 increase가 0보다 크다면 increase는 문자 +와 increase(데이터형 변환)
  3. return 으로 마무리

💬 코멘트

알고리즘의 대장정 마무리.
진짜 어려웠다가 컴퓨터 붙잡고 여기저기 검색하고
공부 범위 나눠서 조절해서 공부하고
이제 아주 조큼 이해가고 코드가 보이려는데 다음 진도가 기다리고있다...ㅎ...
내일 테스트를 앞두고 좀 어려웠던 부분, 몇가지 더 따라해봐야겠다..

0개의 댓글