재귀 알고리즘
- n1, n2 사이의 합
class NumSum:
def __init__(self, n1, n2):
self.n1 = n1
self.n2 = n2
self.bigNum = 0
self.smallNum = 0
self.setN1N2(n1, n2)
def setN1N2(self, n1, n2):
if self.n2 > self.n1:
self.bigNum = self.n2
self.smallNum = self.n1
else:
self.bigNum = self.n1
self.smallNum = self.n2
def addNum(self, n):
if n <2:
return n
return n + self.addNum(n-1)
def sumBeetweenNums(self):
return self.addNum(self.bigNum-1) - self.addNum(self.smallNum)
import mod
num1 = int(input('number1: '))
num2 = int(input('number2: '))
ns = mod.NumSum(num1, num2)
print(ns.sumBeetweenNums())
평균 알고리즘
- top5Players
class MaxMin:
def __init__(self, ns):
self.nums = ns
self.maxNum = 0
self.minNumIdxmaxNumIdx = 0
self.minNum = 0
self.minNumIdx = 0
def setMaxNumAndIdx(self):
self.maxNum = 0
for i, n in enumerate(self.nums):
if n > self.maxNum:
self.maxNum = n
self.maxNumIdx = i
def setMinNumAndIdx(self):
self.minNum = 10
for i, n in enumerate(self.nums):
if n < self.minNum:
self.minNum = n
self.minNumIdx = i
def removeMaxScore(self):
self.setMaxNumAndIdx()
self.nums.pop(self.maxNumIdx)
def removeMinScore(self):
self.setMinNumAndIdx()
self.nums.pop(self.minNumIdx)
def removeMaxMin(self):
self.removeMaxScore()
self.removeMinScore()
return self.nums
class Top5Players:
def __init__(self, cScores, nScore):
self.cScores = cScores
self.nScore = nScore
def setAlignScores(self):
nearIdx = 0
minNum = 10
for i, s in enumerate(self.cScores):
absNum = abs(self.nScore - s)
if absNum < minNum:
minNum = absNum
nearIdx = i
if self.nScore >= self.cScores[nearIdx]:
for i in range(len(self.cScores)-1, nearIdx, -1):
self.cScores[i] = self.cScores[i-1]
self.cScores[nearIdx] = self.nScore
else:
for i in range(len(self.cScores)-1, nearIdx+1, -1):
self.cScores[i] = self.cScores[i-1]
self.cScores[nearIdx+1] = self.nScore
def getFinalTop5Scores(self):
self.setAlignScores()
return self.cScores
import maxminMod
import nearMod
top5scores = [9.12, 8.95, 8.12, 6.90, 6.18]
myScores = [6.7, 5.9, 8.1, 7.9, 6.7, 7.3, 7.2, 8.2, 6.2, 5.8]
print('myScores : {}'.format(myScores))
ms = maxminMod.MaxMin(myScores)
removeMaxMinScores = ms.removeMaxMin()
print('removeMaxMinScores : {}'.format(removeMaxMinScores))
total = 0
average = 0
for n in removeMaxMinScores:
total += n
average = round(total / len(removeMaxMinScores), 2)
print('최대최소 점수 뺀 합 :{}\t평균 :{}'.format(round(total,2), average))
top5scoresList = nearMod.Top5Players(top5scores, average)
print(top5scoresList.getFinalTop5Scores())