선택정렬 : 가장 작은 데이터랑 자리 변경
선택정렬 알고리즘을 이용해 학생 20명의 시험 점수를 오름차순과 내림차순으로 정렬하는 모듈을 만들어라 시험점수는 50 ~ 100까지로 한다.
scores : [74, 93, 62, 89, 57, 80, 55, 76, 63, 98, 83, 53, 69, 100, 58, 94, 71, 95, 78, 82]
모듈
def sortNumber(ns, asc=True):
if asc:
for i in range(len(ns) -1):
midIdx = i
for j in range(i+1, len(ns)):
if ns[midIdx] > ns[j]
midIdx = j
ns[i], ns[minIdx] = ns[midIdx], ns[i]
else:
for i in range(len(ns) -1):
midIdx = i
for j in range(i+1, len(ns)):
if ns[midIdx] < ns[j]
midIdx = j
ns[i], ns[minIdx] = ns[midIdx], ns[i]
return ns
실행
import random
import sortMod as sm
scores = random.sample(range(50, 101), 20)
print(f'scores: {scores}')
print(f'scores length: {len(scores)}')
result = sm.sortNumber(scores)
print(f'result: {result}')
result = sm.sortNumber(scores, asc = False)
print(f'result: {result}')
최댓값
리스트에서 아스키 코드가 가장 큰 값을 찾는 알고리즘을 만들어보자
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
chars = ['c', 'x', 'Q', 'A', 'e', 'P', 'p']
mc = MaxAlgorithm(chars)
maxChar = mc.getMaxChar()
print(f'maxChar : {maxChar}')
최솟값
리스트에서 아스키 코드가 가장 작은 값을 찾는 알고리즘을 만들어보자
class MinAlgorithm:
def __init__(self, cs):
self.chars = cs
self.minChar = 0
def getMinChar(self):
self.minChar = self.chars[0] #하나 지정하고 계속 비교!
for c in self.chars:
if ord(self.minChar) < ord(c):
self.minChar = c
return self.minChar
chars = ['c', 'x', 'Q', 'A', 'e', 'P', 'p']
ma = MinAlgorithm(chars)
minChar = ma.getMaxChar()
print(f'minChar : {minChar}')
최빈값
모듈
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
실행
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.setMaxNumIdxAndNum()
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.setMaxNumIdxAndNum()
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
평균값
점수의 평균을 구하고 순위를 정하는 알고리즘을 만들어라
score = [8.9, 7.6, 8.2, 9.1, 8.8, 8.1, 7.9, 7.2, 8.7]
모듈
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.currentsScores):
absNum = abs(self.newScore - s)
if absNum < minNum:
minNum = absNum
nearIdx = i
nearScore = s
if self.newScore >= self.currentScores[nearIdx]:
for i in range(len(self.currentScores)-1, nearIdx, -1):
self.currentScore[i] = self.currentScores[i-1]
self.currentScores[nearIdx] = self.newScore
else:
for i in range(len(self.currentScores)-1, nearIdx+1, -1):
self.currentScore[i] = self.currentScores[i-1]
self.currentScores[nearIdx] = self.newScore
def getFinalTop5Scores(self):
return self.currentScores
실행
import near
score = [8.9, 7.6, 8.2, 9.1, 8.8, 8.1, 7.9, 7.2, 8.7]
top5PlayerScores = [9.12, 8.95, 8.12, 7.90, 7.88]
print(f'top5PlayerScores: {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.setAlignScores()