import time
# 0, 1, ..., 9998, 9999
list_a = range(10000)
# list_a์ ๋์ ํฉ์ ๊ตฌํ๋ค. ์๊ฐ๋ณต์ก๋๋ Θ(n²)
def func0(list_a):
ret = []
for i in range(len(list_a)):
suma = 0
for a in list_a[:i+1]:
suma += a
ret.append(suma)
return ret
# list_a์ ๋์ ํฉ์ ๊ตฌํ๋ค. ์๊ฐ๋ณต์ก๋๋ Θ(n)
def func1(list_a):
ret = []
suma = 0
for a in list_a:
suma += a
ret.append(suma)
return ret
start0 = time.monotonic()
ret0 = func0(list_a)
elapsedtime0 = time.monotonic() - start0
start1 = time.monotonic()
ret1 = func1(list_a)
elapsedtime1 = time.monotonic() - start1
# ๋ ํจ์ซ๊ฐ์ด ๊ฐ๋ค๋ฉด
if ret0 == ret1:
print(elapsedtime0, elapsedtime1)
์ ์ฝ๋๋ฅผ ์คํํด๋ณด๋ฉด func0์ ์คํ ์๊ฐ์ 2.1089999999999236์ด, func1์ ์คํ ์๊ฐ์ 0.016000000000076398์ด์์ ์ ์ ์๋ค.
๋ ํจ์์ ๋ฐํ๊ฐ์ ๊ฐ์ง๋ง ์คํ ์๊ฐ์ ๋ค๋ฅด๋ค. ์ ๊ทธ๋ด๊น?
list_a์ ๊ธธ์ด๋ฅผ n์ด๋ผ ํ์. ์ ์ฝ๋์์๋ n=10000์ด๋ค.
func0์ ๋ณด๋ฉด ์ด์ค for๋ฌธ์ด ์ฌ์ฉ๋์๋ค. ๋ฐ๊นฅ for๋ฌธ์ list_a์ ๊ธธ์ด, ์ฆ n๋ฒ ๋ฐ๋ณต๋๊ณ , ์์ชฝ for๋ฌธ์ i๋ฒ ๋ฐ๋ณต๋๋ ๊ฒ์ ์ ์ ์๋ค. ๋ฐ๊นฅ for๋ฌธ์ด ํ ๋ฒ ๋ ๋๋ง๋ค i๋ 1์ฉ ์ฆ๊ฐํ๋ค. ์ฌ๊ธฐ์ i๋ ์ฒซ์งธํญ์ด 0, ๋ง์ง๋งํญ์ด n-1, ๊ณต์ฐจ๊ฐ 1์ธ ๋ฑ์ฐจ์์ด์ ์์์ด๋ค. ๋ฐ๋ผ์ ์์ชฝ for๋ฌธ์ด ๋ฐ๋ณต๋๋ ํ์๋ ๋ฑ์ฐจ์์ด์ ํฉ ๊ณต์์ ์ํด n(n-1)/2์ด๋ค. ์ฐ์ฐ ํ์๊ฐ n์ ๋ํ ์ด์ฐจ์์ผ๋ก ๋ํ๋ด์ด์ง๋ค. ์๊ฐ ๋ณต์ก๋๋ ์ฐ์ฐ ํ์์ ๋น๋กํ๋ฏ๋ก ์๊ฐ ๋ณต์ก๋๋ฅผ Θ(n(n-1)/2) = Θ(n²) ์ด๋ผ๊ณ ํ ์ ์๋ค.
func1์ ๋ณด๋ฉด for๋ฌธ์ด ํ๋์ด๋ค. ๋ฐ๋ณต๋ฌธ์ด n๋ฒ๋งํผ ๋ฐ๋ณต๋๋ฏ๋ก ์๊ฐ ๋ณต์ก๋๋ Θ(n)์ด๋ค.

์ด๋ฏธ์ง ์ถ์ฒ: Comparison computational complexity - Time complexity - Wikipedia
Time complexity - Wikipedia
From Wikipedia, the free encyclopedia Estimate of time taken for running an algorithm Graphs of functions commonly used in the analysis of algorithms, showing the number of operations N as the result of input size n for each function In theoretical compute
en.wikipedia.org
N=n๊ณผ N=n²์ ์ฐจ์ด๋ ์ด๋ง์ด๋งํ๋ค.
n = 100
a = 0
for x in range(10):
for y in range(n):
for z in range(n-10):
a += 1
์ ์ฝ๋๋ ์ผ์ค for๋ฌธ์ด์ง๋ง ์๊ฐ ๋ณต์ก๋๋ ์ฌ์ ํ Θ(n²)์ด๋ค.
์๋ํ๋ฉด ๋ช
๋ น ํ์๊ฐ (n-10)*n*10 ์ผ๋ก n์ ๋ํ ์ด์ฐจ์์ผ๋ก ๋ํ๋ด์ด์ง๊ธฐ ๋๋ฌธ์ด๋ค.