[데이터분석]파이썬 스터디노트13

bin·2023년 2월 24일
0

파이썬

목록 보기
12/12
post-thumbnail

최댓값

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

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

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

        return self.maxNum;

ma = MaxAlgorithm([-2,-4,5,7,10,0,8,20,-11])
maxNum = ma.getMaxNum()
print(f'maxNum: {maxNum}')

최솟값

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

    def getMinNum(self):
        self.minNum = self.nums[0]

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

        return self.minNum;

ma = MinAlgorithm([-2,-4,5,7,10,0,8,20,-11])
minNum = ma.getMinNum()
print(f'minNum: {minNum}')

최빈값

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 n > self.maxNum:
                self.maxNum = n
                self. maxNumIdx = i

    def getMaxNum(self):
        return self.maxNum

    def getMaxNumIdx(self):
        return self.maxNumIdx

nums = [1, 3, 7, 6, 7, 7, 7, 12, 12, 17]
maxAlo = MaxAlgorithm(nums)
maxAlo.setMaxIdxAndNum()
maxNum = maxAlo.getMaxNum()

indexes = [0 for i in range(maxNum + 1)]

for n in nums:
    indexes[n] += 1

maxAlo = MaxAlgorithm(indexes)
maxAlo.setMaxIdxAndNum()
maxNum = maxAlo.getMaxNum()
maxNumIndex = maxAlo.getMaxNumIdx()

print(f'{maxNumIndex}의 빈도수가 {maxNum}로 가장 높다.')

근삿값: 특정 값(참 값)과 가장 가까운 값

import random
nums = random.sample(range(0, 50), 20)  #중복 불가
print(f'nums: {nums}')

inputNum = int(input('input number: '))
print(f'inputNum: {inputNum}')

nearNum = 0
minNum = 50  #차이

for n in nums:
    absNum = abs(n - inputNum)
    if absNum < minNum:
        minNum = absNum
        nearNum = n

print(f'nearNum : {nearNum}')

평균

🔔실습

<모듈>

class Top5Players:
    def __init__(self, cs, ns):
        self.currentScores = cs
        self.newScores = ns

    def setAlignScore(self):
        nearIdx = 0 ; nearScore = 0 ; minNum = 10

        for i, s in enumerate(self.currentScores):
            absNum = abs(self.newScores - s)

            if absNum < minNum:
                minNum = absNum
                nearIdx = i
                nearScore = s

        if self.newScores >= self.currentScores[nearIdx]:
            for i in range(len(self.currentScores)-1, nearIdx, -1):
                self.currentScores[i] = self.currentScores[i-1] #하나씩 밀려남

            self.currentScores[nearIdx] = self.newScores

        else:
            for i in range(len(self.currentScores)-1, nearIdx +1, -1):
                self.currentScores[i] = self.currentScores[i-1]

            self.currentScores[nearIdx] = self.newScores

    def getFinalTop5Scores(self):
        return self.currentScores

<실행파일>

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'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.setAlignScore()
top5PlayerScores = tp.getFinalTop5Scores()
print(f'top5PlayerScores: {top5PlayerScores}')

재귀알고리즘: 나 자신을 다시 호출

  • 반복문 대신 재귀함수를 이용한 예
def recusion(num):
    if num > 0:
        print('*' * num)
        return recusion(num - 1)

    else:
        return 1

recusion(10)
  • 팩토리얼
def factorial(num):
    if num > 0:
        return num*factorial (num-1)
    else:
        return 1
  • 유클리드 호제법
def gcd(n1, n2):
    if n1 % n2 ==0:
        return n2
    
    else:
        return gcd(n2, n1 % n2)
  • 하노이의 탑
            #원판개수, 출발기둥, 도착기둥, 경유기둥
def moveDisc(discCnt, fromBar, toBar, viaBar):
    if discCnt == 1:
        print(f'{discCnt}disc를 {fromBar}에서 {toBar}(으)로 이동!')

    else:
        #(discCnt-1)개들을 경유 기둥으로 이동
        moveDisc(discCnt-1, fromBar, viaBar, toBar)

        #discCnt를 목적 기둥으로 이동
        print(f'{discCnt}disc를 {fromBar}에서 {toBar}(으)로 이동!')

        #(discCnt-1)개들을 도착 기둥으로 이동
        moveDisc(discCnt-1, viaBar, toBar, fromBar)
  • 병합정렬: 자료구조를 분할하고 각각의 분할된 자료구조를 정렬한 후 다시 병합하여 정렬
def mSort(ns):

    if len(ns) < 2:
        return ns

    midIdx = len(ns) // 2
    leftNums = mSort(ns[0:midIdx])
    rightNums = mSort(ns[midIdx:len(ns)])  #분할

    mergeNums = []  #병합
    leftIdx = 0; rightIdx = 0
    while leftIdx < len(leftNums) and rightIdx < len(rightNums):

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

        else:
            mergeNums.append(rightNums[rightIdx])
            rightIdx += 1

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

    return mergeNums
  • 퀵정렬: 기준 값보다 작은 값과 큰 값으로 분리한 후 다시 합친다
def qSort(ns):
    if len(ns) < 2:
        return ns

    midIdx = len(ns) // 2
    midVal = ns[midIdx]

    smallNums = []; sameNums = []; bigNums = []

    for n in ns:
        if n < midVal:
            smallNums.append(n)

        elif n == midVal:
            sameNums.append(n)

        else:
            bigNums.append(n)

    return qSort(smallNums) + sameNums + qSort(bigNums)

0개의 댓글