Skip to content

Commit 09ba8d7

Browse files
committed
finish
1 parent f8ccabe commit 09ba8d7

File tree

66 files changed

+1051
-642
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

66 files changed

+1051
-642
lines changed

.python-version

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
3.7.0

10장_검색/1_sequential_search.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ def test_sequential_search():
99
seq = [1, 5, 6, 8, 3]
1010
n1 = 5
1111
n2 = 7
12-
assert(sequential_search(seq, n1) == True)
13-
assert(sequential_search(seq, n2) == False)
12+
assert(sequential_search(seq, n1) is True)
13+
assert(sequential_search(seq, n2) is False)
1414
print("테스트 통과!")
1515

1616

10장_검색/2_ordered_sequential_search.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ def test_ordered_sequential_search():
1212
seq = [1, 2, 4, 5, 6, 8, 10]
1313
n1 = 10
1414
n2 = 7
15-
assert(ordered_sequential_search(seq, n1) == True)
16-
assert(ordered_sequential_search(seq, n2) == False)
15+
assert(ordered_sequential_search(seq, n1) is True)
16+
assert(ordered_sequential_search(seq, n2) is False)
1717
print("테스트 통과!")
1818

1919

10장_검색/3_quick_select.py

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import random
22

33

4-
def quickSelect(seq, k):
5-
# 이 부분은 퀵 정렬과 같다.
4+
def quick_select_cache(seq, k):
65
len_seq = len(seq)
76
if len_seq < 2:
87
return seq[0]
8+
99
# 피벗을 무작위로 선택할 수 있다.
1010
# pivot = random.choice(seq)
1111
ipivot = len_seq // 2
@@ -14,23 +14,54 @@ def quickSelect(seq, k):
1414
smallerList = [x for i, x in enumerate(seq) if x <= pivot and i != ipivot]
1515
largerList = [x for i, x in enumerate(seq) if x > pivot and i != ipivot]
1616

17-
# 이 부분에서 퀵 정렬과 다르다.
18-
m = len(smallerList) + 1
17+
m = len(smallerList)
1918
if k == m:
2019
return pivot
2120
elif k < m:
22-
return quickSelect(smallerList, k)
21+
return quick_select_cache(smallerList, k)
2322
else:
24-
return quickSelect(largerList, k-m-1)
23+
return quick_select_cache(largerList, k-m-1)
2524

2625

27-
if __name__ == "__main__":
28-
seq = [10, 60, 100, 50, 60, 75, 31, 50, 30, 20, 120, 170, 200]
29-
# seq = [3, 7, 2, 1, 4, 6, 5, 10, 9, 11]
26+
def swap(seq, x, y):
27+
seq[x], seq[y] = seq[y], seq[x]
28+
29+
30+
def quick_select(seq, k, left=None, right=None):
31+
left = left or 0
32+
right = right or len(seq) - 1
33+
# ipivot = random.randint(left, right)
34+
ipivot = len(seq) // 2
35+
pivot = seq[ipivot]
36+
37+
# 피벗을 정렬 범위 밖으로 이동한다.
38+
swap(seq, ipivot, right)
39+
swapIndex, i = left, left
40+
while i < right:
41+
if pivot < seq[i]:
42+
swap(seq, i, swapIndex)
43+
swapIndex += 1
44+
i += 1
3045

46+
# 피벗 위치를 확정한다.
47+
swap(seq, right, swapIndex)
48+
49+
# 피벗 위치를 확인한다.
50+
rank = len(seq) - swapIndex
51+
if k == rank:
52+
return seq[swapIndex]
53+
elif k < rank:
54+
return quick_select(seq, k, swapIndex+1, right)
55+
else:
56+
return quick_select(seq, k, left, swapIndex-1)
57+
58+
59+
if __name__ == "__main__":
60+
seq = [3, 7, 2, 1, 4, 6, 5, 10, 9, 11]
3161
k = len(seq) // 2
3262
print(sorted(seq))
33-
print(quickSelect(seq, k))
63+
print(quick_select_cache(seq, k-1))
64+
print(quick_select(seq, k))
3465
# 중앙값(median) 출력을 위해서 넘파이를 사용함
3566
import numpy
3667
print(numpy.median(seq))

10장_검색/5_search_entry_matrix.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@ def find_elem_matrix_bool(m1, value):
1515

1616
def test_find_elem_matrix_bool():
1717
m1 = [[1, 2, 8, 9], [2, 4, 9, 12], [4, 7, 10, 13], [6, 8, 11, 15]]
18-
assert(find_elem_matrix_bool(m1, 8) == True)
19-
assert(find_elem_matrix_bool(m1, 3) == False)
18+
assert(find_elem_matrix_bool(m1, 8) is True)
19+
assert(find_elem_matrix_bool(m1, 3) is False)
2020
m2 = [[0]]
21-
assert(find_elem_matrix_bool(m2, 0) == True)
21+
assert(find_elem_matrix_bool(m2, 0) is True)
2222
print("테스트 통과!")
2323

2424

10장_검색/6_searching_in_a_matrix.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@ def test_searching_in_a_matrix():
2121
a = [[1, 3, 5], [7, 9, 11], [13, 15, 17]]
2222
import numpy
2323
b = numpy.array([(1, 2), (3, 4)])
24-
assert(searching_in_a_matrix(a, 13) == True)
25-
assert(searching_in_a_matrix(a, 14) == False)
26-
assert(searching_in_a_matrix(b, 3) == True)
27-
assert(searching_in_a_matrix(b, 5) == False)
24+
assert(searching_in_a_matrix(a, 13) is True)
25+
assert(searching_in_a_matrix(a, 14) is False)
26+
assert(searching_in_a_matrix(b, 3) is True)
27+
assert(searching_in_a_matrix(b, 5) is False)
2828
print("테스트 통과!")
2929

3030

11장_동적_프로그래밍/1_memo.py

Lines changed: 0 additions & 31 deletions
This file was deleted.
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
from functools import wraps
2+
3+
from benchmark import benchmark
4+
5+
6+
def memo(func):
7+
cache = {}
8+
9+
@wraps(func)
10+
def wrap(*args):
11+
if args not in cache:
12+
cache[args] = func(*args)
13+
return cache[args]
14+
return wrap
15+
16+
17+
def fib(n):
18+
if n < 2:
19+
return 1
20+
else:
21+
return fib(n-1) + fib(n-2)
22+
23+
24+
@memo
25+
def fib2(n):
26+
if n < 2:
27+
return 1
28+
else:
29+
return fib2(n-1) + fib2(n-2)
30+
31+
32+
def fib3(m, n):
33+
if m[n] == 0:
34+
m[n] = fib3(m, n-1) + fib3(m, n-2)
35+
return m[n]
36+
37+
38+
@benchmark
39+
def test_fib(n):
40+
print(fib(n))
41+
42+
43+
@benchmark
44+
def test_fib2(n):
45+
print(fib2(n))
46+
47+
48+
@benchmark
49+
def test_fib3(n):
50+
m = [0] * (n+1)
51+
m[0], m[1] = 1, 1
52+
print(fib3(m, n))
53+
54+
55+
if __name__ == "__main__":
56+
n = 35
57+
test_fib(n)
58+
test_fib2(n)
59+
test_fib3(n)

11장_동적_프로그래밍/2_memoized_longest_inc_subseq.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
1+
from bisect import bisect
12
from itertools import combinations
23
from functools import wraps
3-
from bisect import bisect
44

5-
from timeit import timeit
5+
from benchmark import benchmark
66

77

8-
# 단순 반복문
98
def naive_longest_inc_subseq(seq):
9+
""" 1) 단순한 방법 """
1010
for length in range(len(seq), 0, -1):
1111
for sub in combinations(seq, length):
1212
if list(sub) == sorted(sub):
1313
return len(sub)
1414

1515

16-
# 동적 프로그래밍
1716
def dp_longest_inc_subseq(seq):
17+
""" 2) 동적 프로그래밍 """
1818
L = [1] * len(seq)
19+
res = []
1920
for cur, val in enumerate(seq):
2021
for pre in range(cur):
2122
if seq[pre] <= val:
2223
L[cur] = max(L[cur], 1 + L[pre])
2324
return max(L)
2425

2526

26-
# 메모이제이션
2727
def memo(func):
2828
cache = {}
2929

@@ -36,6 +36,7 @@ def wrap(*args):
3636

3737

3838
def memoized_longest_inc_subseq(seq):
39+
""" 3) 메모이제이션 """
3940
@memo
4041
def L(cur):
4142
res = 1
@@ -46,41 +47,43 @@ def L(cur):
4647
return max(L(i) for i in range(len(seq)))
4748

4849

49-
# 이진 검색
5050
def longest_inc_bisec(seq):
51+
""" 4) 이진 검색 """
5152
end = []
5253
for val in seq:
5354
idx = bisect(end, val)
5455
if idx == len(end):
5556
end.append(val)
5657
else:
5758
end[idx] = val
59+
# print(end)
5860
return len(end)
5961

6062

61-
@timeit
63+
@benchmark
6264
def test_naive_longest_inc_subseq():
6365
print(naive_longest_inc_subseq(s1))
6466

6567

66-
@timeit
68+
@benchmark
6769
def test_dp_longest_inc_subseq():
6870
print(dp_longest_inc_subseq(s1))
6971

7072

71-
@timeit
73+
@benchmark
7274
def test_memoized_longest_inc_subseq():
7375
print(memoized_longest_inc_subseq(s1))
7476

7577

76-
@timeit
78+
@benchmark
7779
def test_longest_inc_bisec():
7880
print(longest_inc_bisec(s1))
7981

8082

8183
if __name__ == "__main__":
82-
from random import randrange
83-
s1 = [randrange(100) for i in range(20)]
84+
# from random import randrange
85+
# s1 = [randrange(100) for i in range(20)]
86+
s1 = [94, 8, 78, 22, 38, 79, 93, 8, 84, 39]
8487
print(s1)
8588
test_naive_longest_inc_subseq()
8689
test_dp_longest_inc_subseq()
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from functools import wraps
2+
import time
3+
4+
5+
def benchmark(method):
6+
@wraps(method)
7+
def timed(*args, **kw):
8+
ts = time.time()
9+
result = method(*args, **kw)
10+
te = time.time()
11+
# print("%r: %2.2f ms" % (method.__name__, (te - ts) * 1000))
12+
# print(f"{method.__name__}: {((te-ts)*1000):.2f} ms")
13+
print("{0}: {1:0.2f} ms".format(method.__name__, ((te-ts)*1000)))
14+
return result
15+
16+
return timed

0 commit comments

Comments
 (0)