1. 자료구조 문제풀이

문제1)

inputNum = int(input('숫자 입력: '))
listA = []
listB = []

#약수
for i in range(1,inputNum+1):
    if i == 1:
        listA.append(i)
    else:
        if inputNum % i == 0:
            listA.append(i)

#소수
for num in range(2,inputNum+1):
    flag = True
    for n in range(2,num):
        if num % n == 0:
            flag = False
            break

    if flag:
        listB.append(num)

print(f'{inputNum}의 약수 : {listA}')
print(f'{inputNum}까지 소수 : {listB}')
숫자 입력: 10
10의 약수 : [1, 2, 5, 10]
10까지 소수 : [2, 3, 5, 7]

문제2)

import random

ranList = random.sample(range(1,101),10)
evenList = []
oddList = []

for i in ranList:
    if i % 2 == 0:
        evenList.append(i)
    else:
        oddList.append(i)

lengthEven = len(evenList)
lengthOdd = len(oddList)

print(f'짝수 리스트 : {evenList}, 개수 : {lengthEven}')
print(f'홀수 리스트 : {oddList}, 개수 : {lengthOdd}')
짝수 리스트 : [36, 8, 84, 90, 74], 개수 : 5
홀수 리스트 : [83, 15, 45, 49, 99], 개수 : 5

문제3)

  1. 방문자 나이를 저장할 리스트 변수 선언
  2. 난수로 방문자 나이 생성 100개 해서 방문자 저장 리스트에 append
  3. 나이 구분을 group으로 변수설정
  4. 방문자 나이 리스트를 반복문을 돌려 구분되는 나이를 조건으로 수를 1씩 더함
  5. group에 나이에 따라 수가 저장 되었으면 각각 가격을 곱해서 또 다른 변수에 저장
  6. 영수증 양식 만들어 출력
import random

visitors = []

for n in range(100):
    #방문자 나이
    visitors.append(random.randint(1,100))

group1, group2, group3, group4, group5 = 0,0,0,0,0
for age in visitors:
    if age >0 and age <=7:
        group1 +=1
    elif age >= 8 and age <=13:
        group2 +=1
    elif age >= 14 and age <=19:
        group3 +=1
    elif age >= 20 and age <=64:
        group4 +=1
    else:
        group5 +=1

group1Price = group1*0
group2Price = group2*200
group3Price = group3*300
group4Price = group4*500
group5Price = group5*0

print('-'*25)
print(f'영유아 : {group1}명 : {group1Price}원')
print(f'어린이 : {group2}명 : {group2Price}원')
print(f'청소년 : {group3}명 : {group3Price}원')
print(f'성인 : {group4}명 : {group4Price}원')
print(f'어르신 : {group5}명 : {group5Price}원')
print('-'*25)
sum = group1Price+group2Price+group3Price+group4Price+group5Price
print('총합 : {}원'.format(format(sum,',')))
-------------------------
영유아 : 7명 : 0원
어린이 : 9명 : 1800원
청소년 : 5명 : 1500원
성인 : 35명 : 17500원
어르신 : 44명 : 0원
-------------------------
총합 : 20,800원

문제4)

numbers = [2,22,7,8,9,2,7,3,5,2,7,1,3]
print(f'처음 리스트 = {numbers}')

idx = 0
while True:

    #반복문 끝
    if idx >= len(numbers):
        break

    #중복된 숫자 하나 제거 후 다시 비교 idx가 늘어나면 안되기 때문에 continue사용
    if numbers.count(numbers[idx]) >=2:
        numbers.remove(numbers[idx])
        continue

    #중복이 되지 않았다면
    idx +=1

print(f'중복 제거 리스트 = {numbers}')
처음 리스트 = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
중복 제거 리스트 = [22, 8, 9, 5, 2, 7, 1, 3]

문제5)

numbers = [4,6,7,9]
result =[]

for n1 in numbers:
    for n2 in numbers:
        if n1 == n2:
            continue

        result.append([n1,n2])

print(f'result = {result}')
print(f'개수 = {len(result)}')
result = [[4, 6], [4, 7], [4, 9], [6, 4], [6, 7], [6, 9], [7, 4], 
		 [7, 6], [7, 9], [9, 4], [9, 6], [9, 7]]
개수 = 12

numbers = [4,6,7,9]
result =[]

for n1 in numbers:
    for n2 in numbers:
        if n1 == n2:
            continue
        for n3 in numbers:
            if n1 == n3 or n2 == n3:
                continue

            result.append([n1,n2,n3])

print(f'result = {result}')
print(f'개수 = {len(result)}')
result = [[4, 6, 7], [4, 6, 9], [4, 7, 6], [4, 7, 9], [4, 9, 6], [4, 9, 7], 
         [6, 4, 7], [6, 4, 9], [6, 7, 4], [6, 7, 9], [6, 9, 4], [6, 9, 7],
         [7, 4, 6], [7, 4, 9], [7, 6, 4], [7, 6, 9], [7, 9, 4], [7, 9, 6], 
         [9, 4, 6], [9, 4, 7], [9, 6, 4], [9, 6, 7], [9, 7, 4], [9, 7, 6]]
개수 = 24

문제6)

scores = ((3.7,4.2), (2.9,4.3),(4.1,4.2))
total = 0

for s1 in scores:
    for s2 in s1:
        total += s2

total = round(total,2)
avg = round(total / 6,2)
print(f'3학년 까지 총 점 : {total}')
print(f'3학년 까지 평균 : {avg}')

#4학년에 받아야 하는 학점을 알기 위해서는
#4.0을 받기위한 총점에서 지금까지의 총점을 빼면 된다.
grade4Target = round(4.0*8 - total,1)
print(f'4학년 목표 총점 : {grade4Target}')

minScore = round(grade4Target/2,1)
print(f'4학년 한 한기 최소 학점 : {minScore}')

#구한 4학년 목표 학점을 튜플에 넣기
scores = list(scores)
scores.append((minScore,minScore))
scores = tuple(scores)
print(f'총 점 : {scores}')
3학년 까지 총 점 : 23.4
3학년 까지 평균 : 3.9
4학년 목표 총점 : 8.6
4학년 한 한기 최소 학점 : 4.3
총 학점 : ((3.7, 4.2), (2.9, 4.3), (4.1, 4.2), (4.3, 4.3))

문제7)

for문 이용

tuple1 = (1,3,2,6,12,5,7,8)
tuple2 = (0,5,2,9,8,6,17,3)

tempHap = list(tuple1)
tempGyo = list()

for num in tuple2:
    if num not in tempHap:
        tempHap.append(num)
    else:
        tempGyo.append(num)

tempHap = tuple(sorted(tempHap))
tempGyo = tuple(sorted(tempGyo))

print(f'합집합(중복x) : {tempHap}')
print(f'교집합 : {tempGyo}')
합집합(중복x) : (0, 1, 2, 3, 5, 6, 7, 8, 9, 12, 17)
교집합 : (2, 3, 5, 6, 8)

while문 이용

tuple1 = (1,3,2,6,12,5,7,8)
tuple2 = (0,5,2,9,8,6,17,3)

tempHap = tuple1 + tuple2
tempGyo = list()

tempHap = list(tempHap)
print(f'tempHap : {tempHap}')
print(f'tempGyo : {tempGyo}')

idx = 0
while True:
    if idx >= len(tempHap):
        break

    if tempHap.count(tempHap[idx]) >=2:
        tempGyo.append(tempHap[idx])
        tempHap.remove(tempHap[idx])
        continue
    idx+=1

tempHap = tuple(sorted(tempHap))
tempGyo = tuple(sorted(tempGyo))

print(f'합집합(중복x) : {tempHap}')
print(f'교집합 : {tempGyo}')
합집합(중복x) : (0, 1, 2, 3, 5, 6, 7, 8, 9, 12, 17)
교집합 : (2, 3, 5, 6, 8)

문제8)

korScore = int(input('국어 점수 :'))
engScore = int(input('영어 점수 :'))
matScore = int(input('수핟 점수 :'))
sciScore = int(input('과학 점수 :'))
hisScore = int(input('국사 점수 :'))

scores = (
    {'kor':korScore},
    {'eng':engScore},
    {'mat':matScore},
    {'sci':sciScore},
    {'his':hisScore}
)

print(scores)

for item in scores:
    for key in item.keys():
        if item[key]>90:
            item[key] = 'A'
        elif item[key]>80:
            item[key]='B'
        elif item[key] > 70:
            item[key] = 'C'
        elif item[key] > 60:
            item[key] = 'D'
        else:
            item[key] = 'f'

print(scores)
국어 점수 :92
영어 점수 :86
수핟 점수 :77
과학 점수 :68
국사 점수 :54
({'kor': 92}, {'eng': 86}, {'mat': 77}, {'sci': 68}, {'his': 54})
({'kor': 'A'}, {'eng': 'B'}, {'mat': 'C'}, {'sci': 'D'}, {'his': 'f'})

문제9)

fruits = (
    {'수박':8},
    {'포도':13},
    {'참외':12},
    {'사과':17},
    {'자두':19},
    {'자몽':15}
)

fruits = list(fruits)

#튜플 안 아이템의 인덱스를 이용해서 0과 1, 0과2, 0과3... 비교후 작은게 앞으로 오게 하기
#가장 처음 비교할 인덱스를 cIdx, 비교당할 인덱스를 nIdx
cIdx = 0; nIdx=1
eIdx = len(fruits)-1

flag =True
while flag:
    curDic = fruits[cIdx]
    nexDic = fruits[nIdx]

    #해당 딕의 과일 개수
    curDicCnt = list(curDic.values())[0]
    nexDicCnt = list(nexDic.values())[0]


    #'<'일때 오름차순, '>'일때 내림차순
    if nexDicCnt < curDicCnt:
        fruits.insert(cIdx, fruits.pop(nIdx))
        nIdx = cIdx + 1
        continue

    nIdx +=1
    if nIdx > eIdx:
        cIdx+=1
        nIdx = cIdx +1

        if cIdx == 5:
            flag = False
fruits = tuple(fruits)

print(f'fruits : {fruits}')
fruits : ({'수박': 8}, {'참외': 12}, {'포도': 13}, {'자몽': 15}, {'사과': 17}, {'자두': 19})

문제10)

studentCnt = (
    {'class01':18},
    {'class02':21},
    {'class03':20},
    {'class04':19},
    {'class05':22},
    {'class06':20},
    {'class07':23},
    {'class08':17}
)

#젙체 학생수 변수
totalCnt =0
#학생수 제일 적은 학급의 학생수
minStdCnt = 0
#학생수 제일 적은 학급
minCls = ''

maxStdCnt = 0
maxCls = ''

#편차 담길 리스트
deviation = []

for idx, dic in enumerate(studentCnt):
    #총 학생수 (튜플 안의 아이템이 딕셔너리이고 그 딕셔너리의 벨류들을 모두 더한 것이 총 학생수)
    for k, v in dic.items():
        totalCnt = totalCnt+v

        #가장 많은 학생수
        if maxStdCnt < v:
            maxStdCnt = v
            maxCls = k

        if minStdCnt == 0 or minStdCnt > v:
            minStdCnt = v
            minCls = k
avgStuCnt = totalCnt / len(studentCnt)
print(f'전체 학생 수 : {totalCnt}')
print(f'평균 학생 수 : {avgStuCnt}')
print(f'학생 수가 가장 적은 학급 : {minCls}({minStdCnt}명)')
print(f'학생 수가 가장 적은 학급 : {maxCls}({maxStdCnt}명)')

#학급별 편차
for idx,dic in enumerate(studentCnt):
    for k,v in dic.items():
        deviation.append(v - avgStuCnt)

print(f'학급별 학생 편차 : {deviation}')
전체 학생 수 : 160
평균 학생 수 : 20.0
학생 수가 가장 적은 학급 : class08(17명)
학생 수가 가장 적은 학급 : class07(23명)
학급별 학생 편차 : [-2.0, 1.0, 0.0, -1.0, 2.0, 0.0, 3.0, -3.0]

문제11)

subject = ['국어','영어','수학','과학','국사']
scores = {}

for i in subject:
    score = int(input(i + ' 점수 입력:'))
    scores[i] = score

print(f'scores = {scores}')
국어 점수 입력:88
영어 점수 입력:96
수학 점수 입력:89
과학 점수 입력:79
국사 점수 입력:83
scores = {'국어': 88, '영어': 96, '수학': 89, '과학': 79, '국사': 83}

문제12)

dic ={}

for n in range(3,11):
    hap = 180*(n-2)
    gac = int(hap / n)
    dic[n] = [hap,gac]

print(f'dic = {dic}')
dic = {3: [180, 60], 4: [360, 90], 5: [540, 108], 6: [720, 120], 7: [900, 128], 8: [1080, 135], 
	   9: [1260, 140], 10: [1440, 144]}

dic = {}

for n1 in range(2,11):
    tempList = []
    for n2 in range(1,n1+1):
        if n1 % n2 ==0:
            tempList.append(n2)

    dic[n1] = tempList
print(f'dic = {dic}')
dic = {2: [1, 2], 3: [1, 3], 4: [1, 2, 4], 5: [1, 5], 6: [1, 2, 3, 6], 7: [1, 7], 8: [1, 2, 4, 8], 
       9: [1, 3, 9], 10: [1, 2, 5, 10]}

문제13)

aboutPython = '파이썬은 1991년 프로그래머인 귀도 반 로섬이 발표한 고급 프로그래밍 언어이다.'

#split()함수는 문자열 공백 기준으로 리스트에 넣어 반환해줌
splitList = aboutPython.split()
print(splitList)

dic = {}

for idx,v in enumerate(splitList):
    dic[idx] = v

print(dic)
['파이썬은', '1991년', '프로그래머인', '귀도', '반', '로섬이', '발표한', '고급', '프로그래밍', '언어이다.']
{0: '파이썬은', 1: '1991년', 2: '프로그래머인', 3: '귀도', 4: '반', 5: '로섬이', 6: '발표한', 7: '고급', 8: '프로그래밍', 9: '언어이다.'}

words = {'꺼지다':'가다',
         '쩔다':'엄청나다',
         '짭새':'경찰관',
         '꼽사리':'중간에 낀 사람',
         '먹튀':'먹고 도망',
         '지린다':'겁을 먹다',
         '쪼개다':'웃다',
         '뒷담 까다':'험담하다'}

txt = '강도는 서로 쪼개다, 짭새를 보고 빠르게 따돌리며 먹튀했다.'

keys = list(words.keys())
print(keys)
for key in keys:
    if key in txt:
        txt = txt.replace(key, words[key])

print(txt)
강도는 서로 웃다, 경찰관를 보고 빠르게 따돌리며 먹고 도망했다.

문제14)

dic = {}

#회원가입
n = 1
while n < 3:
    mail = input('메일 입력 :')
    pw = input('비번 입력 :')

    if mail in dic:
        print('이미 사용중인 메일 입니다.')
        continue

    dic[mail] = pw
    n+=1

#전체 조회
for key in dic.keys():
    print(f'{key} : {dic[key]}')

#위 코드에서 특정 회원 계정 삭제 하는 코드

while True:
    deletId = input('삭제 계정 입력:')

    if deletId in dic:
        deletPw = input('비번 입력:')
        if dic[deletId] == deletPw:
            del dic[deletId]
            print(f'{deletId}계정 삭제 완료')
            break
        else:
            print('비번 확인')
    
    else:
        print('계정 확인')
메일 입력 :aaa@gmail.com
비번 입력 :1234
메일 입력 :bbb@gmail.com
비번 입력 :5678
aaa@gmail.com : 1234
bbb@gmail.com : 5678
삭제 계정 입력:aaa@gmail.com
비번 입력:1234
aaa@gmail.com계정 삭제 완료

⭐⭐ 1. 알고리즘 ⭐⭐

선형으로 나열되어 있는 데이터를 순차적으로 스캔하면서 원하는 값(인덱스)를 찾는다.

  • 예시
datas = [3, 2, 5, 7, 9, 1, 0, 8, 6, 4]
print(datas)
print(len(datas))


searchData = int(input('찾을 숫자 입력: '))
searchResultIdx = -1    #존재하지 않는 변수 주고

n=0
while True:

    if n == len(datas):
        searchResultIdx = -1
        break
    elif datas[n] == searchData:
        searchResultIdx = n
        break
    n+=1

print(f'searchResultIdx = {searchResultIdx}')
[3, 2, 5, 7, 9, 1, 0, 8, 6, 4]
10
찾을 숫자 입력: 9
searchResultIdx = 4

보초법

  • 마지막 인덱스에 찾으려는 값을 추가해서
    검색이 마지막 인덱스 까지 도달하기 전에 값을 찾으면 검색성공,
    마지막 인덱스에서 찾게 된다면 검색 실패
    ->코드가 간략화 될 수 있다.

보초법 예제.

datas = [3, 2, 5, 7, 9, 1, 0, 8, 6, 4]
print(datas)
print(len(datas))


searchData = int(input('찾을 숫자 입력: '))
searchResultIdx = -1    #존재하지 않는 변수 주고

datas.append(searchData)

n=0
while True:

    if datas[n] == searchData:
        if n != len(datas)-1:
            searchResultIdx = n
        break

    n+=1
    
print(f'searchResultIdx = {searchResultIdx}')
[3, 2, 5, 7, 9, 1, 0, 8, 6, 4]
10
찾을 숫자 입력: 9
searchResultIdx = 4

실습1.

리스트에서 가장 앞에 있는 7을 검색하고 인덱스와 개수 출력 (보초법 사용)

nums =[4, 7, 10, 2, 4, 7, 0, 2, 7, 3, 9]

print(f'nums = {nums}')
print(f'length : {len(nums)}')

def searchNum(tempNum):
    searchData = int(input('찾을 숫자 입력 :'))

    #검색 서공한 데이터 넣어줄 리스트
    searchResultIdxs = []

    tempNum.append(searchData)

    n=0
    while True:
        if tempNum[n] == searchData:
            if n != len(tempNum)-1:
                searchResultIdxs.append(n)
            else:
                break
        n+=1
    return searchResultIdxs

print(f'nums = {nums}')
print(f'length : {len(nums)}')
print(f'searchResultIdxs = {searchNum(nums)}')
print(f'searchResultCnt = {len(searchNum(nums))}')
nums = [4, 7, 10, 2, 4, 7, 0, 2, 7, 3, 9]
length : 11
nums = [4, 7, 10, 2, 4, 7, 0, 2, 7, 3, 9]
length : 11
찾을 숫자 입력 :7
searchResultIdxs = [1, 5, 8]
찾을 숫자 입력 :7
searchResultCnt = 4


전제조건이 정렬되어 있는 상태이다. 만약 정렬 되어 있지 않다면 정렬 부터 시켜야 한다.

datas = [1,2,3,4,5,6,7,8,9,10,11]

print(f'datas = {datas}')
print(f'datas length : {len(datas)}')


def binarySearch(target):
    searchData = int(input('검색 할 숫자 입력 : '))
    searchResultIdx = -1

    staIdx = 0
    endIdx = len(target)-1
    midIdx = (staIdx + endIdx) // 2
    midVal = target[midIdx]

    print(f'midIdx : {midIdx}')
    print(f'midVal : {midVal}')


    while searchData <= target[len(target)-1] and searchData >= target[0]:

        if searchData == target[len(target)-1]:
            searchResultIdx = len(target)-1
            break

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

        elif searchData < midVal:
            endIdx = midIdx
            midIdx = (staIdx + endIdx) //2
            midVal = target[midIdx]
            print(f'midIdx : {midIdx}')
            print(f'midVal : {midVal}')

        elif searchData == midVal:
            searchResultIdx = midIdx
            break

    return searchResultIdx

print(f'searchResultIdx : {binarySearch(datas)}')
datas = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
datas length : 11
검색 할 숫자 입력 : 5
midIdx : 5
midVal : 6
midIdx : 2
midVal : 3
midIdx : 3
midVal : 4
midIdx : 4
midVal : 5
searchResultIdx : 4

3) 순위(Rank)

수의 크고 작음을 이용해서 수의 순서를 정하는 것을 순위라고 한다.

숫자 하나하나 모두 비교 하되
비교하는 기준 숫자가 비교되는 숫자보다 작으면 비교 하는 숫자의 인덱스 번호를 증가
-> num1 < num2
모두 돌고나서는 가장 큰 수는 인덱스가 하나도 늘지 않아 0일테고
가장 낮은 수는 계속 인덱스가 늘어나 마지막 순위일 것이다.

import random

nums = random.sample(range(50,101),20)

#순위가 표시 될 리스트 선언,  초기화 0을 20개 다 쓰기는 비효율적이니 
#for문을 사용해서 0값이 20개가 있는 리스트 선언

ranks = [0 for i in range(20)]
print(nums)
print(ranks)

for idx, num1 in enumerate(nums):
    for num2 in nums:
        if num1 < num2:
            ranks[idx] +=1

print(nums)
print(ranks)

for idx, num in enumerate(nums):
    print(f'num : {num} \t ranks : {ranks[idx]+1}')
[74, 51, 86, 99, 95, 53, 100, 81, 92, 54, 66, 82, 67, 94, 62, 80, 87, 55, 96, 70]
[11, 19, 7, 1, 3, 18, 0, 9, 5, 17, 14, 8, 13, 4, 15, 10, 6, 16, 2, 12]
num : 74 	 ranks : 12
num : 51 	 ranks : 20
num : 86 	 ranks : 8
num : 99 	 ranks : 2
num : 95 	 ranks : 4
num : 53 	 ranks : 19
num : 100 	 ranks : 1
num : 81 	 ranks : 10
num : 92 	 ranks : 6
num : 54 	 ranks : 18
num : 66 	 ranks : 15
num : 82 	 ranks : 9
num : 67 	 ranks : 14
num : 94 	 ranks : 5
num : 62 	 ranks : 16
num : 80 	 ranks : 11
num : 87 	 ranks : 7
num : 55 	 ranks : 17
num : 96 	 ranks : 3
num : 70 	 ranks : 13

실습1.

rankModuel.py

class RankDeviation:
    def __init__(self, mss, ess):
        self.midStuScos = mss
        self.endStuScos = ess
        self.midRanks = [0 for i in range(len(mss))]
        self.endRanks = [0 for i in range(len(ess))]
        self.rankDeviation = [0 for i in range(len(ess))]

    #중간고사, 기말고사 점수랑 랭크 정해주는 함수
    def setRank(self,ss,rs):
        for idx, sco1 in enumerate(ss):
            for sco2 in ss:
                if sco1 < sco2:
                    rs[idx]+=1
    #중간고사 점수 입력해주는 함수
    def setMidRank(self):
        self.setRank(self.midStuScos, self.midRanks)

    def getMidRank(self):
        return self.midRanks

    #기말고사 점수 입력해주는 함수
    def setEndRank(self):
        self.setRank(self.endStuScos, self.endRanks)

    def getEndRank(self):
        return self.endRanks

    #중간대비 기말 순위 편차
    def printRanksDeviation(self):

        for idx,mRank in enumerate(self.midRanks):
            deviation = mRank - self.endRanks[idx]

            if deviation > 0:
                deviation = '상승' + str(abs(deviation))
            elif deviation < 0:
                deviation = '하락' + str(abs(deviation))
            else:
                deviation = '동등' + str(abs(deviation))

            print(f'mid_rank : {mRank} \t end_rank : {self.endRanks[idx]} \t Deviation : {deviation}')

rank02.py (실행파일)

#순위 실습
#학생들의 중간고사 기말고사 성적 순위 전하고 중간고사대비 기말고사 순위 변화 출력(시험 점수는 난수)
import rankModuel as rm
import random

midStuScos = random.sample(range(50,101),20)
endStuScos = random.sample(range(50,101),20)

tr = rm.RankDeviation(midStuScos,endStuScos)

tr.setMidRank()
print(f'midStuScos : {midStuScos}')
print(f'mid_rank : {tr.getMidRank()}')


tr.setEndRank()
print(f'endStuScos : {endStuScos}')
print(f'end_rank : {tr.getEndRank()}')

tr.printRanksDeviation()
[82, 56, 84, 80, 67, 100, 70, 95, 90, 83, 58, 54, 57, 53, 81, 97, 51, 59, 85, 63]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[82, 56, 84, 80, 67, 100, 70, 95, 90, 83, 58, 54, 57, 53, 81, 97, 51, 59, 85, 63]
[7, 16, 5, 9, 11, 0, 10, 2, 3, 6, 14, 17, 15, 18, 8, 1, 19, 13, 4, 12]
num : 82 	 ranks : 8
num : 56 	 ranks : 17
num : 84 	 ranks : 6
num : 80 	 ranks : 10
num : 67 	 ranks : 12
num : 100 	 ranks : 1
num : 70 	 ranks : 11
num : 95 	 ranks : 3
num : 90 	 ranks : 4
num : 83 	 ranks : 7
num : 58 	 ranks : 15
num : 54 	 ranks : 18
num : 57 	 ranks : 16
num : 53 	 ranks : 19
num : 81 	 ranks : 9
num : 97 	 ranks : 2
num : 51 	 ranks : 20
num : 59 	 ranks : 14
num : 85 	 ranks : 5
num : 63 	 ranks : 13

4) 버블정렬(Bubble Sort)

처음부터 끝까지 인접하는 인덱스의 값을 순차적으로 비교한면서 큰 숫자를 가장 끝으로 옮기는 알고리즘

nums = [10, 2, 7, 21, 0]
print(f'not sorted nums : {nums}')

length = len(nums)-1

for i in range(length):
    for j in range(length-i):
        if nums[j] > nums[j+1]:
            '''
            #num1, num2 자리바꾸기 방법1
            temp = nums[j]
            nums[j] = nums[j+1]
            nums[j+1] = temp
            '''
            #num1, num2 자리바꾸기 방법2(python에서 사용 가능)
            nums[j], nums[j+1] = nums[j+1], nums[j]

print(f'sorted nums : {nums}')
not sorted nums : [10, 2, 7, 21, 0]
sorted nums : [0, 2, 7, 10, 21]

실습1.

bubbleModuel.py

def bubbleSort(ns):
    length = len(ns)-1
    for i in range(length):
        for j in range(length-i):
            if ns[j] > ns[j+1]:
                ns[j],ns[j+1]=ns[j+1],ns[j]
    return ns

bubble02.py

not sorted nums : [10, 2, 7, 21, 0]
sorted nums : [0, 2, 7, 10, 21]

깊은복사 이용

#처음 print되는 students는 정렬되있지 않지만 정렬 후 students를 출력해보면
#정렬되어 있따. 이것은 얕은복사로 모듈로 students를 보내면 students를 직접
#사용해서 정렬시킨 후에는 항상 정렬이 된 리스트로 작용하게 되는 것이다.
#깊은 복사를 해서 작성해 보자

bubbleModuel.py

import copy
def bubbleSort(ns, deepCopy =True):

    #cns라는 새로운 리스트를 복사해서 사용(깊은복사)
    if deepCopy:
        cns = copy.copy(ns)
    #얕은복사
    else:
        cns = ns

    length = len(cns)-1
    for i in range(length):
        for j in range(length-i):
            if cns[j] > cns[j+1]:
                cns[j],cns[j+1]=cns[j+1],cns[j]
    return cns

bubble02.py

import random
import bubbleModuel as bm

students = []

for i in range(20):
    students.append(random.randint(170,186))

print(f'students : {students}')

#얕은복사 그대로
sortedStu = bm.bubbleSort(students, deepCopy=False)
#깊은복사 기능 사용
sortedStu = bm.bubbleSort(students)
print(f'students : {students}')
print(f'sortedStu : {sortedStu}')
not sorted nums : [10, 2, 7, 21, 0]
sorted nums : [0, 2, 7, 10, 21]
profile
취업공부

0개의 댓글