📝 알고리즘 문제풀이
📌 알고리즘
✏ 선형검색 알고리즘

import random
rNums = random.sample(range(1,21), 10)
print(f'rNums : {rNums}')
searchNum = int(input('input nums : '))
searchResultIdx = -1
print(f'search number : {searchNum}')
n = 0
while True:
if n == len(rNums):
print('search fail!')
break
if rNums[n] == searchNum:
searchResultIdx = n
print('search success!')
print(f'search result number index : {searchResultIdx}')
break
n += 1
if searchResultIdx == -1 :
print('No result')
print(f'search result number index : {searchResultIdx}')
else :
print('result')
print(f'search result number : {rNums[searchResultIdx]}')
print(f'search result number index : {searchResultIdx}')
↓
rNums : [20, 19, 10, 1, 15, 17, 3, 14, 7, 5]
input nums : 15
search number : 15
search success!
search result number index : 4
result
search result number : 15
search result number index : 4
✏ 이진검색 알고리즘

import random
nums = random.sample(range(1, 31), 20)
print(f'nums : {nums}')
nums.sort()
searchNum = int(input('input nums : '))
searchResultIdx = -1
startIdx = 0
endIdx = len(nums) - 1
lastIdx = len(nums) - 1
midIdx = (startIdx + endIdx) // 2
midVal = nums[midIdx]
print(f'startIdx :{startIdx}, endIdx : {endIdx}')
print(f'midIdx :{midIdx}, midVal : {midVal}')
while searchNum <= nums[lastIdx] and searchNum >= nums[0]:
if searchNum not in nums:
print(f'search num({searchNum}) is not in nums')
break
else:
if searchNum == nums[lastIdx]:
searchResultIdx = lastIdx
break
if searchNum < midVal:
endIdx = midIdx
midIdx = (startIdx + endIdx) // 2
midVal = nums[midIdx]
print(f'startIdx :{startIdx}, endIdx : {endIdx}')
print(f'midIdx :{midIdx}, midVal : {midVal}')
elif searchNum > midVal:
startIdx = midIdx
midIdx = (startIdx + endIdx) // 2
midVal = nums[midIdx]
print(f'+startIdx :{startIdx}, endIdx : {endIdx}')
print(f'+midIdx :{midIdx}, midVal : {midVal}')
elif searchNum == midVal:
searchResultIdx = midIdx
print(f'-startIdx :{startIdx}, endIdx : {endIdx}')
print(f'-midIdx :{midIdx}, midVal : {midVal}')
break
print(f'search num : {searchNum}')
print(f'Search number({({searchNum})}) index : {searchResultIdx}')
print(f'Search result num : {searchNum}')
↓
nums : [6, 19, 5, 23, 14, 13, 20, 22, 8, 16, 24, 21, 1, 17, 29, 30, 2, 3, 15, 28]
input nums : 23
startIdx :0, endIdx : 19
midIdx :9, midVal : 16
+startIdx :9, endIdx : 19
+midIdx :14, midVal : 22
+startIdx :14, endIdx : 19
+midIdx :16, midVal : 24
startIdx :14, endIdx : 16
midIdx :15, midVal : 23
-startIdx :14, endIdx : 16
-midIdx :15, midVal : 23
search num : 23
Search number({23}) index : 15
Search result num : 23
✏ 순위 알고리즘

def rankAlgorithm(ns):
ranks = [0 for i in range(len(ns))]
for idx, n1 in enumerate(ns):
for n2 in ns:
if n1 < n2:
ranks[idx] += 1
print(f'nums : {ns}')
print(f'ranks : {ranks}')
for i, n in enumerate(ns):
print(f'num : {n} \t rank: {ranks[i]+1}')
sortedNums = [0 for i in range(len(ranks))]
for idx, rank in enumerate(ranks):
sortedNums[rank] = ns[idx]
return sortedNums
↓
nums : [66, 98, 64, 53, 85, 69, 92, 70, 90, 57, 54, 86,
84, 50, 73, 91, 76, 68, 81, 80]
ranks : [14, 0, 15, 18, 5, 12, 1, 11, 3, 16, 17, 4, 6,
19, 10, 2, 9, 13, 7, 8]
num : 66 rank: 15
num : 98 rank: 1
num : 64 rank: 16
num : 53 rank: 19
num : 85 rank: 6
num : 69 rank: 13
num : 92 rank: 2
num : 70 rank: 12
num : 90 rank: 4
num : 57 rank: 17
num : 54 rank: 18
num : 86 rank: 5
num : 84 rank: 7
num : 50 rank: 20
num : 73 rank: 11
num : 91 rank: 3
num : 76 rank: 10
num : 68 rank: 14
num : 81 rank: 8
num : 80 rank: 9
sNums : [98, 92, 91, 90, 86, 85, 84, 81, 80, 76, 73,
70, 69, 68, 66, 64, 57, 54, 53, 50]

datas = [32, 'a', 'z', 45, 'G', 39, 50, 'T', 't', 22, 31, 55, 's', 63, 59, 'E']
print(f'datas: {datas}')
ascIIDatas = []
for data in datas:
if str(data).isalpha():
ascIIDatas.append(ord(data))
continue
ascIIDatas.append(data)
print(ascIIDatas)
ranks = [0 for i in range(len(ascIIDatas))]
print(f'ranks before : {ranks}')
for idx, data1 in enumerate(ascIIDatas):
for data2 in ascIIDatas:
if data1 < data2:
ranks[idx] += 1
print(f'ranks after : {ranks}')
for i, d in enumerate(datas):
print(f'data : {d:>2}, \t rank: {ranks[i] + 1}')
↓
datas: [32, 'a', 'z', 45, 'G', 39, 50, 'T', 't', 22,
31, 55, 's', 63, 59, 'E']
[32, 97, 122, 45, 71, 39, 50, 84, 116, 22, 31, 55, 115,
63, 59, 69]
ranks before : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0]
ranks after : [13, 3, 0, 11, 5, 12, 10, 4, 1, 15, 14,
9, 2, 7, 8, 6]
data : 32, rank: 14
data : a, rank: 4
data : z, rank: 1
data : 45, rank: 12
data : G, rank: 6
data : 39, rank: 13
data : 50, rank: 11
data : T, rank: 5
data : t, rank: 2
data : 22, rank: 16
data : 31, rank: 15
data : 55, rank: 10
data : s, rank: 3
data : 63, rank: 8
data : 59, rank: 9
data : E, rank: 7
✏ 버블정렬 알고리즘

import copy
def bubbleAlgorithm(ns, asc=True):
cns = copy.copy(ns)
length = len(cns) - 1
for i in range(length):
for j in range(length-i):
if asc :
if cns[j] > cns[j+1]:
cns[j], cns[j+1] = cns[j+1], cns[j]
else:
if cns[j] < cns[j+1]:
cns[j], cns[j+1] = cns[j+1], cns[j]
print(f'ns : {cns}')
print()
return cns
import random
import bubbleMod
if __name__ == '__main__':
nums = random.sample(range(1,21), 10)
print(f'not sorted nums : {nums}')
result = bubbleMod.bubbleAlgorithm(nums)
print(f'sorted nums ny ASC : {result}')
result = bubbleMod.bubbleAlgorithm(nums, asc=False)
print(f'sorted nums ny DESC: {result}')
↓
not sorted nums : [14, 1, 17, 18, 9, 5, 2, 16, 20, 10]
ns : [1, 14, 17, 18, 9, 5, 2, 16, 20, 10]
ns : [1, 14, 17, 18, 9, 5, 2, 16, 20, 10]
ns : [1, 14, 17, 18, 9, 5, 2, 16, 20, 10]
ns : [1, 14, 17, 9, 18, 5, 2, 16, 20, 10]
ns : [1, 14, 17, 9, 5, 18, 2, 16, 20, 10]
ns : [1, 14, 17, 9, 5, 2, 18, 16, 20, 10]
ns : [1, 14, 17, 9, 5, 2, 16, 18, 20, 10]
ns : [1, 14, 17, 9, 5, 2, 16, 18, 20, 10]
ns : [1, 14, 17, 9, 5, 2, 16, 18, 10, 20]
ns : [1, 14, 17, 9, 5, 2, 16, 18, 10, 20]
ns : [1, 14, 17, 9, 5, 2, 16, 18, 10, 20]
ns : [1, 14, 9, 17, 5, 2, 16, 18, 10, 20]
ns : [1, 14, 9, 5, 17, 2, 16, 18, 10, 20]
ns : [1, 14, 9, 5, 2, 17, 16, 18, 10, 20]
ns : [1, 14, 9, 5, 2, 16, 17, 18, 10, 20]
ns : [1, 14, 9, 5, 2, 16, 17, 18, 10, 20]
ns : [1, 14, 9, 5, 2, 16, 17, 10, 18, 20]
ns : [1, 14, 9, 5, 2, 16, 17, 10, 18, 20]
ns : [1, 9, 14, 5, 2, 16, 17, 10, 18, 20]
ns : [1, 9, 5, 14, 2, 16, 17, 10, 18, 20]
ns : [1, 9, 5, 2, 14, 16, 17, 10, 18, 20]
ns : [1, 9, 5, 2, 14, 16, 17, 10, 18, 20]
ns : [1, 9, 5, 2, 14, 16, 17, 10, 18, 20]
ns : [1, 9, 5, 2, 14, 16, 10, 17, 18, 20]
ns : [1, 9, 5, 2, 14, 16, 10, 17, 18, 20]
ns : [1, 5, 9, 2, 14, 16, 10, 17, 18, 20]
ns : [1, 5, 2, 9, 14, 16, 10, 17, 18, 20]
ns : [1, 5, 2, 9, 14, 16, 10, 17, 18, 20]
ns : [1, 5, 2, 9, 14, 16, 10, 17, 18, 20]
ns : [1, 5, 2, 9, 14, 10, 16, 17, 18, 20]
ns : [1, 5, 2, 9, 14, 10, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 14, 10, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 14, 10, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 14, 10, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
sorted nums ny ASC : [1, 2, 5, 9, 10, 14, 16, 17, 18, 20]
ns : [14, 1, 17, 18, 9, 5, 2, 16, 20, 10]
ns : [14, 17, 1, 18, 9, 5, 2, 16, 20, 10]
ns : [14, 17, 18, 1, 9, 5, 2, 16, 20, 10]
ns : [14, 17, 18, 9, 1, 5, 2, 16, 20, 10]
ns : [14, 17, 18, 9, 5, 1, 2, 16, 20, 10]
ns : [14, 17, 18, 9, 5, 2, 1, 16, 20, 10]
ns : [14, 17, 18, 9, 5, 2, 16, 1, 20, 10]
ns : [14, 17, 18, 9, 5, 2, 16, 20, 1, 10]
ns : [14, 17, 18, 9, 5, 2, 16, 20, 10, 1]
ns : [17, 14, 18, 9, 5, 2, 16, 20, 10, 1]
ns : [17, 18, 14, 9, 5, 2, 16, 20, 10, 1]
ns : [17, 18, 14, 9, 5, 2, 16, 20, 10, 1]
ns : [17, 18, 14, 9, 5, 2, 16, 20, 10, 1]
ns : [17, 18, 14, 9, 5, 2, 16, 20, 10, 1]
ns : [17, 18, 14, 9, 5, 16, 2, 20, 10, 1]
ns : [17, 18, 14, 9, 5, 16, 20, 2, 10, 1]
ns : [17, 18, 14, 9, 5, 16, 20, 10, 2, 1]
ns : [18, 17, 14, 9, 5, 16, 20, 10, 2, 1]
ns : [18, 17, 14, 9, 5, 16, 20, 10, 2, 1]
ns : [18, 17, 14, 9, 5, 16, 20, 10, 2, 1]
ns : [18, 17, 14, 9, 5, 16, 20, 10, 2, 1]
ns : [18, 17, 14, 9, 16, 5, 20, 10, 2, 1]
ns : [18, 17, 14, 9, 16, 20, 5, 10, 2, 1]
ns : [18, 17, 14, 9, 16, 20, 10, 5, 2, 1]
ns : [18, 17, 14, 9, 16, 20, 10, 5, 2, 1]
ns : [18, 17, 14, 9, 16, 20, 10, 5, 2, 1]
ns : [18, 17, 14, 9, 16, 20, 10, 5, 2, 1]
ns : [18, 17, 14, 16, 9, 20, 10, 5, 2, 1]
ns : [18, 17, 14, 16, 20, 9, 10, 5, 2, 1]
ns : [18, 17, 14, 16, 20, 10, 9, 5, 2, 1]
ns : [18, 17, 14, 16, 20, 10, 9, 5, 2, 1]
ns : [18, 17, 14, 16, 20, 10, 9, 5, 2, 1]
ns : [18, 17, 16, 14, 20, 10, 9, 5, 2, 1]
ns : [18, 17, 16, 20, 14, 10, 9, 5, 2, 1]
ns : [18, 17, 16, 20, 14, 10, 9, 5, 2, 1]
ns : [18, 17, 16, 20, 14, 10, 9, 5, 2, 1]
ns : [18, 17, 16, 20, 14, 10, 9, 5, 2, 1]
ns : [18, 17, 20, 16, 14, 10, 9, 5, 2, 1]
ns : [18, 17, 20, 16, 14, 10, 9, 5, 2, 1]
ns : [18, 17, 20, 16, 14, 10, 9, 5, 2, 1]
ns : [18, 20, 17, 16, 14, 10, 9, 5, 2, 1]
ns : [18, 20, 17, 16, 14, 10, 9, 5, 2, 1]
ns : [20, 18, 17, 16, 14, 10, 9, 5, 2, 1]
ns : [20, 18, 17, 16, 14, 10, 9, 5, 2, 1]
ns : [20, 18, 17, 16, 14, 10, 9, 5, 2, 1]
sorted nums ny DESC: [20, 18, 17, 16, 14, 10, 9, 5, 2, 1]
✏ 삽입정렬 알고리즘

import copy
def insertAlgorithm(ns,asc=True):
cns = copy.copy(ns)
for i1 in range(1, len(cns)):
i2 = i1 -1
cNum = cns[i1]
if asc :
while cns[i2] > cNum and i2 >= 0:
cns[i2 + 1] = cns[i2]
i2 -= 1
else :
while cns[i2] < cNum and i2 >= 0:
cns[i2 + 1] = cns[i2]
i2 -= 1
cns[i2 + 1] = cNum
print(f'cns : {cns}')
return cns
import random
import insertMod
if __name__ == '__main__' :
nums = random.sample(range(1, 21), 10)
print(f'not sorted nums : \n{nums}')
result = insertMod.insertAlgorithm(nums)
print(f'sorted nums by ASC : \n{result}')
print()
print(f'not sorted nums : \n{nums}')
result = insertMod.insertAlgorithm(nums, asc=False)
print(f'sorted nums by DESC : \n{result}')
↓
not sorted nums :
[20, 11, 12, 1, 4, 15, 17, 6, 9, 16]
cns : [11, 20, 12, 1, 4, 15, 17, 6, 9, 16]
cns : [11, 12, 20, 1, 4, 15, 17, 6, 9, 16]
cns : [1, 11, 12, 20, 4, 15, 17, 6, 9, 16]
cns : [1, 4, 11, 12, 20, 15, 17, 6, 9, 16]
cns : [1, 4, 11, 12, 15, 20, 17, 6, 9, 16]
cns : [1, 4, 11, 12, 15, 17, 20, 6, 9, 16]
cns : [1, 4, 6, 11, 12, 15, 17, 20, 9, 16]
cns : [1, 4, 6, 9, 11, 12, 15, 17, 20, 16]
cns : [1, 4, 6, 9, 11, 12, 15, 16, 17, 20]
sorted nums by ASC :
[1, 4, 6, 9, 11, 12, 15, 16, 17, 20]
not sorted nums :
[20, 11, 12, 1, 4, 15, 17, 6, 9, 16]
cns : [20, 11, 12, 1, 4, 15, 17, 6, 9, 16]
cns : [20, 12, 11, 1, 4, 15, 17, 6, 9, 16]
cns : [20, 12, 11, 1, 4, 15, 17, 6, 9, 16]
cns : [20, 12, 11, 4, 1, 15, 17, 6, 9, 16]
cns : [20, 15, 12, 11, 4, 1, 17, 6, 9, 16]
cns : [20, 17, 15, 12, 11, 4, 1, 6, 9, 16]
cns : [20, 17, 15, 12, 11, 6, 4, 1, 9, 16]
cns : [20, 17, 15, 12, 11, 9, 6, 4, 1, 16]
cns : [20, 17, 16, 15, 12, 11, 9, 6, 4, 1]
sorted nums by DESC :
[20, 17, 16, 15, 12, 11, 9, 6, 4, 1]
✏ 선택정렬 알고리즘

import copy
def selectAlgorithm(ns, asc=True):
cns = copy.copy(ns)
for i in range(len(cns) - 1):
minIdx = i
for j in range(i+1, len(cns)):
if asc :
if cns[minIdx] > cns[j]:
minIdx = j
else:
if cns[minIdx] < cns[j]:
minIdx = j
cns[i], cns[minIdx] = cns[minIdx], cns[i]
print(f' nums : {cns}')
return cns
import random
import selectMod
if __name__ == '__main__' :
nums = random.sample(range(1, 21), 10)
print(f'not sorted nums : \n{nums}')
result = selectMod.selectAlgorithm(nums)
print(f'sorted nums by ASC : \n{result}')
print()
print(f'not sorted nums : \n{nums}')
result = selectMod.selectAlgorithm(nums, asc=False)
print(f'sorted nums by DESC : \n{result}')
↓
not sorted nums :
[15, 17, 16, 20, 2, 8, 10, 12, 4, 19]
nums : [2, 17, 16, 20, 15, 8, 10, 12, 4, 19]
nums : [2, 4, 16, 20, 15, 8, 10, 12, 17, 19]
nums : [2, 4, 8, 20, 15, 16, 10, 12, 17, 19]
nums : [2, 4, 8, 10, 15, 16, 20, 12, 17, 19]
nums : [2, 4, 8, 10, 12, 16, 20, 15, 17, 19]
nums : [2, 4, 8, 10, 12, 15, 20, 16, 17, 19]
nums : [2, 4, 8, 10, 12, 15, 16, 20, 17, 19]
nums : [2, 4, 8, 10, 12, 15, 16, 17, 20, 19]
nums : [2, 4, 8, 10, 12, 15, 16, 17, 19, 20]
sorted nums by ASC :
[2, 4, 8, 10, 12, 15, 16, 17, 19, 20]
not sorted nums :
[15, 17, 16, 20, 2, 8, 10, 12, 4, 19]
nums : [20, 17, 16, 15, 2, 8, 10, 12, 4, 19]
nums : [20, 19, 16, 15, 2, 8, 10, 12, 4, 17]
nums : [20, 19, 17, 15, 2, 8, 10, 12, 4, 16]
nums : [20, 19, 17, 16, 2, 8, 10, 12, 4, 15]
nums : [20, 19, 17, 16, 15, 8, 10, 12, 4, 2]
nums : [20, 19, 17, 16, 15, 12, 10, 8, 4, 2]
nums : [20, 19, 17, 16, 15, 12, 10, 8, 4, 2]
nums : [20, 19, 17, 16, 15, 12, 10, 8, 4, 2]
nums : [20, 19, 17, 16, 15, 12, 10, 8, 4, 2]
sorted nums by DESC :
[20, 19, 17, 16, 15, 12, 10, 8, 4, 2]
✏ 병합정렬

def mSort(ns, asc=True):
if len(ns) < 2 :
return ns
midIdx = len(ns) // 2
leftNums = mSort(ns[0:midIdx], asc=asc)
rightNums = mSort(ns[midIdx:len(ns)], asc=asc)
mergeNums = []
lefIdx = 0; rightIdx = 0
while lefIdx < len(leftNums) and rightIdx < len(rightNums):
if asc:
if leftNums[lefIdx] < rightNums[rightIdx]:
mergeNums.append(leftNums[lefIdx])
lefIdx += 1
else :
mergeNums.append(rightNums[rightIdx])
rightIdx += 1
else:
if leftNums[lefIdx] > rightNums[rightIdx]:
mergeNums.append(leftNums[lefIdx])
lefIdx += 1
else :
mergeNums.append(rightNums[rightIdx])
rightIdx += 1
mergeNums += leftNums[lefIdx:]
mergeNums += rightNums[rightIdx:]
print(f'mergeNums : {mergeNums}')
return mergeNums
import random
import merge
rNums = random.sample(range(1, 101), 10)
print(f'rNums : {rNums}')
result = merge.mSort(rNums)
print(f'sorted nums by ASC : {result}')
result = merge.mSort(rNums, asc=False)
print(f'sorted nums by ASC : {result}')
↓
rNums : [99, 29, 72, 88, 10, 86, 19, 38, 8, 61]
mergeNums : [29, 99]
mergeNums : [10, 88]
mergeNums : [10, 72, 88]
mergeNums : [10, 29, 72, 88, 99]
mergeNums : [19, 86]
mergeNums : [8, 61]
mergeNums : [8, 38, 61]
mergeNums : [8, 19, 38, 61, 86]
mergeNums : [8, 10, 19, 29, 38, 61, 72, 86, 88, 99]
sorted nums by ASC : [8, 10, 19, 29, 38, 61, 72, 86, 88, 99]
mergeNums : [99, 29]
mergeNums : [88, 10]
mergeNums : [88, 72, 10]
mergeNums : [99, 88, 72, 29, 10]
mergeNums : [86, 19]
mergeNums : [61, 8]
mergeNums : [61, 38, 8]
mergeNums : [86, 61, 38, 19, 8]
mergeNums : [99, 88, 86, 72, 61, 38, 29, 19, 10, 8]
sorted nums by ASC : [99, 88, 86, 72, 61, 38, 29, 19, 10, 8]
✏ 최댓값 알고리즘

class MaxAlgorithm:
def __init__(self, ns):
self.nums = ns
selfmaxNum = 0
self.maxNumCnt = 0
def setMaxNum(self):
self.maxNum = 0
for i in self.nums:
if self.maxNum < i:
self.maxNum = i
return self.maxNum
def getMaxNum(self):
self.setMaxNum()
return self.maxNum
def setMaxNumCnt(self):
self.setMaxNum()
for i in self.nums:
if self.maxNum == i:
self.maxNumCnt += 1
def getMaxNumCnt(self):
self.setMaxNumCnt()
return self.maxNumCnt
import random
import maxMod01
if __name__ == '__main__' :
nums = []
for i in range(30):
nums.append(random.randint(1, 50))
print(f'nums : {nums}')
ma = maxMod01.MaxAlgorithm(nums)
print(f'maxNum : {ma.getMaxNum()}')
print(f'maxNumCnt : {ma.getMaxNumCnt()}')
↓
nums : [5, 10, 43, 48, 17, 13, 22, 44, 35, 6, 48, 1,
33, 3, 46, 21, 41, 21, 37, 18, 43, 28, 35, 14, 40, 3,
38, 41, 39, 19]
maxNum : 48
maxNumCnt : 2

def getAvg(ns):
total = 0
for i in ns:
total += i
return total / len(ns)
def getMax(ns):
maxN = ns[0]
for n in ns:
if maxN < n:
maxN = n
return maxN
def getDeviation(n1, n2):
return abs(n1-n2)
import random
import maxMod02
if __name__ == '__main__' :
scores = random.sample(range(50, 101),20)
print(f'scores : {scores}')
scoresAvg = maxMod02.getAvg(scores)
scoreMax = maxMod02.getMax(scores)
deviation = round(maxMod02.getDeviation(scoresAvg, scoreMax), 2)
print(f'scoreAvg : {scoresAvg}')
print(f'scoreMax : {scoreMax}')
print(f'deviation : {deviation}')
↓
scores : [95, 53, 56, 78, 59, 82, 74, 75, 77, 62, 83,
97, 73, 71, 87, 96, 81, 93, 61, 66]
scoreAvg : 75.95
scoreMax : 97
deviation : 21.05
✏ 최솟값 알고즘

import random
def getMinNum(ns):
minN = ns[0]
for n in ns:
if minN > n:
minN = n
return minN
def getMinCnt(ns, minNum):
minNumCnt = 0
for i in ns:
if minNum == i:
minNumCnt += 1
return minNumCnt
nums = []
for i in range(30):
nums.append(random.randint(1, 50))
print(f'nums : {nums}')
result = getMinNum(nums)
resultCnt = getMinCnt(nums, result)
print(f'minNum : {result}')
print(f'minNumCnt : {resultCnt}')
↓
nums : [6, 42, 37, 47, 28, 37, 36, 41, 10, 10, 47, 34,
9, 7, 23, 23, 6, 41, 17, 38, 32, 41, 48, 40, 21, 13,
39, 9, 38, 8]
minNum : 6
minNumCnt : 2

def getAvg(ns):
total = 0
for i in ns:
total += i
return total / len(ns)
def getMin(ns):
minN = ns[0]
for n in ns:
if minN > n:
minN = n
return minN
def getDeviation(n1,n2):
return round(abs(n1-n2), 2)
import minMod
import random
scroes = random.sample(range(70, 101), 20)
scoresAvg = minMod.getAvg(scroes)
scoresMin = minMod.getMin(scroes)
deviation = minMod.getDeviation(scoresAvg, scoresMin)
print(f'scoresAvg : {scoresAvg}')
print(f'scoresMin : {scoresMin}')
print(f'deviation : {deviation}')
↓
scoresAvg : 84.25
scoresMin : 71
deviation : 13.25
✏ 최빈값 알고리즘

class MaxAlgorithm:
def __init__(self, ns):
self.nums = ns
self.maxNum = 0
self.maxNumIdx = 0
def setMaxIdxAndNum(self):
self.maxNum = 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 getMaxIdx(self):
return self.maxNumIdx
import maxMod
class ModeAlgorithm:
def __init__(self, ns, mn):
self.nums = ns
self.maxNum = mn
self.indexes = []
def setIndexList(self):
self.indexes = [0 for i in range(self.maxNum + 1)]
for n in self.nums:
self.indexes[n] = 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:
maxAlo = maxMod.MaxAlgorithm(self.indexes)
maxAlo.setMaxIdxAndNum()
maxNum = maxAlo.getMaxNum()
maxNumIdx = maxAlo.getMaxIdx()
if maxNum == 0:
break
print(f'{n:0>3} {maxNumIdx}세 빈도수 : {maxNum} \t', end='')
print('+' * maxNum)
self.indexes[maxNumIdx] = 0
n += 1
import modeMod
import maxMod
ages = [25, 27, 27, 24, 31, 34, 33, 31, 29, 25,
45, 37, 38, 46, 47, 22, 24, 29, 33, 35,
27, 34, 37, 40, 42, 29, 27, 25, 26, 27,
31, 31, 32, 38, 25, 27, 28, 40, 41, 34]
print(f'employee cnt: {len(ages)}명')
maxAlo = maxMod.MaxAlgorithm(ages)
maxAlo.setMaxIdxAndNum()
maxAge = maxAlo.getMaxNum()
print(f'maxAge : {maxAge}세')
modeAlo = modeMod.ModeAlgorithm(ages, maxAge)
modeAlo.setIndexList()
print(f'IndexList : {modeAlo.getIndexList()}')
modeAlo.printAges()
↓
employee cnt: 40명
maxAge : 47세
IndexList : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 4, 1, 6, 1, 3, 0, 4, 1, 2, 3, 1, 0, 2, 2, 0, 2, 1, 1, 0, 0, 1, 1, 1]
001 27세 빈도수 : 6 ++++++
002 25세 빈도수 : 4 ++++
003 31세 빈도수 : 4 ++++
004 29세 빈도수 : 3 +++
005 34세 빈도수 : 3 +++
006 24세 빈도수 : 2 ++
007 33세 빈도수 : 2 ++
008 37세 빈도수 : 2 ++
009 38세 빈도수 : 2 ++
010 40세 빈도수 : 2 ++
011 22세 빈도수 : 1 +
012 26세 빈도수 : 1 +
013 28세 빈도수 : 1 +
014 32세 빈도수 : 1 +
015 35세 빈도수 : 1 +
016 41세 빈도수 : 1 +
017 42세 빈도수 : 1 +
018 45세 빈도수 : 1 +
019 46세 빈도수 : 1 +
020 47세 빈도수 : 1 +

class LottoMode:
def __init__(self, ln):
self.lottoNums = ln
self.modeList = [0 for i in range(1,47)]
def getLottoNumMod(self):
for roundNums in self.lottoNums:
for num in roundNums:
self.modeList[num] = self.modeList[num] + 1
return self.modeList
def printModeList(self):
if sum(self.modeList) == 0:
return None
for i, m in enumerate(self.modeList):
if i != 0 :
print(f'로또 번호 : {i:>2}, 빈도 : {m}, {"*" * m}')
import random
import lottoMod
lottoList = []
tLotto = []
for i in range(10):
tLotto = random.sample(range(1, 46), 6)
lottoList.append(tLotto)
print(f'lottoList : {lottoList}')
lm = lottoMod.LottoMode(lottoList)
mList = lm.getLottoNumMod()
lm.printModeList()
↓
lottoList : [[2, 23, 27, 44, 4, 8], [12, 33, 45, 32,
16, 20], [20, 16, 7, 4, 36, 34], [34, 11, 40, 30, 24,
12], [28, 30, 40, 11, 38, 32], [27, 36, 3, 22, 28, 5],
[12, 21, 1, 41, 38, 22], [27, 35, 40, 21, 7, 31], [15,
31, 6, 10, 45, 28], [24, 16, 38, 4, 9, 33]]
로또 번호 : 1, 빈도 : 1, *
로또 번호 : 2, 빈도 : 1, *
로또 번호 : 3, 빈도 : 1, *
로또 번호 : 4, 빈도 : 3, ***
로또 번호 : 5, 빈도 : 1, *
로또 번호 : 6, 빈도 : 1, *
로또 번호 : 7, 빈도 : 2, **
로또 번호 : 8, 빈도 : 1, *
로또 번호 : 9, 빈도 : 1, *
로또 번호 : 10, 빈도 : 1, *
로또 번호 : 11, 빈도 : 2, **
로또 번호 : 12, 빈도 : 3, ***
로또 번호 : 13, 빈도 : 0,
로또 번호 : 14, 빈도 : 0,
로또 번호 : 15, 빈도 : 1, *
로또 번호 : 16, 빈도 : 3, ***
로또 번호 : 17, 빈도 : 0,
로또 번호 : 18, 빈도 : 0,
로또 번호 : 19, 빈도 : 0,
로또 번호 : 20, 빈도 : 2, **
로또 번호 : 21, 빈도 : 2, **
로또 번호 : 22, 빈도 : 2, **
로또 번호 : 23, 빈도 : 1, *
로또 번호 : 24, 빈도 : 2, **
로또 번호 : 25, 빈도 : 0,
로또 번호 : 26, 빈도 : 0,
로또 번호 : 27, 빈도 : 3, ***
로또 번호 : 28, 빈도 : 3, ***
로또 번호 : 29, 빈도 : 0,
로또 번호 : 30, 빈도 : 2, **
로또 번호 : 31, 빈도 : 2, **
로또 번호 : 32, 빈도 : 2, **
로또 번호 : 33, 빈도 : 2, **
로또 번호 : 34, 빈도 : 2, **
로또 번호 : 35, 빈도 : 1, *
로또 번호 : 36, 빈도 : 2, **
로또 번호 : 37, 빈도 : 0,
로또 번호 : 38, 빈도 : 3, ***
로또 번호 : 39, 빈도 : 0,
로또 번호 : 40, 빈도 : 3, ***
로또 번호 : 41, 빈도 : 1, *
로또 번호 : 42, 빈도 : 0,
로또 번호 : 43, 빈도 : 0,
로또 번호 : 44, 빈도 : 1, *
로또 번호 : 45, 빈도 : 2, **
✏ 근삿값 알고리즘

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]
import nearMod01
depth = int(float(input('input depth : ')))
print(f'depth: {depth}m')
na = nearMod01.NearAlgorithm(depth)
temp = na.getNearNumbers()
print(f'water temperature : {temp}도')
↓
input depth : 28
depth: 28m
water temperature : 6도

class BmiAlgorithm:
def __init__(self, h, w):
self.BMISection = {
18.5:['저체중', '정상'],
23: ['정상', '과체중'],
25: ['과체중', '비만']
}
self.userHeight = h
self.userWeight = w
self.userBMI = 0
self.userCondition = ''
self.nearNum = 0
self.minNum = 25
def calculatorBMI(self):
self.userBMI = round(self.userWeight / (self.userHeight * self.userHeight),2)
print(f'self.userMBI : {self.userBMI}')
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'nearNum : {self.nearNum}')
if self.userBMI <= self.nearNum:
self.userCondition = self.BMISection[self.nearNum][0]
else:
self.userCondition = self.BMISection[self.nearNum][1]
print(f'condition : {self.userCondition}')
import nearMod02
uHeight = float(input('input height(m)'))
uWeight = float(input('input weight(kg)'))
na = nearMod02.BmiAlgorithm(uHeight, uWeight)
na.calculatorBMI()
na.printUserCondition()
↓
input height(m)1.75
input weight(kg)65
self.userMBI : 21.22
nearNum : 23
condition : 정상
✏ 재귀 알고리즘

sales = [1200, 1300, 12500, 11000, 10500, 98000, 91000, 91500, 10500, 11500, 12000, 12500]
def salesUpAndDown(ss):
if len(ss) == 1:
return ss
print(f'sales : {ss}')
currentSales = ss.pop(0)
nextSales = ss[0]
increase = nextSales - currentSales
if increase > 0:
increase = '+' + str(increase)
print(f'매출 증감액 : {increase}')
return salesUpAndDown(ss)
if __name__ == '__main__' :
salesUpAndDown(sales)
↓
sales : [1200, 1300, 12500, 11000, 10500, 98000, 91000,
91500, 10500, 11500, 12000, 12500]
매출 증감액 : +100
sales : [1300, 12500, 11000, 10500, 98000, 91000,
91500, 10500, 11500, 12000, 12500]
매출 증감액 : +11200
sales : [12500, 11000, 10500, 98000, 91000, 91500,
10500, 11500, 12000, 12500]
매출 증감액 : -1500
sales : [11000, 10500, 98000, 91000, 91500, 10500,
11500, 12000, 12500]
매출 증감액 : -500
sales : [10500, 98000, 91000, 91500, 10500, 11500,
12000, 12500]
매출 증감액 : +87500
sales : [98000, 91000, 91500, 10500, 11500, 12000,
12500]
매출 증감액 : -7000
sales : [91000, 91500, 10500, 11500, 12000, 12500]
매출 증감액 : +500
sales : [91500, 10500, 11500, 12000, 12500]
매출 증감액 : -81000
sales : [10500, 11500, 12000, 12500]
매출 증감액 : +1000
sales : [11500, 12000, 12500]
매출 증감액 : +500
sales : [12000, 12500]
매출 증감액 : +500

class NumsSum :
def __init__(self, n1, n2):
self.bigNum = 0
self.smallNum = 0
self.setMin2(n1, n2)
def setMin2(self, n1, n2):
self.bigNum = n1
self.smallNum = n2
if n1 < n2:
self.bigNum = n2
self.smallNum = n1
def addNum(self,n):
if n <= 1:
return n
return n + self.addNum(n-1)
def sumBetweenNums(self):
return self.addNum(self.bigNum - 1) - self.addNum(self.smallNum)
import returnMod
num1 = int(input('input number1 : '))
num2 = int(input('input number2 : '))
ns = returnMod.NumsSum(num1, num2)
result = ns.sumBetweenNums()
print(f'result : {result}')
↓
input number1 : 10
input number2 : 3
result : 39
✏ 평균 알고리즘

import copy
class AvgAlorithm:
def __init__(self, l1, l2):
self.scores = l1
self.top5Scores = l2
self.maxN = 0
self.maxIdx = 0
self.minN = 0
self.minIdx = 0
self.total = 0
self.scoresAvg = 0
self.finalTop5Scores = copy.copy(self.top5Scores)
self.sortedTop5Scores = []
self.nearN = 0
def setMaxNumAndIdx(self):
self. maxN = 0
self.maxIdx = 0
for i,n in enumerate(self.scores):
if self.maxN < n:
self.maxN = n
self.maxIdx = i
def getMaxNum(self):
return self.maxN
def getMaxNumIdx(self):
return self.maxIdx
def setMinNumAndIdx(self):
self.setMaxNumAndIdx()
del self.scores[self.maxIdx]
self.minN = self.scores[0]
self.minIdx = 0
for i, n in enumerate(self.scores):
if self.minN > n:
self.minN = n
self.minIdx = i
def getMinNum(self):
return self.minN
def getMinNumIdx(self):
return self.minIdx
def setScoresAvg(self):
self.setMinNumAndIdx()
del self.scores[self.minIdx]
self.total = 0
for n in self.scores:
self.total += n
self.scoresAvg = round(self.total / len(self.scores),2)
return self.scoresAvg
def getTotal(self):
return round(self.total, 2)
def getScoresAvg(self):
return self.scoresAvg
def setTop5Scores(self):
self.scoresAvg
self.finalTop5Scores.append(self.scoresAvg)
def getTop5Scores(self):
return self.finalTop5Scores
def setSortedTop5Scores(self):
self.sortedTop5Scores = copy.copy(self.finalTop5Scores)
for n1 in range(len(self.sortedTop5Scores)):
for n2 in range(len(self.sortedTop5Scores)-1):
if self.sortedTop5Scores[n2] < self.sortedTop5Scores[n2+1]:
self.sortedTop5Scores[n2],self.sortedTop5Scores[n2+1] = self.sortedTop5Scores[n2+1], self.sortedTop5Scores[n2]
del self.sortedTop5Scores[len(self.sortedTop5Scores)-1]
return self.sortedTop5Scores
def getSortedTop5Scores(self):
return self.sortedTop5Scores
def printRankTop5Scores(self):
print('현재 전체 순위')
for i, n in enumerate(self.top5Scores):
print(f'{i + 1}위 → {n}')
print('↓')
print('최종 전체 순위')
for i, n in enumerate(self.sortedTop5Scores):
print(f'{i+1}위 → {n}')
import avgMod01
top5Scores = [9.12, 8.95, 8.12, 6.90, 6.18]
scores = [6.7, 5.9, 8.1, 7.9, 6.7, 7.3, 7.2, 8.2, 6.2, 5.8]
print(f'scores: {scores}')
am = avgMod01.AvgAlorithm(scores, top5Scores)
am.setScoresAvg()
scoresTotal = am.getTotal()
scoresAvg = am.getScoresAvg()
am.setTop5Scores()
top5 = am.getTop5Scores()
am.setSortedTop5Scores()
sortedTop5Scores = am.getSortedTop5Scores()
print(f'scoresTotal : {scoresTotal}')
print(f'scoresAvg : {scoresAvg}')
print(f'this scoresAvg in top5 : {top5}')
print(f'getSortedTop5Scores : {sortedTop5Scores}')
printRank = am.printRankTop5Scores()
↓
scores: [6.7, 5.9, 8.1, 7.9, 6.7, 7.3, 7.2, 8.2, 6.2, 5.8]
scoresTotal : 56.0
scoresAvg : 7.0
this scoresAvg in top5 : [9.12, 8.95, 8.12, 6.9, 6.18, 7.0]
getSortedTop5Scores : [9.12, 8.95, 8.12, 7.0, 6.9]
현재 전체 순위
1위 → 9.12
2위 → 8.95
3위 → 8.12
4위 → 6.9
5위 → 6.18
↓
최종 전체 순위
1위 → 9.12
2위 → 8.95
3위 → 8.12
4위 → 7.0
5위 → 6.9

kor_avg = 88; eng_avg = 82; mat_avg = 90
sci_avg = 78; his_avg = 92
hong_kor_score = 85; hong_eng_score = 90; hong_mat_score = 82
hong_sci_score = 88; hong_his_score = 100
stu19Cnt_kor_total = kor_avg * 20 - hong_kor_score
stu19Cnt_eng_total = eng_avg * 20 - hong_eng_score
stu19Cnt_mat_total = mat_avg * 20 - hong_mat_score
stu19Cnt_sci_total = sci_avg * 20 - hong_sci_score
stu19Cnt_his_total = his_avg * 20 - hong_his_score
stu19Cnt_kor_avg = stu19Cnt_kor_total / 19
stu19Cnt_eng_avg = stu19Cnt_eng_total / 19
stu19Cnt_mat_avg = stu19Cnt_mat_total / 19
stu19Cnt_sci_avg = stu19Cnt_sci_total / 19
stu19Cnt_his_avg = stu19Cnt_his_total / 19
kor_gap = hong_kor_score - stu19Cnt_kor_avg
eng_gap = hong_eng_score - stu19Cnt_eng_avg
mat_gap = hong_mat_score - stu19Cnt_mat_avg
sci_gap = hong_sci_score - stu19Cnt_sci_avg
his_gap = hong_his_score - stu19Cnt_his_avg
print(f'국어 점수 차이 : {"+" + str(round(kor_gap,2)) if kor_gap > 0 else round(kor_gap,2)}')
print(f'영어 점수 차이 : {"+" + str(round(eng_gap,2)) if eng_gap > 0 else round(eng_gap,2)}')
print(f'수학 점수 차이 : {"+" + str(round(mat_gap,2)) if mat_gap > 0 else round(mat_gap,2)}')
print(f'과학 점수 차이 : {"+" + str(round(sci_gap,2)) if sci_gap > 0 else round(sci_gap,2)}')
print(f'국사 점수 차이 : {"+" + str(round(his_gap,2)) if his_gap > 0 else round(his_gap,2)}')
stu19Cnt_total = stu19Cnt_kor_avg + stu19Cnt_mat_avg + stu19Cnt_eng_avg + stu19Cnt_sci_avg + stu19Cnt_his_avg
stu19Cnt_avg = stu19Cnt_total / 5
hong_total = hong_kor_score + hong_eng_score + hong_mat_score + hong_sci_score + hong_his_score
hong_avg = hong_total / 5
avg_gap = round(hong_avg - stu19Cnt_avg, 2)
print(f'평균 차이 : {"+" + str(round(avg_gap,2)) if avg_gap > 0 else round(avg_gap,2)}')
↓
국어 점수 차이 : -3.16
영어 점수 차이 : +8.42
수학 점수 차이 : -8.42
과학 점수 차이 : +10.53
국사 점수 차이 : +8.42
평균 차이 : +3.16