Chapter 03
선형 리스트
Linear List
Part 1  선형 리스트의 개념 · Concept of Linear List
Part 2  선형 리스트의 구현 · Implementation of Linear List
Part 3  선형 리스트의 응용 · Applications of Linear List
01
Part 1
선형 리스트의 개념
Concept of Linear List
약 1시간 · Approx. 1 hour

생활 속 선형 리스트

Linear Lists in Everyday Life
한국어

우리 주변의 선형 리스트

맛집이나 마트에서 줄을 서는 것처럼, 데이터를 일정한 순서로 나열한 것을 선형 리스트라고 합니다.

🍜 맛집 대기줄

먼저 온 손님이 먼저 순서를 갖고, 도착한 순서대로 한 줄로 서게 됩니다.

🎵 플레이리스트

노래를 추가한 순서대로 재생목록에 나열되어 순서대로 재생됩니다.

✅ 할 일 목록(To-do List)

오늘 해야 할 일을 순서대로 적어두고 위에서부터 처리합니다.

핵심 포인트

이처럼 일정한 순서로 데이터를 나열하는 방식이 컴퓨터 안에서도 그대로 쓰입니다. 이것이 바로 선형 리스트입니다.

English

Linear Lists Around Us

Just like standing in line at a restaurant or store, a linear list arranges data in a specific order.

🍜 Waiting Line at a Restaurant

The first customer to arrive gets the first turn — everyone lines up in arrival order.

🎵 Music Playlist

Songs are listed in the order they were added, and played back in that same order.

✅ To-Do List

Tasks for today are written down in order and handled one by one from the top.

Key Point

Arranging data in a fixed order like this is exactly how computers organize data too. This is called a linear list.

선형 리스트의 개념

Concept of Linear List
한국어

선형 리스트란?

선형 리스트(Linear List)는 데이터를 일정한 순서로 나열한 자료구조입니다.

  • 순차 리스트(Ordered List)라고도 부릅니다.
  • 입력한 순서대로 데이터를 저장하는 경우에 적당합니다.
  • 배열(array)을 이용해 구현하는 것이 가장 간단합니다.
katok (Array) Dahyun Jungyeon Tzuyu Sana Jihyo [0] [1] [2] [3] [4] 100 104 108 112 116 Memory Address Fig 3-1. Linear List Stored in Array
English

What is a Linear List?

A Linear List is a data structure that arranges data in a specific order.

  • Also called an Ordered List or Sequential List.
  • Suitable when data should be stored in the order it was entered.
  • The simplest way to implement it is with an array.
katok (Array) Dahyun Jungyeon Tzuyu Sana Jihyo [0] [1] [2] [3] [4] 100 104 108 112 116 Memory Address Fig 3-1. Linear List Stored in Array

선형 리스트의 예

Examples of Linear List
한국어

주변에서 찾아보는 선형 리스트

  • 카톡 친구 목록 — 연락(메시지)이 많이 온 순서로 표시
  • 좋아하는 프로그래밍 언어 순위 — 선호도 순서로 나열
  • 오늘 수업할 과목 — 시간표 순서로 나열
Fav Languages Python C# Java C++ Kotlin KakaoTalk Friends Dahyun(200) Jungyeon(150) Tzuyu(90) Sana(30) Jihyo(15) Today's Classes Data Structures Database English Programming Fig 3-2. Examples of Linear Lists
English

Linear Lists Found Around You

  • KakaoTalk friend list — sorted by how often they message you
  • Favorite programming language ranking — sorted by preference
  • Today's class schedule — sorted by class time
Fav Languages Python C# Java C++ Kotlin KakaoTalk Friends Dahyun(200) Jungyeon(150) Tzuyu(90) Sana(30) Jihyo(15) Today's Classes Data Structures Database English Programming Fig 3-2. Examples of Linear Lists

배열에 저장된 선형 리스트

Linear List Stored in Array
한국어

논리적 순서 vs 물리적 순서

배열에 저장된 데이터는 메모리 주소를 가지고 있습니다. 인덱스가 증가할수록 메모리 주소도 일정하게 증가합니다.

논리적 순서 (Logical Order)

우리가 인식하는 데이터의 순서. [0], [1], [2] ... 인덱스로 표현됩니다.

물리적 순서 (Physical Order)

실제 컴퓨터 메모리에 저장되는 순서. 메모리 주소로 표현됩니다.

선형 리스트에서는 논리적 순서와 물리적 순서가 동일합니다. 즉, 인덱스가 1 증가하면 메모리 주소도 데이터 크기만큼 증가합니다.

파이썬에서 메모리 주소 확인하기

>>> a = "다현" >>> id(a) 140312135857200 # 변수 a의 메모리 주소

id() 함수를 사용하면 객체가 저장된 메모리 주소를 확인할 수 있습니다.

English

Logical Order vs Physical Order

Data stored in an array has a memory address. As the index increases, the memory address increases consistently as well.

Logical Order

The order we perceive the data in. Represented by index: [0], [1], [2] ...

Physical Order

The order data is actually stored in computer memory. Represented by memory addresses.

In a linear list, the logical order and physical order are identical. That is, as the index increases by 1, the memory address increases by the size of one element.

Checking Memory Addresses in Python

>>> a = "Dahyun" >>> id(a) 140312135857200 # memory address of variable a

The id() function lets you check the memory address where an object is stored.

데이터 삽입 원리

Data Insertion Principle
한국어

3단계로 이해하는 삽입 과정

1빈칸 확보 — 리스트 끝에 데이터 하나가 더 들어갈 자리를 만듭니다.
2자리 이동 — 삽입할 위치부터 끝까지 데이터를 뒤에서부터 한 칸씩 뒤로 이동합니다.
3데이터 삽입 — 비워진 자리에 새 데이터를 넣습니다.
① Original + empty space Dahyun Jungyeon Tzuyu Sana Jihyo None ② Shift right from position 3 Dahyun Jungyeon Tzuyu None Sana Jihyo ③ Insert "Mina" at position 3 Dahyun Jungyeon Tzuyu Mina Sana Jihyo Fig 3-3. Data Insertion Process in Linear List
English

Understanding Insertion in 3 Steps

1Secure empty space — make room for one more element at the end of the list.
2Shift data — move data from the back toward the insertion point, one slot at a time.
3Insert data — place the new data into the now-empty slot.
① Original + empty space Dahyun Jungyeon Tzuyu Sana Jihyo None ② Shift right from position 3 Dahyun Jungyeon Tzuyu None Sana Jihyo ③ Insert "Mina" at position 3 Dahyun Jungyeon Tzuyu Mina Sana Jihyo Fig 3-3. Data Insertion Process in Linear List

데이터 삭제 원리

Data Deletion Principle
한국어

3단계로 이해하는 삭제 과정

1데이터 삭제 — 삭제할 위치의 데이터를 지웁니다(None으로 처리).
2자리 이동 — 삭제한 위치 뒤의 데이터를 앞으로 한 칸씩 이동합니다.
3빈칸 제거 — 맨 뒤에 남은 빈칸을 배열에서 제거합니다.
① Delete data at position 4 (Sana) Dahyun Jungyeon Tzuyu Mina None Jihyo ② Shift left to fill the gap Dahyun Jungyeon Tzuyu Mina Jihyo None ③ Remove last empty slot Dahyun Jungyeon Tzuyu Mina Jihyo Fig 3-4. Data Deletion Process in Linear List
English

Understanding Deletion in 3 Steps

1Delete data — clear the data at the position to be deleted (set to None).
2Shift data — move data after that position forward, one slot at a time.
3Remove empty space — remove the now-empty slot left at the end of the array.
① Delete data at position 4 (Sana) Dahyun Jungyeon Tzuyu Mina None Jihyo ② Shift left to fill the gap Dahyun Jungyeon Tzuyu Mina Jihyo None ③ Remove last empty slot Dahyun Jungyeon Tzuyu Mina Jihyo Fig 3-4. Data Deletion Process in Linear List

Code03-01.py — 선형 리스트 생성

Creating a Linear List
한국어

add_data() 함수로 리스트 만들기

1 katok = [] # 빈 배열 2 3 def add_data(friend) : 4 katok.append(None) 5 kLen = len(katok) 6 katok[kLen-1] = friend 7 8 add_data('다현') 9 add_data('정연') 10 add_data('쯔위') 11 add_data('사나') 12 add_data('지효') 13 14 print(katok)

실행 결과

['다현', '정연', '쯔위', '사나', '지효']
동작 원리

append(None)으로 빈 자리를 만든 뒤, len(katok)으로 길이를 구해 마지막 위치에 데이터를 대입합니다.

English

Building a List with add_data()

1 katok = [] # empty array 2 3 def add_data(friend) : 4 katok.append(None) 5 kLen = len(katok) 6 katok[kLen-1] = friend 7 8 add_data('Dahyun') 9 add_data('Jungyeon') 10 add_data('Tzuyu') 11 add_data('Sana') 12 add_data('Jihyo') 13 14 print(katok)

Execution Result

['다현', '정연', '쯔위', '사나', '지효']
How It Works

append(None) creates an empty slot, then len(katok) gets the length, and the new data is assigned to the last position.

Part 1 연습문제

Part 1 Practice
한국어
연습 1-1

선형 리스트에서 데이터를 중간에 삽입할 때, 왜 뒤에서부터 이동해야 하는지 설명하시오.

연습 1-2

선형 리스트와 일반 배열의 차이점은 무엇인가?

연습 1-3

5명의 친구 이름을 선형 리스트로 생성하는 코드를 작성하시오.

English
Practice 1-1

When inserting data in the middle of a linear list, explain why we must shift from the back.

Practice 1-2

What is the difference between a linear list and a regular array?

Practice 1-3

Write code to create a linear list with 5 friend names.

02
Part 2
선형 리스트의 구현
Implementation of Linear List
약 1.5시간 · Approx. 1.5 hours

데이터 삽입 — 끝에 삽입

Data Insertion — Insert at End
한국어

가장 간단한 삽입: 끝에 추가

append()로 빈칸을 하나 추가한 다음, 그 자리에 데이터를 대입하면 끝에 삽입됩니다.

Before Dahyun Jungyn Tzuyu Sana Jihyo After append(None) Dahyun Jungyn Tzuyu Sana Jihyo None After katok[5] = 'Solar' Dahyun Jungyn Tzuyu Sana Jihyo Solar
Fig 3-5. Inserting Data at the End
katok.append(None) kLen = len(katok) katok[kLen-1] = '솔라'
English

The Simplest Insertion: Add at the End

Use append() to add one empty slot, then assign the new data into that slot to insert at the end.

Before Dahyun Jungyn Tzuyu Sana Jihyo After append(None) Dahyun Jungyn Tzuyu Sana Jihyo None After katok[5] = 'Solar' Dahyun Jungyn Tzuyu Sana Jihyo Solar
Fig 3-5. Inserting Data at the End
katok.append(None) kLen = len(katok) katok[kLen-1] = 'Solar'

데이터 삽입 — 중간에 삽입

Data Insertion — Insert in Middle
한국어

Code03-02.py: insert_data() 함수

빈칸 추가 → 뒤에서부터 한 칸씩 이동 → 지정 위치에 삽입합니다.

[0]Dahyn [1]Jungy [2]Tzuyu [3]Sana [4]Jihyo [5]None Shift from back: [4]→[5], [3]→[4] then insert at [2] [0]Dahyn [1]Jungy [2]Solar [3]Tzuyu [4]Sana [5]Jihyo
Fig 3-6. Middle Insertion Step by Step
def insert_data(position, friend) : if position < 0 or position > len(katok) : print("데이터를 삽입할 범위를 벗어났습니다.") return katok.append(None) kLen = len(katok) for i in range(kLen-1, position, -1) : katok[i] = katok[i-1] katok[i-1] = None katok[position] = friend
English

Code03-02.py: The insert_data() Function

Add an empty slot → shift elements one at a time starting from the back → insert at the specified position.

[0]Dahyn [1]Jungy [2]Tzuyu [3]Sana [4]Jihyo [5]None Shift from back: [4]→[5], [3]→[4] then insert at [2] [0]Dahyn [1]Jungy [2]Solar [3]Tzuyu [4]Sana [5]Jihyo
Fig 3-6. Middle Insertion Step by Step
def insert_data(position, friend) : if position < 0 or position > len(katok) : print("Out of insertion range.") return katok.append(None) kLen = len(katok) for i in range(kLen-1, position, -1) : katok[i] = katok[i-1] katok[i-1] = None katok[position] = friend

데이터 삽입 함수 실행

Insert Function Execution
한국어

insert_data() 호출 결과 확인

① insert_data(2, '솔라')

위치 2에 '솔라'를 삽입합니다. 기존 [2]번부터 끝까지의 데이터가 뒤로 한 칸씩 밀립니다.

['다현', '정연', '솔라', '쯔위', '사나', '지효']

② insert_data(6, '문별')

position이 배열 길이(6)와 같으면 맨 끝에 삽입되는 경우입니다.

['다현', '정연', '솔라', '쯔위', '사나', '지효', '문별']

주의

position이 0보다 작거나 리스트 길이보다 크면 삽입 범위를 벗어났다는 오류 메시지를 출력합니다.

English

Checking insert_data() Results

① insert_data(2, 'Solar')

Inserts 'Solar' at position 2. All existing data from index [2] onward shifts one slot to the right.

['다현', '정연', '솔라', '쯔위', '사나', '지효']

② insert_data(6, 'Moonbyul')

When position equals the array's length (6), the item is inserted at the very end.

['다현', '정연', '솔라', '쯔위', '사나', '지효', '문별']

Caution

If position is less than 0 or greater than the list length, an out-of-range error message is printed.

데이터 삭제 — 중간 삭제

Data Deletion — Delete from Middle
한국어

Code03-03.py: delete_data() 함수

지정 위치 데이터 삭제 → 앞으로 한 칸씩 이동 → 마지막 빈칸 제거합니다.

[0]Dahyn [1]None [2]Tzuyu [3]Sana [4]Jihyo Shift left: [2]→[1], [3]→[2], [4]→[3] [0]Dahyn [1]Tzuyu [2]Sana [3]Jihyo del
Fig 3-7. Middle Deletion Step by Step
def delete_data(position) : if position < 0 or position > len(katok) : print("데이터를 삭제할 범위를 벗어났습니다.") return kLen = len(katok) katok[position] = None for i in range(position+1, kLen) : katok[i-1] = katok[i] katok[i] = None del(katok[kLen-1])
English

Code03-03.py: The delete_data() Function

Delete data at the given position → shift the rest forward one slot at a time → remove the last empty slot.

[0]Dahyn [1]None [2]Tzuyu [3]Sana [4]Jihyo Shift left: [2]→[1], [3]→[2], [4]→[3] [0]Dahyn [1]Tzuyu [2]Sana [3]Jihyo del
Fig 3-7. Middle Deletion Step by Step
def delete_data(position) : if position < 0 or position > len(katok) : print("Out of deletion range.") return kLen = len(katok) katok[position] = None for i in range(position+1, kLen) : katok[i-1] = katok[i] katok[i] = None del(katok[kLen-1])

데이터 삭제 실행

Delete Function Execution
한국어

delete_data() 호출 결과 확인

원본: ['다현', '정연', '쯔위', '사나', '지효']

① delete_data(1)

위치 1의 '정연'을 삭제합니다.

['다현', '쯔위', '사나', '지효']

② delete_data(3)

위 결과에서 위치 3의 '지효'를 삭제합니다.

['다현', '쯔위', '사나']

핵심

del(katok[kLen-1])을 실행하지 않으면 리스트 끝에 None이 남아 길이가 줄지 않습니다.

English

Checking delete_data() Results

Original: ['다현', '정연', '쯔위', '사나', '지효']

① delete_data(1)

Deletes '정연' at position 1.

['다현', '쯔위', '사나', '지효']

② delete_data(3)

From the result above, deletes '지효' at position 3.

['다현', '쯔위', '사나']

Key Point

Without del(katok[kLen-1]), a leftover None stays at the end and the list's length never shrinks.

일반 구현 — 선형 리스트 생성 함수

General Implementation — Create Function
한국어

add_data() 함수 상세 설명

Step 1: append(None) None katok = [] → [None] Step 2: kLen=1, katok[0]='Dahyun' Dahyun Step 3: append(None), katok[1]='Jungyeon' Dahyun Jungyn
Fig 3-10. How add_data() Works
1katok.append(None) — 배열 끝에 빈칸(None)을 추가합니다.
2kLen = len(katok) — 현재 배열의 길이를 구합니다.
3katok[kLen-1] = friend — 방금 만든 마지막 빈칸에 데이터를 넣습니다.
English

Detailed Explanation of add_data()

Step 1: append(None) None katok = [] → [None] Step 2: kLen=1, katok[0]='Dahyun' Dahyun Step 3: append(None), katok[1]='Jungyeon' Dahyun Jungyn
Fig 3-10. How add_data() Works
1katok.append(None) — appends an empty slot (None) to the end of the array.
2kLen = len(katok) — gets the current length of the array.
3katok[kLen-1] = friend — assigns the data into the newly created last slot.

일반 구현 — 삽입 함수

General Implementation — Insert Function
한국어

insert_data(position, friend) 상세

1범위 검사 — position이 0보다 작거나 len(katok)보다 크면 오류 처리 후 반환합니다.
2append — 배열 끝에 None을 추가해 자리를 하나 늘립니다.
3이동 루프range(kLen-1, position, -1)로 뒤에서부터 앞으로 한 칸씩 값을 옮깁니다.
4대입 — 비워진 position 위치에 새 데이터를 넣습니다.

왜 뒤에서부터 이동해야 할까?

앞에서부터 이동하면 옮기기 전에 다음 데이터를 덮어써서 잃어버립니다. 반드시 뒤(끝)에서부터 앞으로 이동해야 데이터가 보존됩니다.

for i in range(kLen-1, position, -1) : katok[i] = katok[i-1] katok[i-1] = None
English

Details of insert_data(position, friend)

1Range check — if position is less than 0 or greater than len(katok), print an error and return.
2Append — add a None to the end of the array to make one extra slot.
3Shift loop — using range(kLen-1, position, -1), move values from back to front one slot at a time.
4Assign — place the new data into the now-empty position.

Why shift from the back?

Shifting from the front would overwrite and lose the next value before it's moved. You must shift from the back (end) toward the front to preserve all data.

for i in range(kLen-1, position, -1) : katok[i] = katok[i-1] katok[i-1] = None

일반 구현 — 삭제 함수

General Implementation — Delete Function
한국어

delete_data(position) 상세

1범위 검사 — position이 0보다 작거나 len(katok)보다 크면 오류 처리 후 반환합니다.
2None 처리 — 삭제할 위치의 값을 None으로 만듭니다.
3이동 루프range(position+1, kLen)로 앞으로 한 칸씩 값을 옮깁니다.
4del — 마지막에 남은 빈칸을 del(katok[kLen-1])로 완전히 제거합니다.

삽입과의 차이

삽입은 뒤에서 앞으로 이동, 삭제는 앞에서 뒤로 이동합니다. 이동 방향이 반대입니다.

for i in range(position+1, kLen) : katok[i-1] = katok[i] katok[i] = None del(katok[kLen-1])
English

Details of delete_data(position)

1Range check — if position is less than 0 or greater than len(katok), print an error and return.
2Set to None — set the value at the delete position to None.
3Shift loop — using range(position+1, kLen), move values forward one slot at a time.
4del — completely remove the leftover empty slot at the end with del(katok[kLen-1]).

Difference from Insertion

Insertion shifts from back to front, while deletion shifts from front to back — the direction is reversed.

for i in range(position+1, kLen) : katok[i-1] = katok[i] katok[i] = None del(katok[kLen-1])

완성 프로그램 Code03-04.py

Complete Program
한국어

메뉴 기반 프로그램

1:추가, 2:삽입, 3:삭제, 4:종료 메뉴로 동작하는 대화형 프로그램입니다.

## 전역 변수 선언 부분 ## katok = [] select = -1 ## 메인 코드 부분 ## if __name__ == "__main__" : while (select != 4) : select = int(input("선택하세요(1:추가, 2:삽입, 3:삭제, 4:종료)--> ")) if (select == 1) : data = input("추가할 데이터--> ") add_data(data) print(katok) elif (select == 2) : pos = int(input("삽입할 위치--> ")) data = input("추가할 데이터--> ") insert_data(pos, data) print(katok) elif (select == 3) : pos = int(input("삭제할 위치--> ")) delete_data(pos) print(katok) elif (select == 4) : print(katok) else : print("1~4 중 하나를 입력하세요.") continue

구성

add_data(), insert_data(), delete_data() 함수를 모두 정의한 뒤, 무한 반복문(while)으로 사용자 선택을 처리합니다.

English

Menu-Driven Program

An interactive program driven by a menu: 1:Add, 2:Insert, 3:Delete, 4:Exit.

## Global variables ## katok = [] select = -1 ## Main code ## if __name__ == "__main__" : while (select != 4) : select = int(input("Select(1:Add,2:Insert,3:Delete,4:Exit)--> ")) if (select == 1) : data = input("Data to add--> ") add_data(data) print(katok) elif (select == 2) : pos = int(input("Position--> ")) data = input("Data to add--> ") insert_data(pos, data) print(katok) elif (select == 3) : pos = int(input("Position--> ")) delete_data(pos) print(katok) elif (select == 4) : print(katok) else : print("Enter a number 1~4.") continue

Structure

After defining add_data(), insert_data(), and delete_data(), an infinite while loop handles the user's menu choices.

Part 2 연습문제

Part 2 Practice
한국어
연습 2-1

Code03-02.py에서 position 검증이 없으면 어떤 문제가 발생하는지 설명하시오.

연습 2-2

삭제 함수에서 del(katok[kLen-1])을 하지 않으면 결과가 어떻게 달라지는가?

연습 2-3

Code03-04.py를 수정하여 '검색' 기능(특정 데이터 위치 찾기)을 추가하시오.

English
Practice 2-1

In Code03-02.py, what problems occur if position validation is missing?

Practice 2-2

In the delete function, how does the result change if we skip del(katok[kLen-1])?

Practice 2-3

Modify Code03-04.py to add a 'search' feature (find position of specific data).

03
Part 3
선형 리스트의 응용
Applications of Linear List
약 1시간 · Approx. 1 hour

다항식의 선형 리스트 표현

Polynomial Representation with Linear List
한국어

다항식을 배열로 저장하기

P(x) = 7x³ − 4x² + 0x¹ + 5x⁰

각 항의 계수(coefficient)만 순서대로 배열에 저장하면 다항식을 표현할 수 있습니다.

계수를 배열로 저장: [7, -4, 0, 5]

7 -4 0 5 x⁰ [0] [1] [2] [3] Fig 3-8. Polynomial Represented as Array
인덱스와 지수의 관계

인덱스 i의 지수는 (전체 항 개수 - 1) - i로 계산됩니다.

English

Storing a Polynomial as an Array

P(x) = 7x³ − 4x² + 0x¹ + 5x⁰

Storing only the coefficients of each term, in order, is enough to represent the polynomial.

Coefficient array: [7, -4, 0, 5]

7 -4 0 5 x⁰ [0] [1] [2] [3] Fig 3-8. Polynomial Represented as Array
Index-to-Exponent Relationship

The exponent for index i is computed as (total number of terms - 1) - i.

다항식 출력 함수

Polynomial Print Function (printPoly)
한국어

Code03-05.py: printPoly() 함수

최고차항부터 순서대로 문자열을 만들어 다항식을 출력합니다.

def printPoly(p_x) : term = len(p_x) - 1 polyStr = "P(x) = " for i in range(len(px)) : coef = p_x[i] if (coef >= 0) : polyStr += "+" polyStr += str(coef) + "x^" + str(term) + " " term -= 1 return polyStr
1term = len(p_x) - 1 — 최고차항의 지수부터 시작합니다.
2계수가 0 이상이면 "+"기호를 붙입니다(음수는 자체 부호 사용).
3한 항을 처리할 때마다 term을 1씩 줄입니다.
English

Code03-05.py: The printPoly() Function

Builds a string term by term, from the highest degree down, to print the polynomial.

def printPoly(p_x) : term = len(p_x) - 1 polyStr = "P(x) = " for i in range(len(px)) : coef = p_x[i] if (coef >= 0) : polyStr += "+" polyStr += str(coef) + "x^" + str(term) + " " term -= 1 return polyStr
1term = len(p_x) - 1 — start from the exponent of the highest-degree term.
2if the coefficient is 0 or greater, prepend a "+" sign (negatives already have their own sign).
3decrease term by 1 after processing each term.

다항식 계산 함수

Polynomial Calculate Function (calcPoly)
한국어

Code03-05.py: calcPoly() 함수

특정 x값을 대입하여 다항식의 값을 계산합니다.

def calcPoly(xVal, p_x) : retValue = 0 term = len(p_x) - 1 for i in range(len(px)) : coef = p_x[i] retValue += coef * xValue ** term term -= 1 return retValue

계산 예시

P(x) = 7x³ - 4x² + 0x¹ + 5x⁰, x = 2일 때:

7×2³ - 4×2² + 0×2¹ + 5×2⁰ = 56 - 16 + 0 + 5 = 45

※ 교재 예제와 값이 다를 수 있으므로 직접 계산해 확인해 봅시다.

English

Code03-05.py: The calcPoly() Function

Substitutes a specific x value to compute the polynomial's result.

def calcPoly(xVal, p_x) : retValue = 0 term = len(p_x) - 1 for i in range(len(px)) : coef = p_x[i] retValue += coef * xValue ** term term -= 1 return retValue

Example Calculation

For P(x) = 7x³ - 4x² + 0x¹ + 5x⁰ with x = 2:

7×2³ - 4×2² + 0×2¹ + 5×2⁰ = 56 - 16 + 0 + 5 = 45

※ Verify the exact value yourself — it may differ slightly from the textbook.

Code03-05.py 전체 코드

Complete Code
한국어

메인 코드와 실행 결과

px = [7, -4, 0, 5] if __name__ == "__main__" : pStr = printPoly(px) print(pStr) xValue = int(input("X 값-->")) pxValue = calcPoly(xValue, px) print(pxValue)

실행 결과 (X = 2)

P(x) = +7x^3 -4x^2 +0x^1 +5x^0 X 값-->2 37

한계점

이 방식은 지수가 매우 큰 경우(예: x³⁰⁰) 배열에 사용하지 않는 항까지 모두 저장해야 해서 메모리가 낭비됩니다.

English

Main Code and Execution Result

px = [7, -4, 0, 5] if __name__ == "__main__" : pStr = printPoly(px) print(pStr) xValue = int(input("X value-->")) pxValue = calcPoly(xValue, px) print(pxValue)

Execution Result (X = 2)

P(x) = +7x^3 -4x^2 +0x^1 +5x^0 X value-->2 37

Limitation

For very large exponents (e.g., x³⁰⁰), this approach must store every unused term in the array, wasting memory.

특수 다항식 처리

Special Polynomial Processing
한국어

지수가 큰 다항식 처리

P(x) = 7x³⁰⁰ − 4x²⁰ + 5x⁰

이런 경우 모든 지수 자리를 배열에 저장하면 매우 비효율적입니다.

0이 아닌 계수와 그 차수만 별도로 저장하는 방식을 사용합니다.

tx (degrees) 300 20 0 px (coefficients) 7 -4 5 Fig 3-9. Sparse Polynomial with Degree-Coefficient Pairs
2개의 배열로 표현

tx = [300, 20, 0] (차수), px = [7, -4, 5] (계수)

English

Handling Polynomials with Large Exponents

P(x) = 7x³⁰⁰ − 4x²⁰ + 5x⁰

Storing every possible exponent slot in an array here would be extremely inefficient.

Instead, store only the non-zero coefficients and their degrees.

tx (degrees) 300 20 0 px (coefficients) 7 -4 5 Fig 3-9. Sparse Polynomial with Degree-Coefficient Pairs
Represented by Two Arrays

tx = [300, 20, 0] (degrees), px = [7, -4, 5] (coefficients)

Code03-06.py 특수 다항식 프로그램

Special Polynomial Program
한국어

차수-계수 쌍 배열을 이용한 구현

def printPoly(t_x, p_x) : polyStr = "P(x) = " for i in range(len(p_x)) : term = t_x[i] coef = p_x[i] if (coef >= 0) : polyStr += "+" polyStr += str(coef) + "x^" + str(term) + " " return polyStr def calcPoly(xVal, t_x, p_x) : retValue = 0 for i in range(len(px)) : term = t_x[i] coef = p_x[i] retValue += coef * xValue ** term return retValue tx = [300, 20, 0] px = [7, -4, 5]

핵심 차이

t_x[i]로 실제 지수를 바로 읽어오므로, 지수를 1씩 감소시키는 term -= 1 코드가 필요 없습니다.

English

Implementation Using Degree-Coefficient Pairs

def printPoly(t_x, p_x) : polyStr = "P(x) = " for i in range(len(p_x)) : term = t_x[i] coef = p_x[i] if (coef >= 0) : polyStr += "+" polyStr += str(coef) + "x^" + str(term) + " " return polyStr def calcPoly(xVal, t_x, p_x) : retValue = 0 for i in range(len(px)) : term = t_x[i] coef = p_x[i] retValue += coef * xValue ** term return retValue tx = [300, 20, 0] px = [7, -4, 5]

Key Difference

Since t_x[i] gives the actual exponent directly, there's no need for a term -= 1 decrement.

응용예제 1 — 카톡 친구 자동 삽입

App Example 1 — Auto-Insert Friends
한국어

Ex03-01.py: 카톡 횟수에 따른 자동 삽입

카톡 횟수(count)에 따라 자동으로 알맞은 순위 위치에 삽입하는 함수입니다.

katok = [('다현', 200), ('정연', 150), ('쯔위', 90), ('사나', 30), ('지효', 15)] def find_and_insert_data(friend, k_count) : findPos = -1 for i in range(len(katok)) : pair = katok[i] if k_count >= pair[1] : findPos = i break if findPos == -1 : findPos = len(katok) insert_data(findPos, (friend, k_count))
1리스트를 앞에서부터 탐색하며 새 카톡 횟수보다 작거나 같은 첫 위치를 찾습니다.
2끝까지 못 찾으면 맨 끝(len(katok))에 삽입합니다.
3찾은 위치에 (친구, 카톡횟수) 튜플을 insert_data()로 삽입합니다.
English

Ex03-01.py: Auto-Insert by Chat Count

Automatically inserts a friend into the correct ranking position based on their chat count.

katok = [('다현', 200), ('정연', 150), ('쯔위', 90), ('사나', 30), ('지효', 15)] def find_and_insert_data(friend, k_count) : findPos = -1 for i in range(len(katok)) : pair = katok[i] if k_count >= pair[1] : findPos = i break if findPos == -1 : findPos = len(katok) insert_data(findPos, (friend, k_count))
1Scans the list from the front to find the first position whose count is less than or equal to the new count.
2If no such position is found, inserts at the very end (len(katok)).
3Inserts the (friend, count) tuple at that position using insert_data().

응용예제 2 — 2차원 배열 활용

App Example 2 — 2D Array for Polynomial
한국어

Ex03-02.py: 차수와 계수를 하나의 배열로

기존에 tx, px 두 배열로 나누어 쓰던 것을 2차원 배열 하나로 통합합니다.

px = [ [300, 20, 0], [7, -4, 5] ] def printPoly(p_x): polyStr = "P(x) = " for i in range(len(p_x[0])): term = p_x[0][i] coef = p_x[1][i] if (coef >= 0): polyStr += "+" polyStr += str(coef) + "x^" + str(term) + " " return polyStr
구조 비교

px[0] = 차수 배열 [300, 20, 0]
px[1] = 계수 배열 [7, -4, 5]

장점

관련된 두 배열을 하나의 변수로 관리하므로, 함수에 넘길 인자가 줄어들고 데이터 관리가 편리해집니다.

English

Ex03-02.py: Combining Degrees and Coefficients

Merges what used to be two separate arrays (tx, px) into a single 2D array.

px = [ [300, 20, 0], [7, -4, 5] ] def printPoly(p_x): polyStr = "P(x) = " for i in range(len(p_x[0])): term = p_x[0][i] coef = p_x[1][i] if (coef >= 0): polyStr += "+" polyStr += str(coef) + "x^" + str(term) + " " return polyStr
Structure Comparison

px[0] = degree array [300, 20, 0]
px[1] = coefficient array [7, -4, 5]

Advantage

Managing two related arrays as a single variable reduces the number of function arguments and simplifies data handling.

Part 3 연습문제

Part 3 Practice
한국어
연습 3-1

다항식 P(x) = 3x⁴ + 2x² - 1을 배열로 표현하시오.

연습 3-2

Code03-06.py의 방식으로 P(x) = 5x¹⁰⁰ + 3x⁵⁰ - 2x¹⁰ + 1을 표현하시오.

연습 3-3

Ex03-01.py에서 동일한 연락 횟수일 때 새 친구가 앞에 오는 이유를 설명하시오.

English
Practice 3-1

Represent polynomial P(x) = 3x⁴ + 2x² - 1 as an array.

Practice 3-2

Using Code03-06.py's approach, represent P(x) = 5x¹⁰⁰ + 3x⁵⁰ - 2x¹⁰ + 1.

Practice 3-3

In Ex03-01.py, explain why a new friend with the same chat count is placed before existing ones.

1 / 31