[제로베이스 데이터 취업스쿨] 23.06.26 스터디 노트

김준호·2023년 6월 26일
0
post-thumbnail

알고리즘 문제풀이

문제1) 선형검색

linearSearch.py

def linearSearch(ns, sn):

    searchResultIdx = -1

    print(f'Numbers : {ns}')
    print(f'Search Numbers : {sn}')

    n = 0
    while True:

        if n == len(ns):
            print('Search Fail')
            break

        if ns[n] == sn:
            searchResultIdx = n
            print(f'Search Success!')
            print(f'Search index : {searchResultIdx}')
            break
        n+=1
    return searchResultIdx

linear.py

import random
import linearSearch as ls

if __name__ == '__main__':

    rNum = random.sample(range(1,21),10)

    searchNum = int(input('input search Number : '))

    resultIdx = ls.linearSearch(rNum,searchNum)
    if resultIdx == -1:
        print(f'no result')
        print(f'Search result index : {resultIdx}')
    else:
        print('>>>Search Result<<<<')
        print(f'Search result index : {resultIdx}')
        print(f'search result Number : {rNum[resultIdx]}')
input search Number : 7
Numbers : [15, 10, 18, 11, 16, 8, 7, 3, 14, 20]
Search Numbers : 7
Search Success!
Search index : 6
>>>Search Result<<<<
Search result index : 6
search result Number : 7

문제2) 이진검색

검색 중 인접한 두 수 사이의 값을 검색한다면 무한으로 검색이 되어 무한루프에 빠지는 것을 주의

binaryModuel.py

def searchNumByBinary(ns, sn):

    searchResultIdx = -1
    staIdx = 0
    endIdx = len(ns)-1
    midIdx = (staIdx + endIdx) // 2
    midVal = ns[midIdx]
    print(f'staIdx : {staIdx}, endIdx : {endIdx}')
    print(f'midIdx : {midIdx}, midVal : {midVal}')


    while sn > ns[0] and sn <= ns[len(ns)-1]:
        if sn == ns[len(ns)-1]:
            searchResultIdx = len(ns)-1
            break
		
        #검색할 수가 딱 2개 수 사이에 있지만 찾을 수 없으면 무한루프가 되기 때문에 
        #그 상황이 오면 break를 걸어 반복문을 나와야 한다.
        if staIdx + 1 == endIdx:
            if ns[staIdx] != sn and ns[endIdx] != sn:
                break

        if sn > midVal:
            staIdx = midIdx
            midIdx = (staIdx + endIdx)//2
            midVal = ns[midIdx]
            print(f'+staIdx : {staIdx}, endIdx : {endIdx}')
            print(f'+midIdx : {midIdx}, midVal : {midVal}')

        elif sn == midVal:
            searchResultIdx = midIdx
            break

        elif  sn < midVal:
            endIdx = midIdx
            midIdx = (staIdx + endIdx) // 2
            midVal = ns[midIdx]
            print(f'-staIdx : {staIdx}, endIdx : {endIdx}')
            print(f'-midIdx : {midIdx}, midVal : {midVal}')

    return searchResultIdx

binary.py

import binaryModuel as bm

if __name__ == '__main__':

    nums=[1,2,4,6,7,8,10,11,13,15,16,17,20,21,23,24,27,28]
    searchNum = int(input('input search Number : '))


    resultIdx = bm.searchNumByBinary(nums, searchNum)
    print(f'nums : {nums}')

    if resultIdx == -1:
        print('search Fail!')
        print(f'search result index : {resultIdx}')
    else:
        print('>>> Search Result <<<')
        print(f'Search Result index : {resultIdx}')
        print(f'Search Result nums : {nums[resultIdx]}')

검색 성공

input search Number : 8
staIdx : 0, endIdx : 17
midIdx : 8, midVal : 13
-staIdx : 0, endIdx : 8
-midIdx : 4, midVal : 7
+staIdx : 4, endIdx : 8
+midIdx : 6, midVal : 10
-staIdx : 4, endIdx : 6
-midIdx : 5, midVal : 8
nums : [1, 2, 4, 6, 7, 8, 10, 11, 13, 15, 16, 17, 20, 21, 23, 24, 27, 28]
>>> Search Result <<<
Search Result index : 5
Search Result nums : 8

검색 실패

input search Number : 9
staIdx : 0, endIdx : 17
midIdx : 8, midVal : 13
-staIdx : 0, endIdx : 8
-midIdx : 4, midVal : 7
+staIdx : 4, endIdx : 8
+midIdx : 6, midVal : 10
-staIdx : 4, endIdx : 6
-midIdx : 5, midVal : 8
+staIdx : 5, endIdx : 6
+midIdx : 5, midVal : 8
nums : [1, 2, 4, 6, 7, 8, 10, 11, 13, 15, 16, 17, 20, 21, 23, 24, 27, 28]
search Fail!
search result index : -1

문제3) 순위

rankAlgorithm.py

def rankAlgorithm(ns):

    ranks = [0 for i in range(len(ns))]

    for idx, n1 in enumerate(ns):
        for n2 in ns:
            if n2 > n1:
                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}')

    sortedNum = [0 for i in range(len(ns))]

    for idx, rank in enumerate(ranks):
        sortedNum[rank] = ns[idx]
    return sortedNum
import random
import rnakAlgorithm as ra

if __name__ == '__main__':
    nums = random.sample(range(50,101),20)
    sortNums = ra.rankAlgorithm(nums)
    print(f'sortNums : {sortNums}')
nums : [70, 79, 80, 78, 54, 53, 75, 55, 100, 63, 66, 64, 69, 62, 77, 68, 94, 61, 89, 71]
ranks : [9, 4, 3, 5, 18, 19, 7, 17, 0, 14, 12, 13, 10, 15, 6, 11, 1, 16, 2, 8]
num : 70 	 rank: 10
num : 79 	 rank: 5
num : 80 	 rank: 4
num : 78 	 rank: 6
num : 54 	 rank: 19
num : 53 	 rank: 20
num : 75 	 rank: 8
num : 55 	 rank: 18
num : 100 	 rank: 1
num : 63 	 rank: 15
num : 66 	 rank: 13
num : 64 	 rank: 14
num : 69 	 rank: 11
num : 62 	 rank: 16
num : 77 	 rank: 7
num : 68 	 rank: 12
num : 94 	 rank: 2
num : 61 	 rank: 17
num : 89 	 rank: 3
num : 71 	 rank: 9
sortNums : [100, 94, 89, 80, 79, 78, 77, 75, 71, 70, 69, 68, 66, 64, 63, 62, 61, 55, 54, 53]

문제4) 순위2

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:
        #isalpha()함수는 정수는 받지 못해서 data들을 문자열로 캐스팅 후
        #사용
    if str(data).isalpha():
        ascIIDatas.append(ord(data))
        continue
    ascIIDatas.append(data)

print(f'ascIIDatas : {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 data2 > data1:
            ranks[idx] +=1

print(f'ranks after : {ranks}')

for i, d in enumerate(datas):
    #:>2 = 두자리를 오른쪽 정렬
    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']
ascIIDatas : [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 

문제5) 버블정렬

bubbleSortModuel.py

import copy
def bubbleSorted(ns, asc=True):
    c_ns = copy.copy(ns)
    length = len(c_ns)-1

    for i in range(length):
        for j in range(length - i):
            if asc:
                if c_ns[j] > c_ns[j+1]:
                    c_ns[j],c_ns[j+1] = c_ns[j+1],c_ns[j]
            else:
                if c_ns[j] < c_ns[j+1]:
                    c_ns[j],c_ns[j+1] = c_ns[j+1],c_ns[j]

            print(f'ns : {c_ns}')
        print()
    return c_ns

bubbleSort.py (실행파일)

import bubbleSortModuel as bs
import random
if __name__ == '__main__':
    nums = random.sample(range(1,21),10)
    print(f'not sorted nums : {nums}')

    result = bs.bubbleSorted(nums)
    print(f'sorted nums by ASC : {result}')

    result = bs.bubbleSorted(nums, asc=False)
    print(f'sorted nums by DSC : {result}')
not sorted nums : [20, 6, 17, 9, 10, 12, 5, 11, 2, 8]
ns : [6, 20, 17, 9, 10, 12, 5, 11, 2, 8]
ns : [6, 17, 20, 9, 10, 12, 5, 11, 2, 8]
ns : [6, 17, 9, 20, 10, 12, 5, 11, 2, 8]
ns : [6, 17, 9, 10, 20, 12, 5, 11, 2, 8]
ns : [6, 17, 9, 10, 12, 20, 5, 11, 2, 8]
ns : [6, 17, 9, 10, 12, 5, 20, 11, 2, 8]
ns : [6, 17, 9, 10, 12, 5, 11, 20, 2, 8]
ns : [6, 17, 9, 10, 12, 5, 11, 2, 20, 8]
ns : [6, 17, 9, 10, 12, 5, 11, 2, 8, 20]

ns : [6, 17, 9, 10, 12, 5, 11, 2, 8, 20]
ns : [6, 9, 17, 10, 12, 5, 11, 2, 8, 20]
ns : [6, 9, 10, 17, 12, 5, 11, 2, 8, 20]
ns : [6, 9, 10, 12, 17, 5, 11, 2, 8, 20]
ns : [6, 9, 10, 12, 5, 17, 11, 2, 8, 20]
ns : [6, 9, 10, 12, 5, 11, 17, 2, 8, 20]
ns : [6, 9, 10, 12, 5, 11, 2, 17, 8, 20]
ns : [6, 9, 10, 12, 5, 11, 2, 8, 17, 20]

ns : [6, 9, 10, 12, 5, 11, 2, 8, 17, 20]
ns : [6, 9, 10, 12, 5, 11, 2, 8, 17, 20]
ns : [6, 9, 10, 12, 5, 11, 2, 8, 17, 20]
ns : [6, 9, 10, 5, 12, 11, 2, 8, 17, 20]
ns : [6, 9, 10, 5, 11, 12, 2, 8, 17, 20]
ns : [6, 9, 10, 5, 11, 2, 12, 8, 17, 20]
ns : [6, 9, 10, 5, 11, 2, 8, 12, 17, 20]

ns : [6, 9, 10, 5, 11, 2, 8, 12, 17, 20]
ns : [6, 9, 10, 5, 11, 2, 8, 12, 17, 20]
ns : [6, 9, 5, 10, 11, 2, 8, 12, 17, 20]
ns : [6, 9, 5, 10, 11, 2, 8, 12, 17, 20]
ns : [6, 9, 5, 10, 2, 11, 8, 12, 17, 20]
ns : [6, 9, 5, 10, 2, 8, 11, 12, 17, 20]

ns : [6, 9, 5, 10, 2, 8, 11, 12, 17, 20]
ns : [6, 5, 9, 10, 2, 8, 11, 12, 17, 20]
ns : [6, 5, 9, 10, 2, 8, 11, 12, 17, 20]
ns : [6, 5, 9, 2, 10, 8, 11, 12, 17, 20]
ns : [6, 5, 9, 2, 8, 10, 11, 12, 17, 20]

ns : [5, 6, 9, 2, 8, 10, 11, 12, 17, 20]
ns : [5, 6, 9, 2, 8, 10, 11, 12, 17, 20]
ns : [5, 6, 2, 9, 8, 10, 11, 12, 17, 20]
ns : [5, 6, 2, 8, 9, 10, 11, 12, 17, 20]

ns : [5, 6, 2, 8, 9, 10, 11, 12, 17, 20]
ns : [5, 2, 6, 8, 9, 10, 11, 12, 17, 20]
ns : [5, 2, 6, 8, 9, 10, 11, 12, 17, 20]

ns : [2, 5, 6, 8, 9, 10, 11, 12, 17, 20]
ns : [2, 5, 6, 8, 9, 10, 11, 12, 17, 20]

ns : [2, 5, 6, 8, 9, 10, 11, 12, 17, 20]

sorted nums by ASC : [2, 5, 6, 8, 9, 10, 11, 12, 17, 20]

ns : [20, 6, 17, 9, 10, 12, 5, 11, 2, 8]
ns : [20, 17, 6, 9, 10, 12, 5, 11, 2, 8]
ns : [20, 17, 9, 6, 10, 12, 5, 11, 2, 8]
ns : [20, 17, 9, 10, 6, 12, 5, 11, 2, 8]
ns : [20, 17, 9, 10, 12, 6, 5, 11, 2, 8]
ns : [20, 17, 9, 10, 12, 6, 5, 11, 2, 8]
ns : [20, 17, 9, 10, 12, 6, 11, 5, 2, 8]
ns : [20, 17, 9, 10, 12, 6, 11, 5, 2, 8]
ns : [20, 17, 9, 10, 12, 6, 11, 5, 8, 2]

ns : [20, 17, 9, 10, 12, 6, 11, 5, 8, 2]
ns : [20, 17, 9, 10, 12, 6, 11, 5, 8, 2]
ns : [20, 17, 10, 9, 12, 6, 11, 5, 8, 2]
ns : [20, 17, 10, 12, 9, 6, 11, 5, 8, 2]
ns : [20, 17, 10, 12, 9, 6, 11, 5, 8, 2]
ns : [20, 17, 10, 12, 9, 11, 6, 5, 8, 2]
ns : [20, 17, 10, 12, 9, 11, 6, 5, 8, 2]
ns : [20, 17, 10, 12, 9, 11, 6, 8, 5, 2]

ns : [20, 17, 10, 12, 9, 11, 6, 8, 5, 2]
ns : [20, 17, 10, 12, 9, 11, 6, 8, 5, 2]
ns : [20, 17, 12, 10, 9, 11, 6, 8, 5, 2]
ns : [20, 17, 12, 10, 9, 11, 6, 8, 5, 2]
ns : [20, 17, 12, 10, 11, 9, 6, 8, 5, 2]
ns : [20, 17, 12, 10, 11, 9, 6, 8, 5, 2]
ns : [20, 17, 12, 10, 11, 9, 8, 6, 5, 2]

ns : [20, 17, 12, 10, 11, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 10, 11, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 10, 11, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]

ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]

ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]

ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]

ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]
ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]

ns : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]

sorted nums by DSC : [20, 17, 12, 11, 10, 9, 8, 6, 5, 2]

문제6) 삽입정렬

insertSortModuel.py

import copy
def insertSort(ns, asc=True):
    c_ns = copy.copy(ns)

    for i1 in range(1,len(c_ns)):
        i2 = i1 -1
        c_Num = c_ns[i1]
        if asc: #ascending
            n = 0
            while c_ns[i2] > c_Num and i2 >= 0:
                c_ns[i2+1] = c_ns[i2]
                i2 -= 1
        else:   #decending
            while c_ns[i2] < c_Num and i2 >= 0:
                c_ns[i2+1] = c_ns[i2]
                i2 -= 1

        c_ns[i2 +1] = c_Num
        print(f'c_ns : {c_ns}')

    return c_ns

insertSort.py (실행파일)

import insertSortMdouel as ism
import random

if __name__ == '__main__':
    nums = random.sample(range(1,21),10)
    print(f'not sorted nums:\n {nums}')
    result = ism.insertSort(nums)
    print(f'sorted nums by ASC :\n {result}')
    print()
    print(f'not sorted nums:\n {nums}')
    result = ism.insertSort(nums,asc=False)
    print(f'sorted nums by DSC :\n {result}')
not sorted nums:
 [8, 20, 5, 17, 7, 4, 13, 9, 6, 19]
c_ns : [8, 20, 5, 17, 7, 4, 13, 9, 6, 19]
c_ns : [5, 8, 20, 17, 7, 4, 13, 9, 6, 19]
c_ns : [5, 8, 17, 20, 7, 4, 13, 9, 6, 19]
c_ns : [5, 7, 8, 17, 20, 4, 13, 9, 6, 19]
c_ns : [4, 5, 7, 8, 17, 20, 13, 9, 6, 19]
c_ns : [4, 5, 7, 8, 13, 17, 20, 9, 6, 19]
c_ns : [4, 5, 7, 8, 9, 13, 17, 20, 6, 19]
c_ns : [4, 5, 6, 7, 8, 9, 13, 17, 20, 19]
c_ns : [4, 5, 6, 7, 8, 9, 13, 17, 19, 20]
sorted nums by ASC :
 [4, 5, 6, 7, 8, 9, 13, 17, 19, 20]

not sorted nums:
 [8, 20, 5, 17, 7, 4, 13, 9, 6, 19]
c_ns : [20, 8, 5, 17, 7, 4, 13, 9, 6, 19]
c_ns : [20, 8, 5, 17, 7, 4, 13, 9, 6, 19]
c_ns : [20, 17, 8, 5, 7, 4, 13, 9, 6, 19]
c_ns : [20, 17, 8, 7, 5, 4, 13, 9, 6, 19]
c_ns : [20, 17, 8, 7, 5, 4, 13, 9, 6, 19]
c_ns : [20, 17, 13, 8, 7, 5, 4, 9, 6, 19]
c_ns : [20, 17, 13, 9, 8, 7, 5, 4, 6, 19]
c_ns : [20, 17, 13, 9, 8, 7, 6, 5, 4, 19]
c_ns : [20, 19, 17, 13, 9, 8, 7, 6, 5, 4]
sorted nums by DSC :
 [20, 19, 17, 13, 9, 8, 7, 6, 5, 4]

문제7) 선택정렬

selectSortModuel.py

import copy
def selectSort(ns, asc=True):
    c_ns = copy.copy(ns)
    for i in range(len(c_ns)-1):
        minIdx = i

        for j in range(i+1,len(c_ns)):
            if asc:
                if c_ns[minIdx] > c_ns[j]:
                    minIdx = j
            else:
                if c_ns[minIdx] < c_ns[j]:
                    minIdx = j

        c_ns[i],c_ns[minIdx] = c_ns[minIdx],c_ns[i]
        print(f'nums : {c_ns}')

    return c_ns

selectSort.py

import random
import selectSortModuel as ssm

if __name__ == '__main__':
    nums = random.sample(range(1,21),10)
    print(f'not sort nums :\n {nums}')
    result = ssm.selectSort(nums)
    print(f'sorted nums by ASC: {result}')
    print()
    print(f'not sort nums :\n {nums}')
    result = ssm.selectSort(nums, asc = False)
    print(f'sorted nums by DSC: {result}')
not sort nums :
 [11, 12, 4, 5, 7, 14, 16, 18, 13, 8]
nums : [4, 12, 11, 5, 7, 14, 16, 18, 13, 8]
nums : [4, 5, 11, 12, 7, 14, 16, 18, 13, 8]
nums : [4, 5, 7, 12, 11, 14, 16, 18, 13, 8]
nums : [4, 5, 7, 8, 11, 14, 16, 18, 13, 12]
nums : [4, 5, 7, 8, 11, 14, 16, 18, 13, 12]
nums : [4, 5, 7, 8, 11, 12, 16, 18, 13, 14]
nums : [4, 5, 7, 8, 11, 12, 13, 18, 16, 14]
nums : [4, 5, 7, 8, 11, 12, 13, 14, 16, 18]
nums : [4, 5, 7, 8, 11, 12, 13, 14, 16, 18]
sorted nums by ASC: [4, 5, 7, 8, 11, 12, 13, 14, 16, 18]

not sort nums :
 [11, 12, 4, 5, 7, 14, 16, 18, 13, 8]
nums : [18, 12, 4, 5, 7, 14, 16, 11, 13, 8]
nums : [18, 16, 4, 5, 7, 14, 12, 11, 13, 8]
nums : [18, 16, 14, 5, 7, 4, 12, 11, 13, 8]
nums : [18, 16, 14, 13, 7, 4, 12, 11, 5, 8]
nums : [18, 16, 14, 13, 12, 4, 7, 11, 5, 8]
nums : [18, 16, 14, 13, 12, 11, 7, 4, 5, 8]
nums : [18, 16, 14, 13, 12, 11, 8, 4, 5, 7]
nums : [18, 16, 14, 13, 12, 11, 8, 7, 5, 4]
nums : [18, 16, 14, 13, 12, 11, 8, 7, 5, 4]
sorted nums by DSC: [18, 16, 14, 13, 12, 11, 8, 7, 5, 4]

문제8) 병합정렬

mergeSortModuel.py

def mergeSort(ns, asc=True):

    if len(ns)<2:
        return ns

    midIdx = len(ns)//2
    leftNums = mergeSort(ns[0:midIdx], asc=asc)
    rightNum  = mergeSort(ns[midIdx:len(ns)], asc=asc)

    mergeNums = []
    leftIdx = 0; rightIdx = 0
    while leftIdx < len(leftNums) and rightIdx < len(rightNum):

        if asc:
            if leftNums[leftIdx] < rightNum[rightIdx]:
                mergeNums.append(leftNums[leftIdx])
                leftIdx+=1
            else:
                mergeNums.append(rightNum[rightIdx])
                rightIdx+=1

        else:
            if leftNums[leftIdx] > rightNum[rightIdx]:
                mergeNums.append(leftNums[leftIdx])
                leftIdx+=1
            else:
                mergeNums.append(rightNum[rightIdx])
                rightIdx+=1

    mergeNums += leftNums[leftIdx:]
    mergeNums += rightNum[rightIdx:]

    print(f'mergeNums : {mergeNums}')
    return mergeNums

mergeSort.py

import random
import mergeSortModuel as msm

if __name__ == '__main__':
    nums = random.sample(range(1,100),20)
    print(f'not sort nums : {nums}')
    print(f'mergeSort by ASC : {msm.mergeSort(nums)}')
    print()
    print(f'not sort nums : {nums}')
    print(f'mergeSort by DSC: {msm.mergeSort(nums,asc=False)}')
not sort nums : [97, 43, 54, 9, 5, 46, 37, 1, 69, 24, 86, 13, 65, 61, 76, 3, 29, 44, 77, 23]
mergeNums : [43, 97]
mergeNums : [5, 9]
mergeNums : [5, 9, 54]
mergeNums : [5, 9, 43, 54, 97]
mergeNums : [37, 46]
mergeNums : [24, 69]
mergeNums : [1, 24, 69]
mergeNums : [1, 24, 37, 46, 69]
mergeNums : [1, 5, 9, 24, 37, 43, 46, 54, 69, 97]
mergeNums : [13, 86]
mergeNums : [61, 76]
mergeNums : [61, 65, 76]
mergeNums : [13, 61, 65, 76, 86]
mergeNums : [3, 29]
mergeNums : [23, 77]
mergeNums : [23, 44, 77]
mergeNums : [3, 23, 29, 44, 77]
mergeNums : [3, 13, 23, 29, 44, 61, 65, 76, 77, 86]
mergeNums : [1, 3, 5, 9, 13, 23, 24, 29, 37, 43, 44, 46, 54, 61, 65, 69, 76, 77, 86, 97]
mergeSort : [1, 3, 5, 9, 13, 23, 24, 29, 37, 43, 44, 46, 54, 61, 65, 69, 76, 77, 86, 97]

not sort nums : [97, 43, 54, 9, 5, 46, 37, 1, 69, 24, 86, 13, 65, 61, 76, 3, 29, 44, 77, 23]
mergeNums : [97, 43]
mergeNums : [9, 5]
mergeNums : [54, 9, 5]
mergeNums : [97, 54, 43, 9, 5]
mergeNums : [46, 37]
mergeNums : [69, 24]
mergeNums : [69, 24, 1]
mergeNums : [69, 46, 37, 24, 1]
mergeNums : [97, 69, 54, 46, 43, 37, 24, 9, 5, 1]
mergeNums : [86, 13]
mergeNums : [76, 61]
mergeNums : [76, 65, 61]
mergeNums : [86, 76, 65, 61, 13]
mergeNums : [29, 3]
mergeNums : [77, 23]
mergeNums : [77, 44, 23]
mergeNums : [77, 44, 29, 23, 3]
mergeNums : [86, 77, 76, 65, 61, 44, 29, 23, 13, 3]
mergeNums : [97, 86, 77, 76, 69, 65, 61, 54, 46, 44, 43, 37, 29, 24, 23, 13, 9, 5, 3, 1]
mergeSort : [97, 86, 77, 76, 69, 65, 61, 54, 46, 44, 43, 37, 29, 24, 23, 13, 9, 5, 3, 1]

문제9) 최댓값

maxModuel.py

class MaxAlgorithm:
    def __init__(self, ns):
        self.nums = ns
        self.maxNum = 0
        self.maxNumCnt = 0

    def setMaxNum(self):
        self.maxNum = self.nums[0]

        for n in self.nums:
            if self.maxNum < n:
                self.maxNum = n

    def getMaxNum(self):
        self.setMaxNum()
        return self.maxNum

    def setMaxNumCnt(self):
        self.setMaxNum()

        for n in self.nums:
            if self.maxNum == n:
                self.maxNumCnt+=1

    def getMaxNumCnt(self):
        self.setMaxNumCnt()
        return self.maxNumCnt

max.py (실행파일)

import random
import maxModuel as mm

if __name__ == '__main__':
        
    #중복허용 난수 리스트 생성
    nums = []
    for n in range(30):
        nums.append(random.randint(1,50))

    print(f'nums : {nums}')
    ma = mm.MaxAlgorithm(nums)
    print(f'maxNum : {ma.getMaxNum()}')
    print(f'maxNumCnt : {ma.getMaxNumCnt()}')
nums : [16, 34, 14, 18, 26, 30, 36, 37, 32, 35, 21, 37, 47, 44, 11, 35, 50, 50, 47, 11, 45, 32, 49, 
20, 5, 1, 34, 12, 49, 7]
maxNum : 50
maxNumCnt : 2

문제10) 최댓값2

maxModuel.py

def getAvg(ns):
    total = 0
    for n in ns:
        total += n

    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 round(abs(n1-n2),2)

max.py

import maxModuel
import random

scores = random.sample(range(50,101),20)
print(f'scores : {scores}')

scoresAvg = maxModuel.getAvg(scores)
scoresMax = maxModuel.getMax(scores)

deviation = maxModuel.getDeviation(scoresAvg,scoresMax)

print(f'scoresAvg : {scoresAvg}')
print(f'scoresMax : {scoresMax}')
print(f'deviation : {deviation}')
scores : [60, 59, 72, 73, 91, 96, 94, 57, 87, 51, 79, 58, 67, 65, 77, 62, 99, 75, 95, 71]
scoresAvg : 74.4
scoresMax : 99
deviation : 24.6

문제11) 최솟값

class이용해서

minModuel.py

class MinAlgorithm:
    def __init__(self,ns):
        self.nums = ns
        self.minNum = 0
        self.minNumCnt = 0

    def setMinNum(self):
        ###??????????
        self.minNum = self.nums[0]

        for n in self.nums:
            if self.minNum > n:
                self.minNum = n

    def getMinNum(self):
        self.setMinNum()
        return self.minNum

    def setMinNumCnt(self):
        self.setMinNum()

        for i in self.nums:
            if self.minNum == i:
                self.minNumCnt +=1

    def getMinNumCnt(self):
        self.setMinNumCnt()
        return self.minNumCnt

min.py

import minModuel as mm
import random


if __name__ == '__main__':
    nums = []
    for i in range(30):
        nums.append(random.randint(1,51))

    print(f'nums = {nums}')

    ma = mm.MinAlgorithm(nums)
    print(f'min Num = {ma.getMinNum()}')
    print(f'min Num Cnt = {ma.getMinNumCnt()}')
nums = [19, 21, 46, 9, 43, 50, 19, 39, 43, 7, 25, 3, 1, 29, 4, 15, 51, 12, 41, 44, 16, 29, 17, 
11, 1, 6, 5, 10, 3, 14]
min Num = 1
min Num Cnt = 2

문제12) 최솟값2

  • class를 생성해서 객체를 사용한다면 프로그램이 좀 더 견고해지고 효율적으로 작업 가능

mod2.py

class ScoreManagement:

    def __init__(self, ss):
        self.scores = ss
        self.score_tot = 0
        self.score_avg = 0
        self.score_min = 0
        self.score_max = 0

    def getMinScore(self):
        if self.scores == None or len(self.scores) == 0:
            return None

        self.score_min = self.scores[0]
        for score in self.scores:
            if self.score_min > score:
                self.score_min = score

        return self.score_min

    def getMaxScore(self):
        if self.scores == None or len(self.scores) == 0:
            return None

        self.score_max = self.scores[0]
        for score in self.scores:
            if self.score_max < score:
                self.score_max = score

        return self.score_max

    def getTotScore(self):
        if self.scores == None or len(self.scores) == 0:
            return None

        self.score_tot = 0
        for score in self.scores:
            self.score_tot += score

        return self.score_tot

    def getAvgScore(self):
        if self.scores == None or len(self.scores) == 0:
            return None

        self.score_avg = round(self.getTotScore() / len(self.scores), 2)
        return self.score_avg

    def getMaxDeviation(self):
        result = abs(self.getAvgScore() - self.getMaxScore())
        return round(result, 2)

    def getMinDeviation(self):
        result = abs(self.getAvgScore() - self.getMinScore())
        return round(result, 2)

ex.py

import mod2

scores = [100, 64, 94, 66, 75, 58, 99, 76, 96, 74,
          54, 73, 88, 70, 68, 50, 95, 89, 69, 98]

sm = mod2.ScoreManagement(scores)
print(f'score_avg: {sm.getAvgScore()}')
print(f'score_min: {sm.getMinScore()}')
print(f'score_max: {sm.getMaxScore()}')
print(f'score_min_deviation: {sm.getMinDeviation()}')
print(f'score_max_deviation: {sm.getMaxDeviation()}')

score_avg: 77.8
score_min: 50
score_max: 100
score_min_deviation: 27.8
score_max_deviation: 22.2

문제13) 최빈값

  • 최빈값은 먼저 최댓값 알고리즘을 사용하여 최댓값을 구해야 한다.
  • 최댓값 알고리즘 모듈, 최빈값 알고리즘 모듈, 실행파일 로 구성해야 한다.

maxModuel.py (최댓값 알고리즘 모듈)

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 idx, n in enumerate(self.nums):
            if self.maxNum < n:
                self.maxNum = n
                self.maxNumIdx = idx

    def getMaxNum(self):
        return self.maxNum

    def getMaxIdx(self):
        return self.maxNumIdx

mostComModuel.py (최빈값 알고리즘)

import maxModuel
class ModAlgorithm:
    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] += 1

    def getIndexList(self):
        if sum(self.indexes) == 0:
            return None
        else:
            return self.indexes

    def printAges(self):

        n =1
        while True:

            maxAlo = maxModuel.MaxAlgorithm(self.indexes)
            maxAlo.setMaxIdxAndNum()
            maxNum = maxAlo.getMaxNum()
            maxNumIdx = maxAlo.getMaxIdx()

            if maxNum == 0:
                break
            #:0>3 = 3자리 오른쪽 정렬, 비어있는곳은 0으로
            print(f'[{n:0>3}] {maxNumIdx}세 빈도수 : {maxNum}\t', end='')
            print('+'* maxNum)

            self.indexes[maxNumIdx] = 0

            n+=1

mostcommon.py

import mostComModuel as mcm
import maxModuel as mm

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 = mm.MaxAlgorithm(ages)
maxAlo.setMaxIdxAndNum()
maxAge = maxAlo.getMaxNum()
print(f'max age : {maxAge}세')

modAlo = mcm.ModAlgorithm(ages, maxAge)
modAlo.setIndexList()
print(f' IndexeList : {modAlo.getIndexList()}')

modAlo.printAges()
employee cnt : 40명
max age : 47세
 IndexeList : [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	+

문제14) 최빈값2

mod.py

class LottoMode:

    def __init__(self, ln):
        self.lottoNums = ln
        self.modeList = [0 for n in range(1, 47)]

    def getLottoNumMode(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}')

ex.py

import mod

lottoNums = [[13, 23, 15, 5, 6, 39], [36, 13, 5, 3, 30, 16], [43, 1, 15, 9, 3, 38],
             [32, 42, 24, 45, 8, 31], [18, 39, 41, 11, 4, 9], [12, 39, 11, 38, 32, 5],
             [29, 25, 13, 6, 14, 8], [21, 33, 19, 20, 42, 7], [6, 28, 3, 45, 41, 24],
             [42, 15, 8, 5, 35, 4], [14, 4, 35, 24, 29, 3], [15, 20, 6, 37, 34, 39],
             [27, 5, 32, 15, 25, 19], [45, 25, 2, 8, 30, 43], [4, 19, 33, 10, 6, 24],
             [25, 26, 45, 23, 24, 16], [33, 28, 45, 21, 38, 24], [4, 30, 29, 28, 32, 38],
             [11, 28, 12, 2, 42, 3], [40, 29, 16, 8, 9, 28], [6, 9, 37, 30, 3, 35],
             [29, 18, 41, 28, 38, 15], [9, 31, 13, 44, 1, 36], [36, 1, 37, 32, 15, 12],
             [41, 32, 16, 6, 26, 33], [12, 43, 10, 29, 39, 9], [41, 9, 23, 35, 18, 17],
             [35, 38, 3, 28, 36, 31], [21, 44, 4, 29, 18, 7], [20, 23, 6, 2, 34, 44]]

lm = mod.LottoMode(lottoNums)
mList = lm.getLottoNumMode()
# print(f'mList: {mList}')

lm.printModeList()
번호:  1, 빈도: 3, ***
번호:  2, 빈도: 3, ***
번호:  3, 빈도: 7, *******
번호:  4, 빈도: 6, ******
번호:  5, 빈도: 5, *****
번호:  6, 빈도: 8, ********
번호:  7, 빈도: 2, **
번호:  8, 빈도: 5, *****
번호:  9, 빈도: 7, *******
번호: 10, 빈도: 2, **
번호: 11, 빈도: 3, ***
번호: 12, 빈도: 4, ****
번호: 13, 빈도: 4, ****
번호: 14, 빈도: 2, **
번호: 15, 빈도: 7, *******
번호: 16, 빈도: 4, ****
번호: 17, 빈도: 1, *
번호: 18, 빈도: 4, ****
번호: 19, 빈도: 3, ***
번호: 20, 빈도: 3, ***
번호: 21, 빈도: 3, ***
번호: 22, 빈도: 0, 
번호: 23, 빈도: 4, ****
번호: 24, 빈도: 6, ******
번호: 25, 빈도: 4, ****
번호: 26, 빈도: 2, **
번호: 27, 빈도: 1, *
번호: 28, 빈도: 7, *******
번호: 29, 빈도: 7, *******
번호: 30, 빈도: 4, ****
번호: 31, 빈도: 3, ***
번호: 32, 빈도: 6, ******
번호: 33, 빈도: 4, ****
번호: 34, 빈도: 2, **
번호: 35, 빈도: 5, *****
번호: 36, 빈도: 4, ****
번호: 37, 빈도: 3, ***
번호: 38, 빈도: 6, ******
번호: 39, 빈도: 5, *****
번호: 40, 빈도: 1, *
번호: 41, 빈도: 5, *****
번호: 42, 빈도: 4, ****
번호: 43, 빈도: 3, ***
번호: 44, 빈도: 3, ***
번호: 45, 빈도: 5, *****

문제 15) 근사값

nearModuel.py

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 getNearNumber(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]

near.py (실행파일)

import nearModuel

depth = int(float(input('input depth: ')))
print(f'depth: {depth}m')

na = nearModuel.NearAlgorithm(depth)
temp = na.getNearNumber()
print(f'water temperature: {temp}도')
input depth: 13
depth: 13m
water temperature: 16도

문제16) 근사값2

nearModuel.py

class BmiAlgorithm:

    def __init__(self, w, h):
        self.BMISection = {18.5:['저체중', '정상'],
                           23:['정상','과체중'],
                           25:['과체중', '비만']}
        self.userWeight = w
        self.userHeight = h
        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'userBMI: {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'self.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'self.userCondition: {self.userCondition}')

near.py (실행파일)

import nearModuel

uWeight = float(input('input weight(Kg): '))
uHeight = float(input('input height(m): '))

na = nearModuel.BmiAlgorithm(uWeight, uHeight)
na.calculatorBMI()
na.printUserCondition()
input weight(Kg): 80
input height(m): 1.88
userBMI: 22.63
self.nearNum: 23
self.userCondition: 정상
profile
취업공부

0개의 댓글