제로베이스 데이터 파트타임 스쿨 학습 일지 [25.04.24]

[강의 요약]

[Part 03. 자료구조&알고리즘 with Python_ Ch 01. 자료구조] 강의 수강

26_리스트와 튜플부터 31_튜플과 while문 (02)까지 강의 수강하였음

🐢 100일 챌린지 🔥 : [▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰░                                       ] 39/100일 (39%)

노동요

 

 

 

 

[26_리스트와 튜플]

▶ 코드 : 리스트는 가변, 튜플은 불변

students = ['홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은']
print('students: {}'.format(students))

# 아이템 추가
students.append('강호동')
print('students: {}'.format(students))

# 아이템 변경
students[3] = '유재석'
print('students: {}'.format(students))

# 아이템 삭제
students.pop()
print('students: {}'.format(students))

[출력 결과]

students: ['홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은']
students: ['홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은', '강호동']
students: ['홍길동', '박찬호', '이용규', '유재석', '박승철', '김지은', '강호동']
students: ['홍길동', '박찬호', '이용규', '유재석', '박승철', '김지은']

 

 

▶ 코드 : 튜플에서는 추가/변경/삭제 불가

students = ('홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은')

students.append('강호동')  # 오류 발생
students[3] = '유재석'      # 오류 발생
students.pop()             # 오류 발생

[출력 결과]

AttributeError: 'tuple' object has no attribute 'append'
TypeError: 'tuple' object does not support item assignment
AttributeError: 'tuple' object has no attribute 'pop'

 

 

▶ 코드 : 튜플 선언 시 괄호 생략 가능

students = '홍길동', '박찬호', '이용규', '강호동'
print(students)
print(type(students))

[출력 결과]

('홍길동', '박찬호', '이용규', '강호동')
<class 'tuple'>

 

 

▶ 코드 : 리스트 ↔ 튜플 상호 변환

students = ['홍길동', '박찬호', '이용규', '강호동']
print(students)
print(type(students))

students = tuple(students)
print(students)
print(type(students))

students = list(students)
print(students)
print(type(students))

[출력 결과]

['홍길동', '박찬호', '이용규', '강호동']
<class 'list'>
('홍길동', '박찬호', '이용규', '강호동')
<class 'tuple'>
['홍길동', '박찬호', '이용규', '강호동']
<class 'list'>

 

 

▶ 실습 코드 : 튜플 → 리스트로 변환 후 최고/최저 제거 및 평균 계산

playerScore = (9.5, 8.9, 9.2, 9.8, 8.8, 9.0)
print('playerScore: {}'.format(playerScore))
print(type(playerScore))

# 튜플 → 리스트 변환
playerScore = list(playerScore)
print(type(playerScore))

# 정렬 및 최고/최저 점수 제거
playerScore.sort()
playerScore.pop(0)
playerScore.pop(len(playerScore) - 1)

# 리스트 → 튜플 재변환
playerScore = tuple(playerScore)
print('playerScore: {}'.format(playerScore))
print(type(playerScore))

# 총점 및 평균 계산
sum = 0
avg = 0
for score in playerScore:
    sum += score

avg = sum / len(playerScore)
print('총점: %.2f' % sum)
print('평점: %.2f' % avg)

[출력 결과]

playerScore: (9.5, 8.9, 9.2, 9.8, 8.8, 9.0)
<class 'tuple'>
<class 'list'>
playerScore: (8.9, 9.0, 9.2, 9.5)
<class 'tuple'>
총점: 36.60
평점: 9.15

 

 

 

[27_튜플 아이템 정렬]

▶ 코드 : 리스트로 변환 후 오름차순 정렬

students = ('홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은')
print('students type: {}'.format(type(students)))
print('students: {}'.format(students))

students = list(students)
students.sort()
print('students type: {}'.format(type(students)))
print('students: {}'.format(students))

students = tuple(students)
print('students type: {}'.format(type(students)))
print('students: {}'.format(students))

[출력 결과]

students type: <class 'tuple'>
students: ('홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은')
students type: <class 'list'>
students: ['강호동', '김지은', '박승철', '박찬호', '이용규', '홍길동']
students type: <class 'tuple'>
students: ('강호동', '김지은', '박승철', '박찬호', '이용규', '홍길동')

 

 

 

▶ 코드 : 리스트로 변환 후 내림차순 정렬

students = list(students)
students.sort(reverse=True)
print('students: {}'.format(students))

students = tuple(students)
print('students type: {}'.format(type(students)))
print('students: {}'.format(students))

[출력 결과]

students: ['홍길동', '이용규', '박찬호', '박승철', '김지은', '강호동']
students type: <class 'tuple'>
students: ('홍길동', '이용규', '박찬호', '박승철', '김지은', '강호동')

 

 

▶ 코드 : 숫자 튜플 정렬

numbers = (2, 50, 0.12, 1, 9, 7, 17, 35, 100, 3.14)
print('numbers: {}'.format(numbers))

numbers = list(numbers)
numbers.sort()
print('students: {}'.format(numbers))

numbers.sort(reverse=True)
print('students: {}'.format(numbers))

numbers = tuple(numbers)
print('numbers: {}'.format(numbers))

[출력 결과]

numbers: (2, 50, 0.12, 1, 9, 7, 17, 35, 100, 3.14)
students: [0.12, 1, 2, 3.14, 7, 9, 17, 35, 50, 100]
students: [100, 50, 35, 17, 9, 7, 3.14, 2, 1, 0.12]
numbers: (100, 50, 35, 17, 9, 7, 3.14, 2, 1, 0.12)

 


▶ 코드 : sorted() 함수로 정렬

students = ('홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은')
sortedStudents = sorted(students)

print('sortedStudents type: {}'.format(type(sortedStudents)))
print('sortedStudents: {}'.format(sortedStudents))

print('students type: {}'.format(type(students)))
print('students: {}'.format(students))

sortedStudents = sorted(students, reverse=True)
print('sortedStudents type: {}'.format(type(sortedStudents)))
print('sortedStudents: {}'.format(sortedStudents))

[출력 결과]

sortedStudents type: <class 'list'>
sortedStudents: ['강호동', '김지은', '박승철', '박찬호', '이용규', '홍길동']
students type: <class 'tuple'>
students: ('홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은')
sortedStudents type: <class 'list'>
sortedStudents: ['홍길동', '이용규', '박찬호', '박승철', '김지은', '강호동']

 

 

▶ 실습 코드 : 점수 평균 계산

playerScore = (9.5, 8.9, 9.2, 9.8, 8.8, 9.0)
print('playerScore: {}'.format(playerScore))

playerScore = list(playerScore)
playerScore.sort()
print('playerScore: {}'.format(playerScore))

playerScore.pop(0)
playerScore.pop(len(playerScore) - 1)

playerScore = tuple(playerScore)
print('playerScore: {}'.format(playerScore))

sum = 0
avg = 0
for score in playerScore:
    sum += score

avg = sum / len(playerScore)
print('총점: %.2f' % sum)
print('평점: %.2f' % avg)

[출력 결과]

playerScore: (9.5, 8.9, 9.2, 9.8, 8.8, 9.0)
playerScore: [8.8, 8.9, 9.0, 9.2, 9.5, 9.8]
playerScore: (8.9, 9.0, 9.2, 9.5)
총점: 36.60
평점: 9.15

 

 

 

[28_튜플과 for문 (01)]

▶ 코드 : 일반 튜플 순회

cars = '그랜저', '소나타', '말리부', '카니발', '쏘렌토'

# 인덱스 기반 접근
for i in range(len(cars)):
    print(cars[i])

# 튜플 요소 직접 순회
for car in cars:
    print(car)

[출력 결과]

그랜저
소나타
말리부
카니발
쏘렌토
그랜저
소나타
말리부
카니발
쏘렌토

 

 

▶ 코드 : 내부에 튜플이 있는 튜플 순회

studentCnts = (1, 19), (2, 20), (3, 22), (4, 18), (5, 21)

# 인덱스 접근 방식
for i in range(len(studentCnts)):
    print('{}학급 학생수: {} '.format(studentCnts[i][0], studentCnts[i][1]))

# 언패킹 방식
for classNo, cnt in studentCnts:
    print('{}학급 학생수: {}'.format(classNo, cnt))

[출력 결과]

1학급 학생수: 19 
2학급 학생수: 20 
3학급 학생수: 22 
4학급 학생수: 18 
5학급 학생수: 21 
1학급 학생수: 19
2학급 학생수: 20
3학급 학생수: 22
4학급 학생수: 18
5학급 학생수: 21

 

 

▶ 실습 코드 : 전체 학생 수 및 평균 학생 수 계산

studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

sum = 0
avg = 0
for classNo, cnt in studentCnts:
    print('{}학급 학생수: {}명'.format(classNo, cnt))
    sum += cnt

print('전체 학생 수: {}명'.format(sum))
print('평균 학생 수: {}명'.format(sum / len(studentCnts)))

[출력 결과]

1학급 학생수: 18명
2학급 학생수: 19명
3학급 학생수: 23명
4학급 학생수: 21명
5학급 학생수: 20명
6학급 학생수: 22명
7학급 학생수: 17명
전체 학생 수: 140명
평균 학생 수: 20.0명

 

 

 

 

[29_튜플과 for문 (02)]

▶ 코드 : 튜플과 조건문을 결합한 과락 출력

minScore = 60
scores = (
    ('국어', 58),
    ('영어', 77),
    ('수학', 89),
    ('과학', 99),
    ('국사', 50)
)

# 방식 1: 인덱스 접근
for item in scores:
    if item[1] < minScore:
        print('과락 과목: {}, 점수: {}'.format(item[0], item[1]))

# 방식 2: 언패킹 방식
for subject, score in scores:
    if score < minScore:
        print('과락 과목: {}, 점수: {}'.format(subject, score))

# 방식 3: continue 문 활용
for subject, score in scores:
    if score >= minScore: continue
    print('과락 과목: {}, 점수: {}'.format(subject, score))

[출력 결과]

과락 과목: 국어, 점수: 58
과락 과목: 국사, 점수: 50
과락 과목: 국어, 점수: 58
과락 과목: 국사, 점수: 50
과락 과목: 국어, 점수: 58
과락 과목: 국사, 점수: 50

 

 

▶ 실습 코드 : 사용자 입력 기반 과락 판별

minScore = 60

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

scores = (
    ('국어', korScore),
    ('영어', engScore),
    ('수학', matScore),
    ('과학', sciScore),
    ('국사', hisScore)
)

for subject, score in scores:
    if score < minScore:
        print('과락 과목: {}, 점수: {}'.format(subject, score))

[입력]

국어 점수: 55  
영어 점수: 90  
수학 점수: 88  
과학 점수: 79  
국사 점수: 59

[출력 결과]

과락 과목: 국어, 점수: 55  
과락 과목: 국사, 점수: 59

 

 

▶ 실습 코드 : 학급 학생 수 중 최솟값 / 최댓값 판별

studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

minclassNo = 0; maxclassNo = 0
minCnt = 0; maxCnt = 0

for classNo, cnt in studentCnts:
    if minCnt == 0 or minCnt > cnt:
        minclassNo = classNo
        minCnt = cnt

    if maxCnt < cnt:
        maxclassNo = classNo
        maxCnt = cnt

print('학생 수가 가장 적은 학급(학생수): {}학급({}명)'.format(minclassNo, minCnt))
print('학생 수가 가장 많은 학급(학생수): {}학급({}명)'.format(maxclassNo, maxCnt))

[출력 결과]

학생 수가 가장 적은 학급(학생수): 7학급(17명)  
학생 수가 가장 많은 학급(학생수): 3학급(23명)

 

 

 

[30_튜플과 while문 (01)]

▶ 코드 : 튜플 순회 - while문 3가지 방식

cars = ('그랜저', '소나타', '말리부', '카니발', '쏘렌토')

# 방식 1: while + 인덱스
n = 0
while n < len(cars):
    print(cars[n])
    n += 1

# 방식 2: flag 변수 사용
n = 0
flag = True
while flag:
    print(cars[n])
    n += 1
    if n == len(cars):
        flag = False

# 방식 3: 무한루프 + break
n = 0
while True:
    print(cars[n])
    n += 1
    if n == len(cars):
        break

[출력 결과]

그랜저
소나타
말리부
카니발
쏘렌토
(위 내용이 3번 반복 출력됨)

 

 

▶ 코드 : 튜플(학급, 학생 수) 조회

studentCnts = (1, 19), (2, 20), (3, 22), (4, 18), (5, 21)

n = 0
while n < len(studentCnts):
    print('{}학급 학생수: {} '.format(studentCnts[n][0], studentCnts[n][1]))
    n += 1

[출력 결과]

1학급 학생수: 19 
2학급 학생수: 20 
3학급 학생수: 22 
4학급 학생수: 18 
5학급 학생수: 21

 

 

▶ 실습 코드 : 전체 학생 수 및 평균 계산

studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

sum = 0
avg = 0
n = 0
while n < len(studentCnts):
    classNo = studentCnts[n][0]
    cnt = studentCnts[n][1]
    print('{}학급 학생수: {}명'.format(classNo, cnt))

    sum += cnt
    n += 1

print('전체 학생 수: {}명'.format(sum))
print('평균 학생 수: {}명'.format(sum / len(studentCnts)))

[출력 결과]

1학급 학생수: 18명  
2학급 학생수: 19명  
3학급 학생수: 23명  
4학급 학생수: 21명  
5학급 학생수: 20명  
6학급 학생수: 22명  
7학급 학생수: 17명  
전체 학생 수: 140명  
평균 학생 수: 20.0명

 

 

 

[31_튜플과 while문 (02)]

▶ 코드 : 튜플에서 과락 과목만 출력 (while문)

minScore = 60
scores = (
    ('국어', 58),
    ('영어', 77),
    ('수학', 89),
    ('과학', 99),
    ('국사', 50)
)

n = 0
while n < len(scores):
    if scores[n][1] < minScore:
        print('과락 과목: {}, 점수: {}'.format(scores[n][0], scores[n][1]))
    n += 1

[출력 결과]

과락 과목: 국어, 점수: 58  
과락 과목: 국사, 점수: 50

 

 

▶ 코드 : continue 문으로 과락 필터링

n = 0
while n < len(scores):
    if scores[n][1] >= minScore:
        n += 1
        continue
    print('과락 과목: {}, 점수: {}'.format(scores[n][0], scores[n][1]))
    n += 1

[출력 결과]

과락 과목: 국어, 점수: 58  
과락 과목: 국사, 점수: 50

 

 

▶ 실습 코드 : 사용자 입력 점수 기반 과락 과목 출력

minScore = 60

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

scores = (
    ('국어', korScore),
    ('영어', engScore),
    ('수학', matScore),
    ('과학', sciScore),
    ('국사', hisScore)
)

n = 0
while n < len(scores):
    if scores[n][1] < minScore:
        print('과락 과목: {}, 점수: {}'.format(scores[n][0], scores[n][1]))
    n += 1

[입력]

국어 점수: 55  
영어 점수: 80  
수학 점수: 62  
과학 점수: 91  
국사 점수: 59

[출력 결과]

과락 과목: 국어, 점수: 55  
과락 과목: 국사, 점수: 59

 

 

▶ 실습 코드 : 학급별 학생 수 비교 – 최소 & 최대 학급

studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

minclassNo = 0; maxclassNo = 0
minCnt = 0; maxCnt = 0

n = 0
while n < len(studentCnts):
    if minCnt == 0 or minCnt > studentCnts[n][1]:
        minclassNo = studentCnts[n][0]
        minCnt = studentCnts[n][1]

    if maxCnt < studentCnts[n][1]:
        maxclassNo = studentCnts[n][0]
        maxCnt = studentCnts[n][1]

    n += 1

print('학생 수가 가장 적은 학급(학생수): {}학급({}명)'.format(minclassNo, minCnt))
print('학생 수가 가장 많은 학급(학생수): {}학급({}명)'.format(maxclassNo, maxCnt))

[출력 결과]

학생 수가 가장 적은 학급(학생수): 7학급(17명)  
학생 수가 가장 많은 학급(학생수): 3학급(23명)

 

 

 

[나의 생각 정리]

튜플과 리스트의 차이, 반복문을 활용한 데이터 처리 방식을 실습 코드를 통해 익힐 수 있었다.

리스트 ↔ 튜플 변환을 통해 정렬, 삭제 등 불변 자료형의 한계도 우회할 수 있었고

유용한 로직들을 코드를 통해 정리할 수 있었다.

나중에 찾아보면서 코드 활용을 할 수 있을 것 같다.

 

 

 

[적용점]

코딩 테스트 문제에서 이런 식으로 구현해라고 요구하는 문제들이 있는데

이 글 코드들의 로직들을 적용할 수 있을 것 같다.

 

 

 

“이 글은 제로베이스 데이터 스쿨 주 3일반 강의 자료 일부를 발췌하여 작성되었습니다.”