값구하기: 최댓값, 최솟값, 최빈값, 근삿값, 평균 구하기
# 실습 아스키코드가 가장 큰값, 작은값을 찾는 알고리즘
class MaxAlgorithm:
def __init__(self, cs):
self.chars = cs
self.maxChar = 0
def getMaxChar(self):
self.maxChar = self.chars[0]
for c in self.chars:
if ord(self.maxChar) < ord(c): #최소값은 >기호
self.maxChar = c
return self.maxChar
ma = MaxAlgorithm(['c', 'x', 'Q', 'A', 'e', 'P', 'p'])
maxChar = ma.getMaxChar()
print(f'maxChar: {maxChar}')
# 실습 실행파일
import random
import maxScore as ms
scores = []
for i in range(100):
rn = random.randint(71, 100)
if rn != 100: rn = rn - (rn % 5)
scores.append(rn)
print(f'scores: {scores}')
print(f'scores length: {len(scores)}')
# 최댓값 알고리즘
maxAlo = ms.MaxAlgorithm(scores)
maxAlo.setMaxIdxAndNum()
maxNum = maxAlo.getMaxNum()
print(f'maxNum: {maxNum}')
# 인덱스 리스트 생성
indexes = [0 for i in range(maxNum + 1)]
print(f'indexes: {indexes}')
print(f'indexes length: {len(indexes)}')
# 인덱스 리스트에 빈도 저장
for n in scores:
indexes[n] = indexes[n] + 1
print(f'indexes: {indexes}')
n = 1
while True:
maxAlo = ms.MaxAlgorithm(indexes)
maxAlo.setMaxIdxAndNum()
maxNum = maxAlo.getMaxNum()
maxNumIdx = maxAlo.getMaxNumIdx()
# print(f'maxNum: {maxNum}')
# print(f'maxNumIdx: {maxNumIdx}')
if maxNum == 0:
break
print(f'{n}. {maxNumIdx}빈도수: {maxNum}\t', end='')
print('+' * maxNum)
indexes[maxNumIdx] = 0
n += 1
# 최댓값 클래스
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;
# 실습 실행파일
import near
scores = []
kor = int(input('input kor score: '))
scores.append(kor)
eng = int(input('input eng score: '))
scores.append(eng)
mat = int(input('input mat score: '))
scores.append(mat)
sci = int(input('input sci score: '))
scores.append(sci)
his = int(input('input his score: '))
scores.append(his)
totalScore = sum(scores)
print(f'totalScore: {totalScore}')
avgScore = totalScore / len(scores)
print(f'avgScore: {avgScore}')
grade = near.getNearNum(avgScore)
print(f'grade: {grade}')
# 근삿값 모듈
def getNearNum(an):
baseScore = [95, 85, 75, 65, 55]
nearNum = 0
minNum = 100
for n in baseScore:
absNum = abs(n - an)
if absNum < minNum:
minNum = absNum
nearNum = n
if nearNum == 95:
return 'A'
elif nearNum == 85:
return 'B'
elif nearNum == 75:
return 'C'
elif nearNum == 65:
return 'D'
elif nearNum <= 55:
return 'F'
# 실습 실행파일
import near
scores = (8.9, 7.6, 8.2, 9.1, 8.8, 8.1, 7.9, 9.4, 7.2, 8.7)
top5PlayerScores = [9.12, 8.95, 8.12, 7.90, 7.88]
print(f'Current scores: {top5PlayerScores}')
total = 0
average = 0
for n in scores:
total += n
# 평균 구하기
average = round(total / len(scores), 2)
print(f'total: {total}')
print(f'average: {average}')
tp = near.Top5Players(top5PlayerScores, average)
tp.setAlignScore()
top5PlayerScores = tp.getFinalTop5Scores()
print(f'Final scores: {top5PlayerScores}')
# 근삿값 클래스
class Top5Players:
def __init__(self, cs, ns):
self.currentScores = cs
self.newScore = ns
def setAlignScore(self):
nearIdx = 0
nearScore = 0
minNum = 10.0
for i, s in enumerate(self.currentScores):
absNum = abs(self.newScore - s)
if absNum < minNum:
minNum = absNum
nearIdx = i
nearScore = s
# print(f'nearIdx: {nearIdx}')
# print(f'nearScore: {nearScore}')
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
# print(f'self.currentScores: {self.currentScores}')
def getFinalTop5Scores(self):
return self.currentScores
앞의 스터디노트 내용과 같이 크게 어렵지 않았고 무난하게 수강할 수 있었다. 필요할 때 해당 알고리즘이 생각날지는 모르겠다..
이글은 제로베이스 데이터 취업스쿨의 강의자료 일부를 발췌하여 작성되었습니다.