" Data Structures & Algorithms in Python 시리즈 -1"
Lecture의 번역 정리본은 정리해서 올라올 예정이다.
재귀의 경우, 해설이 필요하여 4장의 경우 연습문제 해설을 함께 올렸다.
코드는 다음 링크에서 확인 가능하다.
def draw_line(tick_length, tick_label=''):
line = '-' * tick_length
if tick_label:
line += ' ' + tick_label
print(line)
def draw_interval(center_length):
if center_length > 0:
draw_interval(center_length - 1)
draw_line(center_length)
draw_interval(center_length - 1)
def draw_ruler(num_inches, major_length):
draw_line(major_length, "0")
for j in range(1, 1+num_inches):
draw_interval(major_length - 1)
draw_line(major_length, str(j))
코드 설명
→ (a) 는 3이 두 번 호출된 것이고, (b)는 4가 한번 호출된 것이다. (위, 아래 줄긋기 제외.)
4.1 Describe a recursive algorithm for finding the maximum element in a sequence, S, of n elements. What is your running time and space usage?
def find_max(arr, index):
if index == len(arr) - 1 : return arr[index]
return max(arr[index], find_max(arr, index+1))
4.3 Draw the recursion trace for the computation of power (2,18), using the repeated squaring algorithm, as implemented in Code Fragment 4.12.
def power(base, top):
if top == 0:
return 1
return base * power(base, top-1)
recursion trace를 해보면, 로 쪼개어 코드 작성이 가능하다.
위 문제를 squaring technique로 더 빠르게 풀어보자.
def power(base, top):
# writing code
if top == 0:
return 1
partial = power(base, top//2) # lower bound
result = partial * partial
if top % 2 == 1:
return result *= base # odd
return reuslt
4.5 Draw the recursion trace for the execution of function PuzzleSolve(3,S,U)
(Code Fragment 4.14), where S is empty and U = {a,b,c,d}.
p. 197의 함수 자체는 U의 집합의 모든 원소에 대해서 중복 없이 k 길이를 가진 문자열을 반환하는 것이다.
Recursion trace
pass
4.7 Describe a recursive function for converting a string of digits into the integer it represents. For example, “13531” represents the integer 13,531.
# recursion 생각 안했을 때.
def str2int(string:str):
cnt=0
for digit, i in enumerate(map(int, string[::-1])):
cnt += ((10**digit) * i)
return cnt
# recursion 풀이.
def str2int(string, length):
# length = len(string)
stand = len(string)
if length <= 0:
return 0
first = string[stand-length]
cnt = str2int(string, length-1)
cnt += int(first) * (10**(length-1))
return cnt
문제 추가
https://www.daleseo.com/sort-merge/ (No slicing version)
def merge_sort(arr):
def sort(low, high):
if high - low < 2:
return
mid = (low + high) // 2
sort(low, mid)
sort(mid, high)
merge(low, mid, high)
def merge(low, mid, high):
temp = []
l, h = low, mid
while l < mid and h < high:
if arr[l] < arr[h]:
temp.append(arr[l])
l += 1
else:
temp.append(arr[h])
h += 1
while l < mid:
temp.append(arr[l])
l += 1
while h < high:
temp.append(arr[h])
h += 1
for i in range(low, high):
arr[i] = temp[i - low]
return sort(0, len(arr))
→ Time usage : SlogS : S* log S
→ Space usage : 1호출 시 필요한 공간의 정도? S
이를 도식화하면 아래와 같이 호출이 일어나게 된다. 맞다. 복잡하다. 그래서 그림으로 한번 그려보면 이해가 수월해진다.