Search

최빈값

 구하는 방법
1.
주어진 리스트(nums)의 최댓값을 찾는다.
2.
(최댓값의 수 + 1)만큼 0 원소를 가지고 있는 배열(indexes)을 생성해준다.
3.
nums 값을 돌면서 해당하는 값과 동일한 indexes 위치에 1씩 더해준다.
4.
nums 의 모든 원소를 수행하고 나면 indexes 값에서 가장 큰 값의 인덱스 값이 nums의 최빈값이 된다.
# 최빈값을 구하기 위해서는 일단 주어진 리스트 배열에서 최댓값을 구해야 한다. # -> 최댓값을 구하는 class 부터 생성해주자. class MaxAlgorithm: def __init__(self,ns): self.nums = ns self.maxNum = 0 self.maxNumIdx = 0 def SetMaxIdxAndNum(self): self.maxNum = self.nums[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 nums = [1,3,7,6,7,7,7,12,12,17] ma = MaxAlgorithm(nums) ma.SetMaxIdxAndNum() maxNum = ma.getMaxNum() print(f'maxNum : {maxNum}') indexes = [0] * (maxNum + 1) print(f'indexes : {indexes}') for n in nums: indexes[n] += 1 print(f'final indexes: {indexes}') # 이 상황에서 최댓값의 index 를 찾아야 최종 답이 된다. -> 다시한번 최댓값 알고리즘을 활용한다. fi = MaxAlgorithm(indexes) fi.SetMaxIdxAndNum() result = fi.getMaxNumIdx() print(f'final mode num : {result}')
Python
복사
# max.py # 최반값을 구하는 알고리즘을 구현하기 위해서는 # 최댓값 알고리즘을 활용해야 되고, # 최댓값과 최댓값의 인덱스를 모두 활용해야 한다. class MaxAlgorithm: def __init__(self,ns): self.nums = ns self.maxNum = 0 self.maxNumIdx = 0 def setMaxNumIdxAndNum(self): self.maxNum = self.nums[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
Python
복사
import random import max as mx scores = [] for _ in range(100): rn = random.randint(70,100) if rn != 100: rn = rn - (rn % 5) # 100점이 아닌 점수들은 5단위로 재설정 scores.append(rn) print(f'scores : {scores}') print(f'scores length : {len(scores)}') # 최댓값 구하고, 최댓값 개수만큼 0을 가지고 있는 배열 초기화 ma = mx.MaxAlgorithm(scores) ma.setMaxNumIdxAndNum() max_score = ma.getMaxNum() print(f'max_score : {max_score}') indexes = [0] * (max_score + 1) print(f'indexes length : {len(indexes)}') # indexes 원소값 설정해주기 for sc in scores: indexes[sc] += 1 n = 1 while True: maxAlo = mx.MaxAlgorithm(indexes) maxAlo.setMaxNumIdxAndNum() modeScore = maxAlo.getMaxNumIdx() # 최빈값 modeCnt = maxAlo.getMaxNum() # 나온 개수 if modeCnt == 0: # indexes 의 가장 많이 나온 개수 가 0이되면 반복문을 탈출 break print(f'{n}. {modeScore}빈도수 : {modeCnt}\t', end='') print('+' * modeCnt) indexes[modeScore] = 0 # 다음 최빈값을 구해주기 위해 필요 n += 1
Python
복사
# max.py class MaxAlgorithm: def __init__(self,ns): self.nums = ns self.maxNum = 0 self.maxIdx = 0 def setMaxNumandIdx(self): self.maxNum = 0 self.maxIdx = 0 for i , n in enumerate(self.nums): if self.maxNum < n: self.maxNum = n self.maxIdx = i def getMaxNum(self): return self.maxNum def getMaxIdx(self): return self.maxIdx
Python
복사
# mode.py import max class ModeAlgorithm: def __init__(self,ns,mn): self.nums = ns self.maxNum = mn self.indexes = [] # 빈도수를 담을 index 리스트 def setIndexList(self): self.indexes = [0] * (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: # indexes 에서 가장 큰 숫자 -> 즉 빈도수가 가장 크게 나온 값을 찾아야되니까 maxAlo = max.MaxAlgorithm(self.indexes) maxAlo.setMaxNumandIdx() maxMod = maxAlo.getMaxNum() maxModidx = maxAlo.getMaxIdx() if maxMod == 0: # 초기화가 안된 것 break print(f'[{n:0>3}] : {maxModidx}세 빈도수 : {maxMod}',end='') print('+' * maxMod) self.indexes[maxModidx] = 0 n += 1
Python
복사
import random import mode, max ages = [] for _ in range(40): ages.append(random.randint(20,50)) print(f'employee cnt : {ages}') max_Al = max.MaxAlgorithm(ages) max_Al.setMaxNumandIdx() max_age = max_Al.getMaxNum() max_idx = max_Al.getMaxIdx() print(f'가장 큰 나이 : {max_age}') print(f'가장 큰 나이의 index : {max_idx}') modAlo = mode.ModeAlgorithm(ages,max_age) modAlo.setIndexList() mode_age = modAlo.getIndexList() print(f'가장 인원수 많은 나이 : {mode_age}') print('-'*50) print('나이대별 인원수 출력') modAlo.PrintAges() # sm = min.ScoreManagement(scores) # min_score = sm.getMinScore() # max_score = sm.getMaxScore() # tot_score = sm.getTotScore() # avg_score = sm.getAvgScore() # dv_max = sm.getMaxDeviation() # dv_min = sm.getMinDeviation()
Python
복사
# mode.py class ModeAlgorithm: def __init__(self,ln): self.lottoNums = ln self.modeList = [0 for i in range(1,47)] # 0 ~ 46 의 인덱스가 들어있는 0 def getLottoNumMode(self): # 2차원 배열이니까 중첩 for문 사용하기 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 else: for i, m in enumerate(self.modeList): if i != 0: print(f'번호 : {i:>2}, 빈도 : {m}, {"*" * m}')
Python
복사
import random import mode lottos = [[random.randint(1,45) for j in range(6)] for i in range(30)] lm = mode.ModeAlgorithm(lottos) mList = lm.getLottoNumMode() # print(f'mList: {mList}') lm.printModeList()
Python
복사
class NearAlgorithm: def __init__(self,d): # 현재 점수와 새 점수를 받아온다. self.temp = {0:24, 5:22, 10:20, 15:16, 20:13, 25:10, 30:6} self.depth = d self.nearNum = 0 self.minNum = 24 # 새 점수가 현재 점수에서 어느 순위에 들어가야되는지 확인 def getNearNumber(self): for n in self.temp.keys(): absNum = abs(n - self.depth) # 입력한 깊이와 차이를 계산 if absNum < self.minNum: self.minNum = absNum self.nearNum = n return self.temp[self.nearNum]
Python
복사
import near depth = int(float(input('input depth : '))) print(f'depth: {depth}') na = near.NearAlgorithm(depth) temp = na.getNearNumber() print(f'water temperature: {temp}도')
Python
복사
class BmiAlgorithm: def __init__(self,w,h): # 현재 점수와 새 점수를 받아온다. self.BmiSection = {18.5:['저체중','정상'], 23:['정상','과체중'], 25:['과체중','비만'], } self.userW = w self.userH = h self.userBmi = 0 self.userCondi = '' self.NearNum = 0 self.minNum = 25 # 새 점수가 현재 점수에서 어느 순위에 들어가야되는지 확인 def CalculatorBmi(self): self.userBmi = round(self.userW / (self.userH * self.userH),2) print(f'self.userBMI : {self.userBmi}') def printUserCondition(self): for i in self.BmiSection.keys(): absBmi = abs(i - self.userBmi) if absBmi < self.minNum: self.minNum = absBmi self.NearNum = i print(f'self.NearNum : {self.NearNum}') if self.userBmi <= self.NearNum: self.userCondi = self.BmiSection[self.NearNum][0] else: self.userCondi = self.BmiSection[self.NearNum][1] print(f'user condition : {self.userCondi}')
Python
복사
import near user_weight = float(input('input weight(kg) : ')) user_height = float(input('input height(m) : ')) na = near.BmiAlgorithm(user_weight, user_height) na.CalculatorBmi() na.printUserCondition()
Python
복사