← 목차로 돌아가기 / Back to Index

🧪 Ch13. 검색 — 실습 코드 / Lab Code: Searching

자료구조와 알고리즘 실습 | Data Structures & Algorithms Lab

💡 학습 팁: 코드를 직접 타이핑하면서 익히세요! 숨겨진 코드는 버튼을 눌러 확인하기 전에 먼저 스스로 생각해 보세요.
💡 Study Tip: Type the code yourself to learn! Try to think about hidden sections before revealing them.

📘 교재 예제 (Code)

📘 Textbook Examples (Code)

Code13-01.py

순차 검색 알고리즘을 구현합니다

## 함수 선언 부분 ## 
def seqSearch(ary, fData) :
## 전역 변수 선언 부분 ## 
dataAry = [188, 150, 168, 162, 105, 120, 177, 50]
findData = 0

## 메인 코드 부분 ## 
Code13-01.py

Implements the sequential (linear) search algorithm

## Function Declarations ## 
def seqSearch(ary, fData) :
## Global Variables ## 
dataAry = [188, 150, 168, 162, 105, 120, 177, 50]
findData = 0

## Main Code ## 
findData = int(input('* Enter value to search. --> '))
print('Array -->', dataAry)
position = seqSearch(dataAry, findData)
if position == -1 :
	print(findData, ' not found.')
else :
	print(findData,' is at ', position, 'position(s)')
Code13-02.py

정렬된 배열에서 순차 검색을 개선합니다

## 함수 선언 부분 ## 
def seqSearch(ary, fData) :
## 전역 변수 선언 부분 ## 
dataAry = [188, 150, 168, 162, 105, 120, 177, 50]
findData = 0

## 메인 코드 부분 ## 
Code13-02.py

Improves sequential search on a sorted array

## Function Declarations ## 
def seqSearch(ary, fData) :
## Global Variables ## 
dataAry = [188, 150, 168, 162, 105, 120, 177, 50]
findData = 0

## Main Code ## 
dataAry.sort()
findData = int(input('* Enter value to search. --> '))
print('Array -->', dataAry)
position = seqSearch(dataAry, findData)
if position == -1 :
	print(findData, ' not found.')
else :
	print(findData, ' is at ', position, 'position(s)')
Code13-03.py

이진 검색 알고리즘을 구현합니다

## 함수 선언 부분 ## 
def binSearch(ary, fData) :
## 전역 변수 선언 부분 ##
dataAry = [ 50, 60, 105, 120, 150, 160, 162, 168, 177, 188]
findData = 162	# 할머니키

## 메인 코드 부분 ##
Code13-03.py

Implements the binary search algorithm

## Function Declarations ## 
def binSearch(ary, fData) :
## Global Variables ##
dataAry = [ 50, 60, 105, 120, 150, 160, 162, 168, 177, 188]
findData = 162	# GrandmaHeight

## Main Code ##
print('Array -->', dataAry)
position = binSearch(dataAry, findData)
if position == -1 :
	print(findData,' not found.')
else :
	print(findData,' is at ', position, 'position(s)')
Code13-04.py

인덱스 테이블을 만들어 검색 성능을 개선합니다

from  operator import itemgetter

## 함수 선언 부분 ## 
def makeIndex(ary, pos) :
def bookSearch(ary, fData) :
## 전역 변수 선언 부분 ##
bookAry = [['어린왕자', '쌩떽쥐베리'],['이방인', '까뮈'], ['부활', '톨스토이'],
		   ['신곡', '단테'], ['돈키호테', '세르반테스'], ['동물농장', '조지오웰'],
		   ['데미안','헤르만헤세'], ['파우스트', '괴테'], ['대지', '펄벅']]
nameIndex = []
authIndex = []

## 메인 코드 부분 ##
Code13-04.py

Creates an index table to improve search performance

from  operator import itemgetter

## Function Declarations ## 
def makeIndex(ary, pos) :
def bookSearch(ary, fData) :
## Global Variables ##
bookAry = [['LittlePrince', 'SaintExupery'],['TheStranger', 'Camus'], ['Resurrection', 'Tolstoy'],
		   ['new song', 'Dante'], ['DonQuixote', 'Cervantes'], ['AnimalFarm', 'GeorgeOrwell'],
		   ['Demian','HermannHesse'], ['Faust', 'Goethe'], ['TheGoodEarth', 'PearlBuck']]
nameIndex = []
authIndex = []

## Main Code ##
print('#Books on shelf ==>', bookAry)
nameIndex = makeIndex(bookAry, 0)
print('#Book title index table ==>', nameIndex)
authIndex = makeIndex(bookAry, 1)
print('#Author name index table ==>', authIndex)

findName = 'new song'
findPos = bookSearch(nameIndex, findName)
if findPos != -1 :
	print(findName, ''s author is', bookAry[findPos][1], '.')
else :
	print(findName, ' Book not found.')

findName = 'Goethe'
findPos = bookSearch(authIndex, findName)
if findPos != -1 :
	print(findName, ''s books are', bookAry[findPos][0], '.')
else :
	print(findName, ' Author not found.')

📗 응용 예제 (Ex)

📗 Applied Examples (Ex)

Ex13-01.py

검색 응용: 대용량 데이터에서 이진 검색 실습

import random

## 함수 선언 부분 ##
def binSearch(ary, fData) :
## 전역 변수 선언 부분 ##
dataAry = ['바나나맛우유', '레쓰비캔커피', '츄파춥스', '도시락', '삼다수', '코카콜라', '삼각김밥']
sellAry = [ random.choice(dataAry) for _ in  range(20)]

## 메인 코드 부분 ##
Ex13-01.py

Search application: binary search on large datasets

import random

## Function Declarations ##
def binSearch(ary, fData) :
## Global Variables ##
dataAry = ['BananaMilk', 'LetsBeCoffee', 'ChupaChups', 'Lunchbox', 'Samdasu', 'CocaCola', 'Onigiri']
sellAry = [ random.choice(dataAry) for _ in  range(20)]

## Main Code ##
print('#All items sold today (dupl., unsorted) -->', sellAry)
sellAry.sort()
print('#All items sold today (dupl., sorted) -->', sellAry)
sellProduct = list(set(sellAry))
print('#Item types sold today (no duplicates) -->', sellProduct)

countList = []
for product in sellProduct :
	count = 0
	pos = 0
	while (pos != -1) :
		pos = binSearch(sellAry, product)
		if pos != -1 :
			count += 1
			del(sellAry[pos])
	countList.append( (product, count))

print()
print("settlement result ==>", countList)
Ex13-02.py

검색 응용: 순차 검색과 이진 검색의 성능을 비교합니다

import random

## 함수 선언 부분 ##
def seqSearch(ary, fData) :
def binSearch(ary, fData) :
## 전역 변수 선언 부분 ##
dataAry, sortedAry = [], []
findData = 7878
count = 0

## 메인 코드 부분 ##
Ex13-02.py

Search application: compares sequential vs. binary search performance

import random

## Function Declarations ##
def seqSearch(ary, fData) :
def binSearch(ary, fData) :
## Global Variables ##
dataAry, sortedAry = [], []
findData = 7878
count = 0

## Main Code ##
dataAry = [ random.randint(0, 999999) for _ in range(1000000)]
dataAry.insert(random.randint(0, 1000000), findData)
sortedAry = sorted(dataAry)

print('#Unsorted array (1M items) -->', dataAry[0:5], '~~~~', dataAry[-5:len(dataAry)])
print('#Sorted array (1M items) -->', sortedAry[0:5], '~~~~', sortedAry[-5:len(sortedAry)])

count =0
pos = seqSearch(dataAry,findData)
if pos != -1 :
	print('Sequential search (unsorted data) -->', count, 'times')

count =0
pos = binSearch(sortedAry, findData)
if pos != -1 :
	print('Binary search (sorted data) -->', count, 'times')

📙 자가 실습 (Self)

📙 Self Practice (Self)

Self13-01.py

순차 검색으로 모든 위치를 찾는 함수를 직접 구현합니다

## 함수 선언부
def seqSearch(ary, fData) :
## 전역 변수부
dataAry = [188, 50, 150, 168, 50, 162, 105, 120, 177, 50]
findData = 50

## 메인 코드부
Self13-01.py

Implements a function to find all positions using sequential search yourself

## Function Declarations
def seqSearch(ary, fData) :
## Global Variables
dataAry = [188, 50, 150, 168, 50, 162, 105, 120, 177, 50]
findData = 50

## Main Code
print('Array -->', dataAry)
positionList = seqSearch(dataAry, findData)
if positionList == [] :
    print(findData,' not found.')
else :
    print(findData,' is at ', positionList, 'position(s)')
Self13-02.py

이진 검색을 직접 구현하고 비교 횟수를 셉니다

import random
## 함수 선언부
def binSearch(ary, fData) :
## 전역 변수부
dataAry = [ ]
findData =  0
count = 0

## 메인 코드부
Self13-02.py

Implements binary search and counts comparisons yourself

import random
## Function Declarations
def binSearch(ary, fData) :
## Global Variables
dataAry = [ ]
findData =  0
count = 0

## Main Code
dataAry = [random.randint(0,100000) for _ in range(100000)]
dataAry.sort()
findData = random.randint(0,100000)
print('Array excerpt -->', dataAry[:5], '~~~~', dataAry[-6:-1])
position = binSearch(dataAry, findData)
if position == -1 :
    print(findData,' not found.')
else :
    print(findData,' is at ', position, 'position(s)')
print('##', count, "search comparisons")